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