1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
84 ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
85 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
86 InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
87 Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
88 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
89 WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
103 HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
104 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109pub use proposed_changes_editor::{
110 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
111};
112use similar::{ChangeTag, TextDiff};
113use std::iter::Peekable;
114use task::{ResolvedTask, TaskTemplate, TaskVariables};
115
116use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
117pub use lsp::CompletionContext;
118use lsp::{
119 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
120 LanguageServerId, LanguageServerName,
121};
122
123use language::BufferSnapshot;
124use movement::TextLayoutDetails;
125pub use multi_buffer::{
126 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
127 ToOffset, ToPoint,
128};
129use multi_buffer::{
130 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
131 ToOffsetUtf16,
132};
133use project::{
134 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
135 project_settings::{GitGutterSetting, ProjectSettings},
136 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
137 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
138};
139use rand::prelude::*;
140use rpc::{proto::*, ErrorExt};
141use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
142use selections_collection::{
143 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
144};
145use serde::{Deserialize, Serialize};
146use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
147use smallvec::SmallVec;
148use snippet::Snippet;
149use std::{
150 any::TypeId,
151 borrow::Cow,
152 cell::RefCell,
153 cmp::{self, Ordering, Reverse},
154 mem,
155 num::NonZeroU32,
156 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
157 path::{Path, PathBuf},
158 rc::Rc,
159 sync::Arc,
160 time::{Duration, Instant},
161};
162pub use sum_tree::Bias;
163use sum_tree::TreeMap;
164use text::{BufferId, OffsetUtf16, Rope};
165use theme::{
166 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
167 ThemeColors, ThemeSettings,
168};
169use ui::{
170 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
171 Tooltip,
172};
173use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
174use workspace::item::{ItemHandle, PreviewTabsSettings};
175use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
176use workspace::{
177 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
178};
179use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
180
181use crate::hover_links::{find_url, find_url_from_range};
182use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
183
184pub const FILE_HEADER_HEIGHT: u32 = 2;
185pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
186pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
187pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
188const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
189const MAX_LINE_LEN: usize = 1024;
190const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
191const MAX_SELECTION_HISTORY_LEN: usize = 1024;
192pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
193#[doc(hidden)]
194pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
195
196pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
197pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
198
199pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
200pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
201
202pub fn render_parsed_markdown(
203 element_id: impl Into<ElementId>,
204 parsed: &language::ParsedMarkdown,
205 editor_style: &EditorStyle,
206 workspace: Option<WeakEntity<Workspace>>,
207 cx: &mut App,
208) -> InteractiveText {
209 let code_span_background_color = cx
210 .theme()
211 .colors()
212 .editor_document_highlight_read_background;
213
214 let highlights = gpui::combine_highlights(
215 parsed.highlights.iter().filter_map(|(range, highlight)| {
216 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
217 Some((range.clone(), highlight))
218 }),
219 parsed
220 .regions
221 .iter()
222 .zip(&parsed.region_ranges)
223 .filter_map(|(region, range)| {
224 if region.code {
225 Some((
226 range.clone(),
227 HighlightStyle {
228 background_color: Some(code_span_background_color),
229 ..Default::default()
230 },
231 ))
232 } else {
233 None
234 }
235 }),
236 );
237
238 let mut links = Vec::new();
239 let mut link_ranges = Vec::new();
240 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
241 if let Some(link) = region.link.clone() {
242 links.push(link);
243 link_ranges.push(range.clone());
244 }
245 }
246
247 InteractiveText::new(
248 element_id,
249 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
250 )
251 .on_click(
252 link_ranges,
253 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
254 markdown::Link::Web { url } => cx.open_url(url),
255 markdown::Link::Path { path } => {
256 if let Some(workspace) = &workspace {
257 _ = workspace.update(cx, |workspace, cx| {
258 workspace
259 .open_abs_path(path.clone(), false, window, cx)
260 .detach();
261 });
262 }
263 }
264 },
265 )
266}
267
268#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
269pub enum InlayId {
270 InlineCompletion(usize),
271 Hint(usize),
272}
273
274impl InlayId {
275 fn id(&self) -> usize {
276 match self {
277 Self::InlineCompletion(id) => *id,
278 Self::Hint(id) => *id,
279 }
280 }
281}
282
283enum DocumentHighlightRead {}
284enum DocumentHighlightWrite {}
285enum InputComposition {}
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, has_more_lines) = crate::inline_completion_edit_text(
5998 &snapshot,
5999 &edits,
6000 edit_preview.as_ref()?,
6001 true,
6002 cx,
6003 )
6004 .first_line_preview();
6005
6006 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6007 .with_highlights(&style.text, highlighted_edits.highlights);
6008
6009 let preview = h_flex()
6010 .gap_1()
6011 .min_w_16()
6012 .child(styled_text)
6013 .when(has_more_lines, |parent| parent.child("…"));
6014
6015 let left = if first_edit_row != cursor_point.row {
6016 render_relative_row_jump("", cursor_point.row, first_edit_row)
6017 .into_any_element()
6018 } else {
6019 Icon::new(IconName::ZedPredict).into_any_element()
6020 };
6021
6022 Some(
6023 h_flex()
6024 .h_full()
6025 .flex_1()
6026 .gap_2()
6027 .pr_1()
6028 .overflow_x_hidden()
6029 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6030 .child(left)
6031 .child(preview),
6032 )
6033 }
6034 }
6035 }
6036
6037 fn render_context_menu(
6038 &self,
6039 style: &EditorStyle,
6040 max_height_in_lines: u32,
6041 y_flipped: bool,
6042 window: &mut Window,
6043 cx: &mut Context<Editor>,
6044 ) -> Option<AnyElement> {
6045 let menu = self.context_menu.borrow();
6046 let menu = menu.as_ref()?;
6047 if !menu.visible() {
6048 return None;
6049 };
6050 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6051 }
6052
6053 fn render_context_menu_aside(
6054 &self,
6055 style: &EditorStyle,
6056 max_size: Size<Pixels>,
6057 cx: &mut Context<Editor>,
6058 ) -> Option<AnyElement> {
6059 self.context_menu.borrow().as_ref().and_then(|menu| {
6060 if menu.visible() {
6061 menu.render_aside(
6062 style,
6063 max_size,
6064 self.workspace.as_ref().map(|(w, _)| w.clone()),
6065 cx,
6066 )
6067 } else {
6068 None
6069 }
6070 })
6071 }
6072
6073 fn hide_context_menu(
6074 &mut self,
6075 window: &mut Window,
6076 cx: &mut Context<Self>,
6077 ) -> Option<CodeContextMenu> {
6078 cx.notify();
6079 self.completion_tasks.clear();
6080 let context_menu = self.context_menu.borrow_mut().take();
6081 self.stale_inline_completion_in_menu.take();
6082 self.update_visible_inline_completion(window, cx);
6083 context_menu
6084 }
6085
6086 fn show_snippet_choices(
6087 &mut self,
6088 choices: &Vec<String>,
6089 selection: Range<Anchor>,
6090 cx: &mut Context<Self>,
6091 ) {
6092 if selection.start.buffer_id.is_none() {
6093 return;
6094 }
6095 let buffer_id = selection.start.buffer_id.unwrap();
6096 let buffer = self.buffer().read(cx).buffer(buffer_id);
6097 let id = post_inc(&mut self.next_completion_id);
6098
6099 if let Some(buffer) = buffer {
6100 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6101 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6102 ));
6103 }
6104 }
6105
6106 pub fn insert_snippet(
6107 &mut self,
6108 insertion_ranges: &[Range<usize>],
6109 snippet: Snippet,
6110 window: &mut Window,
6111 cx: &mut Context<Self>,
6112 ) -> Result<()> {
6113 struct Tabstop<T> {
6114 is_end_tabstop: bool,
6115 ranges: Vec<Range<T>>,
6116 choices: Option<Vec<String>>,
6117 }
6118
6119 let tabstops = self.buffer.update(cx, |buffer, cx| {
6120 let snippet_text: Arc<str> = snippet.text.clone().into();
6121 buffer.edit(
6122 insertion_ranges
6123 .iter()
6124 .cloned()
6125 .map(|range| (range, snippet_text.clone())),
6126 Some(AutoindentMode::EachLine),
6127 cx,
6128 );
6129
6130 let snapshot = &*buffer.read(cx);
6131 let snippet = &snippet;
6132 snippet
6133 .tabstops
6134 .iter()
6135 .map(|tabstop| {
6136 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6137 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6138 });
6139 let mut tabstop_ranges = tabstop
6140 .ranges
6141 .iter()
6142 .flat_map(|tabstop_range| {
6143 let mut delta = 0_isize;
6144 insertion_ranges.iter().map(move |insertion_range| {
6145 let insertion_start = insertion_range.start as isize + delta;
6146 delta +=
6147 snippet.text.len() as isize - insertion_range.len() as isize;
6148
6149 let start = ((insertion_start + tabstop_range.start) as usize)
6150 .min(snapshot.len());
6151 let end = ((insertion_start + tabstop_range.end) as usize)
6152 .min(snapshot.len());
6153 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6154 })
6155 })
6156 .collect::<Vec<_>>();
6157 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6158
6159 Tabstop {
6160 is_end_tabstop,
6161 ranges: tabstop_ranges,
6162 choices: tabstop.choices.clone(),
6163 }
6164 })
6165 .collect::<Vec<_>>()
6166 });
6167 if let Some(tabstop) = tabstops.first() {
6168 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6169 s.select_ranges(tabstop.ranges.iter().cloned());
6170 });
6171
6172 if let Some(choices) = &tabstop.choices {
6173 if let Some(selection) = tabstop.ranges.first() {
6174 self.show_snippet_choices(choices, selection.clone(), cx)
6175 }
6176 }
6177
6178 // If we're already at the last tabstop and it's at the end of the snippet,
6179 // we're done, we don't need to keep the state around.
6180 if !tabstop.is_end_tabstop {
6181 let choices = tabstops
6182 .iter()
6183 .map(|tabstop| tabstop.choices.clone())
6184 .collect();
6185
6186 let ranges = tabstops
6187 .into_iter()
6188 .map(|tabstop| tabstop.ranges)
6189 .collect::<Vec<_>>();
6190
6191 self.snippet_stack.push(SnippetState {
6192 active_index: 0,
6193 ranges,
6194 choices,
6195 });
6196 }
6197
6198 // Check whether the just-entered snippet ends with an auto-closable bracket.
6199 if self.autoclose_regions.is_empty() {
6200 let snapshot = self.buffer.read(cx).snapshot(cx);
6201 for selection in &mut self.selections.all::<Point>(cx) {
6202 let selection_head = selection.head();
6203 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6204 continue;
6205 };
6206
6207 let mut bracket_pair = None;
6208 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6209 let prev_chars = snapshot
6210 .reversed_chars_at(selection_head)
6211 .collect::<String>();
6212 for (pair, enabled) in scope.brackets() {
6213 if enabled
6214 && pair.close
6215 && prev_chars.starts_with(pair.start.as_str())
6216 && next_chars.starts_with(pair.end.as_str())
6217 {
6218 bracket_pair = Some(pair.clone());
6219 break;
6220 }
6221 }
6222 if let Some(pair) = bracket_pair {
6223 let start = snapshot.anchor_after(selection_head);
6224 let end = snapshot.anchor_after(selection_head);
6225 self.autoclose_regions.push(AutocloseRegion {
6226 selection_id: selection.id,
6227 range: start..end,
6228 pair,
6229 });
6230 }
6231 }
6232 }
6233 }
6234 Ok(())
6235 }
6236
6237 pub fn move_to_next_snippet_tabstop(
6238 &mut self,
6239 window: &mut Window,
6240 cx: &mut Context<Self>,
6241 ) -> bool {
6242 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6243 }
6244
6245 pub fn move_to_prev_snippet_tabstop(
6246 &mut self,
6247 window: &mut Window,
6248 cx: &mut Context<Self>,
6249 ) -> bool {
6250 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6251 }
6252
6253 pub fn move_to_snippet_tabstop(
6254 &mut self,
6255 bias: Bias,
6256 window: &mut Window,
6257 cx: &mut Context<Self>,
6258 ) -> bool {
6259 if let Some(mut snippet) = self.snippet_stack.pop() {
6260 match bias {
6261 Bias::Left => {
6262 if snippet.active_index > 0 {
6263 snippet.active_index -= 1;
6264 } else {
6265 self.snippet_stack.push(snippet);
6266 return false;
6267 }
6268 }
6269 Bias::Right => {
6270 if snippet.active_index + 1 < snippet.ranges.len() {
6271 snippet.active_index += 1;
6272 } else {
6273 self.snippet_stack.push(snippet);
6274 return false;
6275 }
6276 }
6277 }
6278 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6279 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6280 s.select_anchor_ranges(current_ranges.iter().cloned())
6281 });
6282
6283 if let Some(choices) = &snippet.choices[snippet.active_index] {
6284 if let Some(selection) = current_ranges.first() {
6285 self.show_snippet_choices(&choices, selection.clone(), cx);
6286 }
6287 }
6288
6289 // If snippet state is not at the last tabstop, push it back on the stack
6290 if snippet.active_index + 1 < snippet.ranges.len() {
6291 self.snippet_stack.push(snippet);
6292 }
6293 return true;
6294 }
6295 }
6296
6297 false
6298 }
6299
6300 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6301 self.transact(window, cx, |this, window, cx| {
6302 this.select_all(&SelectAll, window, cx);
6303 this.insert("", window, cx);
6304 });
6305 }
6306
6307 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6308 self.transact(window, cx, |this, window, cx| {
6309 this.select_autoclose_pair(window, cx);
6310 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6311 if !this.linked_edit_ranges.is_empty() {
6312 let selections = this.selections.all::<MultiBufferPoint>(cx);
6313 let snapshot = this.buffer.read(cx).snapshot(cx);
6314
6315 for selection in selections.iter() {
6316 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6317 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6318 if selection_start.buffer_id != selection_end.buffer_id {
6319 continue;
6320 }
6321 if let Some(ranges) =
6322 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6323 {
6324 for (buffer, entries) in ranges {
6325 linked_ranges.entry(buffer).or_default().extend(entries);
6326 }
6327 }
6328 }
6329 }
6330
6331 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6332 if !this.selections.line_mode {
6333 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6334 for selection in &mut selections {
6335 if selection.is_empty() {
6336 let old_head = selection.head();
6337 let mut new_head =
6338 movement::left(&display_map, old_head.to_display_point(&display_map))
6339 .to_point(&display_map);
6340 if let Some((buffer, line_buffer_range)) = display_map
6341 .buffer_snapshot
6342 .buffer_line_for_row(MultiBufferRow(old_head.row))
6343 {
6344 let indent_size =
6345 buffer.indent_size_for_line(line_buffer_range.start.row);
6346 let indent_len = match indent_size.kind {
6347 IndentKind::Space => {
6348 buffer.settings_at(line_buffer_range.start, cx).tab_size
6349 }
6350 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6351 };
6352 if old_head.column <= indent_size.len && old_head.column > 0 {
6353 let indent_len = indent_len.get();
6354 new_head = cmp::min(
6355 new_head,
6356 MultiBufferPoint::new(
6357 old_head.row,
6358 ((old_head.column - 1) / indent_len) * indent_len,
6359 ),
6360 );
6361 }
6362 }
6363
6364 selection.set_head(new_head, SelectionGoal::None);
6365 }
6366 }
6367 }
6368
6369 this.signature_help_state.set_backspace_pressed(true);
6370 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6371 s.select(selections)
6372 });
6373 this.insert("", window, cx);
6374 let empty_str: Arc<str> = Arc::from("");
6375 for (buffer, edits) in linked_ranges {
6376 let snapshot = buffer.read(cx).snapshot();
6377 use text::ToPoint as TP;
6378
6379 let edits = edits
6380 .into_iter()
6381 .map(|range| {
6382 let end_point = TP::to_point(&range.end, &snapshot);
6383 let mut start_point = TP::to_point(&range.start, &snapshot);
6384
6385 if end_point == start_point {
6386 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6387 .saturating_sub(1);
6388 start_point =
6389 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6390 };
6391
6392 (start_point..end_point, empty_str.clone())
6393 })
6394 .sorted_by_key(|(range, _)| range.start)
6395 .collect::<Vec<_>>();
6396 buffer.update(cx, |this, cx| {
6397 this.edit(edits, None, cx);
6398 })
6399 }
6400 this.refresh_inline_completion(true, false, window, cx);
6401 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6402 });
6403 }
6404
6405 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6406 self.transact(window, cx, |this, window, cx| {
6407 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6408 let line_mode = s.line_mode;
6409 s.move_with(|map, selection| {
6410 if selection.is_empty() && !line_mode {
6411 let cursor = movement::right(map, selection.head());
6412 selection.end = cursor;
6413 selection.reversed = true;
6414 selection.goal = SelectionGoal::None;
6415 }
6416 })
6417 });
6418 this.insert("", window, cx);
6419 this.refresh_inline_completion(true, false, window, cx);
6420 });
6421 }
6422
6423 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6424 if self.move_to_prev_snippet_tabstop(window, cx) {
6425 return;
6426 }
6427
6428 self.outdent(&Outdent, window, cx);
6429 }
6430
6431 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6432 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6433 return;
6434 }
6435
6436 let mut selections = self.selections.all_adjusted(cx);
6437 let buffer = self.buffer.read(cx);
6438 let snapshot = buffer.snapshot(cx);
6439 let rows_iter = selections.iter().map(|s| s.head().row);
6440 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6441
6442 let mut edits = Vec::new();
6443 let mut prev_edited_row = 0;
6444 let mut row_delta = 0;
6445 for selection in &mut selections {
6446 if selection.start.row != prev_edited_row {
6447 row_delta = 0;
6448 }
6449 prev_edited_row = selection.end.row;
6450
6451 // If the selection is non-empty, then increase the indentation of the selected lines.
6452 if !selection.is_empty() {
6453 row_delta =
6454 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6455 continue;
6456 }
6457
6458 // If the selection is empty and the cursor is in the leading whitespace before the
6459 // suggested indentation, then auto-indent the line.
6460 let cursor = selection.head();
6461 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6462 if let Some(suggested_indent) =
6463 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6464 {
6465 if cursor.column < suggested_indent.len
6466 && cursor.column <= current_indent.len
6467 && current_indent.len <= suggested_indent.len
6468 {
6469 selection.start = Point::new(cursor.row, suggested_indent.len);
6470 selection.end = selection.start;
6471 if row_delta == 0 {
6472 edits.extend(Buffer::edit_for_indent_size_adjustment(
6473 cursor.row,
6474 current_indent,
6475 suggested_indent,
6476 ));
6477 row_delta = suggested_indent.len - current_indent.len;
6478 }
6479 continue;
6480 }
6481 }
6482
6483 // Otherwise, insert a hard or soft tab.
6484 let settings = buffer.settings_at(cursor, cx);
6485 let tab_size = if settings.hard_tabs {
6486 IndentSize::tab()
6487 } else {
6488 let tab_size = settings.tab_size.get();
6489 let char_column = snapshot
6490 .text_for_range(Point::new(cursor.row, 0)..cursor)
6491 .flat_map(str::chars)
6492 .count()
6493 + row_delta as usize;
6494 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6495 IndentSize::spaces(chars_to_next_tab_stop)
6496 };
6497 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6498 selection.end = selection.start;
6499 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6500 row_delta += tab_size.len;
6501 }
6502
6503 self.transact(window, cx, |this, window, cx| {
6504 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6505 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6506 s.select(selections)
6507 });
6508 this.refresh_inline_completion(true, false, window, cx);
6509 });
6510 }
6511
6512 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6513 if self.read_only(cx) {
6514 return;
6515 }
6516 let mut selections = self.selections.all::<Point>(cx);
6517 let mut prev_edited_row = 0;
6518 let mut row_delta = 0;
6519 let mut edits = Vec::new();
6520 let buffer = self.buffer.read(cx);
6521 let snapshot = buffer.snapshot(cx);
6522 for selection in &mut selections {
6523 if selection.start.row != prev_edited_row {
6524 row_delta = 0;
6525 }
6526 prev_edited_row = selection.end.row;
6527
6528 row_delta =
6529 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
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 });
6538 }
6539
6540 fn indent_selection(
6541 buffer: &MultiBuffer,
6542 snapshot: &MultiBufferSnapshot,
6543 selection: &mut Selection<Point>,
6544 edits: &mut Vec<(Range<Point>, String)>,
6545 delta_for_start_row: u32,
6546 cx: &App,
6547 ) -> u32 {
6548 let settings = buffer.settings_at(selection.start, cx);
6549 let tab_size = settings.tab_size.get();
6550 let indent_kind = if settings.hard_tabs {
6551 IndentKind::Tab
6552 } else {
6553 IndentKind::Space
6554 };
6555 let mut start_row = selection.start.row;
6556 let mut end_row = selection.end.row + 1;
6557
6558 // If a selection ends at the beginning of a line, don't indent
6559 // that last line.
6560 if selection.end.column == 0 && selection.end.row > selection.start.row {
6561 end_row -= 1;
6562 }
6563
6564 // Avoid re-indenting a row that has already been indented by a
6565 // previous selection, but still update this selection's column
6566 // to reflect that indentation.
6567 if delta_for_start_row > 0 {
6568 start_row += 1;
6569 selection.start.column += delta_for_start_row;
6570 if selection.end.row == selection.start.row {
6571 selection.end.column += delta_for_start_row;
6572 }
6573 }
6574
6575 let mut delta_for_end_row = 0;
6576 let has_multiple_rows = start_row + 1 != end_row;
6577 for row in start_row..end_row {
6578 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6579 let indent_delta = match (current_indent.kind, indent_kind) {
6580 (IndentKind::Space, IndentKind::Space) => {
6581 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6582 IndentSize::spaces(columns_to_next_tab_stop)
6583 }
6584 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6585 (_, IndentKind::Tab) => IndentSize::tab(),
6586 };
6587
6588 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6589 0
6590 } else {
6591 selection.start.column
6592 };
6593 let row_start = Point::new(row, start);
6594 edits.push((
6595 row_start..row_start,
6596 indent_delta.chars().collect::<String>(),
6597 ));
6598
6599 // Update this selection's endpoints to reflect the indentation.
6600 if row == selection.start.row {
6601 selection.start.column += indent_delta.len;
6602 }
6603 if row == selection.end.row {
6604 selection.end.column += indent_delta.len;
6605 delta_for_end_row = indent_delta.len;
6606 }
6607 }
6608
6609 if selection.start.row == selection.end.row {
6610 delta_for_start_row + delta_for_end_row
6611 } else {
6612 delta_for_end_row
6613 }
6614 }
6615
6616 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6617 if self.read_only(cx) {
6618 return;
6619 }
6620 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6621 let selections = self.selections.all::<Point>(cx);
6622 let mut deletion_ranges = Vec::new();
6623 let mut last_outdent = None;
6624 {
6625 let buffer = self.buffer.read(cx);
6626 let snapshot = buffer.snapshot(cx);
6627 for selection in &selections {
6628 let settings = buffer.settings_at(selection.start, cx);
6629 let tab_size = settings.tab_size.get();
6630 let mut rows = selection.spanned_rows(false, &display_map);
6631
6632 // Avoid re-outdenting a row that has already been outdented by a
6633 // previous selection.
6634 if let Some(last_row) = last_outdent {
6635 if last_row == rows.start {
6636 rows.start = rows.start.next_row();
6637 }
6638 }
6639 let has_multiple_rows = rows.len() > 1;
6640 for row in rows.iter_rows() {
6641 let indent_size = snapshot.indent_size_for_line(row);
6642 if indent_size.len > 0 {
6643 let deletion_len = match indent_size.kind {
6644 IndentKind::Space => {
6645 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6646 if columns_to_prev_tab_stop == 0 {
6647 tab_size
6648 } else {
6649 columns_to_prev_tab_stop
6650 }
6651 }
6652 IndentKind::Tab => 1,
6653 };
6654 let start = if has_multiple_rows
6655 || deletion_len > selection.start.column
6656 || indent_size.len < selection.start.column
6657 {
6658 0
6659 } else {
6660 selection.start.column - deletion_len
6661 };
6662 deletion_ranges.push(
6663 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6664 );
6665 last_outdent = Some(row);
6666 }
6667 }
6668 }
6669 }
6670
6671 self.transact(window, cx, |this, window, cx| {
6672 this.buffer.update(cx, |buffer, cx| {
6673 let empty_str: Arc<str> = Arc::default();
6674 buffer.edit(
6675 deletion_ranges
6676 .into_iter()
6677 .map(|range| (range, empty_str.clone())),
6678 None,
6679 cx,
6680 );
6681 });
6682 let selections = this.selections.all::<usize>(cx);
6683 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6684 s.select(selections)
6685 });
6686 });
6687 }
6688
6689 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6690 if self.read_only(cx) {
6691 return;
6692 }
6693 let selections = self
6694 .selections
6695 .all::<usize>(cx)
6696 .into_iter()
6697 .map(|s| s.range());
6698
6699 self.transact(window, cx, |this, window, cx| {
6700 this.buffer.update(cx, |buffer, cx| {
6701 buffer.autoindent_ranges(selections, cx);
6702 });
6703 let selections = this.selections.all::<usize>(cx);
6704 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6705 s.select(selections)
6706 });
6707 });
6708 }
6709
6710 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6711 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6712 let selections = self.selections.all::<Point>(cx);
6713
6714 let mut new_cursors = Vec::new();
6715 let mut edit_ranges = Vec::new();
6716 let mut selections = selections.iter().peekable();
6717 while let Some(selection) = selections.next() {
6718 let mut rows = selection.spanned_rows(false, &display_map);
6719 let goal_display_column = selection.head().to_display_point(&display_map).column();
6720
6721 // Accumulate contiguous regions of rows that we want to delete.
6722 while let Some(next_selection) = selections.peek() {
6723 let next_rows = next_selection.spanned_rows(false, &display_map);
6724 if next_rows.start <= rows.end {
6725 rows.end = next_rows.end;
6726 selections.next().unwrap();
6727 } else {
6728 break;
6729 }
6730 }
6731
6732 let buffer = &display_map.buffer_snapshot;
6733 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6734 let edit_end;
6735 let cursor_buffer_row;
6736 if buffer.max_point().row >= rows.end.0 {
6737 // If there's a line after the range, delete the \n from the end of the row range
6738 // and position the cursor on the next line.
6739 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6740 cursor_buffer_row = rows.end;
6741 } else {
6742 // If there isn't a line after the range, delete the \n from the line before the
6743 // start of the row range and position the cursor there.
6744 edit_start = edit_start.saturating_sub(1);
6745 edit_end = buffer.len();
6746 cursor_buffer_row = rows.start.previous_row();
6747 }
6748
6749 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6750 *cursor.column_mut() =
6751 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6752
6753 new_cursors.push((
6754 selection.id,
6755 buffer.anchor_after(cursor.to_point(&display_map)),
6756 ));
6757 edit_ranges.push(edit_start..edit_end);
6758 }
6759
6760 self.transact(window, cx, |this, window, cx| {
6761 let buffer = this.buffer.update(cx, |buffer, cx| {
6762 let empty_str: Arc<str> = Arc::default();
6763 buffer.edit(
6764 edit_ranges
6765 .into_iter()
6766 .map(|range| (range, empty_str.clone())),
6767 None,
6768 cx,
6769 );
6770 buffer.snapshot(cx)
6771 });
6772 let new_selections = new_cursors
6773 .into_iter()
6774 .map(|(id, cursor)| {
6775 let cursor = cursor.to_point(&buffer);
6776 Selection {
6777 id,
6778 start: cursor,
6779 end: cursor,
6780 reversed: false,
6781 goal: SelectionGoal::None,
6782 }
6783 })
6784 .collect();
6785
6786 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6787 s.select(new_selections);
6788 });
6789 });
6790 }
6791
6792 pub fn join_lines_impl(
6793 &mut self,
6794 insert_whitespace: bool,
6795 window: &mut Window,
6796 cx: &mut Context<Self>,
6797 ) {
6798 if self.read_only(cx) {
6799 return;
6800 }
6801 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6802 for selection in self.selections.all::<Point>(cx) {
6803 let start = MultiBufferRow(selection.start.row);
6804 // Treat single line selections as if they include the next line. Otherwise this action
6805 // would do nothing for single line selections individual cursors.
6806 let end = if selection.start.row == selection.end.row {
6807 MultiBufferRow(selection.start.row + 1)
6808 } else {
6809 MultiBufferRow(selection.end.row)
6810 };
6811
6812 if let Some(last_row_range) = row_ranges.last_mut() {
6813 if start <= last_row_range.end {
6814 last_row_range.end = end;
6815 continue;
6816 }
6817 }
6818 row_ranges.push(start..end);
6819 }
6820
6821 let snapshot = self.buffer.read(cx).snapshot(cx);
6822 let mut cursor_positions = Vec::new();
6823 for row_range in &row_ranges {
6824 let anchor = snapshot.anchor_before(Point::new(
6825 row_range.end.previous_row().0,
6826 snapshot.line_len(row_range.end.previous_row()),
6827 ));
6828 cursor_positions.push(anchor..anchor);
6829 }
6830
6831 self.transact(window, cx, |this, window, cx| {
6832 for row_range in row_ranges.into_iter().rev() {
6833 for row in row_range.iter_rows().rev() {
6834 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6835 let next_line_row = row.next_row();
6836 let indent = snapshot.indent_size_for_line(next_line_row);
6837 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6838
6839 let replace =
6840 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6841 " "
6842 } else {
6843 ""
6844 };
6845
6846 this.buffer.update(cx, |buffer, cx| {
6847 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6848 });
6849 }
6850 }
6851
6852 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6853 s.select_anchor_ranges(cursor_positions)
6854 });
6855 });
6856 }
6857
6858 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6859 self.join_lines_impl(true, window, cx);
6860 }
6861
6862 pub fn sort_lines_case_sensitive(
6863 &mut self,
6864 _: &SortLinesCaseSensitive,
6865 window: &mut Window,
6866 cx: &mut Context<Self>,
6867 ) {
6868 self.manipulate_lines(window, cx, |lines| lines.sort())
6869 }
6870
6871 pub fn sort_lines_case_insensitive(
6872 &mut self,
6873 _: &SortLinesCaseInsensitive,
6874 window: &mut Window,
6875 cx: &mut Context<Self>,
6876 ) {
6877 self.manipulate_lines(window, cx, |lines| {
6878 lines.sort_by_key(|line| line.to_lowercase())
6879 })
6880 }
6881
6882 pub fn unique_lines_case_insensitive(
6883 &mut self,
6884 _: &UniqueLinesCaseInsensitive,
6885 window: &mut Window,
6886 cx: &mut Context<Self>,
6887 ) {
6888 self.manipulate_lines(window, cx, |lines| {
6889 let mut seen = HashSet::default();
6890 lines.retain(|line| seen.insert(line.to_lowercase()));
6891 })
6892 }
6893
6894 pub fn unique_lines_case_sensitive(
6895 &mut self,
6896 _: &UniqueLinesCaseSensitive,
6897 window: &mut Window,
6898 cx: &mut Context<Self>,
6899 ) {
6900 self.manipulate_lines(window, cx, |lines| {
6901 let mut seen = HashSet::default();
6902 lines.retain(|line| seen.insert(*line));
6903 })
6904 }
6905
6906 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6907 let mut revert_changes = HashMap::default();
6908 let snapshot = self.snapshot(window, cx);
6909 for hunk in snapshot
6910 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6911 {
6912 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6913 }
6914 if !revert_changes.is_empty() {
6915 self.transact(window, cx, |editor, window, cx| {
6916 editor.revert(revert_changes, window, cx);
6917 });
6918 }
6919 }
6920
6921 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6922 let Some(project) = self.project.clone() else {
6923 return;
6924 };
6925 self.reload(project, window, cx)
6926 .detach_and_notify_err(window, cx);
6927 }
6928
6929 pub fn revert_selected_hunks(
6930 &mut self,
6931 _: &RevertSelectedHunks,
6932 window: &mut Window,
6933 cx: &mut Context<Self>,
6934 ) {
6935 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6936 self.discard_hunks_in_ranges(selections, window, cx);
6937 }
6938
6939 fn discard_hunks_in_ranges(
6940 &mut self,
6941 ranges: impl Iterator<Item = Range<Point>>,
6942 window: &mut Window,
6943 cx: &mut Context<Editor>,
6944 ) {
6945 let mut revert_changes = HashMap::default();
6946 let snapshot = self.snapshot(window, cx);
6947 for hunk in &snapshot.hunks_for_ranges(ranges) {
6948 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6949 }
6950 if !revert_changes.is_empty() {
6951 self.transact(window, cx, |editor, window, cx| {
6952 editor.revert(revert_changes, window, cx);
6953 });
6954 }
6955 }
6956
6957 pub fn open_active_item_in_terminal(
6958 &mut self,
6959 _: &OpenInTerminal,
6960 window: &mut Window,
6961 cx: &mut Context<Self>,
6962 ) {
6963 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6964 let project_path = buffer.read(cx).project_path(cx)?;
6965 let project = self.project.as_ref()?.read(cx);
6966 let entry = project.entry_for_path(&project_path, cx)?;
6967 let parent = match &entry.canonical_path {
6968 Some(canonical_path) => canonical_path.to_path_buf(),
6969 None => project.absolute_path(&project_path, cx)?,
6970 }
6971 .parent()?
6972 .to_path_buf();
6973 Some(parent)
6974 }) {
6975 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6976 }
6977 }
6978
6979 pub fn prepare_revert_change(
6980 &self,
6981 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6982 hunk: &MultiBufferDiffHunk,
6983 cx: &mut App,
6984 ) -> Option<()> {
6985 let buffer = self.buffer.read(cx);
6986 let diff = buffer.diff_for(hunk.buffer_id)?;
6987 let buffer = buffer.buffer(hunk.buffer_id)?;
6988 let buffer = buffer.read(cx);
6989 let original_text = diff
6990 .read(cx)
6991 .base_text()
6992 .as_ref()?
6993 .as_rope()
6994 .slice(hunk.diff_base_byte_range.clone());
6995 let buffer_snapshot = buffer.snapshot();
6996 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6997 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6998 probe
6999 .0
7000 .start
7001 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7002 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7003 }) {
7004 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7005 Some(())
7006 } else {
7007 None
7008 }
7009 }
7010
7011 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7012 self.manipulate_lines(window, cx, |lines| lines.reverse())
7013 }
7014
7015 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7016 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7017 }
7018
7019 fn manipulate_lines<Fn>(
7020 &mut self,
7021 window: &mut Window,
7022 cx: &mut Context<Self>,
7023 mut callback: Fn,
7024 ) where
7025 Fn: FnMut(&mut Vec<&str>),
7026 {
7027 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7028 let buffer = self.buffer.read(cx).snapshot(cx);
7029
7030 let mut edits = Vec::new();
7031
7032 let selections = self.selections.all::<Point>(cx);
7033 let mut selections = selections.iter().peekable();
7034 let mut contiguous_row_selections = Vec::new();
7035 let mut new_selections = Vec::new();
7036 let mut added_lines = 0;
7037 let mut removed_lines = 0;
7038
7039 while let Some(selection) = selections.next() {
7040 let (start_row, end_row) = consume_contiguous_rows(
7041 &mut contiguous_row_selections,
7042 selection,
7043 &display_map,
7044 &mut selections,
7045 );
7046
7047 let start_point = Point::new(start_row.0, 0);
7048 let end_point = Point::new(
7049 end_row.previous_row().0,
7050 buffer.line_len(end_row.previous_row()),
7051 );
7052 let text = buffer
7053 .text_for_range(start_point..end_point)
7054 .collect::<String>();
7055
7056 let mut lines = text.split('\n').collect_vec();
7057
7058 let lines_before = lines.len();
7059 callback(&mut lines);
7060 let lines_after = lines.len();
7061
7062 edits.push((start_point..end_point, lines.join("\n")));
7063
7064 // Selections must change based on added and removed line count
7065 let start_row =
7066 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7067 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7068 new_selections.push(Selection {
7069 id: selection.id,
7070 start: start_row,
7071 end: end_row,
7072 goal: SelectionGoal::None,
7073 reversed: selection.reversed,
7074 });
7075
7076 if lines_after > lines_before {
7077 added_lines += lines_after - lines_before;
7078 } else if lines_before > lines_after {
7079 removed_lines += lines_before - lines_after;
7080 }
7081 }
7082
7083 self.transact(window, cx, |this, window, cx| {
7084 let buffer = this.buffer.update(cx, |buffer, cx| {
7085 buffer.edit(edits, None, cx);
7086 buffer.snapshot(cx)
7087 });
7088
7089 // Recalculate offsets on newly edited buffer
7090 let new_selections = new_selections
7091 .iter()
7092 .map(|s| {
7093 let start_point = Point::new(s.start.0, 0);
7094 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7095 Selection {
7096 id: s.id,
7097 start: buffer.point_to_offset(start_point),
7098 end: buffer.point_to_offset(end_point),
7099 goal: s.goal,
7100 reversed: s.reversed,
7101 }
7102 })
7103 .collect();
7104
7105 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7106 s.select(new_selections);
7107 });
7108
7109 this.request_autoscroll(Autoscroll::fit(), cx);
7110 });
7111 }
7112
7113 pub fn convert_to_upper_case(
7114 &mut self,
7115 _: &ConvertToUpperCase,
7116 window: &mut Window,
7117 cx: &mut Context<Self>,
7118 ) {
7119 self.manipulate_text(window, cx, |text| text.to_uppercase())
7120 }
7121
7122 pub fn convert_to_lower_case(
7123 &mut self,
7124 _: &ConvertToLowerCase,
7125 window: &mut Window,
7126 cx: &mut Context<Self>,
7127 ) {
7128 self.manipulate_text(window, cx, |text| text.to_lowercase())
7129 }
7130
7131 pub fn convert_to_title_case(
7132 &mut self,
7133 _: &ConvertToTitleCase,
7134 window: &mut Window,
7135 cx: &mut Context<Self>,
7136 ) {
7137 self.manipulate_text(window, cx, |text| {
7138 text.split('\n')
7139 .map(|line| line.to_case(Case::Title))
7140 .join("\n")
7141 })
7142 }
7143
7144 pub fn convert_to_snake_case(
7145 &mut self,
7146 _: &ConvertToSnakeCase,
7147 window: &mut Window,
7148 cx: &mut Context<Self>,
7149 ) {
7150 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7151 }
7152
7153 pub fn convert_to_kebab_case(
7154 &mut self,
7155 _: &ConvertToKebabCase,
7156 window: &mut Window,
7157 cx: &mut Context<Self>,
7158 ) {
7159 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7160 }
7161
7162 pub fn convert_to_upper_camel_case(
7163 &mut self,
7164 _: &ConvertToUpperCamelCase,
7165 window: &mut Window,
7166 cx: &mut Context<Self>,
7167 ) {
7168 self.manipulate_text(window, cx, |text| {
7169 text.split('\n')
7170 .map(|line| line.to_case(Case::UpperCamel))
7171 .join("\n")
7172 })
7173 }
7174
7175 pub fn convert_to_lower_camel_case(
7176 &mut self,
7177 _: &ConvertToLowerCamelCase,
7178 window: &mut Window,
7179 cx: &mut Context<Self>,
7180 ) {
7181 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7182 }
7183
7184 pub fn convert_to_opposite_case(
7185 &mut self,
7186 _: &ConvertToOppositeCase,
7187 window: &mut Window,
7188 cx: &mut Context<Self>,
7189 ) {
7190 self.manipulate_text(window, cx, |text| {
7191 text.chars()
7192 .fold(String::with_capacity(text.len()), |mut t, c| {
7193 if c.is_uppercase() {
7194 t.extend(c.to_lowercase());
7195 } else {
7196 t.extend(c.to_uppercase());
7197 }
7198 t
7199 })
7200 })
7201 }
7202
7203 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7204 where
7205 Fn: FnMut(&str) -> String,
7206 {
7207 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7208 let buffer = self.buffer.read(cx).snapshot(cx);
7209
7210 let mut new_selections = Vec::new();
7211 let mut edits = Vec::new();
7212 let mut selection_adjustment = 0i32;
7213
7214 for selection in self.selections.all::<usize>(cx) {
7215 let selection_is_empty = selection.is_empty();
7216
7217 let (start, end) = if selection_is_empty {
7218 let word_range = movement::surrounding_word(
7219 &display_map,
7220 selection.start.to_display_point(&display_map),
7221 );
7222 let start = word_range.start.to_offset(&display_map, Bias::Left);
7223 let end = word_range.end.to_offset(&display_map, Bias::Left);
7224 (start, end)
7225 } else {
7226 (selection.start, selection.end)
7227 };
7228
7229 let text = buffer.text_for_range(start..end).collect::<String>();
7230 let old_length = text.len() as i32;
7231 let text = callback(&text);
7232
7233 new_selections.push(Selection {
7234 start: (start as i32 - selection_adjustment) as usize,
7235 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7236 goal: SelectionGoal::None,
7237 ..selection
7238 });
7239
7240 selection_adjustment += old_length - text.len() as i32;
7241
7242 edits.push((start..end, text));
7243 }
7244
7245 self.transact(window, cx, |this, window, cx| {
7246 this.buffer.update(cx, |buffer, cx| {
7247 buffer.edit(edits, None, cx);
7248 });
7249
7250 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7251 s.select(new_selections);
7252 });
7253
7254 this.request_autoscroll(Autoscroll::fit(), cx);
7255 });
7256 }
7257
7258 pub fn duplicate(
7259 &mut self,
7260 upwards: bool,
7261 whole_lines: bool,
7262 window: &mut Window,
7263 cx: &mut Context<Self>,
7264 ) {
7265 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7266 let buffer = &display_map.buffer_snapshot;
7267 let selections = self.selections.all::<Point>(cx);
7268
7269 let mut edits = Vec::new();
7270 let mut selections_iter = selections.iter().peekable();
7271 while let Some(selection) = selections_iter.next() {
7272 let mut rows = selection.spanned_rows(false, &display_map);
7273 // duplicate line-wise
7274 if whole_lines || selection.start == selection.end {
7275 // Avoid duplicating the same lines twice.
7276 while let Some(next_selection) = selections_iter.peek() {
7277 let next_rows = next_selection.spanned_rows(false, &display_map);
7278 if next_rows.start < rows.end {
7279 rows.end = next_rows.end;
7280 selections_iter.next().unwrap();
7281 } else {
7282 break;
7283 }
7284 }
7285
7286 // Copy the text from the selected row region and splice it either at the start
7287 // or end of the region.
7288 let start = Point::new(rows.start.0, 0);
7289 let end = Point::new(
7290 rows.end.previous_row().0,
7291 buffer.line_len(rows.end.previous_row()),
7292 );
7293 let text = buffer
7294 .text_for_range(start..end)
7295 .chain(Some("\n"))
7296 .collect::<String>();
7297 let insert_location = if upwards {
7298 Point::new(rows.end.0, 0)
7299 } else {
7300 start
7301 };
7302 edits.push((insert_location..insert_location, text));
7303 } else {
7304 // duplicate character-wise
7305 let start = selection.start;
7306 let end = selection.end;
7307 let text = buffer.text_for_range(start..end).collect::<String>();
7308 edits.push((selection.end..selection.end, text));
7309 }
7310 }
7311
7312 self.transact(window, cx, |this, _, cx| {
7313 this.buffer.update(cx, |buffer, cx| {
7314 buffer.edit(edits, None, cx);
7315 });
7316
7317 this.request_autoscroll(Autoscroll::fit(), cx);
7318 });
7319 }
7320
7321 pub fn duplicate_line_up(
7322 &mut self,
7323 _: &DuplicateLineUp,
7324 window: &mut Window,
7325 cx: &mut Context<Self>,
7326 ) {
7327 self.duplicate(true, true, window, cx);
7328 }
7329
7330 pub fn duplicate_line_down(
7331 &mut self,
7332 _: &DuplicateLineDown,
7333 window: &mut Window,
7334 cx: &mut Context<Self>,
7335 ) {
7336 self.duplicate(false, true, window, cx);
7337 }
7338
7339 pub fn duplicate_selection(
7340 &mut self,
7341 _: &DuplicateSelection,
7342 window: &mut Window,
7343 cx: &mut Context<Self>,
7344 ) {
7345 self.duplicate(false, false, window, cx);
7346 }
7347
7348 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7350 let buffer = self.buffer.read(cx).snapshot(cx);
7351
7352 let mut edits = Vec::new();
7353 let mut unfold_ranges = Vec::new();
7354 let mut refold_creases = Vec::new();
7355
7356 let selections = self.selections.all::<Point>(cx);
7357 let mut selections = selections.iter().peekable();
7358 let mut contiguous_row_selections = Vec::new();
7359 let mut new_selections = Vec::new();
7360
7361 while let Some(selection) = selections.next() {
7362 // Find all the selections that span a contiguous row range
7363 let (start_row, end_row) = consume_contiguous_rows(
7364 &mut contiguous_row_selections,
7365 selection,
7366 &display_map,
7367 &mut selections,
7368 );
7369
7370 // Move the text spanned by the row range to be before the line preceding the row range
7371 if start_row.0 > 0 {
7372 let range_to_move = Point::new(
7373 start_row.previous_row().0,
7374 buffer.line_len(start_row.previous_row()),
7375 )
7376 ..Point::new(
7377 end_row.previous_row().0,
7378 buffer.line_len(end_row.previous_row()),
7379 );
7380 let insertion_point = display_map
7381 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7382 .0;
7383
7384 // Don't move lines across excerpts
7385 if buffer
7386 .excerpt_containing(insertion_point..range_to_move.end)
7387 .is_some()
7388 {
7389 let text = buffer
7390 .text_for_range(range_to_move.clone())
7391 .flat_map(|s| s.chars())
7392 .skip(1)
7393 .chain(['\n'])
7394 .collect::<String>();
7395
7396 edits.push((
7397 buffer.anchor_after(range_to_move.start)
7398 ..buffer.anchor_before(range_to_move.end),
7399 String::new(),
7400 ));
7401 let insertion_anchor = buffer.anchor_after(insertion_point);
7402 edits.push((insertion_anchor..insertion_anchor, text));
7403
7404 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7405
7406 // Move selections up
7407 new_selections.extend(contiguous_row_selections.drain(..).map(
7408 |mut selection| {
7409 selection.start.row -= row_delta;
7410 selection.end.row -= row_delta;
7411 selection
7412 },
7413 ));
7414
7415 // Move folds up
7416 unfold_ranges.push(range_to_move.clone());
7417 for fold in display_map.folds_in_range(
7418 buffer.anchor_before(range_to_move.start)
7419 ..buffer.anchor_after(range_to_move.end),
7420 ) {
7421 let mut start = fold.range.start.to_point(&buffer);
7422 let mut end = fold.range.end.to_point(&buffer);
7423 start.row -= row_delta;
7424 end.row -= row_delta;
7425 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7426 }
7427 }
7428 }
7429
7430 // If we didn't move line(s), preserve the existing selections
7431 new_selections.append(&mut contiguous_row_selections);
7432 }
7433
7434 self.transact(window, cx, |this, window, cx| {
7435 this.unfold_ranges(&unfold_ranges, true, true, cx);
7436 this.buffer.update(cx, |buffer, cx| {
7437 for (range, text) in edits {
7438 buffer.edit([(range, text)], None, cx);
7439 }
7440 });
7441 this.fold_creases(refold_creases, true, window, cx);
7442 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7443 s.select(new_selections);
7444 })
7445 });
7446 }
7447
7448 pub fn move_line_down(
7449 &mut self,
7450 _: &MoveLineDown,
7451 window: &mut Window,
7452 cx: &mut Context<Self>,
7453 ) {
7454 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7455 let buffer = self.buffer.read(cx).snapshot(cx);
7456
7457 let mut edits = Vec::new();
7458 let mut unfold_ranges = Vec::new();
7459 let mut refold_creases = Vec::new();
7460
7461 let selections = self.selections.all::<Point>(cx);
7462 let mut selections = selections.iter().peekable();
7463 let mut contiguous_row_selections = Vec::new();
7464 let mut new_selections = Vec::new();
7465
7466 while let Some(selection) = selections.next() {
7467 // Find all the selections that span a contiguous row range
7468 let (start_row, end_row) = consume_contiguous_rows(
7469 &mut contiguous_row_selections,
7470 selection,
7471 &display_map,
7472 &mut selections,
7473 );
7474
7475 // Move the text spanned by the row range to be after the last line of the row range
7476 if end_row.0 <= buffer.max_point().row {
7477 let range_to_move =
7478 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7479 let insertion_point = display_map
7480 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7481 .0;
7482
7483 // Don't move lines across excerpt boundaries
7484 if buffer
7485 .excerpt_containing(range_to_move.start..insertion_point)
7486 .is_some()
7487 {
7488 let mut text = String::from("\n");
7489 text.extend(buffer.text_for_range(range_to_move.clone()));
7490 text.pop(); // Drop trailing newline
7491 edits.push((
7492 buffer.anchor_after(range_to_move.start)
7493 ..buffer.anchor_before(range_to_move.end),
7494 String::new(),
7495 ));
7496 let insertion_anchor = buffer.anchor_after(insertion_point);
7497 edits.push((insertion_anchor..insertion_anchor, text));
7498
7499 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7500
7501 // Move selections down
7502 new_selections.extend(contiguous_row_selections.drain(..).map(
7503 |mut selection| {
7504 selection.start.row += row_delta;
7505 selection.end.row += row_delta;
7506 selection
7507 },
7508 ));
7509
7510 // Move folds down
7511 unfold_ranges.push(range_to_move.clone());
7512 for fold in display_map.folds_in_range(
7513 buffer.anchor_before(range_to_move.start)
7514 ..buffer.anchor_after(range_to_move.end),
7515 ) {
7516 let mut start = fold.range.start.to_point(&buffer);
7517 let mut end = fold.range.end.to_point(&buffer);
7518 start.row += row_delta;
7519 end.row += row_delta;
7520 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7521 }
7522 }
7523 }
7524
7525 // If we didn't move line(s), preserve the existing selections
7526 new_selections.append(&mut contiguous_row_selections);
7527 }
7528
7529 self.transact(window, cx, |this, window, cx| {
7530 this.unfold_ranges(&unfold_ranges, true, true, cx);
7531 this.buffer.update(cx, |buffer, cx| {
7532 for (range, text) in edits {
7533 buffer.edit([(range, text)], None, cx);
7534 }
7535 });
7536 this.fold_creases(refold_creases, true, window, cx);
7537 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7538 s.select(new_selections)
7539 });
7540 });
7541 }
7542
7543 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7544 let text_layout_details = &self.text_layout_details(window);
7545 self.transact(window, cx, |this, window, cx| {
7546 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7547 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7548 let line_mode = s.line_mode;
7549 s.move_with(|display_map, selection| {
7550 if !selection.is_empty() || line_mode {
7551 return;
7552 }
7553
7554 let mut head = selection.head();
7555 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7556 if head.column() == display_map.line_len(head.row()) {
7557 transpose_offset = display_map
7558 .buffer_snapshot
7559 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7560 }
7561
7562 if transpose_offset == 0 {
7563 return;
7564 }
7565
7566 *head.column_mut() += 1;
7567 head = display_map.clip_point(head, Bias::Right);
7568 let goal = SelectionGoal::HorizontalPosition(
7569 display_map
7570 .x_for_display_point(head, text_layout_details)
7571 .into(),
7572 );
7573 selection.collapse_to(head, goal);
7574
7575 let transpose_start = display_map
7576 .buffer_snapshot
7577 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7578 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7579 let transpose_end = display_map
7580 .buffer_snapshot
7581 .clip_offset(transpose_offset + 1, Bias::Right);
7582 if let Some(ch) =
7583 display_map.buffer_snapshot.chars_at(transpose_start).next()
7584 {
7585 edits.push((transpose_start..transpose_offset, String::new()));
7586 edits.push((transpose_end..transpose_end, ch.to_string()));
7587 }
7588 }
7589 });
7590 edits
7591 });
7592 this.buffer
7593 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7594 let selections = this.selections.all::<usize>(cx);
7595 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7596 s.select(selections);
7597 });
7598 });
7599 }
7600
7601 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7602 self.rewrap_impl(IsVimMode::No, cx)
7603 }
7604
7605 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7606 let buffer = self.buffer.read(cx).snapshot(cx);
7607 let selections = self.selections.all::<Point>(cx);
7608 let mut selections = selections.iter().peekable();
7609
7610 let mut edits = Vec::new();
7611 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7612
7613 while let Some(selection) = selections.next() {
7614 let mut start_row = selection.start.row;
7615 let mut end_row = selection.end.row;
7616
7617 // Skip selections that overlap with a range that has already been rewrapped.
7618 let selection_range = start_row..end_row;
7619 if rewrapped_row_ranges
7620 .iter()
7621 .any(|range| range.overlaps(&selection_range))
7622 {
7623 continue;
7624 }
7625
7626 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7627
7628 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7629 match language_scope.language_name().as_ref() {
7630 "Markdown" | "Plain Text" => {
7631 should_rewrap = true;
7632 }
7633 _ => {}
7634 }
7635 }
7636
7637 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7638
7639 // Since not all lines in the selection may be at the same indent
7640 // level, choose the indent size that is the most common between all
7641 // of the lines.
7642 //
7643 // If there is a tie, we use the deepest indent.
7644 let (indent_size, indent_end) = {
7645 let mut indent_size_occurrences = HashMap::default();
7646 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7647
7648 for row in start_row..=end_row {
7649 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7650 rows_by_indent_size.entry(indent).or_default().push(row);
7651 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7652 }
7653
7654 let indent_size = indent_size_occurrences
7655 .into_iter()
7656 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7657 .map(|(indent, _)| indent)
7658 .unwrap_or_default();
7659 let row = rows_by_indent_size[&indent_size][0];
7660 let indent_end = Point::new(row, indent_size.len);
7661
7662 (indent_size, indent_end)
7663 };
7664
7665 let mut line_prefix = indent_size.chars().collect::<String>();
7666
7667 if let Some(comment_prefix) =
7668 buffer
7669 .language_scope_at(selection.head())
7670 .and_then(|language| {
7671 language
7672 .line_comment_prefixes()
7673 .iter()
7674 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7675 .cloned()
7676 })
7677 {
7678 line_prefix.push_str(&comment_prefix);
7679 should_rewrap = true;
7680 }
7681
7682 if !should_rewrap {
7683 continue;
7684 }
7685
7686 if selection.is_empty() {
7687 'expand_upwards: while start_row > 0 {
7688 let prev_row = start_row - 1;
7689 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7690 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7691 {
7692 start_row = prev_row;
7693 } else {
7694 break 'expand_upwards;
7695 }
7696 }
7697
7698 'expand_downwards: while end_row < buffer.max_point().row {
7699 let next_row = end_row + 1;
7700 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7701 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7702 {
7703 end_row = next_row;
7704 } else {
7705 break 'expand_downwards;
7706 }
7707 }
7708 }
7709
7710 let start = Point::new(start_row, 0);
7711 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7712 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7713 let Some(lines_without_prefixes) = selection_text
7714 .lines()
7715 .map(|line| {
7716 line.strip_prefix(&line_prefix)
7717 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7718 .ok_or_else(|| {
7719 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7720 })
7721 })
7722 .collect::<Result<Vec<_>, _>>()
7723 .log_err()
7724 else {
7725 continue;
7726 };
7727
7728 let wrap_column = buffer
7729 .settings_at(Point::new(start_row, 0), cx)
7730 .preferred_line_length as usize;
7731 let wrapped_text = wrap_with_prefix(
7732 line_prefix,
7733 lines_without_prefixes.join(" "),
7734 wrap_column,
7735 tab_size,
7736 );
7737
7738 // TODO: should always use char-based diff while still supporting cursor behavior that
7739 // matches vim.
7740 let diff = match is_vim_mode {
7741 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7742 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7743 };
7744 let mut offset = start.to_offset(&buffer);
7745 let mut moved_since_edit = true;
7746
7747 for change in diff.iter_all_changes() {
7748 let value = change.value();
7749 match change.tag() {
7750 ChangeTag::Equal => {
7751 offset += value.len();
7752 moved_since_edit = true;
7753 }
7754 ChangeTag::Delete => {
7755 let start = buffer.anchor_after(offset);
7756 let end = buffer.anchor_before(offset + value.len());
7757
7758 if moved_since_edit {
7759 edits.push((start..end, String::new()));
7760 } else {
7761 edits.last_mut().unwrap().0.end = end;
7762 }
7763
7764 offset += value.len();
7765 moved_since_edit = false;
7766 }
7767 ChangeTag::Insert => {
7768 if moved_since_edit {
7769 let anchor = buffer.anchor_after(offset);
7770 edits.push((anchor..anchor, value.to_string()));
7771 } else {
7772 edits.last_mut().unwrap().1.push_str(value);
7773 }
7774
7775 moved_since_edit = false;
7776 }
7777 }
7778 }
7779
7780 rewrapped_row_ranges.push(start_row..=end_row);
7781 }
7782
7783 self.buffer
7784 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7785 }
7786
7787 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7788 let mut text = String::new();
7789 let buffer = self.buffer.read(cx).snapshot(cx);
7790 let mut selections = self.selections.all::<Point>(cx);
7791 let mut clipboard_selections = Vec::with_capacity(selections.len());
7792 {
7793 let max_point = buffer.max_point();
7794 let mut is_first = true;
7795 for selection in &mut selections {
7796 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7797 if is_entire_line {
7798 selection.start = Point::new(selection.start.row, 0);
7799 if !selection.is_empty() && selection.end.column == 0 {
7800 selection.end = cmp::min(max_point, selection.end);
7801 } else {
7802 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7803 }
7804 selection.goal = SelectionGoal::None;
7805 }
7806 if is_first {
7807 is_first = false;
7808 } else {
7809 text += "\n";
7810 }
7811 let mut len = 0;
7812 for chunk in buffer.text_for_range(selection.start..selection.end) {
7813 text.push_str(chunk);
7814 len += chunk.len();
7815 }
7816 clipboard_selections.push(ClipboardSelection {
7817 len,
7818 is_entire_line,
7819 first_line_indent: buffer
7820 .indent_size_for_line(MultiBufferRow(selection.start.row))
7821 .len,
7822 });
7823 }
7824 }
7825
7826 self.transact(window, cx, |this, window, cx| {
7827 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7828 s.select(selections);
7829 });
7830 this.insert("", window, cx);
7831 });
7832 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7833 }
7834
7835 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7836 let item = self.cut_common(window, cx);
7837 cx.write_to_clipboard(item);
7838 }
7839
7840 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7841 self.change_selections(None, window, cx, |s| {
7842 s.move_with(|snapshot, sel| {
7843 if sel.is_empty() {
7844 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7845 }
7846 });
7847 });
7848 let item = self.cut_common(window, cx);
7849 cx.set_global(KillRing(item))
7850 }
7851
7852 pub fn kill_ring_yank(
7853 &mut self,
7854 _: &KillRingYank,
7855 window: &mut Window,
7856 cx: &mut Context<Self>,
7857 ) {
7858 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7859 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7860 (kill_ring.text().to_string(), kill_ring.metadata_json())
7861 } else {
7862 return;
7863 }
7864 } else {
7865 return;
7866 };
7867 self.do_paste(&text, metadata, false, window, cx);
7868 }
7869
7870 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7871 let selections = self.selections.all::<Point>(cx);
7872 let buffer = self.buffer.read(cx).read(cx);
7873 let mut text = String::new();
7874
7875 let mut clipboard_selections = Vec::with_capacity(selections.len());
7876 {
7877 let max_point = buffer.max_point();
7878 let mut is_first = true;
7879 for selection in selections.iter() {
7880 let mut start = selection.start;
7881 let mut end = selection.end;
7882 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7883 if is_entire_line {
7884 start = Point::new(start.row, 0);
7885 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7886 }
7887 if is_first {
7888 is_first = false;
7889 } else {
7890 text += "\n";
7891 }
7892 let mut len = 0;
7893 for chunk in buffer.text_for_range(start..end) {
7894 text.push_str(chunk);
7895 len += chunk.len();
7896 }
7897 clipboard_selections.push(ClipboardSelection {
7898 len,
7899 is_entire_line,
7900 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7901 });
7902 }
7903 }
7904
7905 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7906 text,
7907 clipboard_selections,
7908 ));
7909 }
7910
7911 pub fn do_paste(
7912 &mut self,
7913 text: &String,
7914 clipboard_selections: Option<Vec<ClipboardSelection>>,
7915 handle_entire_lines: bool,
7916 window: &mut Window,
7917 cx: &mut Context<Self>,
7918 ) {
7919 if self.read_only(cx) {
7920 return;
7921 }
7922
7923 let clipboard_text = Cow::Borrowed(text);
7924
7925 self.transact(window, cx, |this, window, cx| {
7926 if let Some(mut clipboard_selections) = clipboard_selections {
7927 let old_selections = this.selections.all::<usize>(cx);
7928 let all_selections_were_entire_line =
7929 clipboard_selections.iter().all(|s| s.is_entire_line);
7930 let first_selection_indent_column =
7931 clipboard_selections.first().map(|s| s.first_line_indent);
7932 if clipboard_selections.len() != old_selections.len() {
7933 clipboard_selections.drain(..);
7934 }
7935 let cursor_offset = this.selections.last::<usize>(cx).head();
7936 let mut auto_indent_on_paste = true;
7937
7938 this.buffer.update(cx, |buffer, cx| {
7939 let snapshot = buffer.read(cx);
7940 auto_indent_on_paste =
7941 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7942
7943 let mut start_offset = 0;
7944 let mut edits = Vec::new();
7945 let mut original_indent_columns = Vec::new();
7946 for (ix, selection) in old_selections.iter().enumerate() {
7947 let to_insert;
7948 let entire_line;
7949 let original_indent_column;
7950 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7951 let end_offset = start_offset + clipboard_selection.len;
7952 to_insert = &clipboard_text[start_offset..end_offset];
7953 entire_line = clipboard_selection.is_entire_line;
7954 start_offset = end_offset + 1;
7955 original_indent_column = Some(clipboard_selection.first_line_indent);
7956 } else {
7957 to_insert = clipboard_text.as_str();
7958 entire_line = all_selections_were_entire_line;
7959 original_indent_column = first_selection_indent_column
7960 }
7961
7962 // If the corresponding selection was empty when this slice of the
7963 // clipboard text was written, then the entire line containing the
7964 // selection was copied. If this selection is also currently empty,
7965 // then paste the line before the current line of the buffer.
7966 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7967 let column = selection.start.to_point(&snapshot).column as usize;
7968 let line_start = selection.start - column;
7969 line_start..line_start
7970 } else {
7971 selection.range()
7972 };
7973
7974 edits.push((range, to_insert));
7975 original_indent_columns.extend(original_indent_column);
7976 }
7977 drop(snapshot);
7978
7979 buffer.edit(
7980 edits,
7981 if auto_indent_on_paste {
7982 Some(AutoindentMode::Block {
7983 original_indent_columns,
7984 })
7985 } else {
7986 None
7987 },
7988 cx,
7989 );
7990 });
7991
7992 let selections = this.selections.all::<usize>(cx);
7993 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7994 s.select(selections)
7995 });
7996 } else {
7997 this.insert(&clipboard_text, window, cx);
7998 }
7999 });
8000 }
8001
8002 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8003 if let Some(item) = cx.read_from_clipboard() {
8004 let entries = item.entries();
8005
8006 match entries.first() {
8007 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8008 // of all the pasted entries.
8009 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8010 .do_paste(
8011 clipboard_string.text(),
8012 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8013 true,
8014 window,
8015 cx,
8016 ),
8017 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8018 }
8019 }
8020 }
8021
8022 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8023 if self.read_only(cx) {
8024 return;
8025 }
8026
8027 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8028 if let Some((selections, _)) =
8029 self.selection_history.transaction(transaction_id).cloned()
8030 {
8031 self.change_selections(None, window, cx, |s| {
8032 s.select_anchors(selections.to_vec());
8033 });
8034 }
8035 self.request_autoscroll(Autoscroll::fit(), cx);
8036 self.unmark_text(window, cx);
8037 self.refresh_inline_completion(true, false, window, cx);
8038 cx.emit(EditorEvent::Edited { transaction_id });
8039 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8040 }
8041 }
8042
8043 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8044 if self.read_only(cx) {
8045 return;
8046 }
8047
8048 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8049 if let Some((_, Some(selections))) =
8050 self.selection_history.transaction(transaction_id).cloned()
8051 {
8052 self.change_selections(None, window, cx, |s| {
8053 s.select_anchors(selections.to_vec());
8054 });
8055 }
8056 self.request_autoscroll(Autoscroll::fit(), cx);
8057 self.unmark_text(window, cx);
8058 self.refresh_inline_completion(true, false, window, cx);
8059 cx.emit(EditorEvent::Edited { transaction_id });
8060 }
8061 }
8062
8063 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8064 self.buffer
8065 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8066 }
8067
8068 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8069 self.buffer
8070 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8071 }
8072
8073 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8074 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8075 let line_mode = s.line_mode;
8076 s.move_with(|map, selection| {
8077 let cursor = if selection.is_empty() && !line_mode {
8078 movement::left(map, selection.start)
8079 } else {
8080 selection.start
8081 };
8082 selection.collapse_to(cursor, SelectionGoal::None);
8083 });
8084 })
8085 }
8086
8087 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8088 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8089 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8090 })
8091 }
8092
8093 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8094 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8095 let line_mode = s.line_mode;
8096 s.move_with(|map, selection| {
8097 let cursor = if selection.is_empty() && !line_mode {
8098 movement::right(map, selection.end)
8099 } else {
8100 selection.end
8101 };
8102 selection.collapse_to(cursor, SelectionGoal::None)
8103 });
8104 })
8105 }
8106
8107 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8108 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8109 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8110 })
8111 }
8112
8113 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8114 if self.take_rename(true, window, cx).is_some() {
8115 return;
8116 }
8117
8118 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8119 cx.propagate();
8120 return;
8121 }
8122
8123 let text_layout_details = &self.text_layout_details(window);
8124 let selection_count = self.selections.count();
8125 let first_selection = self.selections.first_anchor();
8126
8127 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8128 let line_mode = s.line_mode;
8129 s.move_with(|map, selection| {
8130 if !selection.is_empty() && !line_mode {
8131 selection.goal = SelectionGoal::None;
8132 }
8133 let (cursor, goal) = movement::up(
8134 map,
8135 selection.start,
8136 selection.goal,
8137 false,
8138 text_layout_details,
8139 );
8140 selection.collapse_to(cursor, goal);
8141 });
8142 });
8143
8144 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8145 {
8146 cx.propagate();
8147 }
8148 }
8149
8150 pub fn move_up_by_lines(
8151 &mut self,
8152 action: &MoveUpByLines,
8153 window: &mut Window,
8154 cx: &mut Context<Self>,
8155 ) {
8156 if self.take_rename(true, window, cx).is_some() {
8157 return;
8158 }
8159
8160 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8161 cx.propagate();
8162 return;
8163 }
8164
8165 let text_layout_details = &self.text_layout_details(window);
8166
8167 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8168 let line_mode = s.line_mode;
8169 s.move_with(|map, selection| {
8170 if !selection.is_empty() && !line_mode {
8171 selection.goal = SelectionGoal::None;
8172 }
8173 let (cursor, goal) = movement::up_by_rows(
8174 map,
8175 selection.start,
8176 action.lines,
8177 selection.goal,
8178 false,
8179 text_layout_details,
8180 );
8181 selection.collapse_to(cursor, goal);
8182 });
8183 })
8184 }
8185
8186 pub fn move_down_by_lines(
8187 &mut self,
8188 action: &MoveDownByLines,
8189 window: &mut Window,
8190 cx: &mut Context<Self>,
8191 ) {
8192 if self.take_rename(true, window, cx).is_some() {
8193 return;
8194 }
8195
8196 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8197 cx.propagate();
8198 return;
8199 }
8200
8201 let text_layout_details = &self.text_layout_details(window);
8202
8203 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8204 let line_mode = s.line_mode;
8205 s.move_with(|map, selection| {
8206 if !selection.is_empty() && !line_mode {
8207 selection.goal = SelectionGoal::None;
8208 }
8209 let (cursor, goal) = movement::down_by_rows(
8210 map,
8211 selection.start,
8212 action.lines,
8213 selection.goal,
8214 false,
8215 text_layout_details,
8216 );
8217 selection.collapse_to(cursor, goal);
8218 });
8219 })
8220 }
8221
8222 pub fn select_down_by_lines(
8223 &mut self,
8224 action: &SelectDownByLines,
8225 window: &mut Window,
8226 cx: &mut Context<Self>,
8227 ) {
8228 let text_layout_details = &self.text_layout_details(window);
8229 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8230 s.move_heads_with(|map, head, goal| {
8231 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8232 })
8233 })
8234 }
8235
8236 pub fn select_up_by_lines(
8237 &mut self,
8238 action: &SelectUpByLines,
8239 window: &mut Window,
8240 cx: &mut Context<Self>,
8241 ) {
8242 let text_layout_details = &self.text_layout_details(window);
8243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8244 s.move_heads_with(|map, head, goal| {
8245 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8246 })
8247 })
8248 }
8249
8250 pub fn select_page_up(
8251 &mut self,
8252 _: &SelectPageUp,
8253 window: &mut Window,
8254 cx: &mut Context<Self>,
8255 ) {
8256 let Some(row_count) = self.visible_row_count() else {
8257 return;
8258 };
8259
8260 let text_layout_details = &self.text_layout_details(window);
8261
8262 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8263 s.move_heads_with(|map, head, goal| {
8264 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8265 })
8266 })
8267 }
8268
8269 pub fn move_page_up(
8270 &mut self,
8271 action: &MovePageUp,
8272 window: &mut Window,
8273 cx: &mut Context<Self>,
8274 ) {
8275 if self.take_rename(true, window, cx).is_some() {
8276 return;
8277 }
8278
8279 if self
8280 .context_menu
8281 .borrow_mut()
8282 .as_mut()
8283 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8284 .unwrap_or(false)
8285 {
8286 return;
8287 }
8288
8289 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8290 cx.propagate();
8291 return;
8292 }
8293
8294 let Some(row_count) = self.visible_row_count() else {
8295 return;
8296 };
8297
8298 let autoscroll = if action.center_cursor {
8299 Autoscroll::center()
8300 } else {
8301 Autoscroll::fit()
8302 };
8303
8304 let text_layout_details = &self.text_layout_details(window);
8305
8306 self.change_selections(Some(autoscroll), window, cx, |s| {
8307 let line_mode = s.line_mode;
8308 s.move_with(|map, selection| {
8309 if !selection.is_empty() && !line_mode {
8310 selection.goal = SelectionGoal::None;
8311 }
8312 let (cursor, goal) = movement::up_by_rows(
8313 map,
8314 selection.end,
8315 row_count,
8316 selection.goal,
8317 false,
8318 text_layout_details,
8319 );
8320 selection.collapse_to(cursor, goal);
8321 });
8322 });
8323 }
8324
8325 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8326 let text_layout_details = &self.text_layout_details(window);
8327 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8328 s.move_heads_with(|map, head, goal| {
8329 movement::up(map, head, goal, false, text_layout_details)
8330 })
8331 })
8332 }
8333
8334 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8335 self.take_rename(true, window, cx);
8336
8337 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8338 cx.propagate();
8339 return;
8340 }
8341
8342 let text_layout_details = &self.text_layout_details(window);
8343 let selection_count = self.selections.count();
8344 let first_selection = self.selections.first_anchor();
8345
8346 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8347 let line_mode = s.line_mode;
8348 s.move_with(|map, selection| {
8349 if !selection.is_empty() && !line_mode {
8350 selection.goal = SelectionGoal::None;
8351 }
8352 let (cursor, goal) = movement::down(
8353 map,
8354 selection.end,
8355 selection.goal,
8356 false,
8357 text_layout_details,
8358 );
8359 selection.collapse_to(cursor, goal);
8360 });
8361 });
8362
8363 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8364 {
8365 cx.propagate();
8366 }
8367 }
8368
8369 pub fn select_page_down(
8370 &mut self,
8371 _: &SelectPageDown,
8372 window: &mut Window,
8373 cx: &mut Context<Self>,
8374 ) {
8375 let Some(row_count) = self.visible_row_count() else {
8376 return;
8377 };
8378
8379 let text_layout_details = &self.text_layout_details(window);
8380
8381 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8382 s.move_heads_with(|map, head, goal| {
8383 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8384 })
8385 })
8386 }
8387
8388 pub fn move_page_down(
8389 &mut self,
8390 action: &MovePageDown,
8391 window: &mut Window,
8392 cx: &mut Context<Self>,
8393 ) {
8394 if self.take_rename(true, window, cx).is_some() {
8395 return;
8396 }
8397
8398 if self
8399 .context_menu
8400 .borrow_mut()
8401 .as_mut()
8402 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8403 .unwrap_or(false)
8404 {
8405 return;
8406 }
8407
8408 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8409 cx.propagate();
8410 return;
8411 }
8412
8413 let Some(row_count) = self.visible_row_count() else {
8414 return;
8415 };
8416
8417 let autoscroll = if action.center_cursor {
8418 Autoscroll::center()
8419 } else {
8420 Autoscroll::fit()
8421 };
8422
8423 let text_layout_details = &self.text_layout_details(window);
8424 self.change_selections(Some(autoscroll), window, cx, |s| {
8425 let line_mode = s.line_mode;
8426 s.move_with(|map, selection| {
8427 if !selection.is_empty() && !line_mode {
8428 selection.goal = SelectionGoal::None;
8429 }
8430 let (cursor, goal) = movement::down_by_rows(
8431 map,
8432 selection.end,
8433 row_count,
8434 selection.goal,
8435 false,
8436 text_layout_details,
8437 );
8438 selection.collapse_to(cursor, goal);
8439 });
8440 });
8441 }
8442
8443 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8444 let text_layout_details = &self.text_layout_details(window);
8445 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8446 s.move_heads_with(|map, head, goal| {
8447 movement::down(map, head, goal, false, text_layout_details)
8448 })
8449 });
8450 }
8451
8452 pub fn context_menu_first(
8453 &mut self,
8454 _: &ContextMenuFirst,
8455 _window: &mut Window,
8456 cx: &mut Context<Self>,
8457 ) {
8458 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8459 context_menu.select_first(self.completion_provider.as_deref(), cx);
8460 }
8461 }
8462
8463 pub fn context_menu_prev(
8464 &mut self,
8465 _: &ContextMenuPrev,
8466 _window: &mut Window,
8467 cx: &mut Context<Self>,
8468 ) {
8469 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8470 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8471 }
8472 }
8473
8474 pub fn context_menu_next(
8475 &mut self,
8476 _: &ContextMenuNext,
8477 _window: &mut Window,
8478 cx: &mut Context<Self>,
8479 ) {
8480 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8481 context_menu.select_next(self.completion_provider.as_deref(), cx);
8482 }
8483 }
8484
8485 pub fn context_menu_last(
8486 &mut self,
8487 _: &ContextMenuLast,
8488 _window: &mut Window,
8489 cx: &mut Context<Self>,
8490 ) {
8491 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8492 context_menu.select_last(self.completion_provider.as_deref(), cx);
8493 }
8494 }
8495
8496 pub fn move_to_previous_word_start(
8497 &mut self,
8498 _: &MoveToPreviousWordStart,
8499 window: &mut Window,
8500 cx: &mut Context<Self>,
8501 ) {
8502 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8503 s.move_cursors_with(|map, head, _| {
8504 (
8505 movement::previous_word_start(map, head),
8506 SelectionGoal::None,
8507 )
8508 });
8509 })
8510 }
8511
8512 pub fn move_to_previous_subword_start(
8513 &mut self,
8514 _: &MoveToPreviousSubwordStart,
8515 window: &mut Window,
8516 cx: &mut Context<Self>,
8517 ) {
8518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8519 s.move_cursors_with(|map, head, _| {
8520 (
8521 movement::previous_subword_start(map, head),
8522 SelectionGoal::None,
8523 )
8524 });
8525 })
8526 }
8527
8528 pub fn select_to_previous_word_start(
8529 &mut self,
8530 _: &SelectToPreviousWordStart,
8531 window: &mut Window,
8532 cx: &mut Context<Self>,
8533 ) {
8534 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8535 s.move_heads_with(|map, head, _| {
8536 (
8537 movement::previous_word_start(map, head),
8538 SelectionGoal::None,
8539 )
8540 });
8541 })
8542 }
8543
8544 pub fn select_to_previous_subword_start(
8545 &mut self,
8546 _: &SelectToPreviousSubwordStart,
8547 window: &mut Window,
8548 cx: &mut Context<Self>,
8549 ) {
8550 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8551 s.move_heads_with(|map, head, _| {
8552 (
8553 movement::previous_subword_start(map, head),
8554 SelectionGoal::None,
8555 )
8556 });
8557 })
8558 }
8559
8560 pub fn delete_to_previous_word_start(
8561 &mut self,
8562 action: &DeleteToPreviousWordStart,
8563 window: &mut Window,
8564 cx: &mut Context<Self>,
8565 ) {
8566 self.transact(window, cx, |this, window, cx| {
8567 this.select_autoclose_pair(window, cx);
8568 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8569 let line_mode = s.line_mode;
8570 s.move_with(|map, selection| {
8571 if selection.is_empty() && !line_mode {
8572 let cursor = if action.ignore_newlines {
8573 movement::previous_word_start(map, selection.head())
8574 } else {
8575 movement::previous_word_start_or_newline(map, selection.head())
8576 };
8577 selection.set_head(cursor, SelectionGoal::None);
8578 }
8579 });
8580 });
8581 this.insert("", window, cx);
8582 });
8583 }
8584
8585 pub fn delete_to_previous_subword_start(
8586 &mut self,
8587 _: &DeleteToPreviousSubwordStart,
8588 window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 self.transact(window, cx, |this, window, cx| {
8592 this.select_autoclose_pair(window, cx);
8593 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8594 let line_mode = s.line_mode;
8595 s.move_with(|map, selection| {
8596 if selection.is_empty() && !line_mode {
8597 let cursor = movement::previous_subword_start(map, selection.head());
8598 selection.set_head(cursor, SelectionGoal::None);
8599 }
8600 });
8601 });
8602 this.insert("", window, cx);
8603 });
8604 }
8605
8606 pub fn move_to_next_word_end(
8607 &mut self,
8608 _: &MoveToNextWordEnd,
8609 window: &mut Window,
8610 cx: &mut Context<Self>,
8611 ) {
8612 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8613 s.move_cursors_with(|map, head, _| {
8614 (movement::next_word_end(map, head), SelectionGoal::None)
8615 });
8616 })
8617 }
8618
8619 pub fn move_to_next_subword_end(
8620 &mut self,
8621 _: &MoveToNextSubwordEnd,
8622 window: &mut Window,
8623 cx: &mut Context<Self>,
8624 ) {
8625 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8626 s.move_cursors_with(|map, head, _| {
8627 (movement::next_subword_end(map, head), SelectionGoal::None)
8628 });
8629 })
8630 }
8631
8632 pub fn select_to_next_word_end(
8633 &mut self,
8634 _: &SelectToNextWordEnd,
8635 window: &mut Window,
8636 cx: &mut Context<Self>,
8637 ) {
8638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8639 s.move_heads_with(|map, head, _| {
8640 (movement::next_word_end(map, head), SelectionGoal::None)
8641 });
8642 })
8643 }
8644
8645 pub fn select_to_next_subword_end(
8646 &mut self,
8647 _: &SelectToNextSubwordEnd,
8648 window: &mut Window,
8649 cx: &mut Context<Self>,
8650 ) {
8651 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8652 s.move_heads_with(|map, head, _| {
8653 (movement::next_subword_end(map, head), SelectionGoal::None)
8654 });
8655 })
8656 }
8657
8658 pub fn delete_to_next_word_end(
8659 &mut self,
8660 action: &DeleteToNextWordEnd,
8661 window: &mut Window,
8662 cx: &mut Context<Self>,
8663 ) {
8664 self.transact(window, cx, |this, window, cx| {
8665 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8666 let line_mode = s.line_mode;
8667 s.move_with(|map, selection| {
8668 if selection.is_empty() && !line_mode {
8669 let cursor = if action.ignore_newlines {
8670 movement::next_word_end(map, selection.head())
8671 } else {
8672 movement::next_word_end_or_newline(map, selection.head())
8673 };
8674 selection.set_head(cursor, SelectionGoal::None);
8675 }
8676 });
8677 });
8678 this.insert("", window, cx);
8679 });
8680 }
8681
8682 pub fn delete_to_next_subword_end(
8683 &mut self,
8684 _: &DeleteToNextSubwordEnd,
8685 window: &mut Window,
8686 cx: &mut Context<Self>,
8687 ) {
8688 self.transact(window, cx, |this, window, cx| {
8689 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8690 s.move_with(|map, selection| {
8691 if selection.is_empty() {
8692 let cursor = movement::next_subword_end(map, selection.head());
8693 selection.set_head(cursor, SelectionGoal::None);
8694 }
8695 });
8696 });
8697 this.insert("", window, cx);
8698 });
8699 }
8700
8701 pub fn move_to_beginning_of_line(
8702 &mut self,
8703 action: &MoveToBeginningOfLine,
8704 window: &mut Window,
8705 cx: &mut Context<Self>,
8706 ) {
8707 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8708 s.move_cursors_with(|map, head, _| {
8709 (
8710 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8711 SelectionGoal::None,
8712 )
8713 });
8714 })
8715 }
8716
8717 pub fn select_to_beginning_of_line(
8718 &mut self,
8719 action: &SelectToBeginningOfLine,
8720 window: &mut Window,
8721 cx: &mut Context<Self>,
8722 ) {
8723 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8724 s.move_heads_with(|map, head, _| {
8725 (
8726 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8727 SelectionGoal::None,
8728 )
8729 });
8730 });
8731 }
8732
8733 pub fn delete_to_beginning_of_line(
8734 &mut self,
8735 _: &DeleteToBeginningOfLine,
8736 window: &mut Window,
8737 cx: &mut Context<Self>,
8738 ) {
8739 self.transact(window, cx, |this, window, cx| {
8740 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8741 s.move_with(|_, selection| {
8742 selection.reversed = true;
8743 });
8744 });
8745
8746 this.select_to_beginning_of_line(
8747 &SelectToBeginningOfLine {
8748 stop_at_soft_wraps: false,
8749 },
8750 window,
8751 cx,
8752 );
8753 this.backspace(&Backspace, window, cx);
8754 });
8755 }
8756
8757 pub fn move_to_end_of_line(
8758 &mut self,
8759 action: &MoveToEndOfLine,
8760 window: &mut Window,
8761 cx: &mut Context<Self>,
8762 ) {
8763 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8764 s.move_cursors_with(|map, head, _| {
8765 (
8766 movement::line_end(map, head, action.stop_at_soft_wraps),
8767 SelectionGoal::None,
8768 )
8769 });
8770 })
8771 }
8772
8773 pub fn select_to_end_of_line(
8774 &mut self,
8775 action: &SelectToEndOfLine,
8776 window: &mut Window,
8777 cx: &mut Context<Self>,
8778 ) {
8779 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8780 s.move_heads_with(|map, head, _| {
8781 (
8782 movement::line_end(map, head, action.stop_at_soft_wraps),
8783 SelectionGoal::None,
8784 )
8785 });
8786 })
8787 }
8788
8789 pub fn delete_to_end_of_line(
8790 &mut self,
8791 _: &DeleteToEndOfLine,
8792 window: &mut Window,
8793 cx: &mut Context<Self>,
8794 ) {
8795 self.transact(window, cx, |this, window, cx| {
8796 this.select_to_end_of_line(
8797 &SelectToEndOfLine {
8798 stop_at_soft_wraps: false,
8799 },
8800 window,
8801 cx,
8802 );
8803 this.delete(&Delete, window, cx);
8804 });
8805 }
8806
8807 pub fn cut_to_end_of_line(
8808 &mut self,
8809 _: &CutToEndOfLine,
8810 window: &mut Window,
8811 cx: &mut Context<Self>,
8812 ) {
8813 self.transact(window, cx, |this, window, cx| {
8814 this.select_to_end_of_line(
8815 &SelectToEndOfLine {
8816 stop_at_soft_wraps: false,
8817 },
8818 window,
8819 cx,
8820 );
8821 this.cut(&Cut, window, cx);
8822 });
8823 }
8824
8825 pub fn move_to_start_of_paragraph(
8826 &mut self,
8827 _: &MoveToStartOfParagraph,
8828 window: &mut Window,
8829 cx: &mut Context<Self>,
8830 ) {
8831 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8832 cx.propagate();
8833 return;
8834 }
8835
8836 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8837 s.move_with(|map, selection| {
8838 selection.collapse_to(
8839 movement::start_of_paragraph(map, selection.head(), 1),
8840 SelectionGoal::None,
8841 )
8842 });
8843 })
8844 }
8845
8846 pub fn move_to_end_of_paragraph(
8847 &mut self,
8848 _: &MoveToEndOfParagraph,
8849 window: &mut Window,
8850 cx: &mut Context<Self>,
8851 ) {
8852 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8853 cx.propagate();
8854 return;
8855 }
8856
8857 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8858 s.move_with(|map, selection| {
8859 selection.collapse_to(
8860 movement::end_of_paragraph(map, selection.head(), 1),
8861 SelectionGoal::None,
8862 )
8863 });
8864 })
8865 }
8866
8867 pub fn select_to_start_of_paragraph(
8868 &mut self,
8869 _: &SelectToStartOfParagraph,
8870 window: &mut Window,
8871 cx: &mut Context<Self>,
8872 ) {
8873 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8874 cx.propagate();
8875 return;
8876 }
8877
8878 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8879 s.move_heads_with(|map, head, _| {
8880 (
8881 movement::start_of_paragraph(map, head, 1),
8882 SelectionGoal::None,
8883 )
8884 });
8885 })
8886 }
8887
8888 pub fn select_to_end_of_paragraph(
8889 &mut self,
8890 _: &SelectToEndOfParagraph,
8891 window: &mut Window,
8892 cx: &mut Context<Self>,
8893 ) {
8894 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8895 cx.propagate();
8896 return;
8897 }
8898
8899 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8900 s.move_heads_with(|map, head, _| {
8901 (
8902 movement::end_of_paragraph(map, head, 1),
8903 SelectionGoal::None,
8904 )
8905 });
8906 })
8907 }
8908
8909 pub fn move_to_beginning(
8910 &mut self,
8911 _: &MoveToBeginning,
8912 window: &mut Window,
8913 cx: &mut Context<Self>,
8914 ) {
8915 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8916 cx.propagate();
8917 return;
8918 }
8919
8920 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8921 s.select_ranges(vec![0..0]);
8922 });
8923 }
8924
8925 pub fn select_to_beginning(
8926 &mut self,
8927 _: &SelectToBeginning,
8928 window: &mut Window,
8929 cx: &mut Context<Self>,
8930 ) {
8931 let mut selection = self.selections.last::<Point>(cx);
8932 selection.set_head(Point::zero(), SelectionGoal::None);
8933
8934 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8935 s.select(vec![selection]);
8936 });
8937 }
8938
8939 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8940 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8941 cx.propagate();
8942 return;
8943 }
8944
8945 let cursor = self.buffer.read(cx).read(cx).len();
8946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8947 s.select_ranges(vec![cursor..cursor])
8948 });
8949 }
8950
8951 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8952 self.nav_history = nav_history;
8953 }
8954
8955 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8956 self.nav_history.as_ref()
8957 }
8958
8959 fn push_to_nav_history(
8960 &mut self,
8961 cursor_anchor: Anchor,
8962 new_position: Option<Point>,
8963 cx: &mut Context<Self>,
8964 ) {
8965 if let Some(nav_history) = self.nav_history.as_mut() {
8966 let buffer = self.buffer.read(cx).read(cx);
8967 let cursor_position = cursor_anchor.to_point(&buffer);
8968 let scroll_state = self.scroll_manager.anchor();
8969 let scroll_top_row = scroll_state.top_row(&buffer);
8970 drop(buffer);
8971
8972 if let Some(new_position) = new_position {
8973 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8974 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8975 return;
8976 }
8977 }
8978
8979 nav_history.push(
8980 Some(NavigationData {
8981 cursor_anchor,
8982 cursor_position,
8983 scroll_anchor: scroll_state,
8984 scroll_top_row,
8985 }),
8986 cx,
8987 );
8988 }
8989 }
8990
8991 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8992 let buffer = self.buffer.read(cx).snapshot(cx);
8993 let mut selection = self.selections.first::<usize>(cx);
8994 selection.set_head(buffer.len(), SelectionGoal::None);
8995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8996 s.select(vec![selection]);
8997 });
8998 }
8999
9000 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9001 let end = self.buffer.read(cx).read(cx).len();
9002 self.change_selections(None, window, cx, |s| {
9003 s.select_ranges(vec![0..end]);
9004 });
9005 }
9006
9007 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9009 let mut selections = self.selections.all::<Point>(cx);
9010 let max_point = display_map.buffer_snapshot.max_point();
9011 for selection in &mut selections {
9012 let rows = selection.spanned_rows(true, &display_map);
9013 selection.start = Point::new(rows.start.0, 0);
9014 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9015 selection.reversed = false;
9016 }
9017 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9018 s.select(selections);
9019 });
9020 }
9021
9022 pub fn split_selection_into_lines(
9023 &mut self,
9024 _: &SplitSelectionIntoLines,
9025 window: &mut Window,
9026 cx: &mut Context<Self>,
9027 ) {
9028 let mut to_unfold = Vec::new();
9029 let mut new_selection_ranges = Vec::new();
9030 {
9031 let selections = self.selections.all::<Point>(cx);
9032 let buffer = self.buffer.read(cx).read(cx);
9033 for selection in selections {
9034 for row in selection.start.row..selection.end.row {
9035 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9036 new_selection_ranges.push(cursor..cursor);
9037 }
9038 new_selection_ranges.push(selection.end..selection.end);
9039 to_unfold.push(selection.start..selection.end);
9040 }
9041 }
9042 self.unfold_ranges(&to_unfold, true, true, cx);
9043 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9044 s.select_ranges(new_selection_ranges);
9045 });
9046 }
9047
9048 pub fn add_selection_above(
9049 &mut self,
9050 _: &AddSelectionAbove,
9051 window: &mut Window,
9052 cx: &mut Context<Self>,
9053 ) {
9054 self.add_selection(true, window, cx);
9055 }
9056
9057 pub fn add_selection_below(
9058 &mut self,
9059 _: &AddSelectionBelow,
9060 window: &mut Window,
9061 cx: &mut Context<Self>,
9062 ) {
9063 self.add_selection(false, window, cx);
9064 }
9065
9066 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9067 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9068 let mut selections = self.selections.all::<Point>(cx);
9069 let text_layout_details = self.text_layout_details(window);
9070 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9071 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9072 let range = oldest_selection.display_range(&display_map).sorted();
9073
9074 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9075 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9076 let positions = start_x.min(end_x)..start_x.max(end_x);
9077
9078 selections.clear();
9079 let mut stack = Vec::new();
9080 for row in range.start.row().0..=range.end.row().0 {
9081 if let Some(selection) = self.selections.build_columnar_selection(
9082 &display_map,
9083 DisplayRow(row),
9084 &positions,
9085 oldest_selection.reversed,
9086 &text_layout_details,
9087 ) {
9088 stack.push(selection.id);
9089 selections.push(selection);
9090 }
9091 }
9092
9093 if above {
9094 stack.reverse();
9095 }
9096
9097 AddSelectionsState { above, stack }
9098 });
9099
9100 let last_added_selection = *state.stack.last().unwrap();
9101 let mut new_selections = Vec::new();
9102 if above == state.above {
9103 let end_row = if above {
9104 DisplayRow(0)
9105 } else {
9106 display_map.max_point().row()
9107 };
9108
9109 'outer: for selection in selections {
9110 if selection.id == last_added_selection {
9111 let range = selection.display_range(&display_map).sorted();
9112 debug_assert_eq!(range.start.row(), range.end.row());
9113 let mut row = range.start.row();
9114 let positions =
9115 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9116 px(start)..px(end)
9117 } else {
9118 let start_x =
9119 display_map.x_for_display_point(range.start, &text_layout_details);
9120 let end_x =
9121 display_map.x_for_display_point(range.end, &text_layout_details);
9122 start_x.min(end_x)..start_x.max(end_x)
9123 };
9124
9125 while row != end_row {
9126 if above {
9127 row.0 -= 1;
9128 } else {
9129 row.0 += 1;
9130 }
9131
9132 if let Some(new_selection) = self.selections.build_columnar_selection(
9133 &display_map,
9134 row,
9135 &positions,
9136 selection.reversed,
9137 &text_layout_details,
9138 ) {
9139 state.stack.push(new_selection.id);
9140 if above {
9141 new_selections.push(new_selection);
9142 new_selections.push(selection);
9143 } else {
9144 new_selections.push(selection);
9145 new_selections.push(new_selection);
9146 }
9147
9148 continue 'outer;
9149 }
9150 }
9151 }
9152
9153 new_selections.push(selection);
9154 }
9155 } else {
9156 new_selections = selections;
9157 new_selections.retain(|s| s.id != last_added_selection);
9158 state.stack.pop();
9159 }
9160
9161 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9162 s.select(new_selections);
9163 });
9164 if state.stack.len() > 1 {
9165 self.add_selections_state = Some(state);
9166 }
9167 }
9168
9169 pub fn select_next_match_internal(
9170 &mut self,
9171 display_map: &DisplaySnapshot,
9172 replace_newest: bool,
9173 autoscroll: Option<Autoscroll>,
9174 window: &mut Window,
9175 cx: &mut Context<Self>,
9176 ) -> Result<()> {
9177 fn select_next_match_ranges(
9178 this: &mut Editor,
9179 range: Range<usize>,
9180 replace_newest: bool,
9181 auto_scroll: Option<Autoscroll>,
9182 window: &mut Window,
9183 cx: &mut Context<Editor>,
9184 ) {
9185 this.unfold_ranges(&[range.clone()], false, true, cx);
9186 this.change_selections(auto_scroll, window, cx, |s| {
9187 if replace_newest {
9188 s.delete(s.newest_anchor().id);
9189 }
9190 s.insert_range(range.clone());
9191 });
9192 }
9193
9194 let buffer = &display_map.buffer_snapshot;
9195 let mut selections = self.selections.all::<usize>(cx);
9196 if let Some(mut select_next_state) = self.select_next_state.take() {
9197 let query = &select_next_state.query;
9198 if !select_next_state.done {
9199 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9200 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9201 let mut next_selected_range = None;
9202
9203 let bytes_after_last_selection =
9204 buffer.bytes_in_range(last_selection.end..buffer.len());
9205 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9206 let query_matches = query
9207 .stream_find_iter(bytes_after_last_selection)
9208 .map(|result| (last_selection.end, result))
9209 .chain(
9210 query
9211 .stream_find_iter(bytes_before_first_selection)
9212 .map(|result| (0, result)),
9213 );
9214
9215 for (start_offset, query_match) in query_matches {
9216 let query_match = query_match.unwrap(); // can only fail due to I/O
9217 let offset_range =
9218 start_offset + query_match.start()..start_offset + query_match.end();
9219 let display_range = offset_range.start.to_display_point(display_map)
9220 ..offset_range.end.to_display_point(display_map);
9221
9222 if !select_next_state.wordwise
9223 || (!movement::is_inside_word(display_map, display_range.start)
9224 && !movement::is_inside_word(display_map, display_range.end))
9225 {
9226 // TODO: This is n^2, because we might check all the selections
9227 if !selections
9228 .iter()
9229 .any(|selection| selection.range().overlaps(&offset_range))
9230 {
9231 next_selected_range = Some(offset_range);
9232 break;
9233 }
9234 }
9235 }
9236
9237 if let Some(next_selected_range) = next_selected_range {
9238 select_next_match_ranges(
9239 self,
9240 next_selected_range,
9241 replace_newest,
9242 autoscroll,
9243 window,
9244 cx,
9245 );
9246 } else {
9247 select_next_state.done = true;
9248 }
9249 }
9250
9251 self.select_next_state = Some(select_next_state);
9252 } else {
9253 let mut only_carets = true;
9254 let mut same_text_selected = true;
9255 let mut selected_text = None;
9256
9257 let mut selections_iter = selections.iter().peekable();
9258 while let Some(selection) = selections_iter.next() {
9259 if selection.start != selection.end {
9260 only_carets = false;
9261 }
9262
9263 if same_text_selected {
9264 if selected_text.is_none() {
9265 selected_text =
9266 Some(buffer.text_for_range(selection.range()).collect::<String>());
9267 }
9268
9269 if let Some(next_selection) = selections_iter.peek() {
9270 if next_selection.range().len() == selection.range().len() {
9271 let next_selected_text = buffer
9272 .text_for_range(next_selection.range())
9273 .collect::<String>();
9274 if Some(next_selected_text) != selected_text {
9275 same_text_selected = false;
9276 selected_text = None;
9277 }
9278 } else {
9279 same_text_selected = false;
9280 selected_text = None;
9281 }
9282 }
9283 }
9284 }
9285
9286 if only_carets {
9287 for selection in &mut selections {
9288 let word_range = movement::surrounding_word(
9289 display_map,
9290 selection.start.to_display_point(display_map),
9291 );
9292 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9293 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9294 selection.goal = SelectionGoal::None;
9295 selection.reversed = false;
9296 select_next_match_ranges(
9297 self,
9298 selection.start..selection.end,
9299 replace_newest,
9300 autoscroll,
9301 window,
9302 cx,
9303 );
9304 }
9305
9306 if selections.len() == 1 {
9307 let selection = selections
9308 .last()
9309 .expect("ensured that there's only one selection");
9310 let query = buffer
9311 .text_for_range(selection.start..selection.end)
9312 .collect::<String>();
9313 let is_empty = query.is_empty();
9314 let select_state = SelectNextState {
9315 query: AhoCorasick::new(&[query])?,
9316 wordwise: true,
9317 done: is_empty,
9318 };
9319 self.select_next_state = Some(select_state);
9320 } else {
9321 self.select_next_state = None;
9322 }
9323 } else if let Some(selected_text) = selected_text {
9324 self.select_next_state = Some(SelectNextState {
9325 query: AhoCorasick::new(&[selected_text])?,
9326 wordwise: false,
9327 done: false,
9328 });
9329 self.select_next_match_internal(
9330 display_map,
9331 replace_newest,
9332 autoscroll,
9333 window,
9334 cx,
9335 )?;
9336 }
9337 }
9338 Ok(())
9339 }
9340
9341 pub fn select_all_matches(
9342 &mut self,
9343 _action: &SelectAllMatches,
9344 window: &mut Window,
9345 cx: &mut Context<Self>,
9346 ) -> Result<()> {
9347 self.push_to_selection_history();
9348 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9349
9350 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9351 let Some(select_next_state) = self.select_next_state.as_mut() else {
9352 return Ok(());
9353 };
9354 if select_next_state.done {
9355 return Ok(());
9356 }
9357
9358 let mut new_selections = self.selections.all::<usize>(cx);
9359
9360 let buffer = &display_map.buffer_snapshot;
9361 let query_matches = select_next_state
9362 .query
9363 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9364
9365 for query_match in query_matches {
9366 let query_match = query_match.unwrap(); // can only fail due to I/O
9367 let offset_range = query_match.start()..query_match.end();
9368 let display_range = offset_range.start.to_display_point(&display_map)
9369 ..offset_range.end.to_display_point(&display_map);
9370
9371 if !select_next_state.wordwise
9372 || (!movement::is_inside_word(&display_map, display_range.start)
9373 && !movement::is_inside_word(&display_map, display_range.end))
9374 {
9375 self.selections.change_with(cx, |selections| {
9376 new_selections.push(Selection {
9377 id: selections.new_selection_id(),
9378 start: offset_range.start,
9379 end: offset_range.end,
9380 reversed: false,
9381 goal: SelectionGoal::None,
9382 });
9383 });
9384 }
9385 }
9386
9387 new_selections.sort_by_key(|selection| selection.start);
9388 let mut ix = 0;
9389 while ix + 1 < new_selections.len() {
9390 let current_selection = &new_selections[ix];
9391 let next_selection = &new_selections[ix + 1];
9392 if current_selection.range().overlaps(&next_selection.range()) {
9393 if current_selection.id < next_selection.id {
9394 new_selections.remove(ix + 1);
9395 } else {
9396 new_selections.remove(ix);
9397 }
9398 } else {
9399 ix += 1;
9400 }
9401 }
9402
9403 let reversed = self.selections.oldest::<usize>(cx).reversed;
9404
9405 for selection in new_selections.iter_mut() {
9406 selection.reversed = reversed;
9407 }
9408
9409 select_next_state.done = true;
9410 self.unfold_ranges(
9411 &new_selections
9412 .iter()
9413 .map(|selection| selection.range())
9414 .collect::<Vec<_>>(),
9415 false,
9416 false,
9417 cx,
9418 );
9419 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9420 selections.select(new_selections)
9421 });
9422
9423 Ok(())
9424 }
9425
9426 pub fn select_next(
9427 &mut self,
9428 action: &SelectNext,
9429 window: &mut Window,
9430 cx: &mut Context<Self>,
9431 ) -> Result<()> {
9432 self.push_to_selection_history();
9433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9434 self.select_next_match_internal(
9435 &display_map,
9436 action.replace_newest,
9437 Some(Autoscroll::newest()),
9438 window,
9439 cx,
9440 )?;
9441 Ok(())
9442 }
9443
9444 pub fn select_previous(
9445 &mut self,
9446 action: &SelectPrevious,
9447 window: &mut Window,
9448 cx: &mut Context<Self>,
9449 ) -> Result<()> {
9450 self.push_to_selection_history();
9451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9452 let buffer = &display_map.buffer_snapshot;
9453 let mut selections = self.selections.all::<usize>(cx);
9454 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9455 let query = &select_prev_state.query;
9456 if !select_prev_state.done {
9457 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9458 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9459 let mut next_selected_range = None;
9460 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9461 let bytes_before_last_selection =
9462 buffer.reversed_bytes_in_range(0..last_selection.start);
9463 let bytes_after_first_selection =
9464 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9465 let query_matches = query
9466 .stream_find_iter(bytes_before_last_selection)
9467 .map(|result| (last_selection.start, result))
9468 .chain(
9469 query
9470 .stream_find_iter(bytes_after_first_selection)
9471 .map(|result| (buffer.len(), result)),
9472 );
9473 for (end_offset, query_match) in query_matches {
9474 let query_match = query_match.unwrap(); // can only fail due to I/O
9475 let offset_range =
9476 end_offset - query_match.end()..end_offset - query_match.start();
9477 let display_range = offset_range.start.to_display_point(&display_map)
9478 ..offset_range.end.to_display_point(&display_map);
9479
9480 if !select_prev_state.wordwise
9481 || (!movement::is_inside_word(&display_map, display_range.start)
9482 && !movement::is_inside_word(&display_map, display_range.end))
9483 {
9484 next_selected_range = Some(offset_range);
9485 break;
9486 }
9487 }
9488
9489 if let Some(next_selected_range) = next_selected_range {
9490 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9491 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9492 if action.replace_newest {
9493 s.delete(s.newest_anchor().id);
9494 }
9495 s.insert_range(next_selected_range);
9496 });
9497 } else {
9498 select_prev_state.done = true;
9499 }
9500 }
9501
9502 self.select_prev_state = Some(select_prev_state);
9503 } else {
9504 let mut only_carets = true;
9505 let mut same_text_selected = true;
9506 let mut selected_text = None;
9507
9508 let mut selections_iter = selections.iter().peekable();
9509 while let Some(selection) = selections_iter.next() {
9510 if selection.start != selection.end {
9511 only_carets = false;
9512 }
9513
9514 if same_text_selected {
9515 if selected_text.is_none() {
9516 selected_text =
9517 Some(buffer.text_for_range(selection.range()).collect::<String>());
9518 }
9519
9520 if let Some(next_selection) = selections_iter.peek() {
9521 if next_selection.range().len() == selection.range().len() {
9522 let next_selected_text = buffer
9523 .text_for_range(next_selection.range())
9524 .collect::<String>();
9525 if Some(next_selected_text) != selected_text {
9526 same_text_selected = false;
9527 selected_text = None;
9528 }
9529 } else {
9530 same_text_selected = false;
9531 selected_text = None;
9532 }
9533 }
9534 }
9535 }
9536
9537 if only_carets {
9538 for selection in &mut selections {
9539 let word_range = movement::surrounding_word(
9540 &display_map,
9541 selection.start.to_display_point(&display_map),
9542 );
9543 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9544 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9545 selection.goal = SelectionGoal::None;
9546 selection.reversed = false;
9547 }
9548 if selections.len() == 1 {
9549 let selection = selections
9550 .last()
9551 .expect("ensured that there's only one selection");
9552 let query = buffer
9553 .text_for_range(selection.start..selection.end)
9554 .collect::<String>();
9555 let is_empty = query.is_empty();
9556 let select_state = SelectNextState {
9557 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9558 wordwise: true,
9559 done: is_empty,
9560 };
9561 self.select_prev_state = Some(select_state);
9562 } else {
9563 self.select_prev_state = None;
9564 }
9565
9566 self.unfold_ranges(
9567 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9568 false,
9569 true,
9570 cx,
9571 );
9572 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9573 s.select(selections);
9574 });
9575 } else if let Some(selected_text) = selected_text {
9576 self.select_prev_state = Some(SelectNextState {
9577 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9578 wordwise: false,
9579 done: false,
9580 });
9581 self.select_previous(action, window, cx)?;
9582 }
9583 }
9584 Ok(())
9585 }
9586
9587 pub fn toggle_comments(
9588 &mut self,
9589 action: &ToggleComments,
9590 window: &mut Window,
9591 cx: &mut Context<Self>,
9592 ) {
9593 if self.read_only(cx) {
9594 return;
9595 }
9596 let text_layout_details = &self.text_layout_details(window);
9597 self.transact(window, cx, |this, window, cx| {
9598 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9599 let mut edits = Vec::new();
9600 let mut selection_edit_ranges = Vec::new();
9601 let mut last_toggled_row = None;
9602 let snapshot = this.buffer.read(cx).read(cx);
9603 let empty_str: Arc<str> = Arc::default();
9604 let mut suffixes_inserted = Vec::new();
9605 let ignore_indent = action.ignore_indent;
9606
9607 fn comment_prefix_range(
9608 snapshot: &MultiBufferSnapshot,
9609 row: MultiBufferRow,
9610 comment_prefix: &str,
9611 comment_prefix_whitespace: &str,
9612 ignore_indent: bool,
9613 ) -> Range<Point> {
9614 let indent_size = if ignore_indent {
9615 0
9616 } else {
9617 snapshot.indent_size_for_line(row).len
9618 };
9619
9620 let start = Point::new(row.0, indent_size);
9621
9622 let mut line_bytes = snapshot
9623 .bytes_in_range(start..snapshot.max_point())
9624 .flatten()
9625 .copied();
9626
9627 // If this line currently begins with the line comment prefix, then record
9628 // the range containing the prefix.
9629 if line_bytes
9630 .by_ref()
9631 .take(comment_prefix.len())
9632 .eq(comment_prefix.bytes())
9633 {
9634 // Include any whitespace that matches the comment prefix.
9635 let matching_whitespace_len = line_bytes
9636 .zip(comment_prefix_whitespace.bytes())
9637 .take_while(|(a, b)| a == b)
9638 .count() as u32;
9639 let end = Point::new(
9640 start.row,
9641 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9642 );
9643 start..end
9644 } else {
9645 start..start
9646 }
9647 }
9648
9649 fn comment_suffix_range(
9650 snapshot: &MultiBufferSnapshot,
9651 row: MultiBufferRow,
9652 comment_suffix: &str,
9653 comment_suffix_has_leading_space: bool,
9654 ) -> Range<Point> {
9655 let end = Point::new(row.0, snapshot.line_len(row));
9656 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9657
9658 let mut line_end_bytes = snapshot
9659 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9660 .flatten()
9661 .copied();
9662
9663 let leading_space_len = if suffix_start_column > 0
9664 && line_end_bytes.next() == Some(b' ')
9665 && comment_suffix_has_leading_space
9666 {
9667 1
9668 } else {
9669 0
9670 };
9671
9672 // If this line currently begins with the line comment prefix, then record
9673 // the range containing the prefix.
9674 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9675 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9676 start..end
9677 } else {
9678 end..end
9679 }
9680 }
9681
9682 // TODO: Handle selections that cross excerpts
9683 for selection in &mut selections {
9684 let start_column = snapshot
9685 .indent_size_for_line(MultiBufferRow(selection.start.row))
9686 .len;
9687 let language = if let Some(language) =
9688 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9689 {
9690 language
9691 } else {
9692 continue;
9693 };
9694
9695 selection_edit_ranges.clear();
9696
9697 // If multiple selections contain a given row, avoid processing that
9698 // row more than once.
9699 let mut start_row = MultiBufferRow(selection.start.row);
9700 if last_toggled_row == Some(start_row) {
9701 start_row = start_row.next_row();
9702 }
9703 let end_row =
9704 if selection.end.row > selection.start.row && selection.end.column == 0 {
9705 MultiBufferRow(selection.end.row - 1)
9706 } else {
9707 MultiBufferRow(selection.end.row)
9708 };
9709 last_toggled_row = Some(end_row);
9710
9711 if start_row > end_row {
9712 continue;
9713 }
9714
9715 // If the language has line comments, toggle those.
9716 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9717
9718 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9719 if ignore_indent {
9720 full_comment_prefixes = full_comment_prefixes
9721 .into_iter()
9722 .map(|s| Arc::from(s.trim_end()))
9723 .collect();
9724 }
9725
9726 if !full_comment_prefixes.is_empty() {
9727 let first_prefix = full_comment_prefixes
9728 .first()
9729 .expect("prefixes is non-empty");
9730 let prefix_trimmed_lengths = full_comment_prefixes
9731 .iter()
9732 .map(|p| p.trim_end_matches(' ').len())
9733 .collect::<SmallVec<[usize; 4]>>();
9734
9735 let mut all_selection_lines_are_comments = true;
9736
9737 for row in start_row.0..=end_row.0 {
9738 let row = MultiBufferRow(row);
9739 if start_row < end_row && snapshot.is_line_blank(row) {
9740 continue;
9741 }
9742
9743 let prefix_range = full_comment_prefixes
9744 .iter()
9745 .zip(prefix_trimmed_lengths.iter().copied())
9746 .map(|(prefix, trimmed_prefix_len)| {
9747 comment_prefix_range(
9748 snapshot.deref(),
9749 row,
9750 &prefix[..trimmed_prefix_len],
9751 &prefix[trimmed_prefix_len..],
9752 ignore_indent,
9753 )
9754 })
9755 .max_by_key(|range| range.end.column - range.start.column)
9756 .expect("prefixes is non-empty");
9757
9758 if prefix_range.is_empty() {
9759 all_selection_lines_are_comments = false;
9760 }
9761
9762 selection_edit_ranges.push(prefix_range);
9763 }
9764
9765 if all_selection_lines_are_comments {
9766 edits.extend(
9767 selection_edit_ranges
9768 .iter()
9769 .cloned()
9770 .map(|range| (range, empty_str.clone())),
9771 );
9772 } else {
9773 let min_column = selection_edit_ranges
9774 .iter()
9775 .map(|range| range.start.column)
9776 .min()
9777 .unwrap_or(0);
9778 edits.extend(selection_edit_ranges.iter().map(|range| {
9779 let position = Point::new(range.start.row, min_column);
9780 (position..position, first_prefix.clone())
9781 }));
9782 }
9783 } else if let Some((full_comment_prefix, comment_suffix)) =
9784 language.block_comment_delimiters()
9785 {
9786 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9787 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9788 let prefix_range = comment_prefix_range(
9789 snapshot.deref(),
9790 start_row,
9791 comment_prefix,
9792 comment_prefix_whitespace,
9793 ignore_indent,
9794 );
9795 let suffix_range = comment_suffix_range(
9796 snapshot.deref(),
9797 end_row,
9798 comment_suffix.trim_start_matches(' '),
9799 comment_suffix.starts_with(' '),
9800 );
9801
9802 if prefix_range.is_empty() || suffix_range.is_empty() {
9803 edits.push((
9804 prefix_range.start..prefix_range.start,
9805 full_comment_prefix.clone(),
9806 ));
9807 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9808 suffixes_inserted.push((end_row, comment_suffix.len()));
9809 } else {
9810 edits.push((prefix_range, empty_str.clone()));
9811 edits.push((suffix_range, empty_str.clone()));
9812 }
9813 } else {
9814 continue;
9815 }
9816 }
9817
9818 drop(snapshot);
9819 this.buffer.update(cx, |buffer, cx| {
9820 buffer.edit(edits, None, cx);
9821 });
9822
9823 // Adjust selections so that they end before any comment suffixes that
9824 // were inserted.
9825 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9826 let mut selections = this.selections.all::<Point>(cx);
9827 let snapshot = this.buffer.read(cx).read(cx);
9828 for selection in &mut selections {
9829 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9830 match row.cmp(&MultiBufferRow(selection.end.row)) {
9831 Ordering::Less => {
9832 suffixes_inserted.next();
9833 continue;
9834 }
9835 Ordering::Greater => break,
9836 Ordering::Equal => {
9837 if selection.end.column == snapshot.line_len(row) {
9838 if selection.is_empty() {
9839 selection.start.column -= suffix_len as u32;
9840 }
9841 selection.end.column -= suffix_len as u32;
9842 }
9843 break;
9844 }
9845 }
9846 }
9847 }
9848
9849 drop(snapshot);
9850 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9851 s.select(selections)
9852 });
9853
9854 let selections = this.selections.all::<Point>(cx);
9855 let selections_on_single_row = selections.windows(2).all(|selections| {
9856 selections[0].start.row == selections[1].start.row
9857 && selections[0].end.row == selections[1].end.row
9858 && selections[0].start.row == selections[0].end.row
9859 });
9860 let selections_selecting = selections
9861 .iter()
9862 .any(|selection| selection.start != selection.end);
9863 let advance_downwards = action.advance_downwards
9864 && selections_on_single_row
9865 && !selections_selecting
9866 && !matches!(this.mode, EditorMode::SingleLine { .. });
9867
9868 if advance_downwards {
9869 let snapshot = this.buffer.read(cx).snapshot(cx);
9870
9871 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9872 s.move_cursors_with(|display_snapshot, display_point, _| {
9873 let mut point = display_point.to_point(display_snapshot);
9874 point.row += 1;
9875 point = snapshot.clip_point(point, Bias::Left);
9876 let display_point = point.to_display_point(display_snapshot);
9877 let goal = SelectionGoal::HorizontalPosition(
9878 display_snapshot
9879 .x_for_display_point(display_point, text_layout_details)
9880 .into(),
9881 );
9882 (display_point, goal)
9883 })
9884 });
9885 }
9886 });
9887 }
9888
9889 pub fn select_enclosing_symbol(
9890 &mut self,
9891 _: &SelectEnclosingSymbol,
9892 window: &mut Window,
9893 cx: &mut Context<Self>,
9894 ) {
9895 let buffer = self.buffer.read(cx).snapshot(cx);
9896 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9897
9898 fn update_selection(
9899 selection: &Selection<usize>,
9900 buffer_snap: &MultiBufferSnapshot,
9901 ) -> Option<Selection<usize>> {
9902 let cursor = selection.head();
9903 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9904 for symbol in symbols.iter().rev() {
9905 let start = symbol.range.start.to_offset(buffer_snap);
9906 let end = symbol.range.end.to_offset(buffer_snap);
9907 let new_range = start..end;
9908 if start < selection.start || end > selection.end {
9909 return Some(Selection {
9910 id: selection.id,
9911 start: new_range.start,
9912 end: new_range.end,
9913 goal: SelectionGoal::None,
9914 reversed: selection.reversed,
9915 });
9916 }
9917 }
9918 None
9919 }
9920
9921 let mut selected_larger_symbol = false;
9922 let new_selections = old_selections
9923 .iter()
9924 .map(|selection| match update_selection(selection, &buffer) {
9925 Some(new_selection) => {
9926 if new_selection.range() != selection.range() {
9927 selected_larger_symbol = true;
9928 }
9929 new_selection
9930 }
9931 None => selection.clone(),
9932 })
9933 .collect::<Vec<_>>();
9934
9935 if selected_larger_symbol {
9936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9937 s.select(new_selections);
9938 });
9939 }
9940 }
9941
9942 pub fn select_larger_syntax_node(
9943 &mut self,
9944 _: &SelectLargerSyntaxNode,
9945 window: &mut Window,
9946 cx: &mut Context<Self>,
9947 ) {
9948 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9949 let buffer = self.buffer.read(cx).snapshot(cx);
9950 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9951
9952 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9953 let mut selected_larger_node = false;
9954 let new_selections = old_selections
9955 .iter()
9956 .map(|selection| {
9957 let old_range = selection.start..selection.end;
9958 let mut new_range = old_range.clone();
9959 let mut new_node = None;
9960 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9961 {
9962 new_node = Some(node);
9963 new_range = containing_range;
9964 if !display_map.intersects_fold(new_range.start)
9965 && !display_map.intersects_fold(new_range.end)
9966 {
9967 break;
9968 }
9969 }
9970
9971 if let Some(node) = new_node {
9972 // Log the ancestor, to support using this action as a way to explore TreeSitter
9973 // nodes. Parent and grandparent are also logged because this operation will not
9974 // visit nodes that have the same range as their parent.
9975 log::info!("Node: {node:?}");
9976 let parent = node.parent();
9977 log::info!("Parent: {parent:?}");
9978 let grandparent = parent.and_then(|x| x.parent());
9979 log::info!("Grandparent: {grandparent:?}");
9980 }
9981
9982 selected_larger_node |= new_range != old_range;
9983 Selection {
9984 id: selection.id,
9985 start: new_range.start,
9986 end: new_range.end,
9987 goal: SelectionGoal::None,
9988 reversed: selection.reversed,
9989 }
9990 })
9991 .collect::<Vec<_>>();
9992
9993 if selected_larger_node {
9994 stack.push(old_selections);
9995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9996 s.select(new_selections);
9997 });
9998 }
9999 self.select_larger_syntax_node_stack = stack;
10000 }
10001
10002 pub fn select_smaller_syntax_node(
10003 &mut self,
10004 _: &SelectSmallerSyntaxNode,
10005 window: &mut Window,
10006 cx: &mut Context<Self>,
10007 ) {
10008 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10009 if let Some(selections) = stack.pop() {
10010 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10011 s.select(selections.to_vec());
10012 });
10013 }
10014 self.select_larger_syntax_node_stack = stack;
10015 }
10016
10017 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10018 if !EditorSettings::get_global(cx).gutter.runnables {
10019 self.clear_tasks();
10020 return Task::ready(());
10021 }
10022 let project = self.project.as_ref().map(Entity::downgrade);
10023 cx.spawn_in(window, |this, mut cx| async move {
10024 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10025 let Some(project) = project.and_then(|p| p.upgrade()) else {
10026 return;
10027 };
10028 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10029 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10030 }) else {
10031 return;
10032 };
10033
10034 let hide_runnables = project
10035 .update(&mut cx, |project, cx| {
10036 // Do not display any test indicators in non-dev server remote projects.
10037 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10038 })
10039 .unwrap_or(true);
10040 if hide_runnables {
10041 return;
10042 }
10043 let new_rows =
10044 cx.background_executor()
10045 .spawn({
10046 let snapshot = display_snapshot.clone();
10047 async move {
10048 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10049 }
10050 })
10051 .await;
10052
10053 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10054 this.update(&mut cx, |this, _| {
10055 this.clear_tasks();
10056 for (key, value) in rows {
10057 this.insert_tasks(key, value);
10058 }
10059 })
10060 .ok();
10061 })
10062 }
10063 fn fetch_runnable_ranges(
10064 snapshot: &DisplaySnapshot,
10065 range: Range<Anchor>,
10066 ) -> Vec<language::RunnableRange> {
10067 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10068 }
10069
10070 fn runnable_rows(
10071 project: Entity<Project>,
10072 snapshot: DisplaySnapshot,
10073 runnable_ranges: Vec<RunnableRange>,
10074 mut cx: AsyncWindowContext,
10075 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10076 runnable_ranges
10077 .into_iter()
10078 .filter_map(|mut runnable| {
10079 let tasks = cx
10080 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10081 .ok()?;
10082 if tasks.is_empty() {
10083 return None;
10084 }
10085
10086 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10087
10088 let row = snapshot
10089 .buffer_snapshot
10090 .buffer_line_for_row(MultiBufferRow(point.row))?
10091 .1
10092 .start
10093 .row;
10094
10095 let context_range =
10096 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10097 Some((
10098 (runnable.buffer_id, row),
10099 RunnableTasks {
10100 templates: tasks,
10101 offset: MultiBufferOffset(runnable.run_range.start),
10102 context_range,
10103 column: point.column,
10104 extra_variables: runnable.extra_captures,
10105 },
10106 ))
10107 })
10108 .collect()
10109 }
10110
10111 fn templates_with_tags(
10112 project: &Entity<Project>,
10113 runnable: &mut Runnable,
10114 cx: &mut App,
10115 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10116 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10117 let (worktree_id, file) = project
10118 .buffer_for_id(runnable.buffer, cx)
10119 .and_then(|buffer| buffer.read(cx).file())
10120 .map(|file| (file.worktree_id(cx), file.clone()))
10121 .unzip();
10122
10123 (
10124 project.task_store().read(cx).task_inventory().cloned(),
10125 worktree_id,
10126 file,
10127 )
10128 });
10129
10130 let tags = mem::take(&mut runnable.tags);
10131 let mut tags: Vec<_> = tags
10132 .into_iter()
10133 .flat_map(|tag| {
10134 let tag = tag.0.clone();
10135 inventory
10136 .as_ref()
10137 .into_iter()
10138 .flat_map(|inventory| {
10139 inventory.read(cx).list_tasks(
10140 file.clone(),
10141 Some(runnable.language.clone()),
10142 worktree_id,
10143 cx,
10144 )
10145 })
10146 .filter(move |(_, template)| {
10147 template.tags.iter().any(|source_tag| source_tag == &tag)
10148 })
10149 })
10150 .sorted_by_key(|(kind, _)| kind.to_owned())
10151 .collect();
10152 if let Some((leading_tag_source, _)) = tags.first() {
10153 // Strongest source wins; if we have worktree tag binding, prefer that to
10154 // global and language bindings;
10155 // if we have a global binding, prefer that to language binding.
10156 let first_mismatch = tags
10157 .iter()
10158 .position(|(tag_source, _)| tag_source != leading_tag_source);
10159 if let Some(index) = first_mismatch {
10160 tags.truncate(index);
10161 }
10162 }
10163
10164 tags
10165 }
10166
10167 pub fn move_to_enclosing_bracket(
10168 &mut self,
10169 _: &MoveToEnclosingBracket,
10170 window: &mut Window,
10171 cx: &mut Context<Self>,
10172 ) {
10173 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10174 s.move_offsets_with(|snapshot, selection| {
10175 let Some(enclosing_bracket_ranges) =
10176 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10177 else {
10178 return;
10179 };
10180
10181 let mut best_length = usize::MAX;
10182 let mut best_inside = false;
10183 let mut best_in_bracket_range = false;
10184 let mut best_destination = None;
10185 for (open, close) in enclosing_bracket_ranges {
10186 let close = close.to_inclusive();
10187 let length = close.end() - open.start;
10188 let inside = selection.start >= open.end && selection.end <= *close.start();
10189 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10190 || close.contains(&selection.head());
10191
10192 // If best is next to a bracket and current isn't, skip
10193 if !in_bracket_range && best_in_bracket_range {
10194 continue;
10195 }
10196
10197 // Prefer smaller lengths unless best is inside and current isn't
10198 if length > best_length && (best_inside || !inside) {
10199 continue;
10200 }
10201
10202 best_length = length;
10203 best_inside = inside;
10204 best_in_bracket_range = in_bracket_range;
10205 best_destination = Some(
10206 if close.contains(&selection.start) && close.contains(&selection.end) {
10207 if inside {
10208 open.end
10209 } else {
10210 open.start
10211 }
10212 } else if inside {
10213 *close.start()
10214 } else {
10215 *close.end()
10216 },
10217 );
10218 }
10219
10220 if let Some(destination) = best_destination {
10221 selection.collapse_to(destination, SelectionGoal::None);
10222 }
10223 })
10224 });
10225 }
10226
10227 pub fn undo_selection(
10228 &mut self,
10229 _: &UndoSelection,
10230 window: &mut Window,
10231 cx: &mut Context<Self>,
10232 ) {
10233 self.end_selection(window, cx);
10234 self.selection_history.mode = SelectionHistoryMode::Undoing;
10235 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10236 self.change_selections(None, window, cx, |s| {
10237 s.select_anchors(entry.selections.to_vec())
10238 });
10239 self.select_next_state = entry.select_next_state;
10240 self.select_prev_state = entry.select_prev_state;
10241 self.add_selections_state = entry.add_selections_state;
10242 self.request_autoscroll(Autoscroll::newest(), cx);
10243 }
10244 self.selection_history.mode = SelectionHistoryMode::Normal;
10245 }
10246
10247 pub fn redo_selection(
10248 &mut self,
10249 _: &RedoSelection,
10250 window: &mut Window,
10251 cx: &mut Context<Self>,
10252 ) {
10253 self.end_selection(window, cx);
10254 self.selection_history.mode = SelectionHistoryMode::Redoing;
10255 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10256 self.change_selections(None, window, cx, |s| {
10257 s.select_anchors(entry.selections.to_vec())
10258 });
10259 self.select_next_state = entry.select_next_state;
10260 self.select_prev_state = entry.select_prev_state;
10261 self.add_selections_state = entry.add_selections_state;
10262 self.request_autoscroll(Autoscroll::newest(), cx);
10263 }
10264 self.selection_history.mode = SelectionHistoryMode::Normal;
10265 }
10266
10267 pub fn expand_excerpts(
10268 &mut self,
10269 action: &ExpandExcerpts,
10270 _: &mut Window,
10271 cx: &mut Context<Self>,
10272 ) {
10273 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10274 }
10275
10276 pub fn expand_excerpts_down(
10277 &mut self,
10278 action: &ExpandExcerptsDown,
10279 _: &mut Window,
10280 cx: &mut Context<Self>,
10281 ) {
10282 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10283 }
10284
10285 pub fn expand_excerpts_up(
10286 &mut self,
10287 action: &ExpandExcerptsUp,
10288 _: &mut Window,
10289 cx: &mut Context<Self>,
10290 ) {
10291 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10292 }
10293
10294 pub fn expand_excerpts_for_direction(
10295 &mut self,
10296 lines: u32,
10297 direction: ExpandExcerptDirection,
10298
10299 cx: &mut Context<Self>,
10300 ) {
10301 let selections = self.selections.disjoint_anchors();
10302
10303 let lines = if lines == 0 {
10304 EditorSettings::get_global(cx).expand_excerpt_lines
10305 } else {
10306 lines
10307 };
10308
10309 self.buffer.update(cx, |buffer, cx| {
10310 let snapshot = buffer.snapshot(cx);
10311 let mut excerpt_ids = selections
10312 .iter()
10313 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10314 .collect::<Vec<_>>();
10315 excerpt_ids.sort();
10316 excerpt_ids.dedup();
10317 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10318 })
10319 }
10320
10321 pub fn expand_excerpt(
10322 &mut self,
10323 excerpt: ExcerptId,
10324 direction: ExpandExcerptDirection,
10325 cx: &mut Context<Self>,
10326 ) {
10327 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10328 self.buffer.update(cx, |buffer, cx| {
10329 buffer.expand_excerpts([excerpt], lines, direction, cx)
10330 })
10331 }
10332
10333 pub fn go_to_singleton_buffer_point(
10334 &mut self,
10335 point: Point,
10336 window: &mut Window,
10337 cx: &mut Context<Self>,
10338 ) {
10339 self.go_to_singleton_buffer_range(point..point, window, cx);
10340 }
10341
10342 pub fn go_to_singleton_buffer_range(
10343 &mut self,
10344 range: Range<Point>,
10345 window: &mut Window,
10346 cx: &mut Context<Self>,
10347 ) {
10348 let multibuffer = self.buffer().read(cx);
10349 let Some(buffer) = multibuffer.as_singleton() else {
10350 return;
10351 };
10352 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10353 return;
10354 };
10355 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10356 return;
10357 };
10358 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10359 s.select_anchor_ranges([start..end])
10360 });
10361 }
10362
10363 fn go_to_diagnostic(
10364 &mut self,
10365 _: &GoToDiagnostic,
10366 window: &mut Window,
10367 cx: &mut Context<Self>,
10368 ) {
10369 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10370 }
10371
10372 fn go_to_prev_diagnostic(
10373 &mut self,
10374 _: &GoToPrevDiagnostic,
10375 window: &mut Window,
10376 cx: &mut Context<Self>,
10377 ) {
10378 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10379 }
10380
10381 pub fn go_to_diagnostic_impl(
10382 &mut self,
10383 direction: Direction,
10384 window: &mut Window,
10385 cx: &mut Context<Self>,
10386 ) {
10387 let buffer = self.buffer.read(cx).snapshot(cx);
10388 let selection = self.selections.newest::<usize>(cx);
10389
10390 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10391 if direction == Direction::Next {
10392 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10393 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10394 return;
10395 };
10396 self.activate_diagnostics(
10397 buffer_id,
10398 popover.local_diagnostic.diagnostic.group_id,
10399 window,
10400 cx,
10401 );
10402 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10403 let primary_range_start = active_diagnostics.primary_range.start;
10404 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10405 let mut new_selection = s.newest_anchor().clone();
10406 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10407 s.select_anchors(vec![new_selection.clone()]);
10408 });
10409 self.refresh_inline_completion(false, true, window, cx);
10410 }
10411 return;
10412 }
10413 }
10414
10415 let active_group_id = self
10416 .active_diagnostics
10417 .as_ref()
10418 .map(|active_group| active_group.group_id);
10419 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10420 active_diagnostics
10421 .primary_range
10422 .to_offset(&buffer)
10423 .to_inclusive()
10424 });
10425 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10426 if active_primary_range.contains(&selection.head()) {
10427 *active_primary_range.start()
10428 } else {
10429 selection.head()
10430 }
10431 } else {
10432 selection.head()
10433 };
10434
10435 let snapshot = self.snapshot(window, cx);
10436 let primary_diagnostics_before = buffer
10437 .diagnostics_in_range::<usize>(0..search_start)
10438 .filter(|entry| entry.diagnostic.is_primary)
10439 .filter(|entry| entry.range.start != entry.range.end)
10440 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10441 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10442 .collect::<Vec<_>>();
10443 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10444 primary_diagnostics_before
10445 .iter()
10446 .position(|entry| entry.diagnostic.group_id == active_group_id)
10447 });
10448
10449 let primary_diagnostics_after = buffer
10450 .diagnostics_in_range::<usize>(search_start..buffer.len())
10451 .filter(|entry| entry.diagnostic.is_primary)
10452 .filter(|entry| entry.range.start != entry.range.end)
10453 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10454 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10455 .collect::<Vec<_>>();
10456 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10457 primary_diagnostics_after
10458 .iter()
10459 .enumerate()
10460 .rev()
10461 .find_map(|(i, entry)| {
10462 if entry.diagnostic.group_id == active_group_id {
10463 Some(i)
10464 } else {
10465 None
10466 }
10467 })
10468 });
10469
10470 let next_primary_diagnostic = match direction {
10471 Direction::Prev => primary_diagnostics_before
10472 .iter()
10473 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10474 .rev()
10475 .next(),
10476 Direction::Next => primary_diagnostics_after
10477 .iter()
10478 .skip(
10479 last_same_group_diagnostic_after
10480 .map(|index| index + 1)
10481 .unwrap_or(0),
10482 )
10483 .next(),
10484 };
10485
10486 // Cycle around to the start of the buffer, potentially moving back to the start of
10487 // the currently active diagnostic.
10488 let cycle_around = || match direction {
10489 Direction::Prev => primary_diagnostics_after
10490 .iter()
10491 .rev()
10492 .chain(primary_diagnostics_before.iter().rev())
10493 .next(),
10494 Direction::Next => primary_diagnostics_before
10495 .iter()
10496 .chain(primary_diagnostics_after.iter())
10497 .next(),
10498 };
10499
10500 if let Some((primary_range, group_id)) = next_primary_diagnostic
10501 .or_else(cycle_around)
10502 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10503 {
10504 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10505 return;
10506 };
10507 self.activate_diagnostics(buffer_id, group_id, window, cx);
10508 if self.active_diagnostics.is_some() {
10509 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10510 s.select(vec![Selection {
10511 id: selection.id,
10512 start: primary_range.start,
10513 end: primary_range.start,
10514 reversed: false,
10515 goal: SelectionGoal::None,
10516 }]);
10517 });
10518 self.refresh_inline_completion(false, true, window, cx);
10519 }
10520 }
10521 }
10522
10523 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10524 let snapshot = self.snapshot(window, cx);
10525 let selection = self.selections.newest::<Point>(cx);
10526 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10527 }
10528
10529 fn go_to_hunk_after_position(
10530 &mut self,
10531 snapshot: &EditorSnapshot,
10532 position: Point,
10533 window: &mut Window,
10534 cx: &mut Context<Editor>,
10535 ) -> Option<MultiBufferDiffHunk> {
10536 let mut hunk = snapshot
10537 .buffer_snapshot
10538 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10539 .find(|hunk| hunk.row_range.start.0 > position.row);
10540 if hunk.is_none() {
10541 hunk = snapshot
10542 .buffer_snapshot
10543 .diff_hunks_in_range(Point::zero()..position)
10544 .find(|hunk| hunk.row_range.end.0 < position.row)
10545 }
10546 if let Some(hunk) = &hunk {
10547 let destination = Point::new(hunk.row_range.start.0, 0);
10548 self.unfold_ranges(&[destination..destination], false, false, cx);
10549 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10550 s.select_ranges(vec![destination..destination]);
10551 });
10552 }
10553
10554 hunk
10555 }
10556
10557 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10558 let snapshot = self.snapshot(window, cx);
10559 let selection = self.selections.newest::<Point>(cx);
10560 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10561 }
10562
10563 fn go_to_hunk_before_position(
10564 &mut self,
10565 snapshot: &EditorSnapshot,
10566 position: Point,
10567 window: &mut Window,
10568 cx: &mut Context<Editor>,
10569 ) -> Option<MultiBufferDiffHunk> {
10570 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10571 if hunk.is_none() {
10572 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10573 }
10574 if let Some(hunk) = &hunk {
10575 let destination = Point::new(hunk.row_range.start.0, 0);
10576 self.unfold_ranges(&[destination..destination], false, false, cx);
10577 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10578 s.select_ranges(vec![destination..destination]);
10579 });
10580 }
10581
10582 hunk
10583 }
10584
10585 pub fn go_to_definition(
10586 &mut self,
10587 _: &GoToDefinition,
10588 window: &mut Window,
10589 cx: &mut Context<Self>,
10590 ) -> Task<Result<Navigated>> {
10591 let definition =
10592 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10593 cx.spawn_in(window, |editor, mut cx| async move {
10594 if definition.await? == Navigated::Yes {
10595 return Ok(Navigated::Yes);
10596 }
10597 match editor.update_in(&mut cx, |editor, window, cx| {
10598 editor.find_all_references(&FindAllReferences, window, cx)
10599 })? {
10600 Some(references) => references.await,
10601 None => Ok(Navigated::No),
10602 }
10603 })
10604 }
10605
10606 pub fn go_to_declaration(
10607 &mut self,
10608 _: &GoToDeclaration,
10609 window: &mut Window,
10610 cx: &mut Context<Self>,
10611 ) -> Task<Result<Navigated>> {
10612 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10613 }
10614
10615 pub fn go_to_declaration_split(
10616 &mut self,
10617 _: &GoToDeclaration,
10618 window: &mut Window,
10619 cx: &mut Context<Self>,
10620 ) -> Task<Result<Navigated>> {
10621 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10622 }
10623
10624 pub fn go_to_implementation(
10625 &mut self,
10626 _: &GoToImplementation,
10627 window: &mut Window,
10628 cx: &mut Context<Self>,
10629 ) -> Task<Result<Navigated>> {
10630 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10631 }
10632
10633 pub fn go_to_implementation_split(
10634 &mut self,
10635 _: &GoToImplementationSplit,
10636 window: &mut Window,
10637 cx: &mut Context<Self>,
10638 ) -> Task<Result<Navigated>> {
10639 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10640 }
10641
10642 pub fn go_to_type_definition(
10643 &mut self,
10644 _: &GoToTypeDefinition,
10645 window: &mut Window,
10646 cx: &mut Context<Self>,
10647 ) -> Task<Result<Navigated>> {
10648 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10649 }
10650
10651 pub fn go_to_definition_split(
10652 &mut self,
10653 _: &GoToDefinitionSplit,
10654 window: &mut Window,
10655 cx: &mut Context<Self>,
10656 ) -> Task<Result<Navigated>> {
10657 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10658 }
10659
10660 pub fn go_to_type_definition_split(
10661 &mut self,
10662 _: &GoToTypeDefinitionSplit,
10663 window: &mut Window,
10664 cx: &mut Context<Self>,
10665 ) -> Task<Result<Navigated>> {
10666 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10667 }
10668
10669 fn go_to_definition_of_kind(
10670 &mut self,
10671 kind: GotoDefinitionKind,
10672 split: bool,
10673 window: &mut Window,
10674 cx: &mut Context<Self>,
10675 ) -> Task<Result<Navigated>> {
10676 let Some(provider) = self.semantics_provider.clone() else {
10677 return Task::ready(Ok(Navigated::No));
10678 };
10679 let head = self.selections.newest::<usize>(cx).head();
10680 let buffer = self.buffer.read(cx);
10681 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10682 text_anchor
10683 } else {
10684 return Task::ready(Ok(Navigated::No));
10685 };
10686
10687 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10688 return Task::ready(Ok(Navigated::No));
10689 };
10690
10691 cx.spawn_in(window, |editor, mut cx| async move {
10692 let definitions = definitions.await?;
10693 let navigated = editor
10694 .update_in(&mut cx, |editor, window, cx| {
10695 editor.navigate_to_hover_links(
10696 Some(kind),
10697 definitions
10698 .into_iter()
10699 .filter(|location| {
10700 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10701 })
10702 .map(HoverLink::Text)
10703 .collect::<Vec<_>>(),
10704 split,
10705 window,
10706 cx,
10707 )
10708 })?
10709 .await?;
10710 anyhow::Ok(navigated)
10711 })
10712 }
10713
10714 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10715 let selection = self.selections.newest_anchor();
10716 let head = selection.head();
10717 let tail = selection.tail();
10718
10719 let Some((buffer, start_position)) =
10720 self.buffer.read(cx).text_anchor_for_position(head, cx)
10721 else {
10722 return;
10723 };
10724
10725 let end_position = if head != tail {
10726 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10727 return;
10728 };
10729 Some(pos)
10730 } else {
10731 None
10732 };
10733
10734 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10735 let url = if let Some(end_pos) = end_position {
10736 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10737 } else {
10738 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10739 };
10740
10741 if let Some(url) = url {
10742 editor.update(&mut cx, |_, cx| {
10743 cx.open_url(&url);
10744 })
10745 } else {
10746 Ok(())
10747 }
10748 });
10749
10750 url_finder.detach();
10751 }
10752
10753 pub fn open_selected_filename(
10754 &mut self,
10755 _: &OpenSelectedFilename,
10756 window: &mut Window,
10757 cx: &mut Context<Self>,
10758 ) {
10759 let Some(workspace) = self.workspace() else {
10760 return;
10761 };
10762
10763 let position = self.selections.newest_anchor().head();
10764
10765 let Some((buffer, buffer_position)) =
10766 self.buffer.read(cx).text_anchor_for_position(position, cx)
10767 else {
10768 return;
10769 };
10770
10771 let project = self.project.clone();
10772
10773 cx.spawn_in(window, |_, mut cx| async move {
10774 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10775
10776 if let Some((_, path)) = result {
10777 workspace
10778 .update_in(&mut cx, |workspace, window, cx| {
10779 workspace.open_resolved_path(path, window, cx)
10780 })?
10781 .await?;
10782 }
10783 anyhow::Ok(())
10784 })
10785 .detach();
10786 }
10787
10788 pub(crate) fn navigate_to_hover_links(
10789 &mut self,
10790 kind: Option<GotoDefinitionKind>,
10791 mut definitions: Vec<HoverLink>,
10792 split: bool,
10793 window: &mut Window,
10794 cx: &mut Context<Editor>,
10795 ) -> Task<Result<Navigated>> {
10796 // If there is one definition, just open it directly
10797 if definitions.len() == 1 {
10798 let definition = definitions.pop().unwrap();
10799
10800 enum TargetTaskResult {
10801 Location(Option<Location>),
10802 AlreadyNavigated,
10803 }
10804
10805 let target_task = match definition {
10806 HoverLink::Text(link) => {
10807 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10808 }
10809 HoverLink::InlayHint(lsp_location, server_id) => {
10810 let computation =
10811 self.compute_target_location(lsp_location, server_id, window, cx);
10812 cx.background_executor().spawn(async move {
10813 let location = computation.await?;
10814 Ok(TargetTaskResult::Location(location))
10815 })
10816 }
10817 HoverLink::Url(url) => {
10818 cx.open_url(&url);
10819 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10820 }
10821 HoverLink::File(path) => {
10822 if let Some(workspace) = self.workspace() {
10823 cx.spawn_in(window, |_, mut cx| async move {
10824 workspace
10825 .update_in(&mut cx, |workspace, window, cx| {
10826 workspace.open_resolved_path(path, window, cx)
10827 })?
10828 .await
10829 .map(|_| TargetTaskResult::AlreadyNavigated)
10830 })
10831 } else {
10832 Task::ready(Ok(TargetTaskResult::Location(None)))
10833 }
10834 }
10835 };
10836 cx.spawn_in(window, |editor, mut cx| async move {
10837 let target = match target_task.await.context("target resolution task")? {
10838 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10839 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10840 TargetTaskResult::Location(Some(target)) => target,
10841 };
10842
10843 editor.update_in(&mut cx, |editor, window, cx| {
10844 let Some(workspace) = editor.workspace() else {
10845 return Navigated::No;
10846 };
10847 let pane = workspace.read(cx).active_pane().clone();
10848
10849 let range = target.range.to_point(target.buffer.read(cx));
10850 let range = editor.range_for_match(&range);
10851 let range = collapse_multiline_range(range);
10852
10853 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10854 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10855 } else {
10856 window.defer(cx, move |window, cx| {
10857 let target_editor: Entity<Self> =
10858 workspace.update(cx, |workspace, cx| {
10859 let pane = if split {
10860 workspace.adjacent_pane(window, cx)
10861 } else {
10862 workspace.active_pane().clone()
10863 };
10864
10865 workspace.open_project_item(
10866 pane,
10867 target.buffer.clone(),
10868 true,
10869 true,
10870 window,
10871 cx,
10872 )
10873 });
10874 target_editor.update(cx, |target_editor, cx| {
10875 // When selecting a definition in a different buffer, disable the nav history
10876 // to avoid creating a history entry at the previous cursor location.
10877 pane.update(cx, |pane, _| pane.disable_history());
10878 target_editor.go_to_singleton_buffer_range(range, window, cx);
10879 pane.update(cx, |pane, _| pane.enable_history());
10880 });
10881 });
10882 }
10883 Navigated::Yes
10884 })
10885 })
10886 } else if !definitions.is_empty() {
10887 cx.spawn_in(window, |editor, mut cx| async move {
10888 let (title, location_tasks, workspace) = editor
10889 .update_in(&mut cx, |editor, window, cx| {
10890 let tab_kind = match kind {
10891 Some(GotoDefinitionKind::Implementation) => "Implementations",
10892 _ => "Definitions",
10893 };
10894 let title = definitions
10895 .iter()
10896 .find_map(|definition| match definition {
10897 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10898 let buffer = origin.buffer.read(cx);
10899 format!(
10900 "{} for {}",
10901 tab_kind,
10902 buffer
10903 .text_for_range(origin.range.clone())
10904 .collect::<String>()
10905 )
10906 }),
10907 HoverLink::InlayHint(_, _) => None,
10908 HoverLink::Url(_) => None,
10909 HoverLink::File(_) => None,
10910 })
10911 .unwrap_or(tab_kind.to_string());
10912 let location_tasks = definitions
10913 .into_iter()
10914 .map(|definition| match definition {
10915 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10916 HoverLink::InlayHint(lsp_location, server_id) => editor
10917 .compute_target_location(lsp_location, server_id, window, cx),
10918 HoverLink::Url(_) => Task::ready(Ok(None)),
10919 HoverLink::File(_) => Task::ready(Ok(None)),
10920 })
10921 .collect::<Vec<_>>();
10922 (title, location_tasks, editor.workspace().clone())
10923 })
10924 .context("location tasks preparation")?;
10925
10926 let locations = future::join_all(location_tasks)
10927 .await
10928 .into_iter()
10929 .filter_map(|location| location.transpose())
10930 .collect::<Result<_>>()
10931 .context("location tasks")?;
10932
10933 let Some(workspace) = workspace else {
10934 return Ok(Navigated::No);
10935 };
10936 let opened = workspace
10937 .update_in(&mut cx, |workspace, window, cx| {
10938 Self::open_locations_in_multibuffer(
10939 workspace,
10940 locations,
10941 title,
10942 split,
10943 MultibufferSelectionMode::First,
10944 window,
10945 cx,
10946 )
10947 })
10948 .ok();
10949
10950 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10951 })
10952 } else {
10953 Task::ready(Ok(Navigated::No))
10954 }
10955 }
10956
10957 fn compute_target_location(
10958 &self,
10959 lsp_location: lsp::Location,
10960 server_id: LanguageServerId,
10961 window: &mut Window,
10962 cx: &mut Context<Self>,
10963 ) -> Task<anyhow::Result<Option<Location>>> {
10964 let Some(project) = self.project.clone() else {
10965 return Task::ready(Ok(None));
10966 };
10967
10968 cx.spawn_in(window, move |editor, mut cx| async move {
10969 let location_task = editor.update(&mut cx, |_, cx| {
10970 project.update(cx, |project, cx| {
10971 let language_server_name = project
10972 .language_server_statuses(cx)
10973 .find(|(id, _)| server_id == *id)
10974 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10975 language_server_name.map(|language_server_name| {
10976 project.open_local_buffer_via_lsp(
10977 lsp_location.uri.clone(),
10978 server_id,
10979 language_server_name,
10980 cx,
10981 )
10982 })
10983 })
10984 })?;
10985 let location = match location_task {
10986 Some(task) => Some({
10987 let target_buffer_handle = task.await.context("open local buffer")?;
10988 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10989 let target_start = target_buffer
10990 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10991 let target_end = target_buffer
10992 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10993 target_buffer.anchor_after(target_start)
10994 ..target_buffer.anchor_before(target_end)
10995 })?;
10996 Location {
10997 buffer: target_buffer_handle,
10998 range,
10999 }
11000 }),
11001 None => None,
11002 };
11003 Ok(location)
11004 })
11005 }
11006
11007 pub fn find_all_references(
11008 &mut self,
11009 _: &FindAllReferences,
11010 window: &mut Window,
11011 cx: &mut Context<Self>,
11012 ) -> Option<Task<Result<Navigated>>> {
11013 let selection = self.selections.newest::<usize>(cx);
11014 let multi_buffer = self.buffer.read(cx);
11015 let head = selection.head();
11016
11017 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11018 let head_anchor = multi_buffer_snapshot.anchor_at(
11019 head,
11020 if head < selection.tail() {
11021 Bias::Right
11022 } else {
11023 Bias::Left
11024 },
11025 );
11026
11027 match self
11028 .find_all_references_task_sources
11029 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11030 {
11031 Ok(_) => {
11032 log::info!(
11033 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11034 );
11035 return None;
11036 }
11037 Err(i) => {
11038 self.find_all_references_task_sources.insert(i, head_anchor);
11039 }
11040 }
11041
11042 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11043 let workspace = self.workspace()?;
11044 let project = workspace.read(cx).project().clone();
11045 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11046 Some(cx.spawn_in(window, |editor, mut cx| async move {
11047 let _cleanup = defer({
11048 let mut cx = cx.clone();
11049 move || {
11050 let _ = editor.update(&mut cx, |editor, _| {
11051 if let Ok(i) =
11052 editor
11053 .find_all_references_task_sources
11054 .binary_search_by(|anchor| {
11055 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11056 })
11057 {
11058 editor.find_all_references_task_sources.remove(i);
11059 }
11060 });
11061 }
11062 });
11063
11064 let locations = references.await?;
11065 if locations.is_empty() {
11066 return anyhow::Ok(Navigated::No);
11067 }
11068
11069 workspace.update_in(&mut cx, |workspace, window, cx| {
11070 let title = locations
11071 .first()
11072 .as_ref()
11073 .map(|location| {
11074 let buffer = location.buffer.read(cx);
11075 format!(
11076 "References to `{}`",
11077 buffer
11078 .text_for_range(location.range.clone())
11079 .collect::<String>()
11080 )
11081 })
11082 .unwrap();
11083 Self::open_locations_in_multibuffer(
11084 workspace,
11085 locations,
11086 title,
11087 false,
11088 MultibufferSelectionMode::First,
11089 window,
11090 cx,
11091 );
11092 Navigated::Yes
11093 })
11094 }))
11095 }
11096
11097 /// Opens a multibuffer with the given project locations in it
11098 pub fn open_locations_in_multibuffer(
11099 workspace: &mut Workspace,
11100 mut locations: Vec<Location>,
11101 title: String,
11102 split: bool,
11103 multibuffer_selection_mode: MultibufferSelectionMode,
11104 window: &mut Window,
11105 cx: &mut Context<Workspace>,
11106 ) {
11107 // If there are multiple definitions, open them in a multibuffer
11108 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11109 let mut locations = locations.into_iter().peekable();
11110 let mut ranges = Vec::new();
11111 let capability = workspace.project().read(cx).capability();
11112
11113 let excerpt_buffer = cx.new(|cx| {
11114 let mut multibuffer = MultiBuffer::new(capability);
11115 while let Some(location) = locations.next() {
11116 let buffer = location.buffer.read(cx);
11117 let mut ranges_for_buffer = Vec::new();
11118 let range = location.range.to_offset(buffer);
11119 ranges_for_buffer.push(range.clone());
11120
11121 while let Some(next_location) = locations.peek() {
11122 if next_location.buffer == location.buffer {
11123 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11124 locations.next();
11125 } else {
11126 break;
11127 }
11128 }
11129
11130 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11131 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11132 location.buffer.clone(),
11133 ranges_for_buffer,
11134 DEFAULT_MULTIBUFFER_CONTEXT,
11135 cx,
11136 ))
11137 }
11138
11139 multibuffer.with_title(title)
11140 });
11141
11142 let editor = cx.new(|cx| {
11143 Editor::for_multibuffer(
11144 excerpt_buffer,
11145 Some(workspace.project().clone()),
11146 true,
11147 window,
11148 cx,
11149 )
11150 });
11151 editor.update(cx, |editor, cx| {
11152 match multibuffer_selection_mode {
11153 MultibufferSelectionMode::First => {
11154 if let Some(first_range) = ranges.first() {
11155 editor.change_selections(None, window, cx, |selections| {
11156 selections.clear_disjoint();
11157 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11158 });
11159 }
11160 editor.highlight_background::<Self>(
11161 &ranges,
11162 |theme| theme.editor_highlighted_line_background,
11163 cx,
11164 );
11165 }
11166 MultibufferSelectionMode::All => {
11167 editor.change_selections(None, window, cx, |selections| {
11168 selections.clear_disjoint();
11169 selections.select_anchor_ranges(ranges);
11170 });
11171 }
11172 }
11173 editor.register_buffers_with_language_servers(cx);
11174 });
11175
11176 let item = Box::new(editor);
11177 let item_id = item.item_id();
11178
11179 if split {
11180 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11181 } else {
11182 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11183 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11184 pane.close_current_preview_item(window, cx)
11185 } else {
11186 None
11187 }
11188 });
11189 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11190 }
11191 workspace.active_pane().update(cx, |pane, cx| {
11192 pane.set_preview_item_id(Some(item_id), cx);
11193 });
11194 }
11195
11196 pub fn rename(
11197 &mut self,
11198 _: &Rename,
11199 window: &mut Window,
11200 cx: &mut Context<Self>,
11201 ) -> Option<Task<Result<()>>> {
11202 use language::ToOffset as _;
11203
11204 let provider = self.semantics_provider.clone()?;
11205 let selection = self.selections.newest_anchor().clone();
11206 let (cursor_buffer, cursor_buffer_position) = self
11207 .buffer
11208 .read(cx)
11209 .text_anchor_for_position(selection.head(), cx)?;
11210 let (tail_buffer, cursor_buffer_position_end) = self
11211 .buffer
11212 .read(cx)
11213 .text_anchor_for_position(selection.tail(), cx)?;
11214 if tail_buffer != cursor_buffer {
11215 return None;
11216 }
11217
11218 let snapshot = cursor_buffer.read(cx).snapshot();
11219 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11220 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11221 let prepare_rename = provider
11222 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11223 .unwrap_or_else(|| Task::ready(Ok(None)));
11224 drop(snapshot);
11225
11226 Some(cx.spawn_in(window, |this, mut cx| async move {
11227 let rename_range = if let Some(range) = prepare_rename.await? {
11228 Some(range)
11229 } else {
11230 this.update(&mut cx, |this, cx| {
11231 let buffer = this.buffer.read(cx).snapshot(cx);
11232 let mut buffer_highlights = this
11233 .document_highlights_for_position(selection.head(), &buffer)
11234 .filter(|highlight| {
11235 highlight.start.excerpt_id == selection.head().excerpt_id
11236 && highlight.end.excerpt_id == selection.head().excerpt_id
11237 });
11238 buffer_highlights
11239 .next()
11240 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11241 })?
11242 };
11243 if let Some(rename_range) = rename_range {
11244 this.update_in(&mut cx, |this, window, cx| {
11245 let snapshot = cursor_buffer.read(cx).snapshot();
11246 let rename_buffer_range = rename_range.to_offset(&snapshot);
11247 let cursor_offset_in_rename_range =
11248 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11249 let cursor_offset_in_rename_range_end =
11250 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11251
11252 this.take_rename(false, window, cx);
11253 let buffer = this.buffer.read(cx).read(cx);
11254 let cursor_offset = selection.head().to_offset(&buffer);
11255 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11256 let rename_end = rename_start + rename_buffer_range.len();
11257 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11258 let mut old_highlight_id = None;
11259 let old_name: Arc<str> = buffer
11260 .chunks(rename_start..rename_end, true)
11261 .map(|chunk| {
11262 if old_highlight_id.is_none() {
11263 old_highlight_id = chunk.syntax_highlight_id;
11264 }
11265 chunk.text
11266 })
11267 .collect::<String>()
11268 .into();
11269
11270 drop(buffer);
11271
11272 // Position the selection in the rename editor so that it matches the current selection.
11273 this.show_local_selections = false;
11274 let rename_editor = cx.new(|cx| {
11275 let mut editor = Editor::single_line(window, cx);
11276 editor.buffer.update(cx, |buffer, cx| {
11277 buffer.edit([(0..0, old_name.clone())], None, cx)
11278 });
11279 let rename_selection_range = match cursor_offset_in_rename_range
11280 .cmp(&cursor_offset_in_rename_range_end)
11281 {
11282 Ordering::Equal => {
11283 editor.select_all(&SelectAll, window, cx);
11284 return editor;
11285 }
11286 Ordering::Less => {
11287 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11288 }
11289 Ordering::Greater => {
11290 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11291 }
11292 };
11293 if rename_selection_range.end > old_name.len() {
11294 editor.select_all(&SelectAll, window, cx);
11295 } else {
11296 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11297 s.select_ranges([rename_selection_range]);
11298 });
11299 }
11300 editor
11301 });
11302 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11303 if e == &EditorEvent::Focused {
11304 cx.emit(EditorEvent::FocusedIn)
11305 }
11306 })
11307 .detach();
11308
11309 let write_highlights =
11310 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11311 let read_highlights =
11312 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11313 let ranges = write_highlights
11314 .iter()
11315 .flat_map(|(_, ranges)| ranges.iter())
11316 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11317 .cloned()
11318 .collect();
11319
11320 this.highlight_text::<Rename>(
11321 ranges,
11322 HighlightStyle {
11323 fade_out: Some(0.6),
11324 ..Default::default()
11325 },
11326 cx,
11327 );
11328 let rename_focus_handle = rename_editor.focus_handle(cx);
11329 window.focus(&rename_focus_handle);
11330 let block_id = this.insert_blocks(
11331 [BlockProperties {
11332 style: BlockStyle::Flex,
11333 placement: BlockPlacement::Below(range.start),
11334 height: 1,
11335 render: Arc::new({
11336 let rename_editor = rename_editor.clone();
11337 move |cx: &mut BlockContext| {
11338 let mut text_style = cx.editor_style.text.clone();
11339 if let Some(highlight_style) = old_highlight_id
11340 .and_then(|h| h.style(&cx.editor_style.syntax))
11341 {
11342 text_style = text_style.highlight(highlight_style);
11343 }
11344 div()
11345 .block_mouse_down()
11346 .pl(cx.anchor_x)
11347 .child(EditorElement::new(
11348 &rename_editor,
11349 EditorStyle {
11350 background: cx.theme().system().transparent,
11351 local_player: cx.editor_style.local_player,
11352 text: text_style,
11353 scrollbar_width: cx.editor_style.scrollbar_width,
11354 syntax: cx.editor_style.syntax.clone(),
11355 status: cx.editor_style.status.clone(),
11356 inlay_hints_style: HighlightStyle {
11357 font_weight: Some(FontWeight::BOLD),
11358 ..make_inlay_hints_style(cx.app)
11359 },
11360 inline_completion_styles: make_suggestion_styles(
11361 cx.app,
11362 ),
11363 ..EditorStyle::default()
11364 },
11365 ))
11366 .into_any_element()
11367 }
11368 }),
11369 priority: 0,
11370 }],
11371 Some(Autoscroll::fit()),
11372 cx,
11373 )[0];
11374 this.pending_rename = Some(RenameState {
11375 range,
11376 old_name,
11377 editor: rename_editor,
11378 block_id,
11379 });
11380 })?;
11381 }
11382
11383 Ok(())
11384 }))
11385 }
11386
11387 pub fn confirm_rename(
11388 &mut self,
11389 _: &ConfirmRename,
11390 window: &mut Window,
11391 cx: &mut Context<Self>,
11392 ) -> Option<Task<Result<()>>> {
11393 let rename = self.take_rename(false, window, cx)?;
11394 let workspace = self.workspace()?.downgrade();
11395 let (buffer, start) = self
11396 .buffer
11397 .read(cx)
11398 .text_anchor_for_position(rename.range.start, cx)?;
11399 let (end_buffer, _) = self
11400 .buffer
11401 .read(cx)
11402 .text_anchor_for_position(rename.range.end, cx)?;
11403 if buffer != end_buffer {
11404 return None;
11405 }
11406
11407 let old_name = rename.old_name;
11408 let new_name = rename.editor.read(cx).text(cx);
11409
11410 let rename = self.semantics_provider.as_ref()?.perform_rename(
11411 &buffer,
11412 start,
11413 new_name.clone(),
11414 cx,
11415 )?;
11416
11417 Some(cx.spawn_in(window, |editor, mut cx| async move {
11418 let project_transaction = rename.await?;
11419 Self::open_project_transaction(
11420 &editor,
11421 workspace,
11422 project_transaction,
11423 format!("Rename: {} → {}", old_name, new_name),
11424 cx.clone(),
11425 )
11426 .await?;
11427
11428 editor.update(&mut cx, |editor, cx| {
11429 editor.refresh_document_highlights(cx);
11430 })?;
11431 Ok(())
11432 }))
11433 }
11434
11435 fn take_rename(
11436 &mut self,
11437 moving_cursor: bool,
11438 window: &mut Window,
11439 cx: &mut Context<Self>,
11440 ) -> Option<RenameState> {
11441 let rename = self.pending_rename.take()?;
11442 if rename.editor.focus_handle(cx).is_focused(window) {
11443 window.focus(&self.focus_handle);
11444 }
11445
11446 self.remove_blocks(
11447 [rename.block_id].into_iter().collect(),
11448 Some(Autoscroll::fit()),
11449 cx,
11450 );
11451 self.clear_highlights::<Rename>(cx);
11452 self.show_local_selections = true;
11453
11454 if moving_cursor {
11455 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11456 editor.selections.newest::<usize>(cx).head()
11457 });
11458
11459 // Update the selection to match the position of the selection inside
11460 // the rename editor.
11461 let snapshot = self.buffer.read(cx).read(cx);
11462 let rename_range = rename.range.to_offset(&snapshot);
11463 let cursor_in_editor = snapshot
11464 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11465 .min(rename_range.end);
11466 drop(snapshot);
11467
11468 self.change_selections(None, window, cx, |s| {
11469 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11470 });
11471 } else {
11472 self.refresh_document_highlights(cx);
11473 }
11474
11475 Some(rename)
11476 }
11477
11478 pub fn pending_rename(&self) -> Option<&RenameState> {
11479 self.pending_rename.as_ref()
11480 }
11481
11482 fn format(
11483 &mut self,
11484 _: &Format,
11485 window: &mut Window,
11486 cx: &mut Context<Self>,
11487 ) -> Option<Task<Result<()>>> {
11488 let project = match &self.project {
11489 Some(project) => project.clone(),
11490 None => return None,
11491 };
11492
11493 Some(self.perform_format(
11494 project,
11495 FormatTrigger::Manual,
11496 FormatTarget::Buffers,
11497 window,
11498 cx,
11499 ))
11500 }
11501
11502 fn format_selections(
11503 &mut self,
11504 _: &FormatSelections,
11505 window: &mut Window,
11506 cx: &mut Context<Self>,
11507 ) -> Option<Task<Result<()>>> {
11508 let project = match &self.project {
11509 Some(project) => project.clone(),
11510 None => return None,
11511 };
11512
11513 let ranges = self
11514 .selections
11515 .all_adjusted(cx)
11516 .into_iter()
11517 .map(|selection| selection.range())
11518 .collect_vec();
11519
11520 Some(self.perform_format(
11521 project,
11522 FormatTrigger::Manual,
11523 FormatTarget::Ranges(ranges),
11524 window,
11525 cx,
11526 ))
11527 }
11528
11529 fn perform_format(
11530 &mut self,
11531 project: Entity<Project>,
11532 trigger: FormatTrigger,
11533 target: FormatTarget,
11534 window: &mut Window,
11535 cx: &mut Context<Self>,
11536 ) -> Task<Result<()>> {
11537 let buffer = self.buffer.clone();
11538 let (buffers, target) = match target {
11539 FormatTarget::Buffers => {
11540 let mut buffers = buffer.read(cx).all_buffers();
11541 if trigger == FormatTrigger::Save {
11542 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11543 }
11544 (buffers, LspFormatTarget::Buffers)
11545 }
11546 FormatTarget::Ranges(selection_ranges) => {
11547 let multi_buffer = buffer.read(cx);
11548 let snapshot = multi_buffer.read(cx);
11549 let mut buffers = HashSet::default();
11550 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11551 BTreeMap::new();
11552 for selection_range in selection_ranges {
11553 for (buffer, buffer_range, _) in
11554 snapshot.range_to_buffer_ranges(selection_range)
11555 {
11556 let buffer_id = buffer.remote_id();
11557 let start = buffer.anchor_before(buffer_range.start);
11558 let end = buffer.anchor_after(buffer_range.end);
11559 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11560 buffer_id_to_ranges
11561 .entry(buffer_id)
11562 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11563 .or_insert_with(|| vec![start..end]);
11564 }
11565 }
11566 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11567 }
11568 };
11569
11570 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11571 let format = project.update(cx, |project, cx| {
11572 project.format(buffers, target, true, trigger, cx)
11573 });
11574
11575 cx.spawn_in(window, |_, mut cx| async move {
11576 let transaction = futures::select_biased! {
11577 () = timeout => {
11578 log::warn!("timed out waiting for formatting");
11579 None
11580 }
11581 transaction = format.log_err().fuse() => transaction,
11582 };
11583
11584 buffer
11585 .update(&mut cx, |buffer, cx| {
11586 if let Some(transaction) = transaction {
11587 if !buffer.is_singleton() {
11588 buffer.push_transaction(&transaction.0, cx);
11589 }
11590 }
11591
11592 cx.notify();
11593 })
11594 .ok();
11595
11596 Ok(())
11597 })
11598 }
11599
11600 fn restart_language_server(
11601 &mut self,
11602 _: &RestartLanguageServer,
11603 _: &mut Window,
11604 cx: &mut Context<Self>,
11605 ) {
11606 if let Some(project) = self.project.clone() {
11607 self.buffer.update(cx, |multi_buffer, cx| {
11608 project.update(cx, |project, cx| {
11609 project.restart_language_servers_for_buffers(
11610 multi_buffer.all_buffers().into_iter().collect(),
11611 cx,
11612 );
11613 });
11614 })
11615 }
11616 }
11617
11618 fn cancel_language_server_work(
11619 workspace: &mut Workspace,
11620 _: &actions::CancelLanguageServerWork,
11621 _: &mut Window,
11622 cx: &mut Context<Workspace>,
11623 ) {
11624 let project = workspace.project();
11625 let buffers = workspace
11626 .active_item(cx)
11627 .and_then(|item| item.act_as::<Editor>(cx))
11628 .map_or(HashSet::default(), |editor| {
11629 editor.read(cx).buffer.read(cx).all_buffers()
11630 });
11631 project.update(cx, |project, cx| {
11632 project.cancel_language_server_work_for_buffers(buffers, cx);
11633 });
11634 }
11635
11636 fn show_character_palette(
11637 &mut self,
11638 _: &ShowCharacterPalette,
11639 window: &mut Window,
11640 _: &mut Context<Self>,
11641 ) {
11642 window.show_character_palette();
11643 }
11644
11645 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11646 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11647 let buffer = self.buffer.read(cx).snapshot(cx);
11648 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11649 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11650 let is_valid = buffer
11651 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11652 .any(|entry| {
11653 entry.diagnostic.is_primary
11654 && !entry.range.is_empty()
11655 && entry.range.start == primary_range_start
11656 && entry.diagnostic.message == active_diagnostics.primary_message
11657 });
11658
11659 if is_valid != active_diagnostics.is_valid {
11660 active_diagnostics.is_valid = is_valid;
11661 let mut new_styles = HashMap::default();
11662 for (block_id, diagnostic) in &active_diagnostics.blocks {
11663 new_styles.insert(
11664 *block_id,
11665 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11666 );
11667 }
11668 self.display_map.update(cx, |display_map, _cx| {
11669 display_map.replace_blocks(new_styles)
11670 });
11671 }
11672 }
11673 }
11674
11675 fn activate_diagnostics(
11676 &mut self,
11677 buffer_id: BufferId,
11678 group_id: usize,
11679 window: &mut Window,
11680 cx: &mut Context<Self>,
11681 ) {
11682 self.dismiss_diagnostics(cx);
11683 let snapshot = self.snapshot(window, cx);
11684 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11685 let buffer = self.buffer.read(cx).snapshot(cx);
11686
11687 let mut primary_range = None;
11688 let mut primary_message = None;
11689 let diagnostic_group = buffer
11690 .diagnostic_group(buffer_id, group_id)
11691 .filter_map(|entry| {
11692 let start = entry.range.start;
11693 let end = entry.range.end;
11694 if snapshot.is_line_folded(MultiBufferRow(start.row))
11695 && (start.row == end.row
11696 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11697 {
11698 return None;
11699 }
11700 if entry.diagnostic.is_primary {
11701 primary_range = Some(entry.range.clone());
11702 primary_message = Some(entry.diagnostic.message.clone());
11703 }
11704 Some(entry)
11705 })
11706 .collect::<Vec<_>>();
11707 let primary_range = primary_range?;
11708 let primary_message = primary_message?;
11709
11710 let blocks = display_map
11711 .insert_blocks(
11712 diagnostic_group.iter().map(|entry| {
11713 let diagnostic = entry.diagnostic.clone();
11714 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11715 BlockProperties {
11716 style: BlockStyle::Fixed,
11717 placement: BlockPlacement::Below(
11718 buffer.anchor_after(entry.range.start),
11719 ),
11720 height: message_height,
11721 render: diagnostic_block_renderer(diagnostic, None, true, true),
11722 priority: 0,
11723 }
11724 }),
11725 cx,
11726 )
11727 .into_iter()
11728 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11729 .collect();
11730
11731 Some(ActiveDiagnosticGroup {
11732 primary_range: buffer.anchor_before(primary_range.start)
11733 ..buffer.anchor_after(primary_range.end),
11734 primary_message,
11735 group_id,
11736 blocks,
11737 is_valid: true,
11738 })
11739 });
11740 }
11741
11742 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11743 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11744 self.display_map.update(cx, |display_map, cx| {
11745 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11746 });
11747 cx.notify();
11748 }
11749 }
11750
11751 pub fn set_selections_from_remote(
11752 &mut self,
11753 selections: Vec<Selection<Anchor>>,
11754 pending_selection: Option<Selection<Anchor>>,
11755 window: &mut Window,
11756 cx: &mut Context<Self>,
11757 ) {
11758 let old_cursor_position = self.selections.newest_anchor().head();
11759 self.selections.change_with(cx, |s| {
11760 s.select_anchors(selections);
11761 if let Some(pending_selection) = pending_selection {
11762 s.set_pending(pending_selection, SelectMode::Character);
11763 } else {
11764 s.clear_pending();
11765 }
11766 });
11767 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11768 }
11769
11770 fn push_to_selection_history(&mut self) {
11771 self.selection_history.push(SelectionHistoryEntry {
11772 selections: self.selections.disjoint_anchors(),
11773 select_next_state: self.select_next_state.clone(),
11774 select_prev_state: self.select_prev_state.clone(),
11775 add_selections_state: self.add_selections_state.clone(),
11776 });
11777 }
11778
11779 pub fn transact(
11780 &mut self,
11781 window: &mut Window,
11782 cx: &mut Context<Self>,
11783 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11784 ) -> Option<TransactionId> {
11785 self.start_transaction_at(Instant::now(), window, cx);
11786 update(self, window, cx);
11787 self.end_transaction_at(Instant::now(), cx)
11788 }
11789
11790 pub fn start_transaction_at(
11791 &mut self,
11792 now: Instant,
11793 window: &mut Window,
11794 cx: &mut Context<Self>,
11795 ) {
11796 self.end_selection(window, cx);
11797 if let Some(tx_id) = self
11798 .buffer
11799 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11800 {
11801 self.selection_history
11802 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11803 cx.emit(EditorEvent::TransactionBegun {
11804 transaction_id: tx_id,
11805 })
11806 }
11807 }
11808
11809 pub fn end_transaction_at(
11810 &mut self,
11811 now: Instant,
11812 cx: &mut Context<Self>,
11813 ) -> Option<TransactionId> {
11814 if let Some(transaction_id) = self
11815 .buffer
11816 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11817 {
11818 if let Some((_, end_selections)) =
11819 self.selection_history.transaction_mut(transaction_id)
11820 {
11821 *end_selections = Some(self.selections.disjoint_anchors());
11822 } else {
11823 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11824 }
11825
11826 cx.emit(EditorEvent::Edited { transaction_id });
11827 Some(transaction_id)
11828 } else {
11829 None
11830 }
11831 }
11832
11833 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11834 if self.selection_mark_mode {
11835 self.change_selections(None, window, cx, |s| {
11836 s.move_with(|_, sel| {
11837 sel.collapse_to(sel.head(), SelectionGoal::None);
11838 });
11839 })
11840 }
11841 self.selection_mark_mode = true;
11842 cx.notify();
11843 }
11844
11845 pub fn swap_selection_ends(
11846 &mut self,
11847 _: &actions::SwapSelectionEnds,
11848 window: &mut Window,
11849 cx: &mut Context<Self>,
11850 ) {
11851 self.change_selections(None, window, cx, |s| {
11852 s.move_with(|_, sel| {
11853 if sel.start != sel.end {
11854 sel.reversed = !sel.reversed
11855 }
11856 });
11857 });
11858 self.request_autoscroll(Autoscroll::newest(), cx);
11859 cx.notify();
11860 }
11861
11862 pub fn toggle_fold(
11863 &mut self,
11864 _: &actions::ToggleFold,
11865 window: &mut Window,
11866 cx: &mut Context<Self>,
11867 ) {
11868 if self.is_singleton(cx) {
11869 let selection = self.selections.newest::<Point>(cx);
11870
11871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11872 let range = if selection.is_empty() {
11873 let point = selection.head().to_display_point(&display_map);
11874 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11875 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11876 .to_point(&display_map);
11877 start..end
11878 } else {
11879 selection.range()
11880 };
11881 if display_map.folds_in_range(range).next().is_some() {
11882 self.unfold_lines(&Default::default(), window, cx)
11883 } else {
11884 self.fold(&Default::default(), window, cx)
11885 }
11886 } else {
11887 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11888 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11889 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11890 .map(|(snapshot, _, _)| snapshot.remote_id())
11891 .collect();
11892
11893 for buffer_id in buffer_ids {
11894 if self.is_buffer_folded(buffer_id, cx) {
11895 self.unfold_buffer(buffer_id, cx);
11896 } else {
11897 self.fold_buffer(buffer_id, cx);
11898 }
11899 }
11900 }
11901 }
11902
11903 pub fn toggle_fold_recursive(
11904 &mut self,
11905 _: &actions::ToggleFoldRecursive,
11906 window: &mut Window,
11907 cx: &mut Context<Self>,
11908 ) {
11909 let selection = self.selections.newest::<Point>(cx);
11910
11911 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11912 let range = if selection.is_empty() {
11913 let point = selection.head().to_display_point(&display_map);
11914 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11915 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11916 .to_point(&display_map);
11917 start..end
11918 } else {
11919 selection.range()
11920 };
11921 if display_map.folds_in_range(range).next().is_some() {
11922 self.unfold_recursive(&Default::default(), window, cx)
11923 } else {
11924 self.fold_recursive(&Default::default(), window, cx)
11925 }
11926 }
11927
11928 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11929 if self.is_singleton(cx) {
11930 let mut to_fold = Vec::new();
11931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11932 let selections = self.selections.all_adjusted(cx);
11933
11934 for selection in selections {
11935 let range = selection.range().sorted();
11936 let buffer_start_row = range.start.row;
11937
11938 if range.start.row != range.end.row {
11939 let mut found = false;
11940 let mut row = range.start.row;
11941 while row <= range.end.row {
11942 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11943 {
11944 found = true;
11945 row = crease.range().end.row + 1;
11946 to_fold.push(crease);
11947 } else {
11948 row += 1
11949 }
11950 }
11951 if found {
11952 continue;
11953 }
11954 }
11955
11956 for row in (0..=range.start.row).rev() {
11957 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11958 if crease.range().end.row >= buffer_start_row {
11959 to_fold.push(crease);
11960 if row <= range.start.row {
11961 break;
11962 }
11963 }
11964 }
11965 }
11966 }
11967
11968 self.fold_creases(to_fold, true, window, cx);
11969 } else {
11970 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11971
11972 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11973 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11974 .map(|(snapshot, _, _)| snapshot.remote_id())
11975 .collect();
11976 for buffer_id in buffer_ids {
11977 self.fold_buffer(buffer_id, cx);
11978 }
11979 }
11980 }
11981
11982 fn fold_at_level(
11983 &mut self,
11984 fold_at: &FoldAtLevel,
11985 window: &mut Window,
11986 cx: &mut Context<Self>,
11987 ) {
11988 if !self.buffer.read(cx).is_singleton() {
11989 return;
11990 }
11991
11992 let fold_at_level = fold_at.0;
11993 let snapshot = self.buffer.read(cx).snapshot(cx);
11994 let mut to_fold = Vec::new();
11995 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11996
11997 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11998 while start_row < end_row {
11999 match self
12000 .snapshot(window, cx)
12001 .crease_for_buffer_row(MultiBufferRow(start_row))
12002 {
12003 Some(crease) => {
12004 let nested_start_row = crease.range().start.row + 1;
12005 let nested_end_row = crease.range().end.row;
12006
12007 if current_level < fold_at_level {
12008 stack.push((nested_start_row, nested_end_row, current_level + 1));
12009 } else if current_level == fold_at_level {
12010 to_fold.push(crease);
12011 }
12012
12013 start_row = nested_end_row + 1;
12014 }
12015 None => start_row += 1,
12016 }
12017 }
12018 }
12019
12020 self.fold_creases(to_fold, true, window, cx);
12021 }
12022
12023 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12024 if self.buffer.read(cx).is_singleton() {
12025 let mut fold_ranges = Vec::new();
12026 let snapshot = self.buffer.read(cx).snapshot(cx);
12027
12028 for row in 0..snapshot.max_row().0 {
12029 if let Some(foldable_range) = self
12030 .snapshot(window, cx)
12031 .crease_for_buffer_row(MultiBufferRow(row))
12032 {
12033 fold_ranges.push(foldable_range);
12034 }
12035 }
12036
12037 self.fold_creases(fold_ranges, true, window, cx);
12038 } else {
12039 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12040 editor
12041 .update_in(&mut cx, |editor, _, cx| {
12042 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12043 editor.fold_buffer(buffer_id, cx);
12044 }
12045 })
12046 .ok();
12047 });
12048 }
12049 }
12050
12051 pub fn fold_function_bodies(
12052 &mut self,
12053 _: &actions::FoldFunctionBodies,
12054 window: &mut Window,
12055 cx: &mut Context<Self>,
12056 ) {
12057 let snapshot = self.buffer.read(cx).snapshot(cx);
12058
12059 let ranges = snapshot
12060 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12061 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12062 .collect::<Vec<_>>();
12063
12064 let creases = ranges
12065 .into_iter()
12066 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12067 .collect();
12068
12069 self.fold_creases(creases, true, window, cx);
12070 }
12071
12072 pub fn fold_recursive(
12073 &mut self,
12074 _: &actions::FoldRecursive,
12075 window: &mut Window,
12076 cx: &mut Context<Self>,
12077 ) {
12078 let mut to_fold = Vec::new();
12079 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12080 let selections = self.selections.all_adjusted(cx);
12081
12082 for selection in selections {
12083 let range = selection.range().sorted();
12084 let buffer_start_row = range.start.row;
12085
12086 if range.start.row != range.end.row {
12087 let mut found = false;
12088 for row in range.start.row..=range.end.row {
12089 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12090 found = true;
12091 to_fold.push(crease);
12092 }
12093 }
12094 if found {
12095 continue;
12096 }
12097 }
12098
12099 for row in (0..=range.start.row).rev() {
12100 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12101 if crease.range().end.row >= buffer_start_row {
12102 to_fold.push(crease);
12103 } else {
12104 break;
12105 }
12106 }
12107 }
12108 }
12109
12110 self.fold_creases(to_fold, true, window, cx);
12111 }
12112
12113 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12114 let buffer_row = fold_at.buffer_row;
12115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12116
12117 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12118 let autoscroll = self
12119 .selections
12120 .all::<Point>(cx)
12121 .iter()
12122 .any(|selection| crease.range().overlaps(&selection.range()));
12123
12124 self.fold_creases(vec![crease], autoscroll, window, cx);
12125 }
12126 }
12127
12128 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12129 if self.is_singleton(cx) {
12130 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12131 let buffer = &display_map.buffer_snapshot;
12132 let selections = self.selections.all::<Point>(cx);
12133 let ranges = selections
12134 .iter()
12135 .map(|s| {
12136 let range = s.display_range(&display_map).sorted();
12137 let mut start = range.start.to_point(&display_map);
12138 let mut end = range.end.to_point(&display_map);
12139 start.column = 0;
12140 end.column = buffer.line_len(MultiBufferRow(end.row));
12141 start..end
12142 })
12143 .collect::<Vec<_>>();
12144
12145 self.unfold_ranges(&ranges, true, true, cx);
12146 } else {
12147 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12148 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12149 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12150 .map(|(snapshot, _, _)| snapshot.remote_id())
12151 .collect();
12152 for buffer_id in buffer_ids {
12153 self.unfold_buffer(buffer_id, cx);
12154 }
12155 }
12156 }
12157
12158 pub fn unfold_recursive(
12159 &mut self,
12160 _: &UnfoldRecursive,
12161 _window: &mut Window,
12162 cx: &mut Context<Self>,
12163 ) {
12164 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12165 let selections = self.selections.all::<Point>(cx);
12166 let ranges = selections
12167 .iter()
12168 .map(|s| {
12169 let mut range = s.display_range(&display_map).sorted();
12170 *range.start.column_mut() = 0;
12171 *range.end.column_mut() = display_map.line_len(range.end.row());
12172 let start = range.start.to_point(&display_map);
12173 let end = range.end.to_point(&display_map);
12174 start..end
12175 })
12176 .collect::<Vec<_>>();
12177
12178 self.unfold_ranges(&ranges, true, true, cx);
12179 }
12180
12181 pub fn unfold_at(
12182 &mut self,
12183 unfold_at: &UnfoldAt,
12184 _window: &mut Window,
12185 cx: &mut Context<Self>,
12186 ) {
12187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12188
12189 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12190 ..Point::new(
12191 unfold_at.buffer_row.0,
12192 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12193 );
12194
12195 let autoscroll = self
12196 .selections
12197 .all::<Point>(cx)
12198 .iter()
12199 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12200
12201 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12202 }
12203
12204 pub fn unfold_all(
12205 &mut self,
12206 _: &actions::UnfoldAll,
12207 _window: &mut Window,
12208 cx: &mut Context<Self>,
12209 ) {
12210 if self.buffer.read(cx).is_singleton() {
12211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12212 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12213 } else {
12214 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12215 editor
12216 .update(&mut cx, |editor, cx| {
12217 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12218 editor.unfold_buffer(buffer_id, cx);
12219 }
12220 })
12221 .ok();
12222 });
12223 }
12224 }
12225
12226 pub fn fold_selected_ranges(
12227 &mut self,
12228 _: &FoldSelectedRanges,
12229 window: &mut Window,
12230 cx: &mut Context<Self>,
12231 ) {
12232 let selections = self.selections.all::<Point>(cx);
12233 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12234 let line_mode = self.selections.line_mode;
12235 let ranges = selections
12236 .into_iter()
12237 .map(|s| {
12238 if line_mode {
12239 let start = Point::new(s.start.row, 0);
12240 let end = Point::new(
12241 s.end.row,
12242 display_map
12243 .buffer_snapshot
12244 .line_len(MultiBufferRow(s.end.row)),
12245 );
12246 Crease::simple(start..end, display_map.fold_placeholder.clone())
12247 } else {
12248 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12249 }
12250 })
12251 .collect::<Vec<_>>();
12252 self.fold_creases(ranges, true, window, cx);
12253 }
12254
12255 pub fn fold_ranges<T: ToOffset + Clone>(
12256 &mut self,
12257 ranges: Vec<Range<T>>,
12258 auto_scroll: bool,
12259 window: &mut Window,
12260 cx: &mut Context<Self>,
12261 ) {
12262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12263 let ranges = ranges
12264 .into_iter()
12265 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12266 .collect::<Vec<_>>();
12267 self.fold_creases(ranges, auto_scroll, window, cx);
12268 }
12269
12270 pub fn fold_creases<T: ToOffset + Clone>(
12271 &mut self,
12272 creases: Vec<Crease<T>>,
12273 auto_scroll: bool,
12274 window: &mut Window,
12275 cx: &mut Context<Self>,
12276 ) {
12277 if creases.is_empty() {
12278 return;
12279 }
12280
12281 let mut buffers_affected = HashSet::default();
12282 let multi_buffer = self.buffer().read(cx);
12283 for crease in &creases {
12284 if let Some((_, buffer, _)) =
12285 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12286 {
12287 buffers_affected.insert(buffer.read(cx).remote_id());
12288 };
12289 }
12290
12291 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12292
12293 if auto_scroll {
12294 self.request_autoscroll(Autoscroll::fit(), cx);
12295 }
12296
12297 cx.notify();
12298
12299 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12300 // Clear diagnostics block when folding a range that contains it.
12301 let snapshot = self.snapshot(window, cx);
12302 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12303 drop(snapshot);
12304 self.active_diagnostics = Some(active_diagnostics);
12305 self.dismiss_diagnostics(cx);
12306 } else {
12307 self.active_diagnostics = Some(active_diagnostics);
12308 }
12309 }
12310
12311 self.scrollbar_marker_state.dirty = true;
12312 }
12313
12314 /// Removes any folds whose ranges intersect any of the given ranges.
12315 pub fn unfold_ranges<T: ToOffset + Clone>(
12316 &mut self,
12317 ranges: &[Range<T>],
12318 inclusive: bool,
12319 auto_scroll: bool,
12320 cx: &mut Context<Self>,
12321 ) {
12322 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12323 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12324 });
12325 }
12326
12327 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12328 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12329 return;
12330 }
12331 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12332 self.display_map
12333 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12334 cx.emit(EditorEvent::BufferFoldToggled {
12335 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12336 folded: true,
12337 });
12338 cx.notify();
12339 }
12340
12341 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12342 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12343 return;
12344 }
12345 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12346 self.display_map.update(cx, |display_map, cx| {
12347 display_map.unfold_buffer(buffer_id, cx);
12348 });
12349 cx.emit(EditorEvent::BufferFoldToggled {
12350 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12351 folded: false,
12352 });
12353 cx.notify();
12354 }
12355
12356 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12357 self.display_map.read(cx).is_buffer_folded(buffer)
12358 }
12359
12360 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12361 self.display_map.read(cx).folded_buffers()
12362 }
12363
12364 /// Removes any folds with the given ranges.
12365 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12366 &mut self,
12367 ranges: &[Range<T>],
12368 type_id: TypeId,
12369 auto_scroll: bool,
12370 cx: &mut Context<Self>,
12371 ) {
12372 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12373 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12374 });
12375 }
12376
12377 fn remove_folds_with<T: ToOffset + Clone>(
12378 &mut self,
12379 ranges: &[Range<T>],
12380 auto_scroll: bool,
12381 cx: &mut Context<Self>,
12382 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12383 ) {
12384 if ranges.is_empty() {
12385 return;
12386 }
12387
12388 let mut buffers_affected = HashSet::default();
12389 let multi_buffer = self.buffer().read(cx);
12390 for range in ranges {
12391 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12392 buffers_affected.insert(buffer.read(cx).remote_id());
12393 };
12394 }
12395
12396 self.display_map.update(cx, update);
12397
12398 if auto_scroll {
12399 self.request_autoscroll(Autoscroll::fit(), cx);
12400 }
12401
12402 cx.notify();
12403 self.scrollbar_marker_state.dirty = true;
12404 self.active_indent_guides_state.dirty = true;
12405 }
12406
12407 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12408 self.display_map.read(cx).fold_placeholder.clone()
12409 }
12410
12411 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12412 self.buffer.update(cx, |buffer, cx| {
12413 buffer.set_all_diff_hunks_expanded(cx);
12414 });
12415 }
12416
12417 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12418 self.distinguish_unstaged_diff_hunks = true;
12419 }
12420
12421 pub fn expand_all_diff_hunks(
12422 &mut self,
12423 _: &ExpandAllHunkDiffs,
12424 _window: &mut Window,
12425 cx: &mut Context<Self>,
12426 ) {
12427 self.buffer.update(cx, |buffer, cx| {
12428 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12429 });
12430 }
12431
12432 pub fn toggle_selected_diff_hunks(
12433 &mut self,
12434 _: &ToggleSelectedDiffHunks,
12435 _window: &mut Window,
12436 cx: &mut Context<Self>,
12437 ) {
12438 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12439 self.toggle_diff_hunks_in_ranges(ranges, cx);
12440 }
12441
12442 fn diff_hunks_in_ranges<'a>(
12443 &'a self,
12444 ranges: &'a [Range<Anchor>],
12445 buffer: &'a MultiBufferSnapshot,
12446 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12447 ranges.iter().flat_map(move |range| {
12448 let end_excerpt_id = range.end.excerpt_id;
12449 let range = range.to_point(buffer);
12450 let mut peek_end = range.end;
12451 if range.end.row < buffer.max_row().0 {
12452 peek_end = Point::new(range.end.row + 1, 0);
12453 }
12454 buffer
12455 .diff_hunks_in_range(range.start..peek_end)
12456 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12457 })
12458 }
12459
12460 pub fn has_stageable_diff_hunks_in_ranges(
12461 &self,
12462 ranges: &[Range<Anchor>],
12463 snapshot: &MultiBufferSnapshot,
12464 ) -> bool {
12465 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12466 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12467 }
12468
12469 pub fn toggle_staged_selected_diff_hunks(
12470 &mut self,
12471 _: &ToggleStagedSelectedDiffHunks,
12472 _window: &mut Window,
12473 cx: &mut Context<Self>,
12474 ) {
12475 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12476 self.stage_or_unstage_diff_hunks(&ranges, cx);
12477 }
12478
12479 pub fn stage_or_unstage_diff_hunks(
12480 &mut self,
12481 ranges: &[Range<Anchor>],
12482 cx: &mut Context<Self>,
12483 ) {
12484 let Some(project) = &self.project else {
12485 return;
12486 };
12487 let snapshot = self.buffer.read(cx).snapshot(cx);
12488 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12489
12490 let chunk_by = self
12491 .diff_hunks_in_ranges(&ranges, &snapshot)
12492 .chunk_by(|hunk| hunk.buffer_id);
12493 for (buffer_id, hunks) in &chunk_by {
12494 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12495 log::debug!("no buffer for id");
12496 continue;
12497 };
12498 let buffer = buffer.read(cx).snapshot();
12499 let Some((repo, path)) = project
12500 .read(cx)
12501 .repository_and_path_for_buffer_id(buffer_id, cx)
12502 else {
12503 log::debug!("no git repo for buffer id");
12504 continue;
12505 };
12506 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12507 log::debug!("no diff for buffer id");
12508 continue;
12509 };
12510 let Some(secondary_diff) = diff.secondary_diff() else {
12511 log::debug!("no secondary diff for buffer id");
12512 continue;
12513 };
12514
12515 let edits = diff.secondary_edits_for_stage_or_unstage(
12516 stage,
12517 hunks.map(|hunk| {
12518 (
12519 hunk.diff_base_byte_range.clone(),
12520 hunk.secondary_diff_base_byte_range.clone(),
12521 hunk.buffer_range.clone(),
12522 )
12523 }),
12524 &buffer,
12525 );
12526
12527 let index_base = secondary_diff.base_text().map_or_else(
12528 || Rope::from(""),
12529 |snapshot| snapshot.text.as_rope().clone(),
12530 );
12531 let index_buffer = cx.new(|cx| {
12532 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12533 });
12534 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12535 index_buffer.edit(edits, None, cx);
12536 index_buffer.snapshot().as_rope().to_string()
12537 });
12538 let new_index_text = if new_index_text.is_empty()
12539 && (diff.is_single_insertion
12540 || buffer
12541 .file()
12542 .map_or(false, |file| file.disk_state() == DiskState::New))
12543 {
12544 log::debug!("removing from index");
12545 None
12546 } else {
12547 Some(new_index_text)
12548 };
12549
12550 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12551 }
12552 }
12553
12554 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12555 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12556 self.buffer
12557 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12558 }
12559
12560 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12561 self.buffer.update(cx, |buffer, cx| {
12562 let ranges = vec![Anchor::min()..Anchor::max()];
12563 if !buffer.all_diff_hunks_expanded()
12564 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12565 {
12566 buffer.collapse_diff_hunks(ranges, cx);
12567 true
12568 } else {
12569 false
12570 }
12571 })
12572 }
12573
12574 fn toggle_diff_hunks_in_ranges(
12575 &mut self,
12576 ranges: Vec<Range<Anchor>>,
12577 cx: &mut Context<'_, Editor>,
12578 ) {
12579 self.buffer.update(cx, |buffer, cx| {
12580 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12581 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12582 })
12583 }
12584
12585 fn toggle_diff_hunks_in_ranges_narrow(
12586 &mut self,
12587 ranges: Vec<Range<Anchor>>,
12588 cx: &mut Context<'_, Editor>,
12589 ) {
12590 self.buffer.update(cx, |buffer, cx| {
12591 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12592 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12593 })
12594 }
12595
12596 pub(crate) fn apply_all_diff_hunks(
12597 &mut self,
12598 _: &ApplyAllDiffHunks,
12599 window: &mut Window,
12600 cx: &mut Context<Self>,
12601 ) {
12602 let buffers = self.buffer.read(cx).all_buffers();
12603 for branch_buffer in buffers {
12604 branch_buffer.update(cx, |branch_buffer, cx| {
12605 branch_buffer.merge_into_base(Vec::new(), cx);
12606 });
12607 }
12608
12609 if let Some(project) = self.project.clone() {
12610 self.save(true, project, window, cx).detach_and_log_err(cx);
12611 }
12612 }
12613
12614 pub(crate) fn apply_selected_diff_hunks(
12615 &mut self,
12616 _: &ApplyDiffHunk,
12617 window: &mut Window,
12618 cx: &mut Context<Self>,
12619 ) {
12620 let snapshot = self.snapshot(window, cx);
12621 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12622 let mut ranges_by_buffer = HashMap::default();
12623 self.transact(window, cx, |editor, _window, cx| {
12624 for hunk in hunks {
12625 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12626 ranges_by_buffer
12627 .entry(buffer.clone())
12628 .or_insert_with(Vec::new)
12629 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12630 }
12631 }
12632
12633 for (buffer, ranges) in ranges_by_buffer {
12634 buffer.update(cx, |buffer, cx| {
12635 buffer.merge_into_base(ranges, cx);
12636 });
12637 }
12638 });
12639
12640 if let Some(project) = self.project.clone() {
12641 self.save(true, project, window, cx).detach_and_log_err(cx);
12642 }
12643 }
12644
12645 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12646 if hovered != self.gutter_hovered {
12647 self.gutter_hovered = hovered;
12648 cx.notify();
12649 }
12650 }
12651
12652 pub fn insert_blocks(
12653 &mut self,
12654 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12655 autoscroll: Option<Autoscroll>,
12656 cx: &mut Context<Self>,
12657 ) -> Vec<CustomBlockId> {
12658 let blocks = self
12659 .display_map
12660 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12661 if let Some(autoscroll) = autoscroll {
12662 self.request_autoscroll(autoscroll, cx);
12663 }
12664 cx.notify();
12665 blocks
12666 }
12667
12668 pub fn resize_blocks(
12669 &mut self,
12670 heights: HashMap<CustomBlockId, u32>,
12671 autoscroll: Option<Autoscroll>,
12672 cx: &mut Context<Self>,
12673 ) {
12674 self.display_map
12675 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12676 if let Some(autoscroll) = autoscroll {
12677 self.request_autoscroll(autoscroll, cx);
12678 }
12679 cx.notify();
12680 }
12681
12682 pub fn replace_blocks(
12683 &mut self,
12684 renderers: HashMap<CustomBlockId, RenderBlock>,
12685 autoscroll: Option<Autoscroll>,
12686 cx: &mut Context<Self>,
12687 ) {
12688 self.display_map
12689 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12690 if let Some(autoscroll) = autoscroll {
12691 self.request_autoscroll(autoscroll, cx);
12692 }
12693 cx.notify();
12694 }
12695
12696 pub fn remove_blocks(
12697 &mut self,
12698 block_ids: HashSet<CustomBlockId>,
12699 autoscroll: Option<Autoscroll>,
12700 cx: &mut Context<Self>,
12701 ) {
12702 self.display_map.update(cx, |display_map, cx| {
12703 display_map.remove_blocks(block_ids, cx)
12704 });
12705 if let Some(autoscroll) = autoscroll {
12706 self.request_autoscroll(autoscroll, cx);
12707 }
12708 cx.notify();
12709 }
12710
12711 pub fn row_for_block(
12712 &self,
12713 block_id: CustomBlockId,
12714 cx: &mut Context<Self>,
12715 ) -> Option<DisplayRow> {
12716 self.display_map
12717 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12718 }
12719
12720 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12721 self.focused_block = Some(focused_block);
12722 }
12723
12724 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12725 self.focused_block.take()
12726 }
12727
12728 pub fn insert_creases(
12729 &mut self,
12730 creases: impl IntoIterator<Item = Crease<Anchor>>,
12731 cx: &mut Context<Self>,
12732 ) -> Vec<CreaseId> {
12733 self.display_map
12734 .update(cx, |map, cx| map.insert_creases(creases, cx))
12735 }
12736
12737 pub fn remove_creases(
12738 &mut self,
12739 ids: impl IntoIterator<Item = CreaseId>,
12740 cx: &mut Context<Self>,
12741 ) {
12742 self.display_map
12743 .update(cx, |map, cx| map.remove_creases(ids, cx));
12744 }
12745
12746 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12747 self.display_map
12748 .update(cx, |map, cx| map.snapshot(cx))
12749 .longest_row()
12750 }
12751
12752 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12753 self.display_map
12754 .update(cx, |map, cx| map.snapshot(cx))
12755 .max_point()
12756 }
12757
12758 pub fn text(&self, cx: &App) -> String {
12759 self.buffer.read(cx).read(cx).text()
12760 }
12761
12762 pub fn is_empty(&self, cx: &App) -> bool {
12763 self.buffer.read(cx).read(cx).is_empty()
12764 }
12765
12766 pub fn text_option(&self, cx: &App) -> Option<String> {
12767 let text = self.text(cx);
12768 let text = text.trim();
12769
12770 if text.is_empty() {
12771 return None;
12772 }
12773
12774 Some(text.to_string())
12775 }
12776
12777 pub fn set_text(
12778 &mut self,
12779 text: impl Into<Arc<str>>,
12780 window: &mut Window,
12781 cx: &mut Context<Self>,
12782 ) {
12783 self.transact(window, cx, |this, _, cx| {
12784 this.buffer
12785 .read(cx)
12786 .as_singleton()
12787 .expect("you can only call set_text on editors for singleton buffers")
12788 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12789 });
12790 }
12791
12792 pub fn display_text(&self, cx: &mut App) -> String {
12793 self.display_map
12794 .update(cx, |map, cx| map.snapshot(cx))
12795 .text()
12796 }
12797
12798 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12799 let mut wrap_guides = smallvec::smallvec![];
12800
12801 if self.show_wrap_guides == Some(false) {
12802 return wrap_guides;
12803 }
12804
12805 let settings = self.buffer.read(cx).settings_at(0, cx);
12806 if settings.show_wrap_guides {
12807 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12808 wrap_guides.push((soft_wrap as usize, true));
12809 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12810 wrap_guides.push((soft_wrap as usize, true));
12811 }
12812 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12813 }
12814
12815 wrap_guides
12816 }
12817
12818 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12819 let settings = self.buffer.read(cx).settings_at(0, cx);
12820 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12821 match mode {
12822 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12823 SoftWrap::None
12824 }
12825 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12826 language_settings::SoftWrap::PreferredLineLength => {
12827 SoftWrap::Column(settings.preferred_line_length)
12828 }
12829 language_settings::SoftWrap::Bounded => {
12830 SoftWrap::Bounded(settings.preferred_line_length)
12831 }
12832 }
12833 }
12834
12835 pub fn set_soft_wrap_mode(
12836 &mut self,
12837 mode: language_settings::SoftWrap,
12838
12839 cx: &mut Context<Self>,
12840 ) {
12841 self.soft_wrap_mode_override = Some(mode);
12842 cx.notify();
12843 }
12844
12845 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12846 self.text_style_refinement = Some(style);
12847 }
12848
12849 /// called by the Element so we know what style we were most recently rendered with.
12850 pub(crate) fn set_style(
12851 &mut self,
12852 style: EditorStyle,
12853 window: &mut Window,
12854 cx: &mut Context<Self>,
12855 ) {
12856 let rem_size = window.rem_size();
12857 self.display_map.update(cx, |map, cx| {
12858 map.set_font(
12859 style.text.font(),
12860 style.text.font_size.to_pixels(rem_size),
12861 cx,
12862 )
12863 });
12864 self.style = Some(style);
12865 }
12866
12867 pub fn style(&self) -> Option<&EditorStyle> {
12868 self.style.as_ref()
12869 }
12870
12871 // Called by the element. This method is not designed to be called outside of the editor
12872 // element's layout code because it does not notify when rewrapping is computed synchronously.
12873 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12874 self.display_map
12875 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12876 }
12877
12878 pub fn set_soft_wrap(&mut self) {
12879 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12880 }
12881
12882 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12883 if self.soft_wrap_mode_override.is_some() {
12884 self.soft_wrap_mode_override.take();
12885 } else {
12886 let soft_wrap = match self.soft_wrap_mode(cx) {
12887 SoftWrap::GitDiff => return,
12888 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12889 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12890 language_settings::SoftWrap::None
12891 }
12892 };
12893 self.soft_wrap_mode_override = Some(soft_wrap);
12894 }
12895 cx.notify();
12896 }
12897
12898 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12899 let Some(workspace) = self.workspace() else {
12900 return;
12901 };
12902 let fs = workspace.read(cx).app_state().fs.clone();
12903 let current_show = TabBarSettings::get_global(cx).show;
12904 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12905 setting.show = Some(!current_show);
12906 });
12907 }
12908
12909 pub fn toggle_indent_guides(
12910 &mut self,
12911 _: &ToggleIndentGuides,
12912 _: &mut Window,
12913 cx: &mut Context<Self>,
12914 ) {
12915 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12916 self.buffer
12917 .read(cx)
12918 .settings_at(0, cx)
12919 .indent_guides
12920 .enabled
12921 });
12922 self.show_indent_guides = Some(!currently_enabled);
12923 cx.notify();
12924 }
12925
12926 fn should_show_indent_guides(&self) -> Option<bool> {
12927 self.show_indent_guides
12928 }
12929
12930 pub fn toggle_line_numbers(
12931 &mut self,
12932 _: &ToggleLineNumbers,
12933 _: &mut Window,
12934 cx: &mut Context<Self>,
12935 ) {
12936 let mut editor_settings = EditorSettings::get_global(cx).clone();
12937 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12938 EditorSettings::override_global(editor_settings, cx);
12939 }
12940
12941 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12942 self.use_relative_line_numbers
12943 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12944 }
12945
12946 pub fn toggle_relative_line_numbers(
12947 &mut self,
12948 _: &ToggleRelativeLineNumbers,
12949 _: &mut Window,
12950 cx: &mut Context<Self>,
12951 ) {
12952 let is_relative = self.should_use_relative_line_numbers(cx);
12953 self.set_relative_line_number(Some(!is_relative), cx)
12954 }
12955
12956 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12957 self.use_relative_line_numbers = is_relative;
12958 cx.notify();
12959 }
12960
12961 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12962 self.show_gutter = show_gutter;
12963 cx.notify();
12964 }
12965
12966 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12967 self.show_scrollbars = show_scrollbars;
12968 cx.notify();
12969 }
12970
12971 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12972 self.show_line_numbers = Some(show_line_numbers);
12973 cx.notify();
12974 }
12975
12976 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12977 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12978 cx.notify();
12979 }
12980
12981 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12982 self.show_code_actions = Some(show_code_actions);
12983 cx.notify();
12984 }
12985
12986 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12987 self.show_runnables = Some(show_runnables);
12988 cx.notify();
12989 }
12990
12991 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12992 if self.display_map.read(cx).masked != masked {
12993 self.display_map.update(cx, |map, _| map.masked = masked);
12994 }
12995 cx.notify()
12996 }
12997
12998 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12999 self.show_wrap_guides = Some(show_wrap_guides);
13000 cx.notify();
13001 }
13002
13003 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13004 self.show_indent_guides = Some(show_indent_guides);
13005 cx.notify();
13006 }
13007
13008 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13009 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13010 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13011 if let Some(dir) = file.abs_path(cx).parent() {
13012 return Some(dir.to_owned());
13013 }
13014 }
13015
13016 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13017 return Some(project_path.path.to_path_buf());
13018 }
13019 }
13020
13021 None
13022 }
13023
13024 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13025 self.active_excerpt(cx)?
13026 .1
13027 .read(cx)
13028 .file()
13029 .and_then(|f| f.as_local())
13030 }
13031
13032 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13033 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13034 let buffer = buffer.read(cx);
13035 if let Some(project_path) = buffer.project_path(cx) {
13036 let project = self.project.as_ref()?.read(cx);
13037 project.absolute_path(&project_path, cx)
13038 } else {
13039 buffer
13040 .file()
13041 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13042 }
13043 })
13044 }
13045
13046 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13047 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13048 let project_path = buffer.read(cx).project_path(cx)?;
13049 let project = self.project.as_ref()?.read(cx);
13050 let entry = project.entry_for_path(&project_path, cx)?;
13051 let path = entry.path.to_path_buf();
13052 Some(path)
13053 })
13054 }
13055
13056 pub fn reveal_in_finder(
13057 &mut self,
13058 _: &RevealInFileManager,
13059 _window: &mut Window,
13060 cx: &mut Context<Self>,
13061 ) {
13062 if let Some(target) = self.target_file(cx) {
13063 cx.reveal_path(&target.abs_path(cx));
13064 }
13065 }
13066
13067 pub fn copy_path(
13068 &mut self,
13069 _: &zed_actions::workspace::CopyPath,
13070 _window: &mut Window,
13071 cx: &mut Context<Self>,
13072 ) {
13073 if let Some(path) = self.target_file_abs_path(cx) {
13074 if let Some(path) = path.to_str() {
13075 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13076 }
13077 }
13078 }
13079
13080 pub fn copy_relative_path(
13081 &mut self,
13082 _: &zed_actions::workspace::CopyRelativePath,
13083 _window: &mut Window,
13084 cx: &mut Context<Self>,
13085 ) {
13086 if let Some(path) = self.target_file_path(cx) {
13087 if let Some(path) = path.to_str() {
13088 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13089 }
13090 }
13091 }
13092
13093 pub fn copy_file_name_without_extension(
13094 &mut self,
13095 _: &CopyFileNameWithoutExtension,
13096 _: &mut Window,
13097 cx: &mut Context<Self>,
13098 ) {
13099 if let Some(file) = self.target_file(cx) {
13100 if let Some(file_stem) = file.path().file_stem() {
13101 if let Some(name) = file_stem.to_str() {
13102 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13103 }
13104 }
13105 }
13106 }
13107
13108 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13109 if let Some(file) = self.target_file(cx) {
13110 if let Some(file_name) = file.path().file_name() {
13111 if let Some(name) = file_name.to_str() {
13112 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13113 }
13114 }
13115 }
13116 }
13117
13118 pub fn toggle_git_blame(
13119 &mut self,
13120 _: &ToggleGitBlame,
13121 window: &mut Window,
13122 cx: &mut Context<Self>,
13123 ) {
13124 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13125
13126 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13127 self.start_git_blame(true, window, cx);
13128 }
13129
13130 cx.notify();
13131 }
13132
13133 pub fn toggle_git_blame_inline(
13134 &mut self,
13135 _: &ToggleGitBlameInline,
13136 window: &mut Window,
13137 cx: &mut Context<Self>,
13138 ) {
13139 self.toggle_git_blame_inline_internal(true, window, cx);
13140 cx.notify();
13141 }
13142
13143 pub fn git_blame_inline_enabled(&self) -> bool {
13144 self.git_blame_inline_enabled
13145 }
13146
13147 pub fn toggle_selection_menu(
13148 &mut self,
13149 _: &ToggleSelectionMenu,
13150 _: &mut Window,
13151 cx: &mut Context<Self>,
13152 ) {
13153 self.show_selection_menu = self
13154 .show_selection_menu
13155 .map(|show_selections_menu| !show_selections_menu)
13156 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13157
13158 cx.notify();
13159 }
13160
13161 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13162 self.show_selection_menu
13163 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13164 }
13165
13166 fn start_git_blame(
13167 &mut self,
13168 user_triggered: bool,
13169 window: &mut Window,
13170 cx: &mut Context<Self>,
13171 ) {
13172 if let Some(project) = self.project.as_ref() {
13173 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13174 return;
13175 };
13176
13177 if buffer.read(cx).file().is_none() {
13178 return;
13179 }
13180
13181 let focused = self.focus_handle(cx).contains_focused(window, cx);
13182
13183 let project = project.clone();
13184 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13185 self.blame_subscription =
13186 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13187 self.blame = Some(blame);
13188 }
13189 }
13190
13191 fn toggle_git_blame_inline_internal(
13192 &mut self,
13193 user_triggered: bool,
13194 window: &mut Window,
13195 cx: &mut Context<Self>,
13196 ) {
13197 if self.git_blame_inline_enabled {
13198 self.git_blame_inline_enabled = false;
13199 self.show_git_blame_inline = false;
13200 self.show_git_blame_inline_delay_task.take();
13201 } else {
13202 self.git_blame_inline_enabled = true;
13203 self.start_git_blame_inline(user_triggered, window, cx);
13204 }
13205
13206 cx.notify();
13207 }
13208
13209 fn start_git_blame_inline(
13210 &mut self,
13211 user_triggered: bool,
13212 window: &mut Window,
13213 cx: &mut Context<Self>,
13214 ) {
13215 self.start_git_blame(user_triggered, window, cx);
13216
13217 if ProjectSettings::get_global(cx)
13218 .git
13219 .inline_blame_delay()
13220 .is_some()
13221 {
13222 self.start_inline_blame_timer(window, cx);
13223 } else {
13224 self.show_git_blame_inline = true
13225 }
13226 }
13227
13228 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13229 self.blame.as_ref()
13230 }
13231
13232 pub fn show_git_blame_gutter(&self) -> bool {
13233 self.show_git_blame_gutter
13234 }
13235
13236 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13237 self.show_git_blame_gutter && self.has_blame_entries(cx)
13238 }
13239
13240 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13241 self.show_git_blame_inline
13242 && self.focus_handle.is_focused(window)
13243 && !self.newest_selection_head_on_empty_line(cx)
13244 && self.has_blame_entries(cx)
13245 }
13246
13247 fn has_blame_entries(&self, cx: &App) -> bool {
13248 self.blame()
13249 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13250 }
13251
13252 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13253 let cursor_anchor = self.selections.newest_anchor().head();
13254
13255 let snapshot = self.buffer.read(cx).snapshot(cx);
13256 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13257
13258 snapshot.line_len(buffer_row) == 0
13259 }
13260
13261 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13262 let buffer_and_selection = maybe!({
13263 let selection = self.selections.newest::<Point>(cx);
13264 let selection_range = selection.range();
13265
13266 let multi_buffer = self.buffer().read(cx);
13267 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13268 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13269
13270 let (buffer, range, _) = if selection.reversed {
13271 buffer_ranges.first()
13272 } else {
13273 buffer_ranges.last()
13274 }?;
13275
13276 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13277 ..text::ToPoint::to_point(&range.end, &buffer).row;
13278 Some((
13279 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13280 selection,
13281 ))
13282 });
13283
13284 let Some((buffer, selection)) = buffer_and_selection else {
13285 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13286 };
13287
13288 let Some(project) = self.project.as_ref() else {
13289 return Task::ready(Err(anyhow!("editor does not have project")));
13290 };
13291
13292 project.update(cx, |project, cx| {
13293 project.get_permalink_to_line(&buffer, selection, cx)
13294 })
13295 }
13296
13297 pub fn copy_permalink_to_line(
13298 &mut self,
13299 _: &CopyPermalinkToLine,
13300 window: &mut Window,
13301 cx: &mut Context<Self>,
13302 ) {
13303 let permalink_task = self.get_permalink_to_line(cx);
13304 let workspace = self.workspace();
13305
13306 cx.spawn_in(window, |_, mut cx| async move {
13307 match permalink_task.await {
13308 Ok(permalink) => {
13309 cx.update(|_, cx| {
13310 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13311 })
13312 .ok();
13313 }
13314 Err(err) => {
13315 let message = format!("Failed to copy permalink: {err}");
13316
13317 Err::<(), anyhow::Error>(err).log_err();
13318
13319 if let Some(workspace) = workspace {
13320 workspace
13321 .update_in(&mut cx, |workspace, _, cx| {
13322 struct CopyPermalinkToLine;
13323
13324 workspace.show_toast(
13325 Toast::new(
13326 NotificationId::unique::<CopyPermalinkToLine>(),
13327 message,
13328 ),
13329 cx,
13330 )
13331 })
13332 .ok();
13333 }
13334 }
13335 }
13336 })
13337 .detach();
13338 }
13339
13340 pub fn copy_file_location(
13341 &mut self,
13342 _: &CopyFileLocation,
13343 _: &mut Window,
13344 cx: &mut Context<Self>,
13345 ) {
13346 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13347 if let Some(file) = self.target_file(cx) {
13348 if let Some(path) = file.path().to_str() {
13349 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13350 }
13351 }
13352 }
13353
13354 pub fn open_permalink_to_line(
13355 &mut self,
13356 _: &OpenPermalinkToLine,
13357 window: &mut Window,
13358 cx: &mut Context<Self>,
13359 ) {
13360 let permalink_task = self.get_permalink_to_line(cx);
13361 let workspace = self.workspace();
13362
13363 cx.spawn_in(window, |_, mut cx| async move {
13364 match permalink_task.await {
13365 Ok(permalink) => {
13366 cx.update(|_, cx| {
13367 cx.open_url(permalink.as_ref());
13368 })
13369 .ok();
13370 }
13371 Err(err) => {
13372 let message = format!("Failed to open permalink: {err}");
13373
13374 Err::<(), anyhow::Error>(err).log_err();
13375
13376 if let Some(workspace) = workspace {
13377 workspace
13378 .update(&mut cx, |workspace, cx| {
13379 struct OpenPermalinkToLine;
13380
13381 workspace.show_toast(
13382 Toast::new(
13383 NotificationId::unique::<OpenPermalinkToLine>(),
13384 message,
13385 ),
13386 cx,
13387 )
13388 })
13389 .ok();
13390 }
13391 }
13392 }
13393 })
13394 .detach();
13395 }
13396
13397 pub fn insert_uuid_v4(
13398 &mut self,
13399 _: &InsertUuidV4,
13400 window: &mut Window,
13401 cx: &mut Context<Self>,
13402 ) {
13403 self.insert_uuid(UuidVersion::V4, window, cx);
13404 }
13405
13406 pub fn insert_uuid_v7(
13407 &mut self,
13408 _: &InsertUuidV7,
13409 window: &mut Window,
13410 cx: &mut Context<Self>,
13411 ) {
13412 self.insert_uuid(UuidVersion::V7, window, cx);
13413 }
13414
13415 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13416 self.transact(window, cx, |this, window, cx| {
13417 let edits = this
13418 .selections
13419 .all::<Point>(cx)
13420 .into_iter()
13421 .map(|selection| {
13422 let uuid = match version {
13423 UuidVersion::V4 => uuid::Uuid::new_v4(),
13424 UuidVersion::V7 => uuid::Uuid::now_v7(),
13425 };
13426
13427 (selection.range(), uuid.to_string())
13428 });
13429 this.edit(edits, cx);
13430 this.refresh_inline_completion(true, false, window, cx);
13431 });
13432 }
13433
13434 pub fn open_selections_in_multibuffer(
13435 &mut self,
13436 _: &OpenSelectionsInMultibuffer,
13437 window: &mut Window,
13438 cx: &mut Context<Self>,
13439 ) {
13440 let multibuffer = self.buffer.read(cx);
13441
13442 let Some(buffer) = multibuffer.as_singleton() else {
13443 return;
13444 };
13445
13446 let Some(workspace) = self.workspace() else {
13447 return;
13448 };
13449
13450 let locations = self
13451 .selections
13452 .disjoint_anchors()
13453 .iter()
13454 .map(|range| Location {
13455 buffer: buffer.clone(),
13456 range: range.start.text_anchor..range.end.text_anchor,
13457 })
13458 .collect::<Vec<_>>();
13459
13460 let title = multibuffer.title(cx).to_string();
13461
13462 cx.spawn_in(window, |_, mut cx| async move {
13463 workspace.update_in(&mut cx, |workspace, window, cx| {
13464 Self::open_locations_in_multibuffer(
13465 workspace,
13466 locations,
13467 format!("Selections for '{title}'"),
13468 false,
13469 MultibufferSelectionMode::All,
13470 window,
13471 cx,
13472 );
13473 })
13474 })
13475 .detach();
13476 }
13477
13478 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13479 /// last highlight added will be used.
13480 ///
13481 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13482 pub fn highlight_rows<T: 'static>(
13483 &mut self,
13484 range: Range<Anchor>,
13485 color: Hsla,
13486 should_autoscroll: bool,
13487 cx: &mut Context<Self>,
13488 ) {
13489 let snapshot = self.buffer().read(cx).snapshot(cx);
13490 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13491 let ix = row_highlights.binary_search_by(|highlight| {
13492 Ordering::Equal
13493 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13494 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13495 });
13496
13497 if let Err(mut ix) = ix {
13498 let index = post_inc(&mut self.highlight_order);
13499
13500 // If this range intersects with the preceding highlight, then merge it with
13501 // the preceding highlight. Otherwise insert a new highlight.
13502 let mut merged = false;
13503 if ix > 0 {
13504 let prev_highlight = &mut row_highlights[ix - 1];
13505 if prev_highlight
13506 .range
13507 .end
13508 .cmp(&range.start, &snapshot)
13509 .is_ge()
13510 {
13511 ix -= 1;
13512 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13513 prev_highlight.range.end = range.end;
13514 }
13515 merged = true;
13516 prev_highlight.index = index;
13517 prev_highlight.color = color;
13518 prev_highlight.should_autoscroll = should_autoscroll;
13519 }
13520 }
13521
13522 if !merged {
13523 row_highlights.insert(
13524 ix,
13525 RowHighlight {
13526 range: range.clone(),
13527 index,
13528 color,
13529 should_autoscroll,
13530 },
13531 );
13532 }
13533
13534 // If any of the following highlights intersect with this one, merge them.
13535 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13536 let highlight = &row_highlights[ix];
13537 if next_highlight
13538 .range
13539 .start
13540 .cmp(&highlight.range.end, &snapshot)
13541 .is_le()
13542 {
13543 if next_highlight
13544 .range
13545 .end
13546 .cmp(&highlight.range.end, &snapshot)
13547 .is_gt()
13548 {
13549 row_highlights[ix].range.end = next_highlight.range.end;
13550 }
13551 row_highlights.remove(ix + 1);
13552 } else {
13553 break;
13554 }
13555 }
13556 }
13557 }
13558
13559 /// Remove any highlighted row ranges of the given type that intersect the
13560 /// given ranges.
13561 pub fn remove_highlighted_rows<T: 'static>(
13562 &mut self,
13563 ranges_to_remove: Vec<Range<Anchor>>,
13564 cx: &mut Context<Self>,
13565 ) {
13566 let snapshot = self.buffer().read(cx).snapshot(cx);
13567 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13568 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13569 row_highlights.retain(|highlight| {
13570 while let Some(range_to_remove) = ranges_to_remove.peek() {
13571 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13572 Ordering::Less | Ordering::Equal => {
13573 ranges_to_remove.next();
13574 }
13575 Ordering::Greater => {
13576 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13577 Ordering::Less | Ordering::Equal => {
13578 return false;
13579 }
13580 Ordering::Greater => break,
13581 }
13582 }
13583 }
13584 }
13585
13586 true
13587 })
13588 }
13589
13590 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13591 pub fn clear_row_highlights<T: 'static>(&mut self) {
13592 self.highlighted_rows.remove(&TypeId::of::<T>());
13593 }
13594
13595 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13596 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13597 self.highlighted_rows
13598 .get(&TypeId::of::<T>())
13599 .map_or(&[] as &[_], |vec| vec.as_slice())
13600 .iter()
13601 .map(|highlight| (highlight.range.clone(), highlight.color))
13602 }
13603
13604 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13605 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13606 /// Allows to ignore certain kinds of highlights.
13607 pub fn highlighted_display_rows(
13608 &self,
13609 window: &mut Window,
13610 cx: &mut App,
13611 ) -> BTreeMap<DisplayRow, Hsla> {
13612 let snapshot = self.snapshot(window, cx);
13613 let mut used_highlight_orders = HashMap::default();
13614 self.highlighted_rows
13615 .iter()
13616 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13617 .fold(
13618 BTreeMap::<DisplayRow, Hsla>::new(),
13619 |mut unique_rows, highlight| {
13620 let start = highlight.range.start.to_display_point(&snapshot);
13621 let end = highlight.range.end.to_display_point(&snapshot);
13622 let start_row = start.row().0;
13623 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13624 && end.column() == 0
13625 {
13626 end.row().0.saturating_sub(1)
13627 } else {
13628 end.row().0
13629 };
13630 for row in start_row..=end_row {
13631 let used_index =
13632 used_highlight_orders.entry(row).or_insert(highlight.index);
13633 if highlight.index >= *used_index {
13634 *used_index = highlight.index;
13635 unique_rows.insert(DisplayRow(row), highlight.color);
13636 }
13637 }
13638 unique_rows
13639 },
13640 )
13641 }
13642
13643 pub fn highlighted_display_row_for_autoscroll(
13644 &self,
13645 snapshot: &DisplaySnapshot,
13646 ) -> Option<DisplayRow> {
13647 self.highlighted_rows
13648 .values()
13649 .flat_map(|highlighted_rows| highlighted_rows.iter())
13650 .filter_map(|highlight| {
13651 if highlight.should_autoscroll {
13652 Some(highlight.range.start.to_display_point(snapshot).row())
13653 } else {
13654 None
13655 }
13656 })
13657 .min()
13658 }
13659
13660 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13661 self.highlight_background::<SearchWithinRange>(
13662 ranges,
13663 |colors| colors.editor_document_highlight_read_background,
13664 cx,
13665 )
13666 }
13667
13668 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13669 self.breadcrumb_header = Some(new_header);
13670 }
13671
13672 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13673 self.clear_background_highlights::<SearchWithinRange>(cx);
13674 }
13675
13676 pub fn highlight_background<T: 'static>(
13677 &mut self,
13678 ranges: &[Range<Anchor>],
13679 color_fetcher: fn(&ThemeColors) -> Hsla,
13680 cx: &mut Context<Self>,
13681 ) {
13682 self.background_highlights
13683 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13684 self.scrollbar_marker_state.dirty = true;
13685 cx.notify();
13686 }
13687
13688 pub fn clear_background_highlights<T: 'static>(
13689 &mut self,
13690 cx: &mut Context<Self>,
13691 ) -> Option<BackgroundHighlight> {
13692 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13693 if !text_highlights.1.is_empty() {
13694 self.scrollbar_marker_state.dirty = true;
13695 cx.notify();
13696 }
13697 Some(text_highlights)
13698 }
13699
13700 pub fn highlight_gutter<T: 'static>(
13701 &mut self,
13702 ranges: &[Range<Anchor>],
13703 color_fetcher: fn(&App) -> Hsla,
13704 cx: &mut Context<Self>,
13705 ) {
13706 self.gutter_highlights
13707 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13708 cx.notify();
13709 }
13710
13711 pub fn clear_gutter_highlights<T: 'static>(
13712 &mut self,
13713 cx: &mut Context<Self>,
13714 ) -> Option<GutterHighlight> {
13715 cx.notify();
13716 self.gutter_highlights.remove(&TypeId::of::<T>())
13717 }
13718
13719 #[cfg(feature = "test-support")]
13720 pub fn all_text_background_highlights(
13721 &self,
13722 window: &mut Window,
13723 cx: &mut Context<Self>,
13724 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13725 let snapshot = self.snapshot(window, cx);
13726 let buffer = &snapshot.buffer_snapshot;
13727 let start = buffer.anchor_before(0);
13728 let end = buffer.anchor_after(buffer.len());
13729 let theme = cx.theme().colors();
13730 self.background_highlights_in_range(start..end, &snapshot, theme)
13731 }
13732
13733 #[cfg(feature = "test-support")]
13734 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13735 let snapshot = self.buffer().read(cx).snapshot(cx);
13736
13737 let highlights = self
13738 .background_highlights
13739 .get(&TypeId::of::<items::BufferSearchHighlights>());
13740
13741 if let Some((_color, ranges)) = highlights {
13742 ranges
13743 .iter()
13744 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13745 .collect_vec()
13746 } else {
13747 vec![]
13748 }
13749 }
13750
13751 fn document_highlights_for_position<'a>(
13752 &'a self,
13753 position: Anchor,
13754 buffer: &'a MultiBufferSnapshot,
13755 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13756 let read_highlights = self
13757 .background_highlights
13758 .get(&TypeId::of::<DocumentHighlightRead>())
13759 .map(|h| &h.1);
13760 let write_highlights = self
13761 .background_highlights
13762 .get(&TypeId::of::<DocumentHighlightWrite>())
13763 .map(|h| &h.1);
13764 let left_position = position.bias_left(buffer);
13765 let right_position = position.bias_right(buffer);
13766 read_highlights
13767 .into_iter()
13768 .chain(write_highlights)
13769 .flat_map(move |ranges| {
13770 let start_ix = match ranges.binary_search_by(|probe| {
13771 let cmp = probe.end.cmp(&left_position, buffer);
13772 if cmp.is_ge() {
13773 Ordering::Greater
13774 } else {
13775 Ordering::Less
13776 }
13777 }) {
13778 Ok(i) | Err(i) => i,
13779 };
13780
13781 ranges[start_ix..]
13782 .iter()
13783 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13784 })
13785 }
13786
13787 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13788 self.background_highlights
13789 .get(&TypeId::of::<T>())
13790 .map_or(false, |(_, highlights)| !highlights.is_empty())
13791 }
13792
13793 pub fn background_highlights_in_range(
13794 &self,
13795 search_range: Range<Anchor>,
13796 display_snapshot: &DisplaySnapshot,
13797 theme: &ThemeColors,
13798 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13799 let mut results = Vec::new();
13800 for (color_fetcher, ranges) in self.background_highlights.values() {
13801 let color = color_fetcher(theme);
13802 let start_ix = match ranges.binary_search_by(|probe| {
13803 let cmp = probe
13804 .end
13805 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13806 if cmp.is_gt() {
13807 Ordering::Greater
13808 } else {
13809 Ordering::Less
13810 }
13811 }) {
13812 Ok(i) | Err(i) => i,
13813 };
13814 for range in &ranges[start_ix..] {
13815 if range
13816 .start
13817 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13818 .is_ge()
13819 {
13820 break;
13821 }
13822
13823 let start = range.start.to_display_point(display_snapshot);
13824 let end = range.end.to_display_point(display_snapshot);
13825 results.push((start..end, color))
13826 }
13827 }
13828 results
13829 }
13830
13831 pub fn background_highlight_row_ranges<T: 'static>(
13832 &self,
13833 search_range: Range<Anchor>,
13834 display_snapshot: &DisplaySnapshot,
13835 count: usize,
13836 ) -> Vec<RangeInclusive<DisplayPoint>> {
13837 let mut results = Vec::new();
13838 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13839 return vec![];
13840 };
13841
13842 let start_ix = match ranges.binary_search_by(|probe| {
13843 let cmp = probe
13844 .end
13845 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13846 if cmp.is_gt() {
13847 Ordering::Greater
13848 } else {
13849 Ordering::Less
13850 }
13851 }) {
13852 Ok(i) | Err(i) => i,
13853 };
13854 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13855 if let (Some(start_display), Some(end_display)) = (start, end) {
13856 results.push(
13857 start_display.to_display_point(display_snapshot)
13858 ..=end_display.to_display_point(display_snapshot),
13859 );
13860 }
13861 };
13862 let mut start_row: Option<Point> = None;
13863 let mut end_row: Option<Point> = None;
13864 if ranges.len() > count {
13865 return Vec::new();
13866 }
13867 for range in &ranges[start_ix..] {
13868 if range
13869 .start
13870 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13871 .is_ge()
13872 {
13873 break;
13874 }
13875 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13876 if let Some(current_row) = &end_row {
13877 if end.row == current_row.row {
13878 continue;
13879 }
13880 }
13881 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13882 if start_row.is_none() {
13883 assert_eq!(end_row, None);
13884 start_row = Some(start);
13885 end_row = Some(end);
13886 continue;
13887 }
13888 if let Some(current_end) = end_row.as_mut() {
13889 if start.row > current_end.row + 1 {
13890 push_region(start_row, end_row);
13891 start_row = Some(start);
13892 end_row = Some(end);
13893 } else {
13894 // Merge two hunks.
13895 *current_end = end;
13896 }
13897 } else {
13898 unreachable!();
13899 }
13900 }
13901 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13902 push_region(start_row, end_row);
13903 results
13904 }
13905
13906 pub fn gutter_highlights_in_range(
13907 &self,
13908 search_range: Range<Anchor>,
13909 display_snapshot: &DisplaySnapshot,
13910 cx: &App,
13911 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13912 let mut results = Vec::new();
13913 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13914 let color = color_fetcher(cx);
13915 let start_ix = match ranges.binary_search_by(|probe| {
13916 let cmp = probe
13917 .end
13918 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13919 if cmp.is_gt() {
13920 Ordering::Greater
13921 } else {
13922 Ordering::Less
13923 }
13924 }) {
13925 Ok(i) | Err(i) => i,
13926 };
13927 for range in &ranges[start_ix..] {
13928 if range
13929 .start
13930 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13931 .is_ge()
13932 {
13933 break;
13934 }
13935
13936 let start = range.start.to_display_point(display_snapshot);
13937 let end = range.end.to_display_point(display_snapshot);
13938 results.push((start..end, color))
13939 }
13940 }
13941 results
13942 }
13943
13944 /// Get the text ranges corresponding to the redaction query
13945 pub fn redacted_ranges(
13946 &self,
13947 search_range: Range<Anchor>,
13948 display_snapshot: &DisplaySnapshot,
13949 cx: &App,
13950 ) -> Vec<Range<DisplayPoint>> {
13951 display_snapshot
13952 .buffer_snapshot
13953 .redacted_ranges(search_range, |file| {
13954 if let Some(file) = file {
13955 file.is_private()
13956 && EditorSettings::get(
13957 Some(SettingsLocation {
13958 worktree_id: file.worktree_id(cx),
13959 path: file.path().as_ref(),
13960 }),
13961 cx,
13962 )
13963 .redact_private_values
13964 } else {
13965 false
13966 }
13967 })
13968 .map(|range| {
13969 range.start.to_display_point(display_snapshot)
13970 ..range.end.to_display_point(display_snapshot)
13971 })
13972 .collect()
13973 }
13974
13975 pub fn highlight_text<T: 'static>(
13976 &mut self,
13977 ranges: Vec<Range<Anchor>>,
13978 style: HighlightStyle,
13979 cx: &mut Context<Self>,
13980 ) {
13981 self.display_map.update(cx, |map, _| {
13982 map.highlight_text(TypeId::of::<T>(), ranges, style)
13983 });
13984 cx.notify();
13985 }
13986
13987 pub(crate) fn highlight_inlays<T: 'static>(
13988 &mut self,
13989 highlights: Vec<InlayHighlight>,
13990 style: HighlightStyle,
13991 cx: &mut Context<Self>,
13992 ) {
13993 self.display_map.update(cx, |map, _| {
13994 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13995 });
13996 cx.notify();
13997 }
13998
13999 pub fn text_highlights<'a, T: 'static>(
14000 &'a self,
14001 cx: &'a App,
14002 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14003 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14004 }
14005
14006 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14007 let cleared = self
14008 .display_map
14009 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14010 if cleared {
14011 cx.notify();
14012 }
14013 }
14014
14015 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14016 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14017 && self.focus_handle.is_focused(window)
14018 }
14019
14020 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14021 self.show_cursor_when_unfocused = is_enabled;
14022 cx.notify();
14023 }
14024
14025 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14026 cx.notify();
14027 }
14028
14029 fn on_buffer_event(
14030 &mut self,
14031 multibuffer: &Entity<MultiBuffer>,
14032 event: &multi_buffer::Event,
14033 window: &mut Window,
14034 cx: &mut Context<Self>,
14035 ) {
14036 match event {
14037 multi_buffer::Event::Edited {
14038 singleton_buffer_edited,
14039 edited_buffer: buffer_edited,
14040 } => {
14041 self.scrollbar_marker_state.dirty = true;
14042 self.active_indent_guides_state.dirty = true;
14043 self.refresh_active_diagnostics(cx);
14044 self.refresh_code_actions(window, cx);
14045 if self.has_active_inline_completion() {
14046 self.update_visible_inline_completion(window, cx);
14047 }
14048 if let Some(buffer) = buffer_edited {
14049 let buffer_id = buffer.read(cx).remote_id();
14050 if !self.registered_buffers.contains_key(&buffer_id) {
14051 if let Some(project) = self.project.as_ref() {
14052 project.update(cx, |project, cx| {
14053 self.registered_buffers.insert(
14054 buffer_id,
14055 project.register_buffer_with_language_servers(&buffer, cx),
14056 );
14057 })
14058 }
14059 }
14060 }
14061 cx.emit(EditorEvent::BufferEdited);
14062 cx.emit(SearchEvent::MatchesInvalidated);
14063 if *singleton_buffer_edited {
14064 if let Some(project) = &self.project {
14065 #[allow(clippy::mutable_key_type)]
14066 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14067 multibuffer
14068 .all_buffers()
14069 .into_iter()
14070 .filter_map(|buffer| {
14071 buffer.update(cx, |buffer, cx| {
14072 let language = buffer.language()?;
14073 let should_discard = project.update(cx, |project, cx| {
14074 project.is_local()
14075 && !project.has_language_servers_for(buffer, cx)
14076 });
14077 should_discard.not().then_some(language.clone())
14078 })
14079 })
14080 .collect::<HashSet<_>>()
14081 });
14082 if !languages_affected.is_empty() {
14083 self.refresh_inlay_hints(
14084 InlayHintRefreshReason::BufferEdited(languages_affected),
14085 cx,
14086 );
14087 }
14088 }
14089 }
14090
14091 let Some(project) = &self.project else { return };
14092 let (telemetry, is_via_ssh) = {
14093 let project = project.read(cx);
14094 let telemetry = project.client().telemetry().clone();
14095 let is_via_ssh = project.is_via_ssh();
14096 (telemetry, is_via_ssh)
14097 };
14098 refresh_linked_ranges(self, window, cx);
14099 telemetry.log_edit_event("editor", is_via_ssh);
14100 }
14101 multi_buffer::Event::ExcerptsAdded {
14102 buffer,
14103 predecessor,
14104 excerpts,
14105 } => {
14106 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14107 let buffer_id = buffer.read(cx).remote_id();
14108 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14109 if let Some(project) = &self.project {
14110 get_uncommitted_diff_for_buffer(
14111 project,
14112 [buffer.clone()],
14113 self.buffer.clone(),
14114 cx,
14115 )
14116 .detach();
14117 }
14118 }
14119 cx.emit(EditorEvent::ExcerptsAdded {
14120 buffer: buffer.clone(),
14121 predecessor: *predecessor,
14122 excerpts: excerpts.clone(),
14123 });
14124 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14125 }
14126 multi_buffer::Event::ExcerptsRemoved { ids } => {
14127 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14128 let buffer = self.buffer.read(cx);
14129 self.registered_buffers
14130 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14131 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14132 }
14133 multi_buffer::Event::ExcerptsEdited { ids } => {
14134 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14135 }
14136 multi_buffer::Event::ExcerptsExpanded { ids } => {
14137 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14138 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14139 }
14140 multi_buffer::Event::Reparsed(buffer_id) => {
14141 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14142
14143 cx.emit(EditorEvent::Reparsed(*buffer_id));
14144 }
14145 multi_buffer::Event::DiffHunksToggled => {
14146 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14147 }
14148 multi_buffer::Event::LanguageChanged(buffer_id) => {
14149 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14150 cx.emit(EditorEvent::Reparsed(*buffer_id));
14151 cx.notify();
14152 }
14153 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14154 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14155 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14156 cx.emit(EditorEvent::TitleChanged)
14157 }
14158 // multi_buffer::Event::DiffBaseChanged => {
14159 // self.scrollbar_marker_state.dirty = true;
14160 // cx.emit(EditorEvent::DiffBaseChanged);
14161 // cx.notify();
14162 // }
14163 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14164 multi_buffer::Event::DiagnosticsUpdated => {
14165 self.refresh_active_diagnostics(cx);
14166 self.scrollbar_marker_state.dirty = true;
14167 cx.notify();
14168 }
14169 _ => {}
14170 };
14171 }
14172
14173 fn on_display_map_changed(
14174 &mut self,
14175 _: Entity<DisplayMap>,
14176 _: &mut Window,
14177 cx: &mut Context<Self>,
14178 ) {
14179 cx.notify();
14180 }
14181
14182 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14183 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14184 self.refresh_inline_completion(true, false, window, cx);
14185 self.refresh_inlay_hints(
14186 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14187 self.selections.newest_anchor().head(),
14188 &self.buffer.read(cx).snapshot(cx),
14189 cx,
14190 )),
14191 cx,
14192 );
14193
14194 let old_cursor_shape = self.cursor_shape;
14195
14196 {
14197 let editor_settings = EditorSettings::get_global(cx);
14198 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14199 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14200 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14201 }
14202
14203 if old_cursor_shape != self.cursor_shape {
14204 cx.emit(EditorEvent::CursorShapeChanged);
14205 }
14206
14207 let project_settings = ProjectSettings::get_global(cx);
14208 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14209
14210 if self.mode == EditorMode::Full {
14211 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14212 if self.git_blame_inline_enabled != inline_blame_enabled {
14213 self.toggle_git_blame_inline_internal(false, window, cx);
14214 }
14215 }
14216
14217 cx.notify();
14218 }
14219
14220 pub fn set_searchable(&mut self, searchable: bool) {
14221 self.searchable = searchable;
14222 }
14223
14224 pub fn searchable(&self) -> bool {
14225 self.searchable
14226 }
14227
14228 fn open_proposed_changes_editor(
14229 &mut self,
14230 _: &OpenProposedChangesEditor,
14231 window: &mut Window,
14232 cx: &mut Context<Self>,
14233 ) {
14234 let Some(workspace) = self.workspace() else {
14235 cx.propagate();
14236 return;
14237 };
14238
14239 let selections = self.selections.all::<usize>(cx);
14240 let multi_buffer = self.buffer.read(cx);
14241 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14242 let mut new_selections_by_buffer = HashMap::default();
14243 for selection in selections {
14244 for (buffer, range, _) in
14245 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14246 {
14247 let mut range = range.to_point(buffer);
14248 range.start.column = 0;
14249 range.end.column = buffer.line_len(range.end.row);
14250 new_selections_by_buffer
14251 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14252 .or_insert(Vec::new())
14253 .push(range)
14254 }
14255 }
14256
14257 let proposed_changes_buffers = new_selections_by_buffer
14258 .into_iter()
14259 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14260 .collect::<Vec<_>>();
14261 let proposed_changes_editor = cx.new(|cx| {
14262 ProposedChangesEditor::new(
14263 "Proposed changes",
14264 proposed_changes_buffers,
14265 self.project.clone(),
14266 window,
14267 cx,
14268 )
14269 });
14270
14271 window.defer(cx, move |window, cx| {
14272 workspace.update(cx, |workspace, cx| {
14273 workspace.active_pane().update(cx, |pane, cx| {
14274 pane.add_item(
14275 Box::new(proposed_changes_editor),
14276 true,
14277 true,
14278 None,
14279 window,
14280 cx,
14281 );
14282 });
14283 });
14284 });
14285 }
14286
14287 pub fn open_excerpts_in_split(
14288 &mut self,
14289 _: &OpenExcerptsSplit,
14290 window: &mut Window,
14291 cx: &mut Context<Self>,
14292 ) {
14293 self.open_excerpts_common(None, true, window, cx)
14294 }
14295
14296 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14297 self.open_excerpts_common(None, false, window, cx)
14298 }
14299
14300 fn open_excerpts_common(
14301 &mut self,
14302 jump_data: Option<JumpData>,
14303 split: bool,
14304 window: &mut Window,
14305 cx: &mut Context<Self>,
14306 ) {
14307 let Some(workspace) = self.workspace() else {
14308 cx.propagate();
14309 return;
14310 };
14311
14312 if self.buffer.read(cx).is_singleton() {
14313 cx.propagate();
14314 return;
14315 }
14316
14317 let mut new_selections_by_buffer = HashMap::default();
14318 match &jump_data {
14319 Some(JumpData::MultiBufferPoint {
14320 excerpt_id,
14321 position,
14322 anchor,
14323 line_offset_from_top,
14324 }) => {
14325 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14326 if let Some(buffer) = multi_buffer_snapshot
14327 .buffer_id_for_excerpt(*excerpt_id)
14328 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14329 {
14330 let buffer_snapshot = buffer.read(cx).snapshot();
14331 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14332 language::ToPoint::to_point(anchor, &buffer_snapshot)
14333 } else {
14334 buffer_snapshot.clip_point(*position, Bias::Left)
14335 };
14336 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14337 new_selections_by_buffer.insert(
14338 buffer,
14339 (
14340 vec![jump_to_offset..jump_to_offset],
14341 Some(*line_offset_from_top),
14342 ),
14343 );
14344 }
14345 }
14346 Some(JumpData::MultiBufferRow {
14347 row,
14348 line_offset_from_top,
14349 }) => {
14350 let point = MultiBufferPoint::new(row.0, 0);
14351 if let Some((buffer, buffer_point, _)) =
14352 self.buffer.read(cx).point_to_buffer_point(point, cx)
14353 {
14354 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14355 new_selections_by_buffer
14356 .entry(buffer)
14357 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14358 .0
14359 .push(buffer_offset..buffer_offset)
14360 }
14361 }
14362 None => {
14363 let selections = self.selections.all::<usize>(cx);
14364 let multi_buffer = self.buffer.read(cx);
14365 for selection in selections {
14366 for (buffer, mut range, _) in multi_buffer
14367 .snapshot(cx)
14368 .range_to_buffer_ranges(selection.range())
14369 {
14370 // When editing branch buffers, jump to the corresponding location
14371 // in their base buffer.
14372 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14373 let buffer = buffer_handle.read(cx);
14374 if let Some(base_buffer) = buffer.base_buffer() {
14375 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14376 buffer_handle = base_buffer;
14377 }
14378
14379 if selection.reversed {
14380 mem::swap(&mut range.start, &mut range.end);
14381 }
14382 new_selections_by_buffer
14383 .entry(buffer_handle)
14384 .or_insert((Vec::new(), None))
14385 .0
14386 .push(range)
14387 }
14388 }
14389 }
14390 }
14391
14392 if new_selections_by_buffer.is_empty() {
14393 return;
14394 }
14395
14396 // We defer the pane interaction because we ourselves are a workspace item
14397 // and activating a new item causes the pane to call a method on us reentrantly,
14398 // which panics if we're on the stack.
14399 window.defer(cx, move |window, cx| {
14400 workspace.update(cx, |workspace, cx| {
14401 let pane = if split {
14402 workspace.adjacent_pane(window, cx)
14403 } else {
14404 workspace.active_pane().clone()
14405 };
14406
14407 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14408 let editor = buffer
14409 .read(cx)
14410 .file()
14411 .is_none()
14412 .then(|| {
14413 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14414 // so `workspace.open_project_item` will never find them, always opening a new editor.
14415 // Instead, we try to activate the existing editor in the pane first.
14416 let (editor, pane_item_index) =
14417 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14418 let editor = item.downcast::<Editor>()?;
14419 let singleton_buffer =
14420 editor.read(cx).buffer().read(cx).as_singleton()?;
14421 if singleton_buffer == buffer {
14422 Some((editor, i))
14423 } else {
14424 None
14425 }
14426 })?;
14427 pane.update(cx, |pane, cx| {
14428 pane.activate_item(pane_item_index, true, true, window, cx)
14429 });
14430 Some(editor)
14431 })
14432 .flatten()
14433 .unwrap_or_else(|| {
14434 workspace.open_project_item::<Self>(
14435 pane.clone(),
14436 buffer,
14437 true,
14438 true,
14439 window,
14440 cx,
14441 )
14442 });
14443
14444 editor.update(cx, |editor, cx| {
14445 let autoscroll = match scroll_offset {
14446 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14447 None => Autoscroll::newest(),
14448 };
14449 let nav_history = editor.nav_history.take();
14450 editor.change_selections(Some(autoscroll), window, cx, |s| {
14451 s.select_ranges(ranges);
14452 });
14453 editor.nav_history = nav_history;
14454 });
14455 }
14456 })
14457 });
14458 }
14459
14460 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14461 let snapshot = self.buffer.read(cx).read(cx);
14462 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14463 Some(
14464 ranges
14465 .iter()
14466 .map(move |range| {
14467 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14468 })
14469 .collect(),
14470 )
14471 }
14472
14473 fn selection_replacement_ranges(
14474 &self,
14475 range: Range<OffsetUtf16>,
14476 cx: &mut App,
14477 ) -> Vec<Range<OffsetUtf16>> {
14478 let selections = self.selections.all::<OffsetUtf16>(cx);
14479 let newest_selection = selections
14480 .iter()
14481 .max_by_key(|selection| selection.id)
14482 .unwrap();
14483 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14484 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14485 let snapshot = self.buffer.read(cx).read(cx);
14486 selections
14487 .into_iter()
14488 .map(|mut selection| {
14489 selection.start.0 =
14490 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14491 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14492 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14493 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14494 })
14495 .collect()
14496 }
14497
14498 fn report_editor_event(
14499 &self,
14500 event_type: &'static str,
14501 file_extension: Option<String>,
14502 cx: &App,
14503 ) {
14504 if cfg!(any(test, feature = "test-support")) {
14505 return;
14506 }
14507
14508 let Some(project) = &self.project else { return };
14509
14510 // If None, we are in a file without an extension
14511 let file = self
14512 .buffer
14513 .read(cx)
14514 .as_singleton()
14515 .and_then(|b| b.read(cx).file());
14516 let file_extension = file_extension.or(file
14517 .as_ref()
14518 .and_then(|file| Path::new(file.file_name(cx)).extension())
14519 .and_then(|e| e.to_str())
14520 .map(|a| a.to_string()));
14521
14522 let vim_mode = cx
14523 .global::<SettingsStore>()
14524 .raw_user_settings()
14525 .get("vim_mode")
14526 == Some(&serde_json::Value::Bool(true));
14527
14528 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14529 let copilot_enabled = edit_predictions_provider
14530 == language::language_settings::EditPredictionProvider::Copilot;
14531 let copilot_enabled_for_language = self
14532 .buffer
14533 .read(cx)
14534 .settings_at(0, cx)
14535 .show_edit_predictions;
14536
14537 let project = project.read(cx);
14538 telemetry::event!(
14539 event_type,
14540 file_extension,
14541 vim_mode,
14542 copilot_enabled,
14543 copilot_enabled_for_language,
14544 edit_predictions_provider,
14545 is_via_ssh = project.is_via_ssh(),
14546 );
14547 }
14548
14549 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14550 /// with each line being an array of {text, highlight} objects.
14551 fn copy_highlight_json(
14552 &mut self,
14553 _: &CopyHighlightJson,
14554 window: &mut Window,
14555 cx: &mut Context<Self>,
14556 ) {
14557 #[derive(Serialize)]
14558 struct Chunk<'a> {
14559 text: String,
14560 highlight: Option<&'a str>,
14561 }
14562
14563 let snapshot = self.buffer.read(cx).snapshot(cx);
14564 let range = self
14565 .selected_text_range(false, window, cx)
14566 .and_then(|selection| {
14567 if selection.range.is_empty() {
14568 None
14569 } else {
14570 Some(selection.range)
14571 }
14572 })
14573 .unwrap_or_else(|| 0..snapshot.len());
14574
14575 let chunks = snapshot.chunks(range, true);
14576 let mut lines = Vec::new();
14577 let mut line: VecDeque<Chunk> = VecDeque::new();
14578
14579 let Some(style) = self.style.as_ref() else {
14580 return;
14581 };
14582
14583 for chunk in chunks {
14584 let highlight = chunk
14585 .syntax_highlight_id
14586 .and_then(|id| id.name(&style.syntax));
14587 let mut chunk_lines = chunk.text.split('\n').peekable();
14588 while let Some(text) = chunk_lines.next() {
14589 let mut merged_with_last_token = false;
14590 if let Some(last_token) = line.back_mut() {
14591 if last_token.highlight == highlight {
14592 last_token.text.push_str(text);
14593 merged_with_last_token = true;
14594 }
14595 }
14596
14597 if !merged_with_last_token {
14598 line.push_back(Chunk {
14599 text: text.into(),
14600 highlight,
14601 });
14602 }
14603
14604 if chunk_lines.peek().is_some() {
14605 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14606 line.pop_front();
14607 }
14608 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14609 line.pop_back();
14610 }
14611
14612 lines.push(mem::take(&mut line));
14613 }
14614 }
14615 }
14616
14617 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14618 return;
14619 };
14620 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14621 }
14622
14623 pub fn open_context_menu(
14624 &mut self,
14625 _: &OpenContextMenu,
14626 window: &mut Window,
14627 cx: &mut Context<Self>,
14628 ) {
14629 self.request_autoscroll(Autoscroll::newest(), cx);
14630 let position = self.selections.newest_display(cx).start;
14631 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14632 }
14633
14634 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14635 &self.inlay_hint_cache
14636 }
14637
14638 pub fn replay_insert_event(
14639 &mut self,
14640 text: &str,
14641 relative_utf16_range: Option<Range<isize>>,
14642 window: &mut Window,
14643 cx: &mut Context<Self>,
14644 ) {
14645 if !self.input_enabled {
14646 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14647 return;
14648 }
14649 if let Some(relative_utf16_range) = relative_utf16_range {
14650 let selections = self.selections.all::<OffsetUtf16>(cx);
14651 self.change_selections(None, window, cx, |s| {
14652 let new_ranges = selections.into_iter().map(|range| {
14653 let start = OffsetUtf16(
14654 range
14655 .head()
14656 .0
14657 .saturating_add_signed(relative_utf16_range.start),
14658 );
14659 let end = OffsetUtf16(
14660 range
14661 .head()
14662 .0
14663 .saturating_add_signed(relative_utf16_range.end),
14664 );
14665 start..end
14666 });
14667 s.select_ranges(new_ranges);
14668 });
14669 }
14670
14671 self.handle_input(text, window, cx);
14672 }
14673
14674 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14675 let Some(provider) = self.semantics_provider.as_ref() else {
14676 return false;
14677 };
14678
14679 let mut supports = false;
14680 self.buffer().update(cx, |this, cx| {
14681 this.for_each_buffer(|buffer| {
14682 supports |= provider.supports_inlay_hints(buffer, cx);
14683 });
14684 });
14685
14686 supports
14687 }
14688
14689 pub fn is_focused(&self, window: &Window) -> bool {
14690 self.focus_handle.is_focused(window)
14691 }
14692
14693 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14694 cx.emit(EditorEvent::Focused);
14695
14696 if let Some(descendant) = self
14697 .last_focused_descendant
14698 .take()
14699 .and_then(|descendant| descendant.upgrade())
14700 {
14701 window.focus(&descendant);
14702 } else {
14703 if let Some(blame) = self.blame.as_ref() {
14704 blame.update(cx, GitBlame::focus)
14705 }
14706
14707 self.blink_manager.update(cx, BlinkManager::enable);
14708 self.show_cursor_names(window, cx);
14709 self.buffer.update(cx, |buffer, cx| {
14710 buffer.finalize_last_transaction(cx);
14711 if self.leader_peer_id.is_none() {
14712 buffer.set_active_selections(
14713 &self.selections.disjoint_anchors(),
14714 self.selections.line_mode,
14715 self.cursor_shape,
14716 cx,
14717 );
14718 }
14719 });
14720 }
14721 }
14722
14723 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14724 cx.emit(EditorEvent::FocusedIn)
14725 }
14726
14727 fn handle_focus_out(
14728 &mut self,
14729 event: FocusOutEvent,
14730 _window: &mut Window,
14731 _cx: &mut Context<Self>,
14732 ) {
14733 if event.blurred != self.focus_handle {
14734 self.last_focused_descendant = Some(event.blurred);
14735 }
14736 }
14737
14738 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14739 self.blink_manager.update(cx, BlinkManager::disable);
14740 self.buffer
14741 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14742
14743 if let Some(blame) = self.blame.as_ref() {
14744 blame.update(cx, GitBlame::blur)
14745 }
14746 if !self.hover_state.focused(window, cx) {
14747 hide_hover(self, cx);
14748 }
14749
14750 self.hide_context_menu(window, cx);
14751 self.discard_inline_completion(false, cx);
14752 cx.emit(EditorEvent::Blurred);
14753 cx.notify();
14754 }
14755
14756 pub fn register_action<A: Action>(
14757 &mut self,
14758 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14759 ) -> Subscription {
14760 let id = self.next_editor_action_id.post_inc();
14761 let listener = Arc::new(listener);
14762 self.editor_actions.borrow_mut().insert(
14763 id,
14764 Box::new(move |window, _| {
14765 let listener = listener.clone();
14766 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14767 let action = action.downcast_ref().unwrap();
14768 if phase == DispatchPhase::Bubble {
14769 listener(action, window, cx)
14770 }
14771 })
14772 }),
14773 );
14774
14775 let editor_actions = self.editor_actions.clone();
14776 Subscription::new(move || {
14777 editor_actions.borrow_mut().remove(&id);
14778 })
14779 }
14780
14781 pub fn file_header_size(&self) -> u32 {
14782 FILE_HEADER_HEIGHT
14783 }
14784
14785 pub fn revert(
14786 &mut self,
14787 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14788 window: &mut Window,
14789 cx: &mut Context<Self>,
14790 ) {
14791 self.buffer().update(cx, |multi_buffer, cx| {
14792 for (buffer_id, changes) in revert_changes {
14793 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14794 buffer.update(cx, |buffer, cx| {
14795 buffer.edit(
14796 changes.into_iter().map(|(range, text)| {
14797 (range, text.to_string().map(Arc::<str>::from))
14798 }),
14799 None,
14800 cx,
14801 );
14802 });
14803 }
14804 }
14805 });
14806 self.change_selections(None, window, cx, |selections| selections.refresh());
14807 }
14808
14809 pub fn to_pixel_point(
14810 &self,
14811 source: multi_buffer::Anchor,
14812 editor_snapshot: &EditorSnapshot,
14813 window: &mut Window,
14814 ) -> Option<gpui::Point<Pixels>> {
14815 let source_point = source.to_display_point(editor_snapshot);
14816 self.display_to_pixel_point(source_point, editor_snapshot, window)
14817 }
14818
14819 pub fn display_to_pixel_point(
14820 &self,
14821 source: DisplayPoint,
14822 editor_snapshot: &EditorSnapshot,
14823 window: &mut Window,
14824 ) -> Option<gpui::Point<Pixels>> {
14825 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14826 let text_layout_details = self.text_layout_details(window);
14827 let scroll_top = text_layout_details
14828 .scroll_anchor
14829 .scroll_position(editor_snapshot)
14830 .y;
14831
14832 if source.row().as_f32() < scroll_top.floor() {
14833 return None;
14834 }
14835 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14836 let source_y = line_height * (source.row().as_f32() - scroll_top);
14837 Some(gpui::Point::new(source_x, source_y))
14838 }
14839
14840 pub fn has_visible_completions_menu(&self) -> bool {
14841 !self.edit_prediction_preview_is_active()
14842 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14843 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14844 })
14845 }
14846
14847 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14848 self.addons
14849 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14850 }
14851
14852 pub fn unregister_addon<T: Addon>(&mut self) {
14853 self.addons.remove(&std::any::TypeId::of::<T>());
14854 }
14855
14856 pub fn addon<T: Addon>(&self) -> Option<&T> {
14857 let type_id = std::any::TypeId::of::<T>();
14858 self.addons
14859 .get(&type_id)
14860 .and_then(|item| item.to_any().downcast_ref::<T>())
14861 }
14862
14863 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14864 let text_layout_details = self.text_layout_details(window);
14865 let style = &text_layout_details.editor_style;
14866 let font_id = window.text_system().resolve_font(&style.text.font());
14867 let font_size = style.text.font_size.to_pixels(window.rem_size());
14868 let line_height = style.text.line_height_in_pixels(window.rem_size());
14869 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14870
14871 gpui::Size::new(em_width, line_height)
14872 }
14873
14874 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14875 self.load_diff_task.clone()
14876 }
14877}
14878
14879fn get_uncommitted_diff_for_buffer(
14880 project: &Entity<Project>,
14881 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14882 buffer: Entity<MultiBuffer>,
14883 cx: &mut App,
14884) -> Task<()> {
14885 let mut tasks = Vec::new();
14886 project.update(cx, |project, cx| {
14887 for buffer in buffers {
14888 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14889 }
14890 });
14891 cx.spawn(|mut cx| async move {
14892 let diffs = futures::future::join_all(tasks).await;
14893 buffer
14894 .update(&mut cx, |buffer, cx| {
14895 for diff in diffs.into_iter().flatten() {
14896 buffer.add_diff(diff, cx);
14897 }
14898 })
14899 .ok();
14900 })
14901}
14902
14903fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14904 let tab_size = tab_size.get() as usize;
14905 let mut width = offset;
14906
14907 for ch in text.chars() {
14908 width += if ch == '\t' {
14909 tab_size - (width % tab_size)
14910 } else {
14911 1
14912 };
14913 }
14914
14915 width - offset
14916}
14917
14918#[cfg(test)]
14919mod tests {
14920 use super::*;
14921
14922 #[test]
14923 fn test_string_size_with_expanded_tabs() {
14924 let nz = |val| NonZeroU32::new(val).unwrap();
14925 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14926 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14927 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14928 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14929 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14930 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14931 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14932 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14933 }
14934}
14935
14936/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14937struct WordBreakingTokenizer<'a> {
14938 input: &'a str,
14939}
14940
14941impl<'a> WordBreakingTokenizer<'a> {
14942 fn new(input: &'a str) -> Self {
14943 Self { input }
14944 }
14945}
14946
14947fn is_char_ideographic(ch: char) -> bool {
14948 use unicode_script::Script::*;
14949 use unicode_script::UnicodeScript;
14950 matches!(ch.script(), Han | Tangut | Yi)
14951}
14952
14953fn is_grapheme_ideographic(text: &str) -> bool {
14954 text.chars().any(is_char_ideographic)
14955}
14956
14957fn is_grapheme_whitespace(text: &str) -> bool {
14958 text.chars().any(|x| x.is_whitespace())
14959}
14960
14961fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14962 text.chars().next().map_or(false, |ch| {
14963 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14964 })
14965}
14966
14967#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14968struct WordBreakToken<'a> {
14969 token: &'a str,
14970 grapheme_len: usize,
14971 is_whitespace: bool,
14972}
14973
14974impl<'a> Iterator for WordBreakingTokenizer<'a> {
14975 /// Yields a span, the count of graphemes in the token, and whether it was
14976 /// whitespace. Note that it also breaks at word boundaries.
14977 type Item = WordBreakToken<'a>;
14978
14979 fn next(&mut self) -> Option<Self::Item> {
14980 use unicode_segmentation::UnicodeSegmentation;
14981 if self.input.is_empty() {
14982 return None;
14983 }
14984
14985 let mut iter = self.input.graphemes(true).peekable();
14986 let mut offset = 0;
14987 let mut graphemes = 0;
14988 if let Some(first_grapheme) = iter.next() {
14989 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14990 offset += first_grapheme.len();
14991 graphemes += 1;
14992 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14993 if let Some(grapheme) = iter.peek().copied() {
14994 if should_stay_with_preceding_ideograph(grapheme) {
14995 offset += grapheme.len();
14996 graphemes += 1;
14997 }
14998 }
14999 } else {
15000 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15001 let mut next_word_bound = words.peek().copied();
15002 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15003 next_word_bound = words.next();
15004 }
15005 while let Some(grapheme) = iter.peek().copied() {
15006 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15007 break;
15008 };
15009 if is_grapheme_whitespace(grapheme) != is_whitespace {
15010 break;
15011 };
15012 offset += grapheme.len();
15013 graphemes += 1;
15014 iter.next();
15015 }
15016 }
15017 let token = &self.input[..offset];
15018 self.input = &self.input[offset..];
15019 if is_whitespace {
15020 Some(WordBreakToken {
15021 token: " ",
15022 grapheme_len: 1,
15023 is_whitespace: true,
15024 })
15025 } else {
15026 Some(WordBreakToken {
15027 token,
15028 grapheme_len: graphemes,
15029 is_whitespace: false,
15030 })
15031 }
15032 } else {
15033 None
15034 }
15035 }
15036}
15037
15038#[test]
15039fn test_word_breaking_tokenizer() {
15040 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15041 ("", &[]),
15042 (" ", &[(" ", 1, true)]),
15043 ("Ʒ", &[("Ʒ", 1, false)]),
15044 ("Ǽ", &[("Ǽ", 1, false)]),
15045 ("⋑", &[("⋑", 1, false)]),
15046 ("⋑⋑", &[("⋑⋑", 2, false)]),
15047 (
15048 "原理,进而",
15049 &[
15050 ("原", 1, false),
15051 ("理,", 2, false),
15052 ("进", 1, false),
15053 ("而", 1, false),
15054 ],
15055 ),
15056 (
15057 "hello world",
15058 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15059 ),
15060 (
15061 "hello, world",
15062 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15063 ),
15064 (
15065 " hello world",
15066 &[
15067 (" ", 1, true),
15068 ("hello", 5, false),
15069 (" ", 1, true),
15070 ("world", 5, false),
15071 ],
15072 ),
15073 (
15074 "这是什么 \n 钢笔",
15075 &[
15076 ("这", 1, false),
15077 ("是", 1, false),
15078 ("什", 1, false),
15079 ("么", 1, false),
15080 (" ", 1, true),
15081 ("钢", 1, false),
15082 ("笔", 1, false),
15083 ],
15084 ),
15085 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15086 ];
15087
15088 for (input, result) in tests {
15089 assert_eq!(
15090 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15091 result
15092 .iter()
15093 .copied()
15094 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15095 token,
15096 grapheme_len,
15097 is_whitespace,
15098 })
15099 .collect::<Vec<_>>()
15100 );
15101 }
15102}
15103
15104fn wrap_with_prefix(
15105 line_prefix: String,
15106 unwrapped_text: String,
15107 wrap_column: usize,
15108 tab_size: NonZeroU32,
15109) -> String {
15110 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15111 let mut wrapped_text = String::new();
15112 let mut current_line = line_prefix.clone();
15113
15114 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15115 let mut current_line_len = line_prefix_len;
15116 for WordBreakToken {
15117 token,
15118 grapheme_len,
15119 is_whitespace,
15120 } in tokenizer
15121 {
15122 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15123 wrapped_text.push_str(current_line.trim_end());
15124 wrapped_text.push('\n');
15125 current_line.truncate(line_prefix.len());
15126 current_line_len = line_prefix_len;
15127 if !is_whitespace {
15128 current_line.push_str(token);
15129 current_line_len += grapheme_len;
15130 }
15131 } else if !is_whitespace {
15132 current_line.push_str(token);
15133 current_line_len += grapheme_len;
15134 } else if current_line_len != line_prefix_len {
15135 current_line.push(' ');
15136 current_line_len += 1;
15137 }
15138 }
15139
15140 if !current_line.is_empty() {
15141 wrapped_text.push_str(¤t_line);
15142 }
15143 wrapped_text
15144}
15145
15146#[test]
15147fn test_wrap_with_prefix() {
15148 assert_eq!(
15149 wrap_with_prefix(
15150 "# ".to_string(),
15151 "abcdefg".to_string(),
15152 4,
15153 NonZeroU32::new(4).unwrap()
15154 ),
15155 "# abcdefg"
15156 );
15157 assert_eq!(
15158 wrap_with_prefix(
15159 "".to_string(),
15160 "\thello world".to_string(),
15161 8,
15162 NonZeroU32::new(4).unwrap()
15163 ),
15164 "hello\nworld"
15165 );
15166 assert_eq!(
15167 wrap_with_prefix(
15168 "// ".to_string(),
15169 "xx \nyy zz aa bb cc".to_string(),
15170 12,
15171 NonZeroU32::new(4).unwrap()
15172 ),
15173 "// xx yy zz\n// aa bb cc"
15174 );
15175 assert_eq!(
15176 wrap_with_prefix(
15177 String::new(),
15178 "这是什么 \n 钢笔".to_string(),
15179 3,
15180 NonZeroU32::new(4).unwrap()
15181 ),
15182 "这是什\n么 钢\n笔"
15183 );
15184}
15185
15186pub trait CollaborationHub {
15187 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15188 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15189 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15190}
15191
15192impl CollaborationHub for Entity<Project> {
15193 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15194 self.read(cx).collaborators()
15195 }
15196
15197 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15198 self.read(cx).user_store().read(cx).participant_indices()
15199 }
15200
15201 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15202 let this = self.read(cx);
15203 let user_ids = this.collaborators().values().map(|c| c.user_id);
15204 this.user_store().read_with(cx, |user_store, cx| {
15205 user_store.participant_names(user_ids, cx)
15206 })
15207 }
15208}
15209
15210pub trait SemanticsProvider {
15211 fn hover(
15212 &self,
15213 buffer: &Entity<Buffer>,
15214 position: text::Anchor,
15215 cx: &mut App,
15216 ) -> Option<Task<Vec<project::Hover>>>;
15217
15218 fn inlay_hints(
15219 &self,
15220 buffer_handle: Entity<Buffer>,
15221 range: Range<text::Anchor>,
15222 cx: &mut App,
15223 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15224
15225 fn resolve_inlay_hint(
15226 &self,
15227 hint: InlayHint,
15228 buffer_handle: Entity<Buffer>,
15229 server_id: LanguageServerId,
15230 cx: &mut App,
15231 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15232
15233 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15234
15235 fn document_highlights(
15236 &self,
15237 buffer: &Entity<Buffer>,
15238 position: text::Anchor,
15239 cx: &mut App,
15240 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15241
15242 fn definitions(
15243 &self,
15244 buffer: &Entity<Buffer>,
15245 position: text::Anchor,
15246 kind: GotoDefinitionKind,
15247 cx: &mut App,
15248 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15249
15250 fn range_for_rename(
15251 &self,
15252 buffer: &Entity<Buffer>,
15253 position: text::Anchor,
15254 cx: &mut App,
15255 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15256
15257 fn perform_rename(
15258 &self,
15259 buffer: &Entity<Buffer>,
15260 position: text::Anchor,
15261 new_name: String,
15262 cx: &mut App,
15263 ) -> Option<Task<Result<ProjectTransaction>>>;
15264}
15265
15266pub trait CompletionProvider {
15267 fn completions(
15268 &self,
15269 buffer: &Entity<Buffer>,
15270 buffer_position: text::Anchor,
15271 trigger: CompletionContext,
15272 window: &mut Window,
15273 cx: &mut Context<Editor>,
15274 ) -> Task<Result<Vec<Completion>>>;
15275
15276 fn resolve_completions(
15277 &self,
15278 buffer: Entity<Buffer>,
15279 completion_indices: Vec<usize>,
15280 completions: Rc<RefCell<Box<[Completion]>>>,
15281 cx: &mut Context<Editor>,
15282 ) -> Task<Result<bool>>;
15283
15284 fn apply_additional_edits_for_completion(
15285 &self,
15286 _buffer: Entity<Buffer>,
15287 _completions: Rc<RefCell<Box<[Completion]>>>,
15288 _completion_index: usize,
15289 _push_to_history: bool,
15290 _cx: &mut Context<Editor>,
15291 ) -> Task<Result<Option<language::Transaction>>> {
15292 Task::ready(Ok(None))
15293 }
15294
15295 fn is_completion_trigger(
15296 &self,
15297 buffer: &Entity<Buffer>,
15298 position: language::Anchor,
15299 text: &str,
15300 trigger_in_words: bool,
15301 cx: &mut Context<Editor>,
15302 ) -> bool;
15303
15304 fn sort_completions(&self) -> bool {
15305 true
15306 }
15307}
15308
15309pub trait CodeActionProvider {
15310 fn id(&self) -> Arc<str>;
15311
15312 fn code_actions(
15313 &self,
15314 buffer: &Entity<Buffer>,
15315 range: Range<text::Anchor>,
15316 window: &mut Window,
15317 cx: &mut App,
15318 ) -> Task<Result<Vec<CodeAction>>>;
15319
15320 fn apply_code_action(
15321 &self,
15322 buffer_handle: Entity<Buffer>,
15323 action: CodeAction,
15324 excerpt_id: ExcerptId,
15325 push_to_history: bool,
15326 window: &mut Window,
15327 cx: &mut App,
15328 ) -> Task<Result<ProjectTransaction>>;
15329}
15330
15331impl CodeActionProvider for Entity<Project> {
15332 fn id(&self) -> Arc<str> {
15333 "project".into()
15334 }
15335
15336 fn code_actions(
15337 &self,
15338 buffer: &Entity<Buffer>,
15339 range: Range<text::Anchor>,
15340 _window: &mut Window,
15341 cx: &mut App,
15342 ) -> Task<Result<Vec<CodeAction>>> {
15343 self.update(cx, |project, cx| {
15344 project.code_actions(buffer, range, None, cx)
15345 })
15346 }
15347
15348 fn apply_code_action(
15349 &self,
15350 buffer_handle: Entity<Buffer>,
15351 action: CodeAction,
15352 _excerpt_id: ExcerptId,
15353 push_to_history: bool,
15354 _window: &mut Window,
15355 cx: &mut App,
15356 ) -> Task<Result<ProjectTransaction>> {
15357 self.update(cx, |project, cx| {
15358 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15359 })
15360 }
15361}
15362
15363fn snippet_completions(
15364 project: &Project,
15365 buffer: &Entity<Buffer>,
15366 buffer_position: text::Anchor,
15367 cx: &mut App,
15368) -> Task<Result<Vec<Completion>>> {
15369 let language = buffer.read(cx).language_at(buffer_position);
15370 let language_name = language.as_ref().map(|language| language.lsp_id());
15371 let snippet_store = project.snippets().read(cx);
15372 let snippets = snippet_store.snippets_for(language_name, cx);
15373
15374 if snippets.is_empty() {
15375 return Task::ready(Ok(vec![]));
15376 }
15377 let snapshot = buffer.read(cx).text_snapshot();
15378 let chars: String = snapshot
15379 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15380 .collect();
15381
15382 let scope = language.map(|language| language.default_scope());
15383 let executor = cx.background_executor().clone();
15384
15385 cx.background_executor().spawn(async move {
15386 let classifier = CharClassifier::new(scope).for_completion(true);
15387 let mut last_word = chars
15388 .chars()
15389 .take_while(|c| classifier.is_word(*c))
15390 .collect::<String>();
15391 last_word = last_word.chars().rev().collect();
15392
15393 if last_word.is_empty() {
15394 return Ok(vec![]);
15395 }
15396
15397 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15398 let to_lsp = |point: &text::Anchor| {
15399 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15400 point_to_lsp(end)
15401 };
15402 let lsp_end = to_lsp(&buffer_position);
15403
15404 let candidates = snippets
15405 .iter()
15406 .enumerate()
15407 .flat_map(|(ix, snippet)| {
15408 snippet
15409 .prefix
15410 .iter()
15411 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15412 })
15413 .collect::<Vec<StringMatchCandidate>>();
15414
15415 let mut matches = fuzzy::match_strings(
15416 &candidates,
15417 &last_word,
15418 last_word.chars().any(|c| c.is_uppercase()),
15419 100,
15420 &Default::default(),
15421 executor,
15422 )
15423 .await;
15424
15425 // Remove all candidates where the query's start does not match the start of any word in the candidate
15426 if let Some(query_start) = last_word.chars().next() {
15427 matches.retain(|string_match| {
15428 split_words(&string_match.string).any(|word| {
15429 // Check that the first codepoint of the word as lowercase matches the first
15430 // codepoint of the query as lowercase
15431 word.chars()
15432 .flat_map(|codepoint| codepoint.to_lowercase())
15433 .zip(query_start.to_lowercase())
15434 .all(|(word_cp, query_cp)| word_cp == query_cp)
15435 })
15436 });
15437 }
15438
15439 let matched_strings = matches
15440 .into_iter()
15441 .map(|m| m.string)
15442 .collect::<HashSet<_>>();
15443
15444 let result: Vec<Completion> = snippets
15445 .into_iter()
15446 .filter_map(|snippet| {
15447 let matching_prefix = snippet
15448 .prefix
15449 .iter()
15450 .find(|prefix| matched_strings.contains(*prefix))?;
15451 let start = as_offset - last_word.len();
15452 let start = snapshot.anchor_before(start);
15453 let range = start..buffer_position;
15454 let lsp_start = to_lsp(&start);
15455 let lsp_range = lsp::Range {
15456 start: lsp_start,
15457 end: lsp_end,
15458 };
15459 Some(Completion {
15460 old_range: range,
15461 new_text: snippet.body.clone(),
15462 resolved: false,
15463 label: CodeLabel {
15464 text: matching_prefix.clone(),
15465 runs: vec![],
15466 filter_range: 0..matching_prefix.len(),
15467 },
15468 server_id: LanguageServerId(usize::MAX),
15469 documentation: snippet
15470 .description
15471 .clone()
15472 .map(CompletionDocumentation::SingleLine),
15473 lsp_completion: lsp::CompletionItem {
15474 label: snippet.prefix.first().unwrap().clone(),
15475 kind: Some(CompletionItemKind::SNIPPET),
15476 label_details: snippet.description.as_ref().map(|description| {
15477 lsp::CompletionItemLabelDetails {
15478 detail: Some(description.clone()),
15479 description: None,
15480 }
15481 }),
15482 insert_text_format: Some(InsertTextFormat::SNIPPET),
15483 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15484 lsp::InsertReplaceEdit {
15485 new_text: snippet.body.clone(),
15486 insert: lsp_range,
15487 replace: lsp_range,
15488 },
15489 )),
15490 filter_text: Some(snippet.body.clone()),
15491 sort_text: Some(char::MAX.to_string()),
15492 ..Default::default()
15493 },
15494 confirm: None,
15495 })
15496 })
15497 .collect();
15498
15499 Ok(result)
15500 })
15501}
15502
15503impl CompletionProvider for Entity<Project> {
15504 fn completions(
15505 &self,
15506 buffer: &Entity<Buffer>,
15507 buffer_position: text::Anchor,
15508 options: CompletionContext,
15509 _window: &mut Window,
15510 cx: &mut Context<Editor>,
15511 ) -> Task<Result<Vec<Completion>>> {
15512 self.update(cx, |project, cx| {
15513 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15514 let project_completions = project.completions(buffer, buffer_position, options, cx);
15515 cx.background_executor().spawn(async move {
15516 let mut completions = project_completions.await?;
15517 let snippets_completions = snippets.await?;
15518 completions.extend(snippets_completions);
15519 Ok(completions)
15520 })
15521 })
15522 }
15523
15524 fn resolve_completions(
15525 &self,
15526 buffer: Entity<Buffer>,
15527 completion_indices: Vec<usize>,
15528 completions: Rc<RefCell<Box<[Completion]>>>,
15529 cx: &mut Context<Editor>,
15530 ) -> Task<Result<bool>> {
15531 self.update(cx, |project, cx| {
15532 project.lsp_store().update(cx, |lsp_store, cx| {
15533 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15534 })
15535 })
15536 }
15537
15538 fn apply_additional_edits_for_completion(
15539 &self,
15540 buffer: Entity<Buffer>,
15541 completions: Rc<RefCell<Box<[Completion]>>>,
15542 completion_index: usize,
15543 push_to_history: bool,
15544 cx: &mut Context<Editor>,
15545 ) -> Task<Result<Option<language::Transaction>>> {
15546 self.update(cx, |project, cx| {
15547 project.lsp_store().update(cx, |lsp_store, cx| {
15548 lsp_store.apply_additional_edits_for_completion(
15549 buffer,
15550 completions,
15551 completion_index,
15552 push_to_history,
15553 cx,
15554 )
15555 })
15556 })
15557 }
15558
15559 fn is_completion_trigger(
15560 &self,
15561 buffer: &Entity<Buffer>,
15562 position: language::Anchor,
15563 text: &str,
15564 trigger_in_words: bool,
15565 cx: &mut Context<Editor>,
15566 ) -> bool {
15567 let mut chars = text.chars();
15568 let char = if let Some(char) = chars.next() {
15569 char
15570 } else {
15571 return false;
15572 };
15573 if chars.next().is_some() {
15574 return false;
15575 }
15576
15577 let buffer = buffer.read(cx);
15578 let snapshot = buffer.snapshot();
15579 if !snapshot.settings_at(position, cx).show_completions_on_input {
15580 return false;
15581 }
15582 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15583 if trigger_in_words && classifier.is_word(char) {
15584 return true;
15585 }
15586
15587 buffer.completion_triggers().contains(text)
15588 }
15589}
15590
15591impl SemanticsProvider for Entity<Project> {
15592 fn hover(
15593 &self,
15594 buffer: &Entity<Buffer>,
15595 position: text::Anchor,
15596 cx: &mut App,
15597 ) -> Option<Task<Vec<project::Hover>>> {
15598 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15599 }
15600
15601 fn document_highlights(
15602 &self,
15603 buffer: &Entity<Buffer>,
15604 position: text::Anchor,
15605 cx: &mut App,
15606 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15607 Some(self.update(cx, |project, cx| {
15608 project.document_highlights(buffer, position, cx)
15609 }))
15610 }
15611
15612 fn definitions(
15613 &self,
15614 buffer: &Entity<Buffer>,
15615 position: text::Anchor,
15616 kind: GotoDefinitionKind,
15617 cx: &mut App,
15618 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15619 Some(self.update(cx, |project, cx| match kind {
15620 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15621 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15622 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15623 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15624 }))
15625 }
15626
15627 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15628 // TODO: make this work for remote projects
15629 self.update(cx, |this, cx| {
15630 buffer.update(cx, |buffer, cx| {
15631 this.any_language_server_supports_inlay_hints(buffer, cx)
15632 })
15633 })
15634 }
15635
15636 fn inlay_hints(
15637 &self,
15638 buffer_handle: Entity<Buffer>,
15639 range: Range<text::Anchor>,
15640 cx: &mut App,
15641 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15642 Some(self.update(cx, |project, cx| {
15643 project.inlay_hints(buffer_handle, range, cx)
15644 }))
15645 }
15646
15647 fn resolve_inlay_hint(
15648 &self,
15649 hint: InlayHint,
15650 buffer_handle: Entity<Buffer>,
15651 server_id: LanguageServerId,
15652 cx: &mut App,
15653 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15654 Some(self.update(cx, |project, cx| {
15655 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15656 }))
15657 }
15658
15659 fn range_for_rename(
15660 &self,
15661 buffer: &Entity<Buffer>,
15662 position: text::Anchor,
15663 cx: &mut App,
15664 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15665 Some(self.update(cx, |project, cx| {
15666 let buffer = buffer.clone();
15667 let task = project.prepare_rename(buffer.clone(), position, cx);
15668 cx.spawn(|_, mut cx| async move {
15669 Ok(match task.await? {
15670 PrepareRenameResponse::Success(range) => Some(range),
15671 PrepareRenameResponse::InvalidPosition => None,
15672 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15673 // Fallback on using TreeSitter info to determine identifier range
15674 buffer.update(&mut cx, |buffer, _| {
15675 let snapshot = buffer.snapshot();
15676 let (range, kind) = snapshot.surrounding_word(position);
15677 if kind != Some(CharKind::Word) {
15678 return None;
15679 }
15680 Some(
15681 snapshot.anchor_before(range.start)
15682 ..snapshot.anchor_after(range.end),
15683 )
15684 })?
15685 }
15686 })
15687 })
15688 }))
15689 }
15690
15691 fn perform_rename(
15692 &self,
15693 buffer: &Entity<Buffer>,
15694 position: text::Anchor,
15695 new_name: String,
15696 cx: &mut App,
15697 ) -> Option<Task<Result<ProjectTransaction>>> {
15698 Some(self.update(cx, |project, cx| {
15699 project.perform_rename(buffer.clone(), position, new_name, cx)
15700 }))
15701 }
15702}
15703
15704fn inlay_hint_settings(
15705 location: Anchor,
15706 snapshot: &MultiBufferSnapshot,
15707 cx: &mut Context<Editor>,
15708) -> InlayHintSettings {
15709 let file = snapshot.file_at(location);
15710 let language = snapshot.language_at(location).map(|l| l.name());
15711 language_settings(language, file, cx).inlay_hints
15712}
15713
15714fn consume_contiguous_rows(
15715 contiguous_row_selections: &mut Vec<Selection<Point>>,
15716 selection: &Selection<Point>,
15717 display_map: &DisplaySnapshot,
15718 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15719) -> (MultiBufferRow, MultiBufferRow) {
15720 contiguous_row_selections.push(selection.clone());
15721 let start_row = MultiBufferRow(selection.start.row);
15722 let mut end_row = ending_row(selection, display_map);
15723
15724 while let Some(next_selection) = selections.peek() {
15725 if next_selection.start.row <= end_row.0 {
15726 end_row = ending_row(next_selection, display_map);
15727 contiguous_row_selections.push(selections.next().unwrap().clone());
15728 } else {
15729 break;
15730 }
15731 }
15732 (start_row, end_row)
15733}
15734
15735fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15736 if next_selection.end.column > 0 || next_selection.is_empty() {
15737 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15738 } else {
15739 MultiBufferRow(next_selection.end.row)
15740 }
15741}
15742
15743impl EditorSnapshot {
15744 pub fn remote_selections_in_range<'a>(
15745 &'a self,
15746 range: &'a Range<Anchor>,
15747 collaboration_hub: &dyn CollaborationHub,
15748 cx: &'a App,
15749 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15750 let participant_names = collaboration_hub.user_names(cx);
15751 let participant_indices = collaboration_hub.user_participant_indices(cx);
15752 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15753 let collaborators_by_replica_id = collaborators_by_peer_id
15754 .iter()
15755 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15756 .collect::<HashMap<_, _>>();
15757 self.buffer_snapshot
15758 .selections_in_range(range, false)
15759 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15760 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15761 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15762 let user_name = participant_names.get(&collaborator.user_id).cloned();
15763 Some(RemoteSelection {
15764 replica_id,
15765 selection,
15766 cursor_shape,
15767 line_mode,
15768 participant_index,
15769 peer_id: collaborator.peer_id,
15770 user_name,
15771 })
15772 })
15773 }
15774
15775 pub fn hunks_for_ranges(
15776 &self,
15777 ranges: impl Iterator<Item = Range<Point>>,
15778 ) -> Vec<MultiBufferDiffHunk> {
15779 let mut hunks = Vec::new();
15780 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15781 HashMap::default();
15782 for query_range in ranges {
15783 let query_rows =
15784 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15785 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15786 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15787 ) {
15788 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15789 // when the caret is just above or just below the deleted hunk.
15790 let allow_adjacent = hunk.status().is_removed();
15791 let related_to_selection = if allow_adjacent {
15792 hunk.row_range.overlaps(&query_rows)
15793 || hunk.row_range.start == query_rows.end
15794 || hunk.row_range.end == query_rows.start
15795 } else {
15796 hunk.row_range.overlaps(&query_rows)
15797 };
15798 if related_to_selection {
15799 if !processed_buffer_rows
15800 .entry(hunk.buffer_id)
15801 .or_default()
15802 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15803 {
15804 continue;
15805 }
15806 hunks.push(hunk);
15807 }
15808 }
15809 }
15810
15811 hunks
15812 }
15813
15814 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15815 self.display_snapshot.buffer_snapshot.language_at(position)
15816 }
15817
15818 pub fn is_focused(&self) -> bool {
15819 self.is_focused
15820 }
15821
15822 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15823 self.placeholder_text.as_ref()
15824 }
15825
15826 pub fn scroll_position(&self) -> gpui::Point<f32> {
15827 self.scroll_anchor.scroll_position(&self.display_snapshot)
15828 }
15829
15830 fn gutter_dimensions(
15831 &self,
15832 font_id: FontId,
15833 font_size: Pixels,
15834 max_line_number_width: Pixels,
15835 cx: &App,
15836 ) -> Option<GutterDimensions> {
15837 if !self.show_gutter {
15838 return None;
15839 }
15840
15841 let descent = cx.text_system().descent(font_id, font_size);
15842 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15843 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15844
15845 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15846 matches!(
15847 ProjectSettings::get_global(cx).git.git_gutter,
15848 Some(GitGutterSetting::TrackedFiles)
15849 )
15850 });
15851 let gutter_settings = EditorSettings::get_global(cx).gutter;
15852 let show_line_numbers = self
15853 .show_line_numbers
15854 .unwrap_or(gutter_settings.line_numbers);
15855 let line_gutter_width = if show_line_numbers {
15856 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15857 let min_width_for_number_on_gutter = em_advance * 4.0;
15858 max_line_number_width.max(min_width_for_number_on_gutter)
15859 } else {
15860 0.0.into()
15861 };
15862
15863 let show_code_actions = self
15864 .show_code_actions
15865 .unwrap_or(gutter_settings.code_actions);
15866
15867 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15868
15869 let git_blame_entries_width =
15870 self.git_blame_gutter_max_author_length
15871 .map(|max_author_length| {
15872 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15873
15874 /// The number of characters to dedicate to gaps and margins.
15875 const SPACING_WIDTH: usize = 4;
15876
15877 let max_char_count = max_author_length
15878 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15879 + ::git::SHORT_SHA_LENGTH
15880 + MAX_RELATIVE_TIMESTAMP.len()
15881 + SPACING_WIDTH;
15882
15883 em_advance * max_char_count
15884 });
15885
15886 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15887 left_padding += if show_code_actions || show_runnables {
15888 em_width * 3.0
15889 } else if show_git_gutter && show_line_numbers {
15890 em_width * 2.0
15891 } else if show_git_gutter || show_line_numbers {
15892 em_width
15893 } else {
15894 px(0.)
15895 };
15896
15897 let right_padding = if gutter_settings.folds && show_line_numbers {
15898 em_width * 4.0
15899 } else if gutter_settings.folds {
15900 em_width * 3.0
15901 } else if show_line_numbers {
15902 em_width
15903 } else {
15904 px(0.)
15905 };
15906
15907 Some(GutterDimensions {
15908 left_padding,
15909 right_padding,
15910 width: line_gutter_width + left_padding + right_padding,
15911 margin: -descent,
15912 git_blame_entries_width,
15913 })
15914 }
15915
15916 pub fn render_crease_toggle(
15917 &self,
15918 buffer_row: MultiBufferRow,
15919 row_contains_cursor: bool,
15920 editor: Entity<Editor>,
15921 window: &mut Window,
15922 cx: &mut App,
15923 ) -> Option<AnyElement> {
15924 let folded = self.is_line_folded(buffer_row);
15925 let mut is_foldable = false;
15926
15927 if let Some(crease) = self
15928 .crease_snapshot
15929 .query_row(buffer_row, &self.buffer_snapshot)
15930 {
15931 is_foldable = true;
15932 match crease {
15933 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15934 if let Some(render_toggle) = render_toggle {
15935 let toggle_callback =
15936 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15937 if folded {
15938 editor.update(cx, |editor, cx| {
15939 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15940 });
15941 } else {
15942 editor.update(cx, |editor, cx| {
15943 editor.unfold_at(
15944 &crate::UnfoldAt { buffer_row },
15945 window,
15946 cx,
15947 )
15948 });
15949 }
15950 });
15951 return Some((render_toggle)(
15952 buffer_row,
15953 folded,
15954 toggle_callback,
15955 window,
15956 cx,
15957 ));
15958 }
15959 }
15960 }
15961 }
15962
15963 is_foldable |= self.starts_indent(buffer_row);
15964
15965 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15966 Some(
15967 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15968 .toggle_state(folded)
15969 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15970 if folded {
15971 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15972 } else {
15973 this.fold_at(&FoldAt { buffer_row }, window, cx);
15974 }
15975 }))
15976 .into_any_element(),
15977 )
15978 } else {
15979 None
15980 }
15981 }
15982
15983 pub fn render_crease_trailer(
15984 &self,
15985 buffer_row: MultiBufferRow,
15986 window: &mut Window,
15987 cx: &mut App,
15988 ) -> Option<AnyElement> {
15989 let folded = self.is_line_folded(buffer_row);
15990 if let Crease::Inline { render_trailer, .. } = self
15991 .crease_snapshot
15992 .query_row(buffer_row, &self.buffer_snapshot)?
15993 {
15994 let render_trailer = render_trailer.as_ref()?;
15995 Some(render_trailer(buffer_row, folded, window, cx))
15996 } else {
15997 None
15998 }
15999 }
16000}
16001
16002impl Deref for EditorSnapshot {
16003 type Target = DisplaySnapshot;
16004
16005 fn deref(&self) -> &Self::Target {
16006 &self.display_snapshot
16007 }
16008}
16009
16010#[derive(Clone, Debug, PartialEq, Eq)]
16011pub enum EditorEvent {
16012 InputIgnored {
16013 text: Arc<str>,
16014 },
16015 InputHandled {
16016 utf16_range_to_replace: Option<Range<isize>>,
16017 text: Arc<str>,
16018 },
16019 ExcerptsAdded {
16020 buffer: Entity<Buffer>,
16021 predecessor: ExcerptId,
16022 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16023 },
16024 ExcerptsRemoved {
16025 ids: Vec<ExcerptId>,
16026 },
16027 BufferFoldToggled {
16028 ids: Vec<ExcerptId>,
16029 folded: bool,
16030 },
16031 ExcerptsEdited {
16032 ids: Vec<ExcerptId>,
16033 },
16034 ExcerptsExpanded {
16035 ids: Vec<ExcerptId>,
16036 },
16037 BufferEdited,
16038 Edited {
16039 transaction_id: clock::Lamport,
16040 },
16041 Reparsed(BufferId),
16042 Focused,
16043 FocusedIn,
16044 Blurred,
16045 DirtyChanged,
16046 Saved,
16047 TitleChanged,
16048 DiffBaseChanged,
16049 SelectionsChanged {
16050 local: bool,
16051 },
16052 ScrollPositionChanged {
16053 local: bool,
16054 autoscroll: bool,
16055 },
16056 Closed,
16057 TransactionUndone {
16058 transaction_id: clock::Lamport,
16059 },
16060 TransactionBegun {
16061 transaction_id: clock::Lamport,
16062 },
16063 Reloaded,
16064 CursorShapeChanged,
16065}
16066
16067impl EventEmitter<EditorEvent> for Editor {}
16068
16069impl Focusable for Editor {
16070 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16071 self.focus_handle.clone()
16072 }
16073}
16074
16075impl Render for Editor {
16076 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16077 let settings = ThemeSettings::get_global(cx);
16078
16079 let mut text_style = match self.mode {
16080 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16081 color: cx.theme().colors().editor_foreground,
16082 font_family: settings.ui_font.family.clone(),
16083 font_features: settings.ui_font.features.clone(),
16084 font_fallbacks: settings.ui_font.fallbacks.clone(),
16085 font_size: rems(0.875).into(),
16086 font_weight: settings.ui_font.weight,
16087 line_height: relative(settings.buffer_line_height.value()),
16088 ..Default::default()
16089 },
16090 EditorMode::Full => TextStyle {
16091 color: cx.theme().colors().editor_foreground,
16092 font_family: settings.buffer_font.family.clone(),
16093 font_features: settings.buffer_font.features.clone(),
16094 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16095 font_size: settings.buffer_font_size(cx).into(),
16096 font_weight: settings.buffer_font.weight,
16097 line_height: relative(settings.buffer_line_height.value()),
16098 ..Default::default()
16099 },
16100 };
16101 if let Some(text_style_refinement) = &self.text_style_refinement {
16102 text_style.refine(text_style_refinement)
16103 }
16104
16105 let background = match self.mode {
16106 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16107 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16108 EditorMode::Full => cx.theme().colors().editor_background,
16109 };
16110
16111 EditorElement::new(
16112 &cx.entity(),
16113 EditorStyle {
16114 background,
16115 local_player: cx.theme().players().local(),
16116 text: text_style,
16117 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16118 syntax: cx.theme().syntax().clone(),
16119 status: cx.theme().status().clone(),
16120 inlay_hints_style: make_inlay_hints_style(cx),
16121 inline_completion_styles: make_suggestion_styles(cx),
16122 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16123 },
16124 )
16125 }
16126}
16127
16128impl EntityInputHandler for Editor {
16129 fn text_for_range(
16130 &mut self,
16131 range_utf16: Range<usize>,
16132 adjusted_range: &mut Option<Range<usize>>,
16133 _: &mut Window,
16134 cx: &mut Context<Self>,
16135 ) -> Option<String> {
16136 let snapshot = self.buffer.read(cx).read(cx);
16137 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16138 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16139 if (start.0..end.0) != range_utf16 {
16140 adjusted_range.replace(start.0..end.0);
16141 }
16142 Some(snapshot.text_for_range(start..end).collect())
16143 }
16144
16145 fn selected_text_range(
16146 &mut self,
16147 ignore_disabled_input: bool,
16148 _: &mut Window,
16149 cx: &mut Context<Self>,
16150 ) -> Option<UTF16Selection> {
16151 // Prevent the IME menu from appearing when holding down an alphabetic key
16152 // while input is disabled.
16153 if !ignore_disabled_input && !self.input_enabled {
16154 return None;
16155 }
16156
16157 let selection = self.selections.newest::<OffsetUtf16>(cx);
16158 let range = selection.range();
16159
16160 Some(UTF16Selection {
16161 range: range.start.0..range.end.0,
16162 reversed: selection.reversed,
16163 })
16164 }
16165
16166 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16167 let snapshot = self.buffer.read(cx).read(cx);
16168 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16169 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16170 }
16171
16172 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16173 self.clear_highlights::<InputComposition>(cx);
16174 self.ime_transaction.take();
16175 }
16176
16177 fn replace_text_in_range(
16178 &mut self,
16179 range_utf16: Option<Range<usize>>,
16180 text: &str,
16181 window: &mut Window,
16182 cx: &mut Context<Self>,
16183 ) {
16184 if !self.input_enabled {
16185 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16186 return;
16187 }
16188
16189 self.transact(window, cx, |this, window, cx| {
16190 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16191 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16192 Some(this.selection_replacement_ranges(range_utf16, cx))
16193 } else {
16194 this.marked_text_ranges(cx)
16195 };
16196
16197 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16198 let newest_selection_id = this.selections.newest_anchor().id;
16199 this.selections
16200 .all::<OffsetUtf16>(cx)
16201 .iter()
16202 .zip(ranges_to_replace.iter())
16203 .find_map(|(selection, range)| {
16204 if selection.id == newest_selection_id {
16205 Some(
16206 (range.start.0 as isize - selection.head().0 as isize)
16207 ..(range.end.0 as isize - selection.head().0 as isize),
16208 )
16209 } else {
16210 None
16211 }
16212 })
16213 });
16214
16215 cx.emit(EditorEvent::InputHandled {
16216 utf16_range_to_replace: range_to_replace,
16217 text: text.into(),
16218 });
16219
16220 if let Some(new_selected_ranges) = new_selected_ranges {
16221 this.change_selections(None, window, cx, |selections| {
16222 selections.select_ranges(new_selected_ranges)
16223 });
16224 this.backspace(&Default::default(), window, cx);
16225 }
16226
16227 this.handle_input(text, window, cx);
16228 });
16229
16230 if let Some(transaction) = self.ime_transaction {
16231 self.buffer.update(cx, |buffer, cx| {
16232 buffer.group_until_transaction(transaction, cx);
16233 });
16234 }
16235
16236 self.unmark_text(window, cx);
16237 }
16238
16239 fn replace_and_mark_text_in_range(
16240 &mut self,
16241 range_utf16: Option<Range<usize>>,
16242 text: &str,
16243 new_selected_range_utf16: Option<Range<usize>>,
16244 window: &mut Window,
16245 cx: &mut Context<Self>,
16246 ) {
16247 if !self.input_enabled {
16248 return;
16249 }
16250
16251 let transaction = self.transact(window, cx, |this, window, cx| {
16252 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16253 let snapshot = this.buffer.read(cx).read(cx);
16254 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16255 for marked_range in &mut marked_ranges {
16256 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16257 marked_range.start.0 += relative_range_utf16.start;
16258 marked_range.start =
16259 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16260 marked_range.end =
16261 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16262 }
16263 }
16264 Some(marked_ranges)
16265 } else if let Some(range_utf16) = range_utf16 {
16266 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16267 Some(this.selection_replacement_ranges(range_utf16, cx))
16268 } else {
16269 None
16270 };
16271
16272 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16273 let newest_selection_id = this.selections.newest_anchor().id;
16274 this.selections
16275 .all::<OffsetUtf16>(cx)
16276 .iter()
16277 .zip(ranges_to_replace.iter())
16278 .find_map(|(selection, range)| {
16279 if selection.id == newest_selection_id {
16280 Some(
16281 (range.start.0 as isize - selection.head().0 as isize)
16282 ..(range.end.0 as isize - selection.head().0 as isize),
16283 )
16284 } else {
16285 None
16286 }
16287 })
16288 });
16289
16290 cx.emit(EditorEvent::InputHandled {
16291 utf16_range_to_replace: range_to_replace,
16292 text: text.into(),
16293 });
16294
16295 if let Some(ranges) = ranges_to_replace {
16296 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16297 }
16298
16299 let marked_ranges = {
16300 let snapshot = this.buffer.read(cx).read(cx);
16301 this.selections
16302 .disjoint_anchors()
16303 .iter()
16304 .map(|selection| {
16305 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16306 })
16307 .collect::<Vec<_>>()
16308 };
16309
16310 if text.is_empty() {
16311 this.unmark_text(window, cx);
16312 } else {
16313 this.highlight_text::<InputComposition>(
16314 marked_ranges.clone(),
16315 HighlightStyle {
16316 underline: Some(UnderlineStyle {
16317 thickness: px(1.),
16318 color: None,
16319 wavy: false,
16320 }),
16321 ..Default::default()
16322 },
16323 cx,
16324 );
16325 }
16326
16327 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16328 let use_autoclose = this.use_autoclose;
16329 let use_auto_surround = this.use_auto_surround;
16330 this.set_use_autoclose(false);
16331 this.set_use_auto_surround(false);
16332 this.handle_input(text, window, cx);
16333 this.set_use_autoclose(use_autoclose);
16334 this.set_use_auto_surround(use_auto_surround);
16335
16336 if let Some(new_selected_range) = new_selected_range_utf16 {
16337 let snapshot = this.buffer.read(cx).read(cx);
16338 let new_selected_ranges = marked_ranges
16339 .into_iter()
16340 .map(|marked_range| {
16341 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16342 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16343 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16344 snapshot.clip_offset_utf16(new_start, Bias::Left)
16345 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16346 })
16347 .collect::<Vec<_>>();
16348
16349 drop(snapshot);
16350 this.change_selections(None, window, cx, |selections| {
16351 selections.select_ranges(new_selected_ranges)
16352 });
16353 }
16354 });
16355
16356 self.ime_transaction = self.ime_transaction.or(transaction);
16357 if let Some(transaction) = self.ime_transaction {
16358 self.buffer.update(cx, |buffer, cx| {
16359 buffer.group_until_transaction(transaction, cx);
16360 });
16361 }
16362
16363 if self.text_highlights::<InputComposition>(cx).is_none() {
16364 self.ime_transaction.take();
16365 }
16366 }
16367
16368 fn bounds_for_range(
16369 &mut self,
16370 range_utf16: Range<usize>,
16371 element_bounds: gpui::Bounds<Pixels>,
16372 window: &mut Window,
16373 cx: &mut Context<Self>,
16374 ) -> Option<gpui::Bounds<Pixels>> {
16375 let text_layout_details = self.text_layout_details(window);
16376 let gpui::Size {
16377 width: em_width,
16378 height: line_height,
16379 } = self.character_size(window);
16380
16381 let snapshot = self.snapshot(window, cx);
16382 let scroll_position = snapshot.scroll_position();
16383 let scroll_left = scroll_position.x * em_width;
16384
16385 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16386 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16387 + self.gutter_dimensions.width
16388 + self.gutter_dimensions.margin;
16389 let y = line_height * (start.row().as_f32() - scroll_position.y);
16390
16391 Some(Bounds {
16392 origin: element_bounds.origin + point(x, y),
16393 size: size(em_width, line_height),
16394 })
16395 }
16396
16397 fn character_index_for_point(
16398 &mut self,
16399 point: gpui::Point<Pixels>,
16400 _window: &mut Window,
16401 _cx: &mut Context<Self>,
16402 ) -> Option<usize> {
16403 let position_map = self.last_position_map.as_ref()?;
16404 if !position_map.text_hitbox.contains(&point) {
16405 return None;
16406 }
16407 let display_point = position_map.point_for_position(point).previous_valid;
16408 let anchor = position_map
16409 .snapshot
16410 .display_point_to_anchor(display_point, Bias::Left);
16411 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16412 Some(utf16_offset.0)
16413 }
16414}
16415
16416trait SelectionExt {
16417 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16418 fn spanned_rows(
16419 &self,
16420 include_end_if_at_line_start: bool,
16421 map: &DisplaySnapshot,
16422 ) -> Range<MultiBufferRow>;
16423}
16424
16425impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16426 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16427 let start = self
16428 .start
16429 .to_point(&map.buffer_snapshot)
16430 .to_display_point(map);
16431 let end = self
16432 .end
16433 .to_point(&map.buffer_snapshot)
16434 .to_display_point(map);
16435 if self.reversed {
16436 end..start
16437 } else {
16438 start..end
16439 }
16440 }
16441
16442 fn spanned_rows(
16443 &self,
16444 include_end_if_at_line_start: bool,
16445 map: &DisplaySnapshot,
16446 ) -> Range<MultiBufferRow> {
16447 let start = self.start.to_point(&map.buffer_snapshot);
16448 let mut end = self.end.to_point(&map.buffer_snapshot);
16449 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16450 end.row -= 1;
16451 }
16452
16453 let buffer_start = map.prev_line_boundary(start).0;
16454 let buffer_end = map.next_line_boundary(end).0;
16455 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16456 }
16457}
16458
16459impl<T: InvalidationRegion> InvalidationStack<T> {
16460 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16461 where
16462 S: Clone + ToOffset,
16463 {
16464 while let Some(region) = self.last() {
16465 let all_selections_inside_invalidation_ranges =
16466 if selections.len() == region.ranges().len() {
16467 selections
16468 .iter()
16469 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16470 .all(|(selection, invalidation_range)| {
16471 let head = selection.head().to_offset(buffer);
16472 invalidation_range.start <= head && invalidation_range.end >= head
16473 })
16474 } else {
16475 false
16476 };
16477
16478 if all_selections_inside_invalidation_ranges {
16479 break;
16480 } else {
16481 self.pop();
16482 }
16483 }
16484 }
16485}
16486
16487impl<T> Default for InvalidationStack<T> {
16488 fn default() -> Self {
16489 Self(Default::default())
16490 }
16491}
16492
16493impl<T> Deref for InvalidationStack<T> {
16494 type Target = Vec<T>;
16495
16496 fn deref(&self) -> &Self::Target {
16497 &self.0
16498 }
16499}
16500
16501impl<T> DerefMut for InvalidationStack<T> {
16502 fn deref_mut(&mut self) -> &mut Self::Target {
16503 &mut self.0
16504 }
16505}
16506
16507impl InvalidationRegion for SnippetState {
16508 fn ranges(&self) -> &[Range<Anchor>] {
16509 &self.ranges[self.active_index]
16510 }
16511}
16512
16513pub fn diagnostic_block_renderer(
16514 diagnostic: Diagnostic,
16515 max_message_rows: Option<u8>,
16516 allow_closing: bool,
16517 _is_valid: bool,
16518) -> RenderBlock {
16519 let (text_without_backticks, code_ranges) =
16520 highlight_diagnostic_message(&diagnostic, max_message_rows);
16521
16522 Arc::new(move |cx: &mut BlockContext| {
16523 let group_id: SharedString = cx.block_id.to_string().into();
16524
16525 let mut text_style = cx.window.text_style().clone();
16526 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16527 let theme_settings = ThemeSettings::get_global(cx);
16528 text_style.font_family = theme_settings.buffer_font.family.clone();
16529 text_style.font_style = theme_settings.buffer_font.style;
16530 text_style.font_features = theme_settings.buffer_font.features.clone();
16531 text_style.font_weight = theme_settings.buffer_font.weight;
16532
16533 let multi_line_diagnostic = diagnostic.message.contains('\n');
16534
16535 let buttons = |diagnostic: &Diagnostic| {
16536 if multi_line_diagnostic {
16537 v_flex()
16538 } else {
16539 h_flex()
16540 }
16541 .when(allow_closing, |div| {
16542 div.children(diagnostic.is_primary.then(|| {
16543 IconButton::new("close-block", IconName::XCircle)
16544 .icon_color(Color::Muted)
16545 .size(ButtonSize::Compact)
16546 .style(ButtonStyle::Transparent)
16547 .visible_on_hover(group_id.clone())
16548 .on_click(move |_click, window, cx| {
16549 window.dispatch_action(Box::new(Cancel), cx)
16550 })
16551 .tooltip(|window, cx| {
16552 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16553 })
16554 }))
16555 })
16556 .child(
16557 IconButton::new("copy-block", IconName::Copy)
16558 .icon_color(Color::Muted)
16559 .size(ButtonSize::Compact)
16560 .style(ButtonStyle::Transparent)
16561 .visible_on_hover(group_id.clone())
16562 .on_click({
16563 let message = diagnostic.message.clone();
16564 move |_click, _, cx| {
16565 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16566 }
16567 })
16568 .tooltip(Tooltip::text("Copy diagnostic message")),
16569 )
16570 };
16571
16572 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16573 AvailableSpace::min_size(),
16574 cx.window,
16575 cx.app,
16576 );
16577
16578 h_flex()
16579 .id(cx.block_id)
16580 .group(group_id.clone())
16581 .relative()
16582 .size_full()
16583 .block_mouse_down()
16584 .pl(cx.gutter_dimensions.width)
16585 .w(cx.max_width - cx.gutter_dimensions.full_width())
16586 .child(
16587 div()
16588 .flex()
16589 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16590 .flex_shrink(),
16591 )
16592 .child(buttons(&diagnostic))
16593 .child(div().flex().flex_shrink_0().child(
16594 StyledText::new(text_without_backticks.clone()).with_highlights(
16595 &text_style,
16596 code_ranges.iter().map(|range| {
16597 (
16598 range.clone(),
16599 HighlightStyle {
16600 font_weight: Some(FontWeight::BOLD),
16601 ..Default::default()
16602 },
16603 )
16604 }),
16605 ),
16606 ))
16607 .into_any_element()
16608 })
16609}
16610
16611fn inline_completion_edit_text(
16612 current_snapshot: &BufferSnapshot,
16613 edits: &[(Range<Anchor>, String)],
16614 edit_preview: &EditPreview,
16615 include_deletions: bool,
16616 cx: &App,
16617) -> HighlightedText {
16618 let edits = edits
16619 .iter()
16620 .map(|(anchor, text)| {
16621 (
16622 anchor.start.text_anchor..anchor.end.text_anchor,
16623 text.clone(),
16624 )
16625 })
16626 .collect::<Vec<_>>();
16627
16628 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16629}
16630
16631pub fn highlight_diagnostic_message(
16632 diagnostic: &Diagnostic,
16633 mut max_message_rows: Option<u8>,
16634) -> (SharedString, Vec<Range<usize>>) {
16635 let mut text_without_backticks = String::new();
16636 let mut code_ranges = Vec::new();
16637
16638 if let Some(source) = &diagnostic.source {
16639 text_without_backticks.push_str(source);
16640 code_ranges.push(0..source.len());
16641 text_without_backticks.push_str(": ");
16642 }
16643
16644 let mut prev_offset = 0;
16645 let mut in_code_block = false;
16646 let has_row_limit = max_message_rows.is_some();
16647 let mut newline_indices = diagnostic
16648 .message
16649 .match_indices('\n')
16650 .filter(|_| has_row_limit)
16651 .map(|(ix, _)| ix)
16652 .fuse()
16653 .peekable();
16654
16655 for (quote_ix, _) in diagnostic
16656 .message
16657 .match_indices('`')
16658 .chain([(diagnostic.message.len(), "")])
16659 {
16660 let mut first_newline_ix = None;
16661 let mut last_newline_ix = None;
16662 while let Some(newline_ix) = newline_indices.peek() {
16663 if *newline_ix < quote_ix {
16664 if first_newline_ix.is_none() {
16665 first_newline_ix = Some(*newline_ix);
16666 }
16667 last_newline_ix = Some(*newline_ix);
16668
16669 if let Some(rows_left) = &mut max_message_rows {
16670 if *rows_left == 0 {
16671 break;
16672 } else {
16673 *rows_left -= 1;
16674 }
16675 }
16676 let _ = newline_indices.next();
16677 } else {
16678 break;
16679 }
16680 }
16681 let prev_len = text_without_backticks.len();
16682 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16683 text_without_backticks.push_str(new_text);
16684 if in_code_block {
16685 code_ranges.push(prev_len..text_without_backticks.len());
16686 }
16687 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16688 in_code_block = !in_code_block;
16689 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16690 text_without_backticks.push_str("...");
16691 break;
16692 }
16693 }
16694
16695 (text_without_backticks.into(), code_ranges)
16696}
16697
16698fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16699 match severity {
16700 DiagnosticSeverity::ERROR => colors.error,
16701 DiagnosticSeverity::WARNING => colors.warning,
16702 DiagnosticSeverity::INFORMATION => colors.info,
16703 DiagnosticSeverity::HINT => colors.info,
16704 _ => colors.ignored,
16705 }
16706}
16707
16708pub fn styled_runs_for_code_label<'a>(
16709 label: &'a CodeLabel,
16710 syntax_theme: &'a theme::SyntaxTheme,
16711) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16712 let fade_out = HighlightStyle {
16713 fade_out: Some(0.35),
16714 ..Default::default()
16715 };
16716
16717 let mut prev_end = label.filter_range.end;
16718 label
16719 .runs
16720 .iter()
16721 .enumerate()
16722 .flat_map(move |(ix, (range, highlight_id))| {
16723 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16724 style
16725 } else {
16726 return Default::default();
16727 };
16728 let mut muted_style = style;
16729 muted_style.highlight(fade_out);
16730
16731 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16732 if range.start >= label.filter_range.end {
16733 if range.start > prev_end {
16734 runs.push((prev_end..range.start, fade_out));
16735 }
16736 runs.push((range.clone(), muted_style));
16737 } else if range.end <= label.filter_range.end {
16738 runs.push((range.clone(), style));
16739 } else {
16740 runs.push((range.start..label.filter_range.end, style));
16741 runs.push((label.filter_range.end..range.end, muted_style));
16742 }
16743 prev_end = cmp::max(prev_end, range.end);
16744
16745 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16746 runs.push((prev_end..label.text.len(), fade_out));
16747 }
16748
16749 runs
16750 })
16751}
16752
16753pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16754 let mut prev_index = 0;
16755 let mut prev_codepoint: Option<char> = None;
16756 text.char_indices()
16757 .chain([(text.len(), '\0')])
16758 .filter_map(move |(index, codepoint)| {
16759 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16760 let is_boundary = index == text.len()
16761 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16762 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16763 if is_boundary {
16764 let chunk = &text[prev_index..index];
16765 prev_index = index;
16766 Some(chunk)
16767 } else {
16768 None
16769 }
16770 })
16771}
16772
16773pub trait RangeToAnchorExt: Sized {
16774 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16775
16776 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16777 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16778 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16779 }
16780}
16781
16782impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16783 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16784 let start_offset = self.start.to_offset(snapshot);
16785 let end_offset = self.end.to_offset(snapshot);
16786 if start_offset == end_offset {
16787 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16788 } else {
16789 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16790 }
16791 }
16792}
16793
16794pub trait RowExt {
16795 fn as_f32(&self) -> f32;
16796
16797 fn next_row(&self) -> Self;
16798
16799 fn previous_row(&self) -> Self;
16800
16801 fn minus(&self, other: Self) -> u32;
16802}
16803
16804impl RowExt for DisplayRow {
16805 fn as_f32(&self) -> f32 {
16806 self.0 as f32
16807 }
16808
16809 fn next_row(&self) -> Self {
16810 Self(self.0 + 1)
16811 }
16812
16813 fn previous_row(&self) -> Self {
16814 Self(self.0.saturating_sub(1))
16815 }
16816
16817 fn minus(&self, other: Self) -> u32 {
16818 self.0 - other.0
16819 }
16820}
16821
16822impl RowExt for MultiBufferRow {
16823 fn as_f32(&self) -> f32 {
16824 self.0 as f32
16825 }
16826
16827 fn next_row(&self) -> Self {
16828 Self(self.0 + 1)
16829 }
16830
16831 fn previous_row(&self) -> Self {
16832 Self(self.0.saturating_sub(1))
16833 }
16834
16835 fn minus(&self, other: Self) -> u32 {
16836 self.0 - other.0
16837 }
16838}
16839
16840trait RowRangeExt {
16841 type Row;
16842
16843 fn len(&self) -> usize;
16844
16845 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16846}
16847
16848impl RowRangeExt for Range<MultiBufferRow> {
16849 type Row = MultiBufferRow;
16850
16851 fn len(&self) -> usize {
16852 (self.end.0 - self.start.0) as usize
16853 }
16854
16855 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16856 (self.start.0..self.end.0).map(MultiBufferRow)
16857 }
16858}
16859
16860impl RowRangeExt for Range<DisplayRow> {
16861 type Row = DisplayRow;
16862
16863 fn len(&self) -> usize {
16864 (self.end.0 - self.start.0) as usize
16865 }
16866
16867 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16868 (self.start.0..self.end.0).map(DisplayRow)
16869 }
16870}
16871
16872/// If select range has more than one line, we
16873/// just point the cursor to range.start.
16874fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16875 if range.start.row == range.end.row {
16876 range
16877 } else {
16878 range.start..range.start
16879 }
16880}
16881pub struct KillRing(ClipboardItem);
16882impl Global for KillRing {}
16883
16884const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16885
16886fn all_edits_insertions_or_deletions(
16887 edits: &Vec<(Range<Anchor>, String)>,
16888 snapshot: &MultiBufferSnapshot,
16889) -> bool {
16890 let mut all_insertions = true;
16891 let mut all_deletions = true;
16892
16893 for (range, new_text) in edits.iter() {
16894 let range_is_empty = range.to_offset(&snapshot).is_empty();
16895 let text_is_empty = new_text.is_empty();
16896
16897 if range_is_empty != text_is_empty {
16898 if range_is_empty {
16899 all_deletions = false;
16900 } else {
16901 all_insertions = false;
16902 }
16903 } else {
16904 return false;
16905 }
16906
16907 if !all_insertions && !all_deletions {
16908 return false;
16909 }
16910 }
16911 all_insertions || all_deletions
16912}