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, Background, Bounds,
84 ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
85 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
86 HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
87 PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
88 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
89 WeakEntity, 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 CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
103 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
104 TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109use persistence::DB;
110pub use proposed_changes_editor::{
111 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
112};
113use similar::{ChangeTag, TextDiff};
114use std::iter::Peekable;
115use task::{ResolvedTask, TaskTemplate, TaskVariables};
116
117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
118pub use lsp::CompletionContext;
119use lsp::{
120 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
121 LanguageServerId, LanguageServerName,
122};
123
124use language::BufferSnapshot;
125use movement::TextLayoutDetails;
126pub use multi_buffer::{
127 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
128 ToOffset, ToPoint,
129};
130use multi_buffer::{
131 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
132 ToOffsetUtf16,
133};
134use project::{
135 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
136 project_settings::{GitGutterSetting, ProjectSettings},
137 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
138 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
139};
140use rand::prelude::*;
141use rpc::{proto::*, ErrorExt};
142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
143use selections_collection::{
144 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
145};
146use serde::{Deserialize, Serialize};
147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
148use smallvec::SmallVec;
149use snippet::Snippet;
150use std::{
151 any::TypeId,
152 borrow::Cow,
153 cell::RefCell,
154 cmp::{self, Ordering, Reverse},
155 mem,
156 num::NonZeroU32,
157 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
158 path::{Path, PathBuf},
159 rc::Rc,
160 sync::Arc,
161 time::{Duration, Instant},
162};
163pub use sum_tree::Bias;
164use sum_tree::TreeMap;
165use text::{BufferId, OffsetUtf16, Rope};
166use theme::{
167 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
168 ThemeColors, ThemeSettings,
169};
170use ui::{
171 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
172 Tooltip,
173};
174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
175use workspace::{
176 item::{ItemHandle, PreviewTabsSettings},
177 ItemId, RestoreOnStartupBehavior,
178};
179use workspace::{
180 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
181 WorkspaceSettings,
182};
183use workspace::{
184 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
185};
186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
187
188use crate::hover_links::{find_url, find_url_from_range};
189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
190
191pub const FILE_HEADER_HEIGHT: u32 = 2;
192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
196const MAX_LINE_LEN: usize = 1024;
197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
200#[doc(hidden)]
201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
202
203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
205
206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
208
209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
210 alt: true,
211 shift: true,
212 control: false,
213 platform: false,
214 function: false,
215};
216
217pub fn render_parsed_markdown(
218 element_id: impl Into<ElementId>,
219 parsed: &language::ParsedMarkdown,
220 editor_style: &EditorStyle,
221 workspace: Option<WeakEntity<Workspace>>,
222 cx: &mut App,
223) -> InteractiveText {
224 let code_span_background_color = cx
225 .theme()
226 .colors()
227 .editor_document_highlight_read_background;
228
229 let highlights = gpui::combine_highlights(
230 parsed.highlights.iter().filter_map(|(range, highlight)| {
231 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
232 Some((range.clone(), highlight))
233 }),
234 parsed
235 .regions
236 .iter()
237 .zip(&parsed.region_ranges)
238 .filter_map(|(region, range)| {
239 if region.code {
240 Some((
241 range.clone(),
242 HighlightStyle {
243 background_color: Some(code_span_background_color),
244 ..Default::default()
245 },
246 ))
247 } else {
248 None
249 }
250 }),
251 );
252
253 let mut links = Vec::new();
254 let mut link_ranges = Vec::new();
255 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
256 if let Some(link) = region.link.clone() {
257 links.push(link);
258 link_ranges.push(range.clone());
259 }
260 }
261
262 InteractiveText::new(
263 element_id,
264 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
265 )
266 .on_click(
267 link_ranges,
268 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
269 markdown::Link::Web { url } => cx.open_url(url),
270 markdown::Link::Path { path } => {
271 if let Some(workspace) = &workspace {
272 _ = workspace.update(cx, |workspace, cx| {
273 workspace
274 .open_abs_path(path.clone(), false, window, cx)
275 .detach();
276 });
277 }
278 }
279 },
280 )
281}
282
283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub enum InlayId {
285 InlineCompletion(usize),
286 Hint(usize),
287}
288
289impl InlayId {
290 fn id(&self) -> usize {
291 match self {
292 Self::InlineCompletion(id) => *id,
293 Self::Hint(id) => *id,
294 }
295 }
296}
297
298enum DocumentHighlightRead {}
299enum DocumentHighlightWrite {}
300enum InputComposition {}
301enum SelectedTextHighlight {}
302
303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
304pub enum Navigated {
305 Yes,
306 No,
307}
308
309impl Navigated {
310 pub fn from_bool(yes: bool) -> Navigated {
311 if yes {
312 Navigated::Yes
313 } else {
314 Navigated::No
315 }
316 }
317}
318
319pub fn init_settings(cx: &mut App) {
320 EditorSettings::register(cx);
321}
322
323pub fn init(cx: &mut App) {
324 init_settings(cx);
325
326 workspace::register_project_item::<Editor>(cx);
327 workspace::FollowableViewRegistry::register::<Editor>(cx);
328 workspace::register_serializable_item::<Editor>(cx);
329
330 cx.observe_new(
331 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
332 workspace.register_action(Editor::new_file);
333 workspace.register_action(Editor::new_file_vertical);
334 workspace.register_action(Editor::new_file_horizontal);
335 workspace.register_action(Editor::cancel_language_server_work);
336 },
337 )
338 .detach();
339
340 cx.on_action(move |_: &workspace::NewFile, cx| {
341 let app_state = workspace::AppState::global(cx);
342 if let Some(app_state) = app_state.upgrade() {
343 workspace::open_new(
344 Default::default(),
345 app_state,
346 cx,
347 |workspace, window, cx| {
348 Editor::new_file(workspace, &Default::default(), window, cx)
349 },
350 )
351 .detach();
352 }
353 });
354 cx.on_action(move |_: &workspace::NewWindow, cx| {
355 let app_state = workspace::AppState::global(cx);
356 if let Some(app_state) = app_state.upgrade() {
357 workspace::open_new(
358 Default::default(),
359 app_state,
360 cx,
361 |workspace, window, cx| {
362 cx.activate(true);
363 Editor::new_file(workspace, &Default::default(), window, cx)
364 },
365 )
366 .detach();
367 }
368 });
369}
370
371pub struct SearchWithinRange;
372
373trait InvalidationRegion {
374 fn ranges(&self) -> &[Range<Anchor>];
375}
376
377#[derive(Clone, Debug, PartialEq)]
378pub enum SelectPhase {
379 Begin {
380 position: DisplayPoint,
381 add: bool,
382 click_count: usize,
383 },
384 BeginColumnar {
385 position: DisplayPoint,
386 reset: bool,
387 goal_column: u32,
388 },
389 Extend {
390 position: DisplayPoint,
391 click_count: usize,
392 },
393 Update {
394 position: DisplayPoint,
395 goal_column: u32,
396 scroll_delta: gpui::Point<f32>,
397 },
398 End,
399}
400
401#[derive(Clone, Debug)]
402pub enum SelectMode {
403 Character,
404 Word(Range<Anchor>),
405 Line(Range<Anchor>),
406 All,
407}
408
409#[derive(Copy, Clone, PartialEq, Eq, Debug)]
410pub enum EditorMode {
411 SingleLine { auto_width: bool },
412 AutoHeight { max_lines: usize },
413 Full,
414}
415
416#[derive(Copy, Clone, Debug)]
417pub enum SoftWrap {
418 /// Prefer not to wrap at all.
419 ///
420 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
421 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
422 GitDiff,
423 /// Prefer a single line generally, unless an overly long line is encountered.
424 None,
425 /// Soft wrap lines that exceed the editor width.
426 EditorWidth,
427 /// Soft wrap lines at the preferred line length.
428 Column(u32),
429 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
430 Bounded(u32),
431}
432
433#[derive(Clone)]
434pub struct EditorStyle {
435 pub background: Hsla,
436 pub local_player: PlayerColor,
437 pub text: TextStyle,
438 pub scrollbar_width: Pixels,
439 pub syntax: Arc<SyntaxTheme>,
440 pub status: StatusColors,
441 pub inlay_hints_style: HighlightStyle,
442 pub inline_completion_styles: InlineCompletionStyles,
443 pub unnecessary_code_fade: f32,
444}
445
446impl Default for EditorStyle {
447 fn default() -> Self {
448 Self {
449 background: Hsla::default(),
450 local_player: PlayerColor::default(),
451 text: TextStyle::default(),
452 scrollbar_width: Pixels::default(),
453 syntax: Default::default(),
454 // HACK: Status colors don't have a real default.
455 // We should look into removing the status colors from the editor
456 // style and retrieve them directly from the theme.
457 status: StatusColors::dark(),
458 inlay_hints_style: HighlightStyle::default(),
459 inline_completion_styles: InlineCompletionStyles {
460 insertion: HighlightStyle::default(),
461 whitespace: HighlightStyle::default(),
462 },
463 unnecessary_code_fade: Default::default(),
464 }
465 }
466}
467
468pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
469 let show_background = language_settings::language_settings(None, None, cx)
470 .inlay_hints
471 .show_background;
472
473 HighlightStyle {
474 color: Some(cx.theme().status().hint),
475 background_color: show_background.then(|| cx.theme().status().hint_background),
476 ..HighlightStyle::default()
477 }
478}
479
480pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
481 InlineCompletionStyles {
482 insertion: HighlightStyle {
483 color: Some(cx.theme().status().predictive),
484 ..HighlightStyle::default()
485 },
486 whitespace: HighlightStyle {
487 background_color: Some(cx.theme().status().created_background),
488 ..HighlightStyle::default()
489 },
490 }
491}
492
493type CompletionId = usize;
494
495pub(crate) enum EditDisplayMode {
496 TabAccept,
497 DiffPopover,
498 Inline,
499}
500
501enum InlineCompletion {
502 Edit {
503 edits: Vec<(Range<Anchor>, String)>,
504 edit_preview: Option<EditPreview>,
505 display_mode: EditDisplayMode,
506 snapshot: BufferSnapshot,
507 },
508 Move {
509 target: Anchor,
510 snapshot: BufferSnapshot,
511 },
512}
513
514struct InlineCompletionState {
515 inlay_ids: Vec<InlayId>,
516 completion: InlineCompletion,
517 completion_id: Option<SharedString>,
518 invalidation_range: Range<Anchor>,
519}
520
521enum EditPredictionSettings {
522 Disabled,
523 Enabled {
524 show_in_menu: bool,
525 preview_requires_modifier: bool,
526 },
527}
528
529enum InlineCompletionHighlight {}
530
531pub enum MenuInlineCompletionsPolicy {
532 Never,
533 ByProvider,
534}
535
536pub enum EditPredictionPreview {
537 /// Modifier is not pressed
538 Inactive,
539 /// Modifier pressed
540 Active {
541 previous_scroll_position: Option<ScrollAnchor>,
542 },
543}
544
545#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
546struct EditorActionId(usize);
547
548impl EditorActionId {
549 pub fn post_inc(&mut self) -> Self {
550 let answer = self.0;
551
552 *self = Self(answer + 1);
553
554 Self(answer)
555 }
556}
557
558// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
559// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
560
561type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
562type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
563
564#[derive(Default)]
565struct ScrollbarMarkerState {
566 scrollbar_size: Size<Pixels>,
567 dirty: bool,
568 markers: Arc<[PaintQuad]>,
569 pending_refresh: Option<Task<Result<()>>>,
570}
571
572impl ScrollbarMarkerState {
573 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
574 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
575 }
576}
577
578#[derive(Clone, Debug)]
579struct RunnableTasks {
580 templates: Vec<(TaskSourceKind, TaskTemplate)>,
581 offset: MultiBufferOffset,
582 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
583 column: u32,
584 // Values of all named captures, including those starting with '_'
585 extra_variables: HashMap<String, String>,
586 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
587 context_range: Range<BufferOffset>,
588}
589
590impl RunnableTasks {
591 fn resolve<'a>(
592 &'a self,
593 cx: &'a task::TaskContext,
594 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
595 self.templates.iter().filter_map(|(kind, template)| {
596 template
597 .resolve_task(&kind.to_id_base(), cx)
598 .map(|task| (kind.clone(), task))
599 })
600 }
601}
602
603#[derive(Clone)]
604struct ResolvedTasks {
605 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
606 position: Anchor,
607}
608#[derive(Copy, Clone, Debug)]
609struct MultiBufferOffset(usize);
610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
611struct BufferOffset(usize);
612
613// Addons allow storing per-editor state in other crates (e.g. Vim)
614pub trait Addon: 'static {
615 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
616
617 fn render_buffer_header_controls(
618 &self,
619 _: &ExcerptInfo,
620 _: &Window,
621 _: &App,
622 ) -> Option<AnyElement> {
623 None
624 }
625
626 fn to_any(&self) -> &dyn std::any::Any;
627}
628
629#[derive(Debug, Copy, Clone, PartialEq, Eq)]
630pub enum IsVimMode {
631 Yes,
632 No,
633}
634
635/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
636///
637/// See the [module level documentation](self) for more information.
638pub struct Editor {
639 focus_handle: FocusHandle,
640 last_focused_descendant: Option<WeakFocusHandle>,
641 /// The text buffer being edited
642 buffer: Entity<MultiBuffer>,
643 /// Map of how text in the buffer should be displayed.
644 /// Handles soft wraps, folds, fake inlay text insertions, etc.
645 pub display_map: Entity<DisplayMap>,
646 pub selections: SelectionsCollection,
647 pub scroll_manager: ScrollManager,
648 /// When inline assist editors are linked, they all render cursors because
649 /// typing enters text into each of them, even the ones that aren't focused.
650 pub(crate) show_cursor_when_unfocused: bool,
651 columnar_selection_tail: Option<Anchor>,
652 add_selections_state: Option<AddSelectionsState>,
653 select_next_state: Option<SelectNextState>,
654 select_prev_state: Option<SelectNextState>,
655 selection_history: SelectionHistory,
656 autoclose_regions: Vec<AutocloseRegion>,
657 snippet_stack: InvalidationStack<SnippetState>,
658 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
659 ime_transaction: Option<TransactionId>,
660 active_diagnostics: Option<ActiveDiagnosticGroup>,
661 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
662
663 // TODO: make this a access method
664 pub project: Option<Entity<Project>>,
665 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
666 completion_provider: Option<Box<dyn CompletionProvider>>,
667 collaboration_hub: Option<Box<dyn CollaborationHub>>,
668 blink_manager: Entity<BlinkManager>,
669 show_cursor_names: bool,
670 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
671 pub show_local_selections: bool,
672 mode: EditorMode,
673 show_breadcrumbs: bool,
674 show_gutter: bool,
675 show_scrollbars: bool,
676 show_line_numbers: Option<bool>,
677 use_relative_line_numbers: Option<bool>,
678 show_git_diff_gutter: Option<bool>,
679 show_code_actions: Option<bool>,
680 show_runnables: Option<bool>,
681 show_wrap_guides: Option<bool>,
682 show_indent_guides: Option<bool>,
683 placeholder_text: Option<Arc<str>>,
684 highlight_order: usize,
685 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
686 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
687 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
688 scrollbar_marker_state: ScrollbarMarkerState,
689 active_indent_guides_state: ActiveIndentGuidesState,
690 nav_history: Option<ItemNavHistory>,
691 context_menu: RefCell<Option<CodeContextMenu>>,
692 mouse_context_menu: Option<MouseContextMenu>,
693 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
694 signature_help_state: SignatureHelpState,
695 auto_signature_help: Option<bool>,
696 find_all_references_task_sources: Vec<Anchor>,
697 next_completion_id: CompletionId,
698 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
699 code_actions_task: Option<Task<Result<()>>>,
700 selection_highlight_task: Option<Task<()>>,
701 document_highlights_task: Option<Task<()>>,
702 linked_editing_range_task: Option<Task<Option<()>>>,
703 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
704 pending_rename: Option<RenameState>,
705 searchable: bool,
706 cursor_shape: CursorShape,
707 current_line_highlight: Option<CurrentLineHighlight>,
708 collapse_matches: bool,
709 autoindent_mode: Option<AutoindentMode>,
710 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
711 input_enabled: bool,
712 use_modal_editing: bool,
713 read_only: bool,
714 leader_peer_id: Option<PeerId>,
715 remote_id: Option<ViewId>,
716 hover_state: HoverState,
717 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
718 gutter_hovered: bool,
719 hovered_link_state: Option<HoveredLinkState>,
720 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
721 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
722 active_inline_completion: Option<InlineCompletionState>,
723 /// Used to prevent flickering as the user types while the menu is open
724 stale_inline_completion_in_menu: Option<InlineCompletionState>,
725 edit_prediction_settings: EditPredictionSettings,
726 inline_completions_hidden_for_vim_mode: bool,
727 show_inline_completions_override: Option<bool>,
728 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
729 edit_prediction_preview: EditPredictionPreview,
730 edit_prediction_cursor_on_leading_whitespace: bool,
731 edit_prediction_requires_modifier_in_leading_space: bool,
732 inlay_hint_cache: InlayHintCache,
733 next_inlay_id: usize,
734 _subscriptions: Vec<Subscription>,
735 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
736 gutter_dimensions: GutterDimensions,
737 style: Option<EditorStyle>,
738 text_style_refinement: Option<TextStyleRefinement>,
739 next_editor_action_id: EditorActionId,
740 editor_actions:
741 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
742 use_autoclose: bool,
743 use_auto_surround: bool,
744 auto_replace_emoji_shortcode: bool,
745 show_git_blame_gutter: bool,
746 show_git_blame_inline: bool,
747 show_git_blame_inline_delay_task: Option<Task<()>>,
748 distinguish_unstaged_diff_hunks: bool,
749 git_blame_inline_enabled: bool,
750 serialize_dirty_buffers: bool,
751 show_selection_menu: Option<bool>,
752 blame: Option<Entity<GitBlame>>,
753 blame_subscription: Option<Subscription>,
754 custom_context_menu: Option<
755 Box<
756 dyn 'static
757 + Fn(
758 &mut Self,
759 DisplayPoint,
760 &mut Window,
761 &mut Context<Self>,
762 ) -> Option<Entity<ui::ContextMenu>>,
763 >,
764 >,
765 last_bounds: Option<Bounds<Pixels>>,
766 last_position_map: Option<Rc<PositionMap>>,
767 expect_bounds_change: Option<Bounds<Pixels>>,
768 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
769 tasks_update_task: Option<Task<()>>,
770 in_project_search: bool,
771 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
772 breadcrumb_header: Option<String>,
773 focused_block: Option<FocusedBlock>,
774 next_scroll_position: NextScrollCursorCenterTopBottom,
775 addons: HashMap<TypeId, Box<dyn Addon>>,
776 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
777 load_diff_task: Option<Shared<Task<()>>>,
778 selection_mark_mode: bool,
779 toggle_fold_multiple_buffers: Task<()>,
780 _scroll_cursor_center_top_bottom_task: Task<()>,
781 serialize_selections: Task<()>,
782}
783
784#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
785enum NextScrollCursorCenterTopBottom {
786 #[default]
787 Center,
788 Top,
789 Bottom,
790}
791
792impl NextScrollCursorCenterTopBottom {
793 fn next(&self) -> Self {
794 match self {
795 Self::Center => Self::Top,
796 Self::Top => Self::Bottom,
797 Self::Bottom => Self::Center,
798 }
799 }
800}
801
802#[derive(Clone)]
803pub struct EditorSnapshot {
804 pub mode: EditorMode,
805 show_gutter: bool,
806 show_line_numbers: Option<bool>,
807 show_git_diff_gutter: Option<bool>,
808 show_code_actions: Option<bool>,
809 show_runnables: Option<bool>,
810 git_blame_gutter_max_author_length: Option<usize>,
811 pub display_snapshot: DisplaySnapshot,
812 pub placeholder_text: Option<Arc<str>>,
813 is_focused: bool,
814 scroll_anchor: ScrollAnchor,
815 ongoing_scroll: OngoingScroll,
816 current_line_highlight: CurrentLineHighlight,
817 gutter_hovered: bool,
818}
819
820const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
821
822#[derive(Default, Debug, Clone, Copy)]
823pub struct GutterDimensions {
824 pub left_padding: Pixels,
825 pub right_padding: Pixels,
826 pub width: Pixels,
827 pub margin: Pixels,
828 pub git_blame_entries_width: Option<Pixels>,
829}
830
831impl GutterDimensions {
832 /// The full width of the space taken up by the gutter.
833 pub fn full_width(&self) -> Pixels {
834 self.margin + self.width
835 }
836
837 /// The width of the space reserved for the fold indicators,
838 /// use alongside 'justify_end' and `gutter_width` to
839 /// right align content with the line numbers
840 pub fn fold_area_width(&self) -> Pixels {
841 self.margin + self.right_padding
842 }
843}
844
845#[derive(Debug)]
846pub struct RemoteSelection {
847 pub replica_id: ReplicaId,
848 pub selection: Selection<Anchor>,
849 pub cursor_shape: CursorShape,
850 pub peer_id: PeerId,
851 pub line_mode: bool,
852 pub participant_index: Option<ParticipantIndex>,
853 pub user_name: Option<SharedString>,
854}
855
856#[derive(Clone, Debug)]
857struct SelectionHistoryEntry {
858 selections: Arc<[Selection<Anchor>]>,
859 select_next_state: Option<SelectNextState>,
860 select_prev_state: Option<SelectNextState>,
861 add_selections_state: Option<AddSelectionsState>,
862}
863
864enum SelectionHistoryMode {
865 Normal,
866 Undoing,
867 Redoing,
868}
869
870#[derive(Clone, PartialEq, Eq, Hash)]
871struct HoveredCursor {
872 replica_id: u16,
873 selection_id: usize,
874}
875
876impl Default for SelectionHistoryMode {
877 fn default() -> Self {
878 Self::Normal
879 }
880}
881
882#[derive(Default)]
883struct SelectionHistory {
884 #[allow(clippy::type_complexity)]
885 selections_by_transaction:
886 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
887 mode: SelectionHistoryMode,
888 undo_stack: VecDeque<SelectionHistoryEntry>,
889 redo_stack: VecDeque<SelectionHistoryEntry>,
890}
891
892impl SelectionHistory {
893 fn insert_transaction(
894 &mut self,
895 transaction_id: TransactionId,
896 selections: Arc<[Selection<Anchor>]>,
897 ) {
898 self.selections_by_transaction
899 .insert(transaction_id, (selections, None));
900 }
901
902 #[allow(clippy::type_complexity)]
903 fn transaction(
904 &self,
905 transaction_id: TransactionId,
906 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
907 self.selections_by_transaction.get(&transaction_id)
908 }
909
910 #[allow(clippy::type_complexity)]
911 fn transaction_mut(
912 &mut self,
913 transaction_id: TransactionId,
914 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
915 self.selections_by_transaction.get_mut(&transaction_id)
916 }
917
918 fn push(&mut self, entry: SelectionHistoryEntry) {
919 if !entry.selections.is_empty() {
920 match self.mode {
921 SelectionHistoryMode::Normal => {
922 self.push_undo(entry);
923 self.redo_stack.clear();
924 }
925 SelectionHistoryMode::Undoing => self.push_redo(entry),
926 SelectionHistoryMode::Redoing => self.push_undo(entry),
927 }
928 }
929 }
930
931 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
932 if self
933 .undo_stack
934 .back()
935 .map_or(true, |e| e.selections != entry.selections)
936 {
937 self.undo_stack.push_back(entry);
938 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
939 self.undo_stack.pop_front();
940 }
941 }
942 }
943
944 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
945 if self
946 .redo_stack
947 .back()
948 .map_or(true, |e| e.selections != entry.selections)
949 {
950 self.redo_stack.push_back(entry);
951 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
952 self.redo_stack.pop_front();
953 }
954 }
955 }
956}
957
958struct RowHighlight {
959 index: usize,
960 range: Range<Anchor>,
961 color: Hsla,
962 should_autoscroll: bool,
963}
964
965#[derive(Clone, Debug)]
966struct AddSelectionsState {
967 above: bool,
968 stack: Vec<usize>,
969}
970
971#[derive(Clone)]
972struct SelectNextState {
973 query: AhoCorasick,
974 wordwise: bool,
975 done: bool,
976}
977
978impl std::fmt::Debug for SelectNextState {
979 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
980 f.debug_struct(std::any::type_name::<Self>())
981 .field("wordwise", &self.wordwise)
982 .field("done", &self.done)
983 .finish()
984 }
985}
986
987#[derive(Debug)]
988struct AutocloseRegion {
989 selection_id: usize,
990 range: Range<Anchor>,
991 pair: BracketPair,
992}
993
994#[derive(Debug)]
995struct SnippetState {
996 ranges: Vec<Vec<Range<Anchor>>>,
997 active_index: usize,
998 choices: Vec<Option<Vec<String>>>,
999}
1000
1001#[doc(hidden)]
1002pub struct RenameState {
1003 pub range: Range<Anchor>,
1004 pub old_name: Arc<str>,
1005 pub editor: Entity<Editor>,
1006 block_id: CustomBlockId,
1007}
1008
1009struct InvalidationStack<T>(Vec<T>);
1010
1011struct RegisteredInlineCompletionProvider {
1012 provider: Arc<dyn InlineCompletionProviderHandle>,
1013 _subscription: Subscription,
1014}
1015
1016#[derive(Debug)]
1017struct ActiveDiagnosticGroup {
1018 primary_range: Range<Anchor>,
1019 primary_message: String,
1020 group_id: usize,
1021 blocks: HashMap<CustomBlockId, Diagnostic>,
1022 is_valid: bool,
1023}
1024
1025#[derive(Serialize, Deserialize, Clone, Debug)]
1026pub struct ClipboardSelection {
1027 pub len: usize,
1028 pub is_entire_line: bool,
1029 pub first_line_indent: u32,
1030}
1031
1032#[derive(Debug)]
1033pub(crate) struct NavigationData {
1034 cursor_anchor: Anchor,
1035 cursor_position: Point,
1036 scroll_anchor: ScrollAnchor,
1037 scroll_top_row: u32,
1038}
1039
1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1041pub enum GotoDefinitionKind {
1042 Symbol,
1043 Declaration,
1044 Type,
1045 Implementation,
1046}
1047
1048#[derive(Debug, Clone)]
1049enum InlayHintRefreshReason {
1050 Toggle(bool),
1051 SettingsChange(InlayHintSettings),
1052 NewLinesShown,
1053 BufferEdited(HashSet<Arc<Language>>),
1054 RefreshRequested,
1055 ExcerptsRemoved(Vec<ExcerptId>),
1056}
1057
1058impl InlayHintRefreshReason {
1059 fn description(&self) -> &'static str {
1060 match self {
1061 Self::Toggle(_) => "toggle",
1062 Self::SettingsChange(_) => "settings change",
1063 Self::NewLinesShown => "new lines shown",
1064 Self::BufferEdited(_) => "buffer edited",
1065 Self::RefreshRequested => "refresh requested",
1066 Self::ExcerptsRemoved(_) => "excerpts removed",
1067 }
1068 }
1069}
1070
1071pub enum FormatTarget {
1072 Buffers,
1073 Ranges(Vec<Range<MultiBufferPoint>>),
1074}
1075
1076pub(crate) struct FocusedBlock {
1077 id: BlockId,
1078 focus_handle: WeakFocusHandle,
1079}
1080
1081#[derive(Clone)]
1082enum JumpData {
1083 MultiBufferRow {
1084 row: MultiBufferRow,
1085 line_offset_from_top: u32,
1086 },
1087 MultiBufferPoint {
1088 excerpt_id: ExcerptId,
1089 position: Point,
1090 anchor: text::Anchor,
1091 line_offset_from_top: u32,
1092 },
1093}
1094
1095pub enum MultibufferSelectionMode {
1096 First,
1097 All,
1098}
1099
1100impl Editor {
1101 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1102 let buffer = cx.new(|cx| Buffer::local("", cx));
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(
1105 EditorMode::SingleLine { auto_width: false },
1106 buffer,
1107 None,
1108 false,
1109 window,
1110 cx,
1111 )
1112 }
1113
1114 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1115 let buffer = cx.new(|cx| Buffer::local("", cx));
1116 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1117 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1118 }
1119
1120 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1121 let buffer = cx.new(|cx| Buffer::local("", cx));
1122 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1123 Self::new(
1124 EditorMode::SingleLine { auto_width: true },
1125 buffer,
1126 None,
1127 false,
1128 window,
1129 cx,
1130 )
1131 }
1132
1133 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1134 let buffer = cx.new(|cx| Buffer::local("", cx));
1135 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1136 Self::new(
1137 EditorMode::AutoHeight { max_lines },
1138 buffer,
1139 None,
1140 false,
1141 window,
1142 cx,
1143 )
1144 }
1145
1146 pub fn for_buffer(
1147 buffer: Entity<Buffer>,
1148 project: Option<Entity<Project>>,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1153 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1154 }
1155
1156 pub fn for_multibuffer(
1157 buffer: Entity<MultiBuffer>,
1158 project: Option<Entity<Project>>,
1159 show_excerpt_controls: bool,
1160 window: &mut Window,
1161 cx: &mut Context<Self>,
1162 ) -> Self {
1163 Self::new(
1164 EditorMode::Full,
1165 buffer,
1166 project,
1167 show_excerpt_controls,
1168 window,
1169 cx,
1170 )
1171 }
1172
1173 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1174 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1175 let mut clone = Self::new(
1176 self.mode,
1177 self.buffer.clone(),
1178 self.project.clone(),
1179 show_excerpt_controls,
1180 window,
1181 cx,
1182 );
1183 self.display_map.update(cx, |display_map, cx| {
1184 let snapshot = display_map.snapshot(cx);
1185 clone.display_map.update(cx, |display_map, cx| {
1186 display_map.set_state(&snapshot, cx);
1187 });
1188 });
1189 clone.selections.clone_state(&self.selections);
1190 clone.scroll_manager.clone_state(&self.scroll_manager);
1191 clone.searchable = self.searchable;
1192 clone
1193 }
1194
1195 pub fn new(
1196 mode: EditorMode,
1197 buffer: Entity<MultiBuffer>,
1198 project: Option<Entity<Project>>,
1199 show_excerpt_controls: bool,
1200 window: &mut Window,
1201 cx: &mut Context<Self>,
1202 ) -> Self {
1203 let style = window.text_style();
1204 let font_size = style.font_size.to_pixels(window.rem_size());
1205 let editor = cx.entity().downgrade();
1206 let fold_placeholder = FoldPlaceholder {
1207 constrain_width: true,
1208 render: Arc::new(move |fold_id, fold_range, _, cx| {
1209 let editor = editor.clone();
1210 div()
1211 .id(fold_id)
1212 .bg(cx.theme().colors().ghost_element_background)
1213 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1214 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1215 .rounded_sm()
1216 .size_full()
1217 .cursor_pointer()
1218 .child("⋯")
1219 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1220 .on_click(move |_, _window, cx| {
1221 editor
1222 .update(cx, |editor, cx| {
1223 editor.unfold_ranges(
1224 &[fold_range.start..fold_range.end],
1225 true,
1226 false,
1227 cx,
1228 );
1229 cx.stop_propagation();
1230 })
1231 .ok();
1232 })
1233 .into_any()
1234 }),
1235 merge_adjacent: true,
1236 ..Default::default()
1237 };
1238 let display_map = cx.new(|cx| {
1239 DisplayMap::new(
1240 buffer.clone(),
1241 style.font(),
1242 font_size,
1243 None,
1244 show_excerpt_controls,
1245 FILE_HEADER_HEIGHT,
1246 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1247 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1248 fold_placeholder,
1249 cx,
1250 )
1251 });
1252
1253 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1254
1255 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1256
1257 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1258 .then(|| language_settings::SoftWrap::None);
1259
1260 let mut project_subscriptions = Vec::new();
1261 if mode == EditorMode::Full {
1262 if let Some(project) = project.as_ref() {
1263 if buffer.read(cx).is_singleton() {
1264 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1265 cx.emit(EditorEvent::TitleChanged);
1266 }));
1267 }
1268 project_subscriptions.push(cx.subscribe_in(
1269 project,
1270 window,
1271 |editor, _, event, window, cx| {
1272 if let project::Event::RefreshInlayHints = event {
1273 editor
1274 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1275 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1276 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1277 let focus_handle = editor.focus_handle(cx);
1278 if focus_handle.is_focused(window) {
1279 let snapshot = buffer.read(cx).snapshot();
1280 for (range, snippet) in snippet_edits {
1281 let editor_range =
1282 language::range_from_lsp(*range).to_offset(&snapshot);
1283 editor
1284 .insert_snippet(
1285 &[editor_range],
1286 snippet.clone(),
1287 window,
1288 cx,
1289 )
1290 .ok();
1291 }
1292 }
1293 }
1294 }
1295 },
1296 ));
1297 if let Some(task_inventory) = project
1298 .read(cx)
1299 .task_store()
1300 .read(cx)
1301 .task_inventory()
1302 .cloned()
1303 {
1304 project_subscriptions.push(cx.observe_in(
1305 &task_inventory,
1306 window,
1307 |editor, _, window, cx| {
1308 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1309 },
1310 ));
1311 }
1312 }
1313 }
1314
1315 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1316
1317 let inlay_hint_settings =
1318 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1319 let focus_handle = cx.focus_handle();
1320 cx.on_focus(&focus_handle, window, Self::handle_focus)
1321 .detach();
1322 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1323 .detach();
1324 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1325 .detach();
1326 cx.on_blur(&focus_handle, window, Self::handle_blur)
1327 .detach();
1328
1329 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1330 Some(false)
1331 } else {
1332 None
1333 };
1334
1335 let mut code_action_providers = Vec::new();
1336 let mut load_uncommitted_diff = None;
1337 if let Some(project) = project.clone() {
1338 load_uncommitted_diff = Some(
1339 get_uncommitted_diff_for_buffer(
1340 &project,
1341 buffer.read(cx).all_buffers(),
1342 buffer.clone(),
1343 cx,
1344 )
1345 .shared(),
1346 );
1347 code_action_providers.push(Rc::new(project) as Rc<_>);
1348 }
1349
1350 let mut this = Self {
1351 focus_handle,
1352 show_cursor_when_unfocused: false,
1353 last_focused_descendant: None,
1354 buffer: buffer.clone(),
1355 display_map: display_map.clone(),
1356 selections,
1357 scroll_manager: ScrollManager::new(cx),
1358 columnar_selection_tail: None,
1359 add_selections_state: None,
1360 select_next_state: None,
1361 select_prev_state: None,
1362 selection_history: Default::default(),
1363 autoclose_regions: Default::default(),
1364 snippet_stack: Default::default(),
1365 select_larger_syntax_node_stack: Vec::new(),
1366 ime_transaction: Default::default(),
1367 active_diagnostics: None,
1368 soft_wrap_mode_override,
1369 completion_provider: project.clone().map(|project| Box::new(project) as _),
1370 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1371 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1372 project,
1373 blink_manager: blink_manager.clone(),
1374 show_local_selections: true,
1375 show_scrollbars: true,
1376 mode,
1377 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1378 show_gutter: mode == EditorMode::Full,
1379 show_line_numbers: None,
1380 use_relative_line_numbers: None,
1381 show_git_diff_gutter: None,
1382 show_code_actions: None,
1383 show_runnables: None,
1384 show_wrap_guides: None,
1385 show_indent_guides,
1386 placeholder_text: None,
1387 highlight_order: 0,
1388 highlighted_rows: HashMap::default(),
1389 background_highlights: Default::default(),
1390 gutter_highlights: TreeMap::default(),
1391 scrollbar_marker_state: ScrollbarMarkerState::default(),
1392 active_indent_guides_state: ActiveIndentGuidesState::default(),
1393 nav_history: None,
1394 context_menu: RefCell::new(None),
1395 mouse_context_menu: None,
1396 completion_tasks: Default::default(),
1397 signature_help_state: SignatureHelpState::default(),
1398 auto_signature_help: None,
1399 find_all_references_task_sources: Vec::new(),
1400 next_completion_id: 0,
1401 next_inlay_id: 0,
1402 code_action_providers,
1403 available_code_actions: Default::default(),
1404 code_actions_task: Default::default(),
1405 selection_highlight_task: Default::default(),
1406 document_highlights_task: Default::default(),
1407 linked_editing_range_task: Default::default(),
1408 pending_rename: Default::default(),
1409 searchable: true,
1410 cursor_shape: EditorSettings::get_global(cx)
1411 .cursor_shape
1412 .unwrap_or_default(),
1413 current_line_highlight: None,
1414 autoindent_mode: Some(AutoindentMode::EachLine),
1415 collapse_matches: false,
1416 workspace: None,
1417 input_enabled: true,
1418 use_modal_editing: mode == EditorMode::Full,
1419 read_only: false,
1420 use_autoclose: true,
1421 use_auto_surround: true,
1422 auto_replace_emoji_shortcode: false,
1423 leader_peer_id: None,
1424 remote_id: None,
1425 hover_state: Default::default(),
1426 pending_mouse_down: None,
1427 hovered_link_state: Default::default(),
1428 edit_prediction_provider: None,
1429 active_inline_completion: None,
1430 stale_inline_completion_in_menu: None,
1431 edit_prediction_preview: EditPredictionPreview::Inactive,
1432 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1433
1434 gutter_hovered: false,
1435 pixel_position_of_newest_cursor: None,
1436 last_bounds: None,
1437 last_position_map: None,
1438 expect_bounds_change: None,
1439 gutter_dimensions: GutterDimensions::default(),
1440 style: None,
1441 show_cursor_names: false,
1442 hovered_cursors: Default::default(),
1443 next_editor_action_id: EditorActionId::default(),
1444 editor_actions: Rc::default(),
1445 inline_completions_hidden_for_vim_mode: false,
1446 show_inline_completions_override: None,
1447 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1448 edit_prediction_settings: EditPredictionSettings::Disabled,
1449 edit_prediction_cursor_on_leading_whitespace: false,
1450 edit_prediction_requires_modifier_in_leading_space: true,
1451 custom_context_menu: None,
1452 show_git_blame_gutter: false,
1453 show_git_blame_inline: false,
1454 distinguish_unstaged_diff_hunks: false,
1455 show_selection_menu: None,
1456 show_git_blame_inline_delay_task: None,
1457 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1458 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1459 .session
1460 .restore_unsaved_buffers,
1461 blame: None,
1462 blame_subscription: None,
1463 tasks: Default::default(),
1464 _subscriptions: vec![
1465 cx.observe(&buffer, Self::on_buffer_changed),
1466 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1467 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1468 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1469 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1470 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1471 cx.observe_window_activation(window, |editor, window, cx| {
1472 let active = window.is_window_active();
1473 editor.blink_manager.update(cx, |blink_manager, cx| {
1474 if active {
1475 blink_manager.enable(cx);
1476 } else {
1477 blink_manager.disable(cx);
1478 }
1479 });
1480 }),
1481 ],
1482 tasks_update_task: None,
1483 linked_edit_ranges: Default::default(),
1484 in_project_search: false,
1485 previous_search_ranges: None,
1486 breadcrumb_header: None,
1487 focused_block: None,
1488 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1489 addons: HashMap::default(),
1490 registered_buffers: HashMap::default(),
1491 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1492 selection_mark_mode: false,
1493 toggle_fold_multiple_buffers: Task::ready(()),
1494 serialize_selections: Task::ready(()),
1495 text_style_refinement: None,
1496 load_diff_task: load_uncommitted_diff,
1497 };
1498 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1499 this._subscriptions.extend(project_subscriptions);
1500
1501 this.end_selection(window, cx);
1502 this.scroll_manager.show_scrollbar(window, cx);
1503
1504 if mode == EditorMode::Full {
1505 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1506 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1507
1508 if this.git_blame_inline_enabled {
1509 this.git_blame_inline_enabled = true;
1510 this.start_git_blame_inline(false, window, cx);
1511 }
1512
1513 if let Some(buffer) = buffer.read(cx).as_singleton() {
1514 if let Some(project) = this.project.as_ref() {
1515 let handle = project.update(cx, |project, cx| {
1516 project.register_buffer_with_language_servers(&buffer, cx)
1517 });
1518 this.registered_buffers
1519 .insert(buffer.read(cx).remote_id(), handle);
1520 }
1521 }
1522 }
1523
1524 this.report_editor_event("Editor Opened", None, cx);
1525 this
1526 }
1527
1528 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1529 self.mouse_context_menu
1530 .as_ref()
1531 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1532 }
1533
1534 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1535 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1536 }
1537
1538 fn key_context_internal(
1539 &self,
1540 has_active_edit_prediction: bool,
1541 window: &Window,
1542 cx: &App,
1543 ) -> KeyContext {
1544 let mut key_context = KeyContext::new_with_defaults();
1545 key_context.add("Editor");
1546 let mode = match self.mode {
1547 EditorMode::SingleLine { .. } => "single_line",
1548 EditorMode::AutoHeight { .. } => "auto_height",
1549 EditorMode::Full => "full",
1550 };
1551
1552 if EditorSettings::jupyter_enabled(cx) {
1553 key_context.add("jupyter");
1554 }
1555
1556 key_context.set("mode", mode);
1557 if self.pending_rename.is_some() {
1558 key_context.add("renaming");
1559 }
1560
1561 match self.context_menu.borrow().as_ref() {
1562 Some(CodeContextMenu::Completions(_)) => {
1563 key_context.add("menu");
1564 key_context.add("showing_completions");
1565 }
1566 Some(CodeContextMenu::CodeActions(_)) => {
1567 key_context.add("menu");
1568 key_context.add("showing_code_actions")
1569 }
1570 None => {}
1571 }
1572
1573 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1574 if !self.focus_handle(cx).contains_focused(window, cx)
1575 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1576 {
1577 for addon in self.addons.values() {
1578 addon.extend_key_context(&mut key_context, cx)
1579 }
1580 }
1581
1582 if let Some(extension) = self
1583 .buffer
1584 .read(cx)
1585 .as_singleton()
1586 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1587 {
1588 key_context.set("extension", extension.to_string());
1589 }
1590
1591 if has_active_edit_prediction {
1592 if self.edit_prediction_in_conflict() {
1593 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1594 } else {
1595 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1596 key_context.add("copilot_suggestion");
1597 }
1598 }
1599
1600 if self.selection_mark_mode {
1601 key_context.add("selection_mode");
1602 }
1603
1604 key_context
1605 }
1606
1607 pub fn edit_prediction_in_conflict(&self) -> bool {
1608 if !self.show_edit_predictions_in_menu() {
1609 return false;
1610 }
1611
1612 let showing_completions = self
1613 .context_menu
1614 .borrow()
1615 .as_ref()
1616 .map_or(false, |context| {
1617 matches!(context, CodeContextMenu::Completions(_))
1618 });
1619
1620 showing_completions
1621 || self.edit_prediction_requires_modifier()
1622 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1623 // bindings to insert tab characters.
1624 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1625 }
1626
1627 pub fn accept_edit_prediction_keybind(
1628 &self,
1629 window: &Window,
1630 cx: &App,
1631 ) -> AcceptEditPredictionBinding {
1632 let key_context = self.key_context_internal(true, window, cx);
1633 let in_conflict = self.edit_prediction_in_conflict();
1634
1635 AcceptEditPredictionBinding(
1636 window
1637 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1638 .into_iter()
1639 .filter(|binding| {
1640 !in_conflict
1641 || binding
1642 .keystrokes()
1643 .first()
1644 .map_or(false, |keystroke| keystroke.modifiers.modified())
1645 })
1646 .rev()
1647 .min_by_key(|binding| {
1648 binding
1649 .keystrokes()
1650 .first()
1651 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1652 }),
1653 )
1654 }
1655
1656 pub fn new_file(
1657 workspace: &mut Workspace,
1658 _: &workspace::NewFile,
1659 window: &mut Window,
1660 cx: &mut Context<Workspace>,
1661 ) {
1662 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1663 "Failed to create buffer",
1664 window,
1665 cx,
1666 |e, _, _| match e.error_code() {
1667 ErrorCode::RemoteUpgradeRequired => Some(format!(
1668 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1669 e.error_tag("required").unwrap_or("the latest version")
1670 )),
1671 _ => None,
1672 },
1673 );
1674 }
1675
1676 pub fn new_in_workspace(
1677 workspace: &mut Workspace,
1678 window: &mut Window,
1679 cx: &mut Context<Workspace>,
1680 ) -> Task<Result<Entity<Editor>>> {
1681 let project = workspace.project().clone();
1682 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1683
1684 cx.spawn_in(window, |workspace, mut cx| async move {
1685 let buffer = create.await?;
1686 workspace.update_in(&mut cx, |workspace, window, cx| {
1687 let editor =
1688 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1689 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1690 editor
1691 })
1692 })
1693 }
1694
1695 fn new_file_vertical(
1696 workspace: &mut Workspace,
1697 _: &workspace::NewFileSplitVertical,
1698 window: &mut Window,
1699 cx: &mut Context<Workspace>,
1700 ) {
1701 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1702 }
1703
1704 fn new_file_horizontal(
1705 workspace: &mut Workspace,
1706 _: &workspace::NewFileSplitHorizontal,
1707 window: &mut Window,
1708 cx: &mut Context<Workspace>,
1709 ) {
1710 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1711 }
1712
1713 fn new_file_in_direction(
1714 workspace: &mut Workspace,
1715 direction: SplitDirection,
1716 window: &mut Window,
1717 cx: &mut Context<Workspace>,
1718 ) {
1719 let project = workspace.project().clone();
1720 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1721
1722 cx.spawn_in(window, |workspace, mut cx| async move {
1723 let buffer = create.await?;
1724 workspace.update_in(&mut cx, move |workspace, window, cx| {
1725 workspace.split_item(
1726 direction,
1727 Box::new(
1728 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1729 ),
1730 window,
1731 cx,
1732 )
1733 })?;
1734 anyhow::Ok(())
1735 })
1736 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1737 match e.error_code() {
1738 ErrorCode::RemoteUpgradeRequired => Some(format!(
1739 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1740 e.error_tag("required").unwrap_or("the latest version")
1741 )),
1742 _ => None,
1743 }
1744 });
1745 }
1746
1747 pub fn leader_peer_id(&self) -> Option<PeerId> {
1748 self.leader_peer_id
1749 }
1750
1751 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1752 &self.buffer
1753 }
1754
1755 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1756 self.workspace.as_ref()?.0.upgrade()
1757 }
1758
1759 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1760 self.buffer().read(cx).title(cx)
1761 }
1762
1763 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1764 let git_blame_gutter_max_author_length = self
1765 .render_git_blame_gutter(cx)
1766 .then(|| {
1767 if let Some(blame) = self.blame.as_ref() {
1768 let max_author_length =
1769 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1770 Some(max_author_length)
1771 } else {
1772 None
1773 }
1774 })
1775 .flatten();
1776
1777 EditorSnapshot {
1778 mode: self.mode,
1779 show_gutter: self.show_gutter,
1780 show_line_numbers: self.show_line_numbers,
1781 show_git_diff_gutter: self.show_git_diff_gutter,
1782 show_code_actions: self.show_code_actions,
1783 show_runnables: self.show_runnables,
1784 git_blame_gutter_max_author_length,
1785 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1786 scroll_anchor: self.scroll_manager.anchor(),
1787 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1788 placeholder_text: self.placeholder_text.clone(),
1789 is_focused: self.focus_handle.is_focused(window),
1790 current_line_highlight: self
1791 .current_line_highlight
1792 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1793 gutter_hovered: self.gutter_hovered,
1794 }
1795 }
1796
1797 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1798 self.buffer.read(cx).language_at(point, cx)
1799 }
1800
1801 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1802 self.buffer.read(cx).read(cx).file_at(point).cloned()
1803 }
1804
1805 pub fn active_excerpt(
1806 &self,
1807 cx: &App,
1808 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1809 self.buffer
1810 .read(cx)
1811 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1812 }
1813
1814 pub fn mode(&self) -> EditorMode {
1815 self.mode
1816 }
1817
1818 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1819 self.collaboration_hub.as_deref()
1820 }
1821
1822 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1823 self.collaboration_hub = Some(hub);
1824 }
1825
1826 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1827 self.in_project_search = in_project_search;
1828 }
1829
1830 pub fn set_custom_context_menu(
1831 &mut self,
1832 f: impl 'static
1833 + Fn(
1834 &mut Self,
1835 DisplayPoint,
1836 &mut Window,
1837 &mut Context<Self>,
1838 ) -> Option<Entity<ui::ContextMenu>>,
1839 ) {
1840 self.custom_context_menu = Some(Box::new(f))
1841 }
1842
1843 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1844 self.completion_provider = provider;
1845 }
1846
1847 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1848 self.semantics_provider.clone()
1849 }
1850
1851 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1852 self.semantics_provider = provider;
1853 }
1854
1855 pub fn set_edit_prediction_provider<T>(
1856 &mut self,
1857 provider: Option<Entity<T>>,
1858 window: &mut Window,
1859 cx: &mut Context<Self>,
1860 ) where
1861 T: EditPredictionProvider,
1862 {
1863 self.edit_prediction_provider =
1864 provider.map(|provider| RegisteredInlineCompletionProvider {
1865 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1866 if this.focus_handle.is_focused(window) {
1867 this.update_visible_inline_completion(window, cx);
1868 }
1869 }),
1870 provider: Arc::new(provider),
1871 });
1872 self.refresh_inline_completion(false, false, window, cx);
1873 }
1874
1875 pub fn placeholder_text(&self) -> Option<&str> {
1876 self.placeholder_text.as_deref()
1877 }
1878
1879 pub fn set_placeholder_text(
1880 &mut self,
1881 placeholder_text: impl Into<Arc<str>>,
1882 cx: &mut Context<Self>,
1883 ) {
1884 let placeholder_text = Some(placeholder_text.into());
1885 if self.placeholder_text != placeholder_text {
1886 self.placeholder_text = placeholder_text;
1887 cx.notify();
1888 }
1889 }
1890
1891 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1892 self.cursor_shape = cursor_shape;
1893
1894 // Disrupt blink for immediate user feedback that the cursor shape has changed
1895 self.blink_manager.update(cx, BlinkManager::show_cursor);
1896
1897 cx.notify();
1898 }
1899
1900 pub fn set_current_line_highlight(
1901 &mut self,
1902 current_line_highlight: Option<CurrentLineHighlight>,
1903 ) {
1904 self.current_line_highlight = current_line_highlight;
1905 }
1906
1907 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1908 self.collapse_matches = collapse_matches;
1909 }
1910
1911 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1912 let buffers = self.buffer.read(cx).all_buffers();
1913 let Some(project) = self.project.as_ref() else {
1914 return;
1915 };
1916 project.update(cx, |project, cx| {
1917 for buffer in buffers {
1918 self.registered_buffers
1919 .entry(buffer.read(cx).remote_id())
1920 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1921 }
1922 })
1923 }
1924
1925 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1926 if self.collapse_matches {
1927 return range.start..range.start;
1928 }
1929 range.clone()
1930 }
1931
1932 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1933 if self.display_map.read(cx).clip_at_line_ends != clip {
1934 self.display_map
1935 .update(cx, |map, _| map.clip_at_line_ends = clip);
1936 }
1937 }
1938
1939 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1940 self.input_enabled = input_enabled;
1941 }
1942
1943 pub fn set_inline_completions_hidden_for_vim_mode(
1944 &mut self,
1945 hidden: bool,
1946 window: &mut Window,
1947 cx: &mut Context<Self>,
1948 ) {
1949 if hidden != self.inline_completions_hidden_for_vim_mode {
1950 self.inline_completions_hidden_for_vim_mode = hidden;
1951 if hidden {
1952 self.update_visible_inline_completion(window, cx);
1953 } else {
1954 self.refresh_inline_completion(true, false, window, cx);
1955 }
1956 }
1957 }
1958
1959 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1960 self.menu_inline_completions_policy = value;
1961 }
1962
1963 pub fn set_autoindent(&mut self, autoindent: bool) {
1964 if autoindent {
1965 self.autoindent_mode = Some(AutoindentMode::EachLine);
1966 } else {
1967 self.autoindent_mode = None;
1968 }
1969 }
1970
1971 pub fn read_only(&self, cx: &App) -> bool {
1972 self.read_only || self.buffer.read(cx).read_only()
1973 }
1974
1975 pub fn set_read_only(&mut self, read_only: bool) {
1976 self.read_only = read_only;
1977 }
1978
1979 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1980 self.use_autoclose = autoclose;
1981 }
1982
1983 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1984 self.use_auto_surround = auto_surround;
1985 }
1986
1987 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1988 self.auto_replace_emoji_shortcode = auto_replace;
1989 }
1990
1991 pub fn toggle_inline_completions(
1992 &mut self,
1993 _: &ToggleEditPrediction,
1994 window: &mut Window,
1995 cx: &mut Context<Self>,
1996 ) {
1997 if self.show_inline_completions_override.is_some() {
1998 self.set_show_edit_predictions(None, window, cx);
1999 } else {
2000 let show_edit_predictions = !self.edit_predictions_enabled();
2001 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2002 }
2003 }
2004
2005 pub fn set_show_edit_predictions(
2006 &mut self,
2007 show_edit_predictions: Option<bool>,
2008 window: &mut Window,
2009 cx: &mut Context<Self>,
2010 ) {
2011 self.show_inline_completions_override = show_edit_predictions;
2012 self.refresh_inline_completion(false, true, window, cx);
2013 }
2014
2015 fn inline_completions_disabled_in_scope(
2016 &self,
2017 buffer: &Entity<Buffer>,
2018 buffer_position: language::Anchor,
2019 cx: &App,
2020 ) -> bool {
2021 let snapshot = buffer.read(cx).snapshot();
2022 let settings = snapshot.settings_at(buffer_position, cx);
2023
2024 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2025 return false;
2026 };
2027
2028 scope.override_name().map_or(false, |scope_name| {
2029 settings
2030 .edit_predictions_disabled_in
2031 .iter()
2032 .any(|s| s == scope_name)
2033 })
2034 }
2035
2036 pub fn set_use_modal_editing(&mut self, to: bool) {
2037 self.use_modal_editing = to;
2038 }
2039
2040 pub fn use_modal_editing(&self) -> bool {
2041 self.use_modal_editing
2042 }
2043
2044 fn selections_did_change(
2045 &mut self,
2046 local: bool,
2047 old_cursor_position: &Anchor,
2048 show_completions: bool,
2049 window: &mut Window,
2050 cx: &mut Context<Self>,
2051 ) {
2052 window.invalidate_character_coordinates();
2053
2054 // Copy selections to primary selection buffer
2055 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2056 if local {
2057 let selections = self.selections.all::<usize>(cx);
2058 let buffer_handle = self.buffer.read(cx).read(cx);
2059
2060 let mut text = String::new();
2061 for (index, selection) in selections.iter().enumerate() {
2062 let text_for_selection = buffer_handle
2063 .text_for_range(selection.start..selection.end)
2064 .collect::<String>();
2065
2066 text.push_str(&text_for_selection);
2067 if index != selections.len() - 1 {
2068 text.push('\n');
2069 }
2070 }
2071
2072 if !text.is_empty() {
2073 cx.write_to_primary(ClipboardItem::new_string(text));
2074 }
2075 }
2076
2077 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2078 self.buffer.update(cx, |buffer, cx| {
2079 buffer.set_active_selections(
2080 &self.selections.disjoint_anchors(),
2081 self.selections.line_mode,
2082 self.cursor_shape,
2083 cx,
2084 )
2085 });
2086 }
2087 let display_map = self
2088 .display_map
2089 .update(cx, |display_map, cx| display_map.snapshot(cx));
2090 let buffer = &display_map.buffer_snapshot;
2091 self.add_selections_state = None;
2092 self.select_next_state = None;
2093 self.select_prev_state = None;
2094 self.select_larger_syntax_node_stack.clear();
2095 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2096 self.snippet_stack
2097 .invalidate(&self.selections.disjoint_anchors(), buffer);
2098 self.take_rename(false, window, cx);
2099
2100 let new_cursor_position = self.selections.newest_anchor().head();
2101
2102 self.push_to_nav_history(
2103 *old_cursor_position,
2104 Some(new_cursor_position.to_point(buffer)),
2105 cx,
2106 );
2107
2108 if local {
2109 let new_cursor_position = self.selections.newest_anchor().head();
2110 let mut context_menu = self.context_menu.borrow_mut();
2111 let completion_menu = match context_menu.as_ref() {
2112 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2113 _ => {
2114 *context_menu = None;
2115 None
2116 }
2117 };
2118 if let Some(buffer_id) = new_cursor_position.buffer_id {
2119 if !self.registered_buffers.contains_key(&buffer_id) {
2120 if let Some(project) = self.project.as_ref() {
2121 project.update(cx, |project, cx| {
2122 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2123 return;
2124 };
2125 self.registered_buffers.insert(
2126 buffer_id,
2127 project.register_buffer_with_language_servers(&buffer, cx),
2128 );
2129 })
2130 }
2131 }
2132 }
2133
2134 if let Some(completion_menu) = completion_menu {
2135 let cursor_position = new_cursor_position.to_offset(buffer);
2136 let (word_range, kind) =
2137 buffer.surrounding_word(completion_menu.initial_position, true);
2138 if kind == Some(CharKind::Word)
2139 && word_range.to_inclusive().contains(&cursor_position)
2140 {
2141 let mut completion_menu = completion_menu.clone();
2142 drop(context_menu);
2143
2144 let query = Self::completion_query(buffer, cursor_position);
2145 cx.spawn(move |this, mut cx| async move {
2146 completion_menu
2147 .filter(query.as_deref(), cx.background_executor().clone())
2148 .await;
2149
2150 this.update(&mut cx, |this, cx| {
2151 let mut context_menu = this.context_menu.borrow_mut();
2152 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2153 else {
2154 return;
2155 };
2156
2157 if menu.id > completion_menu.id {
2158 return;
2159 }
2160
2161 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2162 drop(context_menu);
2163 cx.notify();
2164 })
2165 })
2166 .detach();
2167
2168 if show_completions {
2169 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2170 }
2171 } else {
2172 drop(context_menu);
2173 self.hide_context_menu(window, cx);
2174 }
2175 } else {
2176 drop(context_menu);
2177 }
2178
2179 hide_hover(self, cx);
2180
2181 if old_cursor_position.to_display_point(&display_map).row()
2182 != new_cursor_position.to_display_point(&display_map).row()
2183 {
2184 self.available_code_actions.take();
2185 }
2186 self.refresh_code_actions(window, cx);
2187 self.refresh_document_highlights(cx);
2188 self.refresh_selected_text_highlights(window, cx);
2189 refresh_matching_bracket_highlights(self, window, cx);
2190 self.update_visible_inline_completion(window, cx);
2191 self.edit_prediction_requires_modifier_in_leading_space = true;
2192 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2193 if self.git_blame_inline_enabled {
2194 self.start_inline_blame_timer(window, cx);
2195 }
2196 }
2197
2198 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2199 cx.emit(EditorEvent::SelectionsChanged { local });
2200
2201 let selections = &self.selections.disjoint;
2202 if selections.len() == 1 {
2203 cx.emit(SearchEvent::ActiveMatchChanged)
2204 }
2205 if local
2206 && self.is_singleton(cx)
2207 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2208 {
2209 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2210 let background_executor = cx.background_executor().clone();
2211 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2212 let snapshot = self.buffer().read(cx).snapshot(cx);
2213 let selections = selections.clone();
2214 self.serialize_selections = cx.background_spawn(async move {
2215 background_executor.timer(Duration::from_millis(100)).await;
2216 let selections = selections
2217 .iter()
2218 .map(|selection| {
2219 (
2220 selection.start.to_offset(&snapshot),
2221 selection.end.to_offset(&snapshot),
2222 )
2223 })
2224 .collect();
2225 DB.save_editor_selections(editor_id, workspace_id, selections)
2226 .await
2227 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2228 .log_err();
2229 });
2230 }
2231 }
2232
2233 cx.notify();
2234 }
2235
2236 pub fn change_selections<R>(
2237 &mut self,
2238 autoscroll: Option<Autoscroll>,
2239 window: &mut Window,
2240 cx: &mut Context<Self>,
2241 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2242 ) -> R {
2243 self.change_selections_inner(autoscroll, true, window, cx, change)
2244 }
2245
2246 fn change_selections_inner<R>(
2247 &mut self,
2248 autoscroll: Option<Autoscroll>,
2249 request_completions: bool,
2250 window: &mut Window,
2251 cx: &mut Context<Self>,
2252 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2253 ) -> R {
2254 let old_cursor_position = self.selections.newest_anchor().head();
2255 self.push_to_selection_history();
2256
2257 let (changed, result) = self.selections.change_with(cx, change);
2258
2259 if changed {
2260 if let Some(autoscroll) = autoscroll {
2261 self.request_autoscroll(autoscroll, cx);
2262 }
2263 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2264
2265 if self.should_open_signature_help_automatically(
2266 &old_cursor_position,
2267 self.signature_help_state.backspace_pressed(),
2268 cx,
2269 ) {
2270 self.show_signature_help(&ShowSignatureHelp, window, cx);
2271 }
2272 self.signature_help_state.set_backspace_pressed(false);
2273 }
2274
2275 result
2276 }
2277
2278 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2279 where
2280 I: IntoIterator<Item = (Range<S>, T)>,
2281 S: ToOffset,
2282 T: Into<Arc<str>>,
2283 {
2284 if self.read_only(cx) {
2285 return;
2286 }
2287
2288 self.buffer
2289 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2290 }
2291
2292 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2293 where
2294 I: IntoIterator<Item = (Range<S>, T)>,
2295 S: ToOffset,
2296 T: Into<Arc<str>>,
2297 {
2298 if self.read_only(cx) {
2299 return;
2300 }
2301
2302 self.buffer.update(cx, |buffer, cx| {
2303 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2304 });
2305 }
2306
2307 pub fn edit_with_block_indent<I, S, T>(
2308 &mut self,
2309 edits: I,
2310 original_indent_columns: Vec<u32>,
2311 cx: &mut Context<Self>,
2312 ) where
2313 I: IntoIterator<Item = (Range<S>, T)>,
2314 S: ToOffset,
2315 T: Into<Arc<str>>,
2316 {
2317 if self.read_only(cx) {
2318 return;
2319 }
2320
2321 self.buffer.update(cx, |buffer, cx| {
2322 buffer.edit(
2323 edits,
2324 Some(AutoindentMode::Block {
2325 original_indent_columns,
2326 }),
2327 cx,
2328 )
2329 });
2330 }
2331
2332 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2333 self.hide_context_menu(window, cx);
2334
2335 match phase {
2336 SelectPhase::Begin {
2337 position,
2338 add,
2339 click_count,
2340 } => self.begin_selection(position, add, click_count, window, cx),
2341 SelectPhase::BeginColumnar {
2342 position,
2343 goal_column,
2344 reset,
2345 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2346 SelectPhase::Extend {
2347 position,
2348 click_count,
2349 } => self.extend_selection(position, click_count, window, cx),
2350 SelectPhase::Update {
2351 position,
2352 goal_column,
2353 scroll_delta,
2354 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2355 SelectPhase::End => self.end_selection(window, cx),
2356 }
2357 }
2358
2359 fn extend_selection(
2360 &mut self,
2361 position: DisplayPoint,
2362 click_count: usize,
2363 window: &mut Window,
2364 cx: &mut Context<Self>,
2365 ) {
2366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2367 let tail = self.selections.newest::<usize>(cx).tail();
2368 self.begin_selection(position, false, click_count, window, cx);
2369
2370 let position = position.to_offset(&display_map, Bias::Left);
2371 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2372
2373 let mut pending_selection = self
2374 .selections
2375 .pending_anchor()
2376 .expect("extend_selection not called with pending selection");
2377 if position >= tail {
2378 pending_selection.start = tail_anchor;
2379 } else {
2380 pending_selection.end = tail_anchor;
2381 pending_selection.reversed = true;
2382 }
2383
2384 let mut pending_mode = self.selections.pending_mode().unwrap();
2385 match &mut pending_mode {
2386 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2387 _ => {}
2388 }
2389
2390 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2391 s.set_pending(pending_selection, pending_mode)
2392 });
2393 }
2394
2395 fn begin_selection(
2396 &mut self,
2397 position: DisplayPoint,
2398 add: bool,
2399 click_count: usize,
2400 window: &mut Window,
2401 cx: &mut Context<Self>,
2402 ) {
2403 if !self.focus_handle.is_focused(window) {
2404 self.last_focused_descendant = None;
2405 window.focus(&self.focus_handle);
2406 }
2407
2408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2409 let buffer = &display_map.buffer_snapshot;
2410 let newest_selection = self.selections.newest_anchor().clone();
2411 let position = display_map.clip_point(position, Bias::Left);
2412
2413 let start;
2414 let end;
2415 let mode;
2416 let mut auto_scroll;
2417 match click_count {
2418 1 => {
2419 start = buffer.anchor_before(position.to_point(&display_map));
2420 end = start;
2421 mode = SelectMode::Character;
2422 auto_scroll = true;
2423 }
2424 2 => {
2425 let range = movement::surrounding_word(&display_map, position);
2426 start = buffer.anchor_before(range.start.to_point(&display_map));
2427 end = buffer.anchor_before(range.end.to_point(&display_map));
2428 mode = SelectMode::Word(start..end);
2429 auto_scroll = true;
2430 }
2431 3 => {
2432 let position = display_map
2433 .clip_point(position, Bias::Left)
2434 .to_point(&display_map);
2435 let line_start = display_map.prev_line_boundary(position).0;
2436 let next_line_start = buffer.clip_point(
2437 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2438 Bias::Left,
2439 );
2440 start = buffer.anchor_before(line_start);
2441 end = buffer.anchor_before(next_line_start);
2442 mode = SelectMode::Line(start..end);
2443 auto_scroll = true;
2444 }
2445 _ => {
2446 start = buffer.anchor_before(0);
2447 end = buffer.anchor_before(buffer.len());
2448 mode = SelectMode::All;
2449 auto_scroll = false;
2450 }
2451 }
2452 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2453
2454 let point_to_delete: Option<usize> = {
2455 let selected_points: Vec<Selection<Point>> =
2456 self.selections.disjoint_in_range(start..end, cx);
2457
2458 if !add || click_count > 1 {
2459 None
2460 } else if !selected_points.is_empty() {
2461 Some(selected_points[0].id)
2462 } else {
2463 let clicked_point_already_selected =
2464 self.selections.disjoint.iter().find(|selection| {
2465 selection.start.to_point(buffer) == start.to_point(buffer)
2466 || selection.end.to_point(buffer) == end.to_point(buffer)
2467 });
2468
2469 clicked_point_already_selected.map(|selection| selection.id)
2470 }
2471 };
2472
2473 let selections_count = self.selections.count();
2474
2475 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2476 if let Some(point_to_delete) = point_to_delete {
2477 s.delete(point_to_delete);
2478
2479 if selections_count == 1 {
2480 s.set_pending_anchor_range(start..end, mode);
2481 }
2482 } else {
2483 if !add {
2484 s.clear_disjoint();
2485 } else if click_count > 1 {
2486 s.delete(newest_selection.id)
2487 }
2488
2489 s.set_pending_anchor_range(start..end, mode);
2490 }
2491 });
2492 }
2493
2494 fn begin_columnar_selection(
2495 &mut self,
2496 position: DisplayPoint,
2497 goal_column: u32,
2498 reset: bool,
2499 window: &mut Window,
2500 cx: &mut Context<Self>,
2501 ) {
2502 if !self.focus_handle.is_focused(window) {
2503 self.last_focused_descendant = None;
2504 window.focus(&self.focus_handle);
2505 }
2506
2507 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2508
2509 if reset {
2510 let pointer_position = display_map
2511 .buffer_snapshot
2512 .anchor_before(position.to_point(&display_map));
2513
2514 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2515 s.clear_disjoint();
2516 s.set_pending_anchor_range(
2517 pointer_position..pointer_position,
2518 SelectMode::Character,
2519 );
2520 });
2521 }
2522
2523 let tail = self.selections.newest::<Point>(cx).tail();
2524 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2525
2526 if !reset {
2527 self.select_columns(
2528 tail.to_display_point(&display_map),
2529 position,
2530 goal_column,
2531 &display_map,
2532 window,
2533 cx,
2534 );
2535 }
2536 }
2537
2538 fn update_selection(
2539 &mut self,
2540 position: DisplayPoint,
2541 goal_column: u32,
2542 scroll_delta: gpui::Point<f32>,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 ) {
2546 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2547
2548 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2549 let tail = tail.to_display_point(&display_map);
2550 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2551 } else if let Some(mut pending) = self.selections.pending_anchor() {
2552 let buffer = self.buffer.read(cx).snapshot(cx);
2553 let head;
2554 let tail;
2555 let mode = self.selections.pending_mode().unwrap();
2556 match &mode {
2557 SelectMode::Character => {
2558 head = position.to_point(&display_map);
2559 tail = pending.tail().to_point(&buffer);
2560 }
2561 SelectMode::Word(original_range) => {
2562 let original_display_range = original_range.start.to_display_point(&display_map)
2563 ..original_range.end.to_display_point(&display_map);
2564 let original_buffer_range = original_display_range.start.to_point(&display_map)
2565 ..original_display_range.end.to_point(&display_map);
2566 if movement::is_inside_word(&display_map, position)
2567 || original_display_range.contains(&position)
2568 {
2569 let word_range = movement::surrounding_word(&display_map, position);
2570 if word_range.start < original_display_range.start {
2571 head = word_range.start.to_point(&display_map);
2572 } else {
2573 head = word_range.end.to_point(&display_map);
2574 }
2575 } else {
2576 head = position.to_point(&display_map);
2577 }
2578
2579 if head <= original_buffer_range.start {
2580 tail = original_buffer_range.end;
2581 } else {
2582 tail = original_buffer_range.start;
2583 }
2584 }
2585 SelectMode::Line(original_range) => {
2586 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2587
2588 let position = display_map
2589 .clip_point(position, Bias::Left)
2590 .to_point(&display_map);
2591 let line_start = display_map.prev_line_boundary(position).0;
2592 let next_line_start = buffer.clip_point(
2593 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2594 Bias::Left,
2595 );
2596
2597 if line_start < original_range.start {
2598 head = line_start
2599 } else {
2600 head = next_line_start
2601 }
2602
2603 if head <= original_range.start {
2604 tail = original_range.end;
2605 } else {
2606 tail = original_range.start;
2607 }
2608 }
2609 SelectMode::All => {
2610 return;
2611 }
2612 };
2613
2614 if head < tail {
2615 pending.start = buffer.anchor_before(head);
2616 pending.end = buffer.anchor_before(tail);
2617 pending.reversed = true;
2618 } else {
2619 pending.start = buffer.anchor_before(tail);
2620 pending.end = buffer.anchor_before(head);
2621 pending.reversed = false;
2622 }
2623
2624 self.change_selections(None, window, cx, |s| {
2625 s.set_pending(pending, mode);
2626 });
2627 } else {
2628 log::error!("update_selection dispatched with no pending selection");
2629 return;
2630 }
2631
2632 self.apply_scroll_delta(scroll_delta, window, cx);
2633 cx.notify();
2634 }
2635
2636 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2637 self.columnar_selection_tail.take();
2638 if self.selections.pending_anchor().is_some() {
2639 let selections = self.selections.all::<usize>(cx);
2640 self.change_selections(None, window, cx, |s| {
2641 s.select(selections);
2642 s.clear_pending();
2643 });
2644 }
2645 }
2646
2647 fn select_columns(
2648 &mut self,
2649 tail: DisplayPoint,
2650 head: DisplayPoint,
2651 goal_column: u32,
2652 display_map: &DisplaySnapshot,
2653 window: &mut Window,
2654 cx: &mut Context<Self>,
2655 ) {
2656 let start_row = cmp::min(tail.row(), head.row());
2657 let end_row = cmp::max(tail.row(), head.row());
2658 let start_column = cmp::min(tail.column(), goal_column);
2659 let end_column = cmp::max(tail.column(), goal_column);
2660 let reversed = start_column < tail.column();
2661
2662 let selection_ranges = (start_row.0..=end_row.0)
2663 .map(DisplayRow)
2664 .filter_map(|row| {
2665 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2666 let start = display_map
2667 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2668 .to_point(display_map);
2669 let end = display_map
2670 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2671 .to_point(display_map);
2672 if reversed {
2673 Some(end..start)
2674 } else {
2675 Some(start..end)
2676 }
2677 } else {
2678 None
2679 }
2680 })
2681 .collect::<Vec<_>>();
2682
2683 self.change_selections(None, window, cx, |s| {
2684 s.select_ranges(selection_ranges);
2685 });
2686 cx.notify();
2687 }
2688
2689 pub fn has_pending_nonempty_selection(&self) -> bool {
2690 let pending_nonempty_selection = match self.selections.pending_anchor() {
2691 Some(Selection { start, end, .. }) => start != end,
2692 None => false,
2693 };
2694
2695 pending_nonempty_selection
2696 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2697 }
2698
2699 pub fn has_pending_selection(&self) -> bool {
2700 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2701 }
2702
2703 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2704 self.selection_mark_mode = false;
2705
2706 if self.clear_expanded_diff_hunks(cx) {
2707 cx.notify();
2708 return;
2709 }
2710 if self.dismiss_menus_and_popups(true, window, cx) {
2711 return;
2712 }
2713
2714 if self.mode == EditorMode::Full
2715 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2716 {
2717 return;
2718 }
2719
2720 cx.propagate();
2721 }
2722
2723 pub fn dismiss_menus_and_popups(
2724 &mut self,
2725 is_user_requested: bool,
2726 window: &mut Window,
2727 cx: &mut Context<Self>,
2728 ) -> bool {
2729 if self.take_rename(false, window, cx).is_some() {
2730 return true;
2731 }
2732
2733 if hide_hover(self, cx) {
2734 return true;
2735 }
2736
2737 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2738 return true;
2739 }
2740
2741 if self.hide_context_menu(window, cx).is_some() {
2742 return true;
2743 }
2744
2745 if self.mouse_context_menu.take().is_some() {
2746 return true;
2747 }
2748
2749 if is_user_requested && self.discard_inline_completion(true, cx) {
2750 return true;
2751 }
2752
2753 if self.snippet_stack.pop().is_some() {
2754 return true;
2755 }
2756
2757 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2758 self.dismiss_diagnostics(cx);
2759 return true;
2760 }
2761
2762 false
2763 }
2764
2765 fn linked_editing_ranges_for(
2766 &self,
2767 selection: Range<text::Anchor>,
2768 cx: &App,
2769 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2770 if self.linked_edit_ranges.is_empty() {
2771 return None;
2772 }
2773 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2774 selection.end.buffer_id.and_then(|end_buffer_id| {
2775 if selection.start.buffer_id != Some(end_buffer_id) {
2776 return None;
2777 }
2778 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2779 let snapshot = buffer.read(cx).snapshot();
2780 self.linked_edit_ranges
2781 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2782 .map(|ranges| (ranges, snapshot, buffer))
2783 })?;
2784 use text::ToOffset as TO;
2785 // find offset from the start of current range to current cursor position
2786 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2787
2788 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2789 let start_difference = start_offset - start_byte_offset;
2790 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2791 let end_difference = end_offset - start_byte_offset;
2792 // Current range has associated linked ranges.
2793 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2794 for range in linked_ranges.iter() {
2795 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2796 let end_offset = start_offset + end_difference;
2797 let start_offset = start_offset + start_difference;
2798 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2799 continue;
2800 }
2801 if self.selections.disjoint_anchor_ranges().any(|s| {
2802 if s.start.buffer_id != selection.start.buffer_id
2803 || s.end.buffer_id != selection.end.buffer_id
2804 {
2805 return false;
2806 }
2807 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2808 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2809 }) {
2810 continue;
2811 }
2812 let start = buffer_snapshot.anchor_after(start_offset);
2813 let end = buffer_snapshot.anchor_after(end_offset);
2814 linked_edits
2815 .entry(buffer.clone())
2816 .or_default()
2817 .push(start..end);
2818 }
2819 Some(linked_edits)
2820 }
2821
2822 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2823 let text: Arc<str> = text.into();
2824
2825 if self.read_only(cx) {
2826 return;
2827 }
2828
2829 let selections = self.selections.all_adjusted(cx);
2830 let mut bracket_inserted = false;
2831 let mut edits = Vec::new();
2832 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2833 let mut new_selections = Vec::with_capacity(selections.len());
2834 let mut new_autoclose_regions = Vec::new();
2835 let snapshot = self.buffer.read(cx).read(cx);
2836
2837 for (selection, autoclose_region) in
2838 self.selections_with_autoclose_regions(selections, &snapshot)
2839 {
2840 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2841 // Determine if the inserted text matches the opening or closing
2842 // bracket of any of this language's bracket pairs.
2843 let mut bracket_pair = None;
2844 let mut is_bracket_pair_start = false;
2845 let mut is_bracket_pair_end = false;
2846 if !text.is_empty() {
2847 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2848 // and they are removing the character that triggered IME popup.
2849 for (pair, enabled) in scope.brackets() {
2850 if !pair.close && !pair.surround {
2851 continue;
2852 }
2853
2854 if enabled && pair.start.ends_with(text.as_ref()) {
2855 let prefix_len = pair.start.len() - text.len();
2856 let preceding_text_matches_prefix = prefix_len == 0
2857 || (selection.start.column >= (prefix_len as u32)
2858 && snapshot.contains_str_at(
2859 Point::new(
2860 selection.start.row,
2861 selection.start.column - (prefix_len as u32),
2862 ),
2863 &pair.start[..prefix_len],
2864 ));
2865 if preceding_text_matches_prefix {
2866 bracket_pair = Some(pair.clone());
2867 is_bracket_pair_start = true;
2868 break;
2869 }
2870 }
2871 if pair.end.as_str() == text.as_ref() {
2872 bracket_pair = Some(pair.clone());
2873 is_bracket_pair_end = true;
2874 break;
2875 }
2876 }
2877 }
2878
2879 if let Some(bracket_pair) = bracket_pair {
2880 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2881 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2882 let auto_surround =
2883 self.use_auto_surround && snapshot_settings.use_auto_surround;
2884 if selection.is_empty() {
2885 if is_bracket_pair_start {
2886 // If the inserted text is a suffix of an opening bracket and the
2887 // selection is preceded by the rest of the opening bracket, then
2888 // insert the closing bracket.
2889 let following_text_allows_autoclose = snapshot
2890 .chars_at(selection.start)
2891 .next()
2892 .map_or(true, |c| scope.should_autoclose_before(c));
2893
2894 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2895 && bracket_pair.start.len() == 1
2896 {
2897 let target = bracket_pair.start.chars().next().unwrap();
2898 let current_line_count = snapshot
2899 .reversed_chars_at(selection.start)
2900 .take_while(|&c| c != '\n')
2901 .filter(|&c| c == target)
2902 .count();
2903 current_line_count % 2 == 1
2904 } else {
2905 false
2906 };
2907
2908 if autoclose
2909 && bracket_pair.close
2910 && following_text_allows_autoclose
2911 && !is_closing_quote
2912 {
2913 let anchor = snapshot.anchor_before(selection.end);
2914 new_selections.push((selection.map(|_| anchor), text.len()));
2915 new_autoclose_regions.push((
2916 anchor,
2917 text.len(),
2918 selection.id,
2919 bracket_pair.clone(),
2920 ));
2921 edits.push((
2922 selection.range(),
2923 format!("{}{}", text, bracket_pair.end).into(),
2924 ));
2925 bracket_inserted = true;
2926 continue;
2927 }
2928 }
2929
2930 if let Some(region) = autoclose_region {
2931 // If the selection is followed by an auto-inserted closing bracket,
2932 // then don't insert that closing bracket again; just move the selection
2933 // past the closing bracket.
2934 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2935 && text.as_ref() == region.pair.end.as_str();
2936 if should_skip {
2937 let anchor = snapshot.anchor_after(selection.end);
2938 new_selections
2939 .push((selection.map(|_| anchor), region.pair.end.len()));
2940 continue;
2941 }
2942 }
2943
2944 let always_treat_brackets_as_autoclosed = snapshot
2945 .settings_at(selection.start, cx)
2946 .always_treat_brackets_as_autoclosed;
2947 if always_treat_brackets_as_autoclosed
2948 && is_bracket_pair_end
2949 && snapshot.contains_str_at(selection.end, text.as_ref())
2950 {
2951 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2952 // and the inserted text is a closing bracket and the selection is followed
2953 // by the closing bracket then move the selection past the closing bracket.
2954 let anchor = snapshot.anchor_after(selection.end);
2955 new_selections.push((selection.map(|_| anchor), text.len()));
2956 continue;
2957 }
2958 }
2959 // If an opening bracket is 1 character long and is typed while
2960 // text is selected, then surround that text with the bracket pair.
2961 else if auto_surround
2962 && bracket_pair.surround
2963 && is_bracket_pair_start
2964 && bracket_pair.start.chars().count() == 1
2965 {
2966 edits.push((selection.start..selection.start, text.clone()));
2967 edits.push((
2968 selection.end..selection.end,
2969 bracket_pair.end.as_str().into(),
2970 ));
2971 bracket_inserted = true;
2972 new_selections.push((
2973 Selection {
2974 id: selection.id,
2975 start: snapshot.anchor_after(selection.start),
2976 end: snapshot.anchor_before(selection.end),
2977 reversed: selection.reversed,
2978 goal: selection.goal,
2979 },
2980 0,
2981 ));
2982 continue;
2983 }
2984 }
2985 }
2986
2987 if self.auto_replace_emoji_shortcode
2988 && selection.is_empty()
2989 && text.as_ref().ends_with(':')
2990 {
2991 if let Some(possible_emoji_short_code) =
2992 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2993 {
2994 if !possible_emoji_short_code.is_empty() {
2995 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2996 let emoji_shortcode_start = Point::new(
2997 selection.start.row,
2998 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2999 );
3000
3001 // Remove shortcode from buffer
3002 edits.push((
3003 emoji_shortcode_start..selection.start,
3004 "".to_string().into(),
3005 ));
3006 new_selections.push((
3007 Selection {
3008 id: selection.id,
3009 start: snapshot.anchor_after(emoji_shortcode_start),
3010 end: snapshot.anchor_before(selection.start),
3011 reversed: selection.reversed,
3012 goal: selection.goal,
3013 },
3014 0,
3015 ));
3016
3017 // Insert emoji
3018 let selection_start_anchor = snapshot.anchor_after(selection.start);
3019 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3020 edits.push((selection.start..selection.end, emoji.to_string().into()));
3021
3022 continue;
3023 }
3024 }
3025 }
3026 }
3027
3028 // If not handling any auto-close operation, then just replace the selected
3029 // text with the given input and move the selection to the end of the
3030 // newly inserted text.
3031 let anchor = snapshot.anchor_after(selection.end);
3032 if !self.linked_edit_ranges.is_empty() {
3033 let start_anchor = snapshot.anchor_before(selection.start);
3034
3035 let is_word_char = text.chars().next().map_or(true, |char| {
3036 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3037 classifier.is_word(char)
3038 });
3039
3040 if is_word_char {
3041 if let Some(ranges) = self
3042 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3043 {
3044 for (buffer, edits) in ranges {
3045 linked_edits
3046 .entry(buffer.clone())
3047 .or_default()
3048 .extend(edits.into_iter().map(|range| (range, text.clone())));
3049 }
3050 }
3051 }
3052 }
3053
3054 new_selections.push((selection.map(|_| anchor), 0));
3055 edits.push((selection.start..selection.end, text.clone()));
3056 }
3057
3058 drop(snapshot);
3059
3060 self.transact(window, cx, |this, window, cx| {
3061 this.buffer.update(cx, |buffer, cx| {
3062 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3063 });
3064 for (buffer, edits) in linked_edits {
3065 buffer.update(cx, |buffer, cx| {
3066 let snapshot = buffer.snapshot();
3067 let edits = edits
3068 .into_iter()
3069 .map(|(range, text)| {
3070 use text::ToPoint as TP;
3071 let end_point = TP::to_point(&range.end, &snapshot);
3072 let start_point = TP::to_point(&range.start, &snapshot);
3073 (start_point..end_point, text)
3074 })
3075 .sorted_by_key(|(range, _)| range.start)
3076 .collect::<Vec<_>>();
3077 buffer.edit(edits, None, cx);
3078 })
3079 }
3080 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3081 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3082 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3083 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3084 .zip(new_selection_deltas)
3085 .map(|(selection, delta)| Selection {
3086 id: selection.id,
3087 start: selection.start + delta,
3088 end: selection.end + delta,
3089 reversed: selection.reversed,
3090 goal: SelectionGoal::None,
3091 })
3092 .collect::<Vec<_>>();
3093
3094 let mut i = 0;
3095 for (position, delta, selection_id, pair) in new_autoclose_regions {
3096 let position = position.to_offset(&map.buffer_snapshot) + delta;
3097 let start = map.buffer_snapshot.anchor_before(position);
3098 let end = map.buffer_snapshot.anchor_after(position);
3099 while let Some(existing_state) = this.autoclose_regions.get(i) {
3100 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3101 Ordering::Less => i += 1,
3102 Ordering::Greater => break,
3103 Ordering::Equal => {
3104 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3105 Ordering::Less => i += 1,
3106 Ordering::Equal => break,
3107 Ordering::Greater => break,
3108 }
3109 }
3110 }
3111 }
3112 this.autoclose_regions.insert(
3113 i,
3114 AutocloseRegion {
3115 selection_id,
3116 range: start..end,
3117 pair,
3118 },
3119 );
3120 }
3121
3122 let had_active_inline_completion = this.has_active_inline_completion();
3123 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3124 s.select(new_selections)
3125 });
3126
3127 if !bracket_inserted {
3128 if let Some(on_type_format_task) =
3129 this.trigger_on_type_formatting(text.to_string(), window, cx)
3130 {
3131 on_type_format_task.detach_and_log_err(cx);
3132 }
3133 }
3134
3135 let editor_settings = EditorSettings::get_global(cx);
3136 if bracket_inserted
3137 && (editor_settings.auto_signature_help
3138 || editor_settings.show_signature_help_after_edits)
3139 {
3140 this.show_signature_help(&ShowSignatureHelp, window, cx);
3141 }
3142
3143 let trigger_in_words =
3144 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3145 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3146 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3147 this.refresh_inline_completion(true, false, window, cx);
3148 });
3149 }
3150
3151 fn find_possible_emoji_shortcode_at_position(
3152 snapshot: &MultiBufferSnapshot,
3153 position: Point,
3154 ) -> Option<String> {
3155 let mut chars = Vec::new();
3156 let mut found_colon = false;
3157 for char in snapshot.reversed_chars_at(position).take(100) {
3158 // Found a possible emoji shortcode in the middle of the buffer
3159 if found_colon {
3160 if char.is_whitespace() {
3161 chars.reverse();
3162 return Some(chars.iter().collect());
3163 }
3164 // If the previous character is not a whitespace, we are in the middle of a word
3165 // and we only want to complete the shortcode if the word is made up of other emojis
3166 let mut containing_word = String::new();
3167 for ch in snapshot
3168 .reversed_chars_at(position)
3169 .skip(chars.len() + 1)
3170 .take(100)
3171 {
3172 if ch.is_whitespace() {
3173 break;
3174 }
3175 containing_word.push(ch);
3176 }
3177 let containing_word = containing_word.chars().rev().collect::<String>();
3178 if util::word_consists_of_emojis(containing_word.as_str()) {
3179 chars.reverse();
3180 return Some(chars.iter().collect());
3181 }
3182 }
3183
3184 if char.is_whitespace() || !char.is_ascii() {
3185 return None;
3186 }
3187 if char == ':' {
3188 found_colon = true;
3189 } else {
3190 chars.push(char);
3191 }
3192 }
3193 // Found a possible emoji shortcode at the beginning of the buffer
3194 chars.reverse();
3195 Some(chars.iter().collect())
3196 }
3197
3198 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3199 self.transact(window, cx, |this, window, cx| {
3200 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3201 let selections = this.selections.all::<usize>(cx);
3202 let multi_buffer = this.buffer.read(cx);
3203 let buffer = multi_buffer.snapshot(cx);
3204 selections
3205 .iter()
3206 .map(|selection| {
3207 let start_point = selection.start.to_point(&buffer);
3208 let mut indent =
3209 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3210 indent.len = cmp::min(indent.len, start_point.column);
3211 let start = selection.start;
3212 let end = selection.end;
3213 let selection_is_empty = start == end;
3214 let language_scope = buffer.language_scope_at(start);
3215 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3216 &language_scope
3217 {
3218 let leading_whitespace_len = buffer
3219 .reversed_chars_at(start)
3220 .take_while(|c| c.is_whitespace() && *c != '\n')
3221 .map(|c| c.len_utf8())
3222 .sum::<usize>();
3223
3224 let trailing_whitespace_len = buffer
3225 .chars_at(end)
3226 .take_while(|c| c.is_whitespace() && *c != '\n')
3227 .map(|c| c.len_utf8())
3228 .sum::<usize>();
3229
3230 let insert_extra_newline =
3231 language.brackets().any(|(pair, enabled)| {
3232 let pair_start = pair.start.trim_end();
3233 let pair_end = pair.end.trim_start();
3234
3235 enabled
3236 && pair.newline
3237 && buffer.contains_str_at(
3238 end + trailing_whitespace_len,
3239 pair_end,
3240 )
3241 && buffer.contains_str_at(
3242 (start - leading_whitespace_len)
3243 .saturating_sub(pair_start.len()),
3244 pair_start,
3245 )
3246 });
3247
3248 // Comment extension on newline is allowed only for cursor selections
3249 let comment_delimiter = maybe!({
3250 if !selection_is_empty {
3251 return None;
3252 }
3253
3254 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3255 return None;
3256 }
3257
3258 let delimiters = language.line_comment_prefixes();
3259 let max_len_of_delimiter =
3260 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3261 let (snapshot, range) =
3262 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3263
3264 let mut index_of_first_non_whitespace = 0;
3265 let comment_candidate = snapshot
3266 .chars_for_range(range)
3267 .skip_while(|c| {
3268 let should_skip = c.is_whitespace();
3269 if should_skip {
3270 index_of_first_non_whitespace += 1;
3271 }
3272 should_skip
3273 })
3274 .take(max_len_of_delimiter)
3275 .collect::<String>();
3276 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3277 comment_candidate.starts_with(comment_prefix.as_ref())
3278 })?;
3279 let cursor_is_placed_after_comment_marker =
3280 index_of_first_non_whitespace + comment_prefix.len()
3281 <= start_point.column as usize;
3282 if cursor_is_placed_after_comment_marker {
3283 Some(comment_prefix.clone())
3284 } else {
3285 None
3286 }
3287 });
3288 (comment_delimiter, insert_extra_newline)
3289 } else {
3290 (None, false)
3291 };
3292
3293 let capacity_for_delimiter = comment_delimiter
3294 .as_deref()
3295 .map(str::len)
3296 .unwrap_or_default();
3297 let mut new_text =
3298 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3299 new_text.push('\n');
3300 new_text.extend(indent.chars());
3301 if let Some(delimiter) = &comment_delimiter {
3302 new_text.push_str(delimiter);
3303 }
3304 if insert_extra_newline {
3305 new_text = new_text.repeat(2);
3306 }
3307
3308 let anchor = buffer.anchor_after(end);
3309 let new_selection = selection.map(|_| anchor);
3310 (
3311 (start..end, new_text),
3312 (insert_extra_newline, new_selection),
3313 )
3314 })
3315 .unzip()
3316 };
3317
3318 this.edit_with_autoindent(edits, cx);
3319 let buffer = this.buffer.read(cx).snapshot(cx);
3320 let new_selections = selection_fixup_info
3321 .into_iter()
3322 .map(|(extra_newline_inserted, new_selection)| {
3323 let mut cursor = new_selection.end.to_point(&buffer);
3324 if extra_newline_inserted {
3325 cursor.row -= 1;
3326 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3327 }
3328 new_selection.map(|_| cursor)
3329 })
3330 .collect();
3331
3332 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3333 s.select(new_selections)
3334 });
3335 this.refresh_inline_completion(true, false, window, cx);
3336 });
3337 }
3338
3339 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3340 let buffer = self.buffer.read(cx);
3341 let snapshot = buffer.snapshot(cx);
3342
3343 let mut edits = Vec::new();
3344 let mut rows = Vec::new();
3345
3346 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3347 let cursor = selection.head();
3348 let row = cursor.row;
3349
3350 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3351
3352 let newline = "\n".to_string();
3353 edits.push((start_of_line..start_of_line, newline));
3354
3355 rows.push(row + rows_inserted as u32);
3356 }
3357
3358 self.transact(window, cx, |editor, window, cx| {
3359 editor.edit(edits, cx);
3360
3361 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3362 let mut index = 0;
3363 s.move_cursors_with(|map, _, _| {
3364 let row = rows[index];
3365 index += 1;
3366
3367 let point = Point::new(row, 0);
3368 let boundary = map.next_line_boundary(point).1;
3369 let clipped = map.clip_point(boundary, Bias::Left);
3370
3371 (clipped, SelectionGoal::None)
3372 });
3373 });
3374
3375 let mut indent_edits = Vec::new();
3376 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3377 for row in rows {
3378 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3379 for (row, indent) in indents {
3380 if indent.len == 0 {
3381 continue;
3382 }
3383
3384 let text = match indent.kind {
3385 IndentKind::Space => " ".repeat(indent.len as usize),
3386 IndentKind::Tab => "\t".repeat(indent.len as usize),
3387 };
3388 let point = Point::new(row.0, 0);
3389 indent_edits.push((point..point, text));
3390 }
3391 }
3392 editor.edit(indent_edits, cx);
3393 });
3394 }
3395
3396 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3397 let buffer = self.buffer.read(cx);
3398 let snapshot = buffer.snapshot(cx);
3399
3400 let mut edits = Vec::new();
3401 let mut rows = Vec::new();
3402 let mut rows_inserted = 0;
3403
3404 for selection in self.selections.all_adjusted(cx) {
3405 let cursor = selection.head();
3406 let row = cursor.row;
3407
3408 let point = Point::new(row + 1, 0);
3409 let start_of_line = snapshot.clip_point(point, Bias::Left);
3410
3411 let newline = "\n".to_string();
3412 edits.push((start_of_line..start_of_line, newline));
3413
3414 rows_inserted += 1;
3415 rows.push(row + rows_inserted);
3416 }
3417
3418 self.transact(window, cx, |editor, window, cx| {
3419 editor.edit(edits, cx);
3420
3421 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3422 let mut index = 0;
3423 s.move_cursors_with(|map, _, _| {
3424 let row = rows[index];
3425 index += 1;
3426
3427 let point = Point::new(row, 0);
3428 let boundary = map.next_line_boundary(point).1;
3429 let clipped = map.clip_point(boundary, Bias::Left);
3430
3431 (clipped, SelectionGoal::None)
3432 });
3433 });
3434
3435 let mut indent_edits = Vec::new();
3436 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3437 for row in rows {
3438 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3439 for (row, indent) in indents {
3440 if indent.len == 0 {
3441 continue;
3442 }
3443
3444 let text = match indent.kind {
3445 IndentKind::Space => " ".repeat(indent.len as usize),
3446 IndentKind::Tab => "\t".repeat(indent.len as usize),
3447 };
3448 let point = Point::new(row.0, 0);
3449 indent_edits.push((point..point, text));
3450 }
3451 }
3452 editor.edit(indent_edits, cx);
3453 });
3454 }
3455
3456 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3457 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3458 original_indent_columns: Vec::new(),
3459 });
3460 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3461 }
3462
3463 fn insert_with_autoindent_mode(
3464 &mut self,
3465 text: &str,
3466 autoindent_mode: Option<AutoindentMode>,
3467 window: &mut Window,
3468 cx: &mut Context<Self>,
3469 ) {
3470 if self.read_only(cx) {
3471 return;
3472 }
3473
3474 let text: Arc<str> = text.into();
3475 self.transact(window, cx, |this, window, cx| {
3476 let old_selections = this.selections.all_adjusted(cx);
3477 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3478 let anchors = {
3479 let snapshot = buffer.read(cx);
3480 old_selections
3481 .iter()
3482 .map(|s| {
3483 let anchor = snapshot.anchor_after(s.head());
3484 s.map(|_| anchor)
3485 })
3486 .collect::<Vec<_>>()
3487 };
3488 buffer.edit(
3489 old_selections
3490 .iter()
3491 .map(|s| (s.start..s.end, text.clone())),
3492 autoindent_mode,
3493 cx,
3494 );
3495 anchors
3496 });
3497
3498 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3499 s.select_anchors(selection_anchors);
3500 });
3501
3502 cx.notify();
3503 });
3504 }
3505
3506 fn trigger_completion_on_input(
3507 &mut self,
3508 text: &str,
3509 trigger_in_words: bool,
3510 window: &mut Window,
3511 cx: &mut Context<Self>,
3512 ) {
3513 if self.is_completion_trigger(text, trigger_in_words, cx) {
3514 self.show_completions(
3515 &ShowCompletions {
3516 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3517 },
3518 window,
3519 cx,
3520 );
3521 } else {
3522 self.hide_context_menu(window, cx);
3523 }
3524 }
3525
3526 fn is_completion_trigger(
3527 &self,
3528 text: &str,
3529 trigger_in_words: bool,
3530 cx: &mut Context<Self>,
3531 ) -> bool {
3532 let position = self.selections.newest_anchor().head();
3533 let multibuffer = self.buffer.read(cx);
3534 let Some(buffer) = position
3535 .buffer_id
3536 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3537 else {
3538 return false;
3539 };
3540
3541 if let Some(completion_provider) = &self.completion_provider {
3542 completion_provider.is_completion_trigger(
3543 &buffer,
3544 position.text_anchor,
3545 text,
3546 trigger_in_words,
3547 cx,
3548 )
3549 } else {
3550 false
3551 }
3552 }
3553
3554 /// If any empty selections is touching the start of its innermost containing autoclose
3555 /// region, expand it to select the brackets.
3556 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3557 let selections = self.selections.all::<usize>(cx);
3558 let buffer = self.buffer.read(cx).read(cx);
3559 let new_selections = self
3560 .selections_with_autoclose_regions(selections, &buffer)
3561 .map(|(mut selection, region)| {
3562 if !selection.is_empty() {
3563 return selection;
3564 }
3565
3566 if let Some(region) = region {
3567 let mut range = region.range.to_offset(&buffer);
3568 if selection.start == range.start && range.start >= region.pair.start.len() {
3569 range.start -= region.pair.start.len();
3570 if buffer.contains_str_at(range.start, ®ion.pair.start)
3571 && buffer.contains_str_at(range.end, ®ion.pair.end)
3572 {
3573 range.end += region.pair.end.len();
3574 selection.start = range.start;
3575 selection.end = range.end;
3576
3577 return selection;
3578 }
3579 }
3580 }
3581
3582 let always_treat_brackets_as_autoclosed = buffer
3583 .settings_at(selection.start, cx)
3584 .always_treat_brackets_as_autoclosed;
3585
3586 if !always_treat_brackets_as_autoclosed {
3587 return selection;
3588 }
3589
3590 if let Some(scope) = buffer.language_scope_at(selection.start) {
3591 for (pair, enabled) in scope.brackets() {
3592 if !enabled || !pair.close {
3593 continue;
3594 }
3595
3596 if buffer.contains_str_at(selection.start, &pair.end) {
3597 let pair_start_len = pair.start.len();
3598 if buffer.contains_str_at(
3599 selection.start.saturating_sub(pair_start_len),
3600 &pair.start,
3601 ) {
3602 selection.start -= pair_start_len;
3603 selection.end += pair.end.len();
3604
3605 return selection;
3606 }
3607 }
3608 }
3609 }
3610
3611 selection
3612 })
3613 .collect();
3614
3615 drop(buffer);
3616 self.change_selections(None, window, cx, |selections| {
3617 selections.select(new_selections)
3618 });
3619 }
3620
3621 /// Iterate the given selections, and for each one, find the smallest surrounding
3622 /// autoclose region. This uses the ordering of the selections and the autoclose
3623 /// regions to avoid repeated comparisons.
3624 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3625 &'a self,
3626 selections: impl IntoIterator<Item = Selection<D>>,
3627 buffer: &'a MultiBufferSnapshot,
3628 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3629 let mut i = 0;
3630 let mut regions = self.autoclose_regions.as_slice();
3631 selections.into_iter().map(move |selection| {
3632 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3633
3634 let mut enclosing = None;
3635 while let Some(pair_state) = regions.get(i) {
3636 if pair_state.range.end.to_offset(buffer) < range.start {
3637 regions = ®ions[i + 1..];
3638 i = 0;
3639 } else if pair_state.range.start.to_offset(buffer) > range.end {
3640 break;
3641 } else {
3642 if pair_state.selection_id == selection.id {
3643 enclosing = Some(pair_state);
3644 }
3645 i += 1;
3646 }
3647 }
3648
3649 (selection, enclosing)
3650 })
3651 }
3652
3653 /// Remove any autoclose regions that no longer contain their selection.
3654 fn invalidate_autoclose_regions(
3655 &mut self,
3656 mut selections: &[Selection<Anchor>],
3657 buffer: &MultiBufferSnapshot,
3658 ) {
3659 self.autoclose_regions.retain(|state| {
3660 let mut i = 0;
3661 while let Some(selection) = selections.get(i) {
3662 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3663 selections = &selections[1..];
3664 continue;
3665 }
3666 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3667 break;
3668 }
3669 if selection.id == state.selection_id {
3670 return true;
3671 } else {
3672 i += 1;
3673 }
3674 }
3675 false
3676 });
3677 }
3678
3679 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3680 let offset = position.to_offset(buffer);
3681 let (word_range, kind) = buffer.surrounding_word(offset, true);
3682 if offset > word_range.start && kind == Some(CharKind::Word) {
3683 Some(
3684 buffer
3685 .text_for_range(word_range.start..offset)
3686 .collect::<String>(),
3687 )
3688 } else {
3689 None
3690 }
3691 }
3692
3693 pub fn toggle_inlay_hints(
3694 &mut self,
3695 _: &ToggleInlayHints,
3696 _: &mut Window,
3697 cx: &mut Context<Self>,
3698 ) {
3699 self.refresh_inlay_hints(
3700 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3701 cx,
3702 );
3703 }
3704
3705 pub fn inlay_hints_enabled(&self) -> bool {
3706 self.inlay_hint_cache.enabled
3707 }
3708
3709 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3710 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3711 return;
3712 }
3713
3714 let reason_description = reason.description();
3715 let ignore_debounce = matches!(
3716 reason,
3717 InlayHintRefreshReason::SettingsChange(_)
3718 | InlayHintRefreshReason::Toggle(_)
3719 | InlayHintRefreshReason::ExcerptsRemoved(_)
3720 );
3721 let (invalidate_cache, required_languages) = match reason {
3722 InlayHintRefreshReason::Toggle(enabled) => {
3723 self.inlay_hint_cache.enabled = enabled;
3724 if enabled {
3725 (InvalidationStrategy::RefreshRequested, None)
3726 } else {
3727 self.inlay_hint_cache.clear();
3728 self.splice_inlays(
3729 &self
3730 .visible_inlay_hints(cx)
3731 .iter()
3732 .map(|inlay| inlay.id)
3733 .collect::<Vec<InlayId>>(),
3734 Vec::new(),
3735 cx,
3736 );
3737 return;
3738 }
3739 }
3740 InlayHintRefreshReason::SettingsChange(new_settings) => {
3741 match self.inlay_hint_cache.update_settings(
3742 &self.buffer,
3743 new_settings,
3744 self.visible_inlay_hints(cx),
3745 cx,
3746 ) {
3747 ControlFlow::Break(Some(InlaySplice {
3748 to_remove,
3749 to_insert,
3750 })) => {
3751 self.splice_inlays(&to_remove, to_insert, cx);
3752 return;
3753 }
3754 ControlFlow::Break(None) => return,
3755 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3756 }
3757 }
3758 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3759 if let Some(InlaySplice {
3760 to_remove,
3761 to_insert,
3762 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3763 {
3764 self.splice_inlays(&to_remove, to_insert, cx);
3765 }
3766 return;
3767 }
3768 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3769 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3770 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3771 }
3772 InlayHintRefreshReason::RefreshRequested => {
3773 (InvalidationStrategy::RefreshRequested, None)
3774 }
3775 };
3776
3777 if let Some(InlaySplice {
3778 to_remove,
3779 to_insert,
3780 }) = self.inlay_hint_cache.spawn_hint_refresh(
3781 reason_description,
3782 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3783 invalidate_cache,
3784 ignore_debounce,
3785 cx,
3786 ) {
3787 self.splice_inlays(&to_remove, to_insert, cx);
3788 }
3789 }
3790
3791 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3792 self.display_map
3793 .read(cx)
3794 .current_inlays()
3795 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3796 .cloned()
3797 .collect()
3798 }
3799
3800 pub fn excerpts_for_inlay_hints_query(
3801 &self,
3802 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3803 cx: &mut Context<Editor>,
3804 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3805 let Some(project) = self.project.as_ref() else {
3806 return HashMap::default();
3807 };
3808 let project = project.read(cx);
3809 let multi_buffer = self.buffer().read(cx);
3810 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3811 let multi_buffer_visible_start = self
3812 .scroll_manager
3813 .anchor()
3814 .anchor
3815 .to_point(&multi_buffer_snapshot);
3816 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3817 multi_buffer_visible_start
3818 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3819 Bias::Left,
3820 );
3821 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3822 multi_buffer_snapshot
3823 .range_to_buffer_ranges(multi_buffer_visible_range)
3824 .into_iter()
3825 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3826 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3827 let buffer_file = project::File::from_dyn(buffer.file())?;
3828 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3829 let worktree_entry = buffer_worktree
3830 .read(cx)
3831 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3832 if worktree_entry.is_ignored {
3833 return None;
3834 }
3835
3836 let language = buffer.language()?;
3837 if let Some(restrict_to_languages) = restrict_to_languages {
3838 if !restrict_to_languages.contains(language) {
3839 return None;
3840 }
3841 }
3842 Some((
3843 excerpt_id,
3844 (
3845 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3846 buffer.version().clone(),
3847 excerpt_visible_range,
3848 ),
3849 ))
3850 })
3851 .collect()
3852 }
3853
3854 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3855 TextLayoutDetails {
3856 text_system: window.text_system().clone(),
3857 editor_style: self.style.clone().unwrap(),
3858 rem_size: window.rem_size(),
3859 scroll_anchor: self.scroll_manager.anchor(),
3860 visible_rows: self.visible_line_count(),
3861 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3862 }
3863 }
3864
3865 pub fn splice_inlays(
3866 &self,
3867 to_remove: &[InlayId],
3868 to_insert: Vec<Inlay>,
3869 cx: &mut Context<Self>,
3870 ) {
3871 self.display_map.update(cx, |display_map, cx| {
3872 display_map.splice_inlays(to_remove, to_insert, cx)
3873 });
3874 cx.notify();
3875 }
3876
3877 fn trigger_on_type_formatting(
3878 &self,
3879 input: String,
3880 window: &mut Window,
3881 cx: &mut Context<Self>,
3882 ) -> Option<Task<Result<()>>> {
3883 if input.len() != 1 {
3884 return None;
3885 }
3886
3887 let project = self.project.as_ref()?;
3888 let position = self.selections.newest_anchor().head();
3889 let (buffer, buffer_position) = self
3890 .buffer
3891 .read(cx)
3892 .text_anchor_for_position(position, cx)?;
3893
3894 let settings = language_settings::language_settings(
3895 buffer
3896 .read(cx)
3897 .language_at(buffer_position)
3898 .map(|l| l.name()),
3899 buffer.read(cx).file(),
3900 cx,
3901 );
3902 if !settings.use_on_type_format {
3903 return None;
3904 }
3905
3906 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3907 // hence we do LSP request & edit on host side only — add formats to host's history.
3908 let push_to_lsp_host_history = true;
3909 // If this is not the host, append its history with new edits.
3910 let push_to_client_history = project.read(cx).is_via_collab();
3911
3912 let on_type_formatting = project.update(cx, |project, cx| {
3913 project.on_type_format(
3914 buffer.clone(),
3915 buffer_position,
3916 input,
3917 push_to_lsp_host_history,
3918 cx,
3919 )
3920 });
3921 Some(cx.spawn_in(window, |editor, mut cx| async move {
3922 if let Some(transaction) = on_type_formatting.await? {
3923 if push_to_client_history {
3924 buffer
3925 .update(&mut cx, |buffer, _| {
3926 buffer.push_transaction(transaction, Instant::now());
3927 })
3928 .ok();
3929 }
3930 editor.update(&mut cx, |editor, cx| {
3931 editor.refresh_document_highlights(cx);
3932 })?;
3933 }
3934 Ok(())
3935 }))
3936 }
3937
3938 pub fn show_completions(
3939 &mut self,
3940 options: &ShowCompletions,
3941 window: &mut Window,
3942 cx: &mut Context<Self>,
3943 ) {
3944 if self.pending_rename.is_some() {
3945 return;
3946 }
3947
3948 let Some(provider) = self.completion_provider.as_ref() else {
3949 return;
3950 };
3951
3952 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3953 return;
3954 }
3955
3956 let position = self.selections.newest_anchor().head();
3957 if position.diff_base_anchor.is_some() {
3958 return;
3959 }
3960 let (buffer, buffer_position) =
3961 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3962 output
3963 } else {
3964 return;
3965 };
3966 let show_completion_documentation = buffer
3967 .read(cx)
3968 .snapshot()
3969 .settings_at(buffer_position, cx)
3970 .show_completion_documentation;
3971
3972 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3973
3974 let trigger_kind = match &options.trigger {
3975 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3976 CompletionTriggerKind::TRIGGER_CHARACTER
3977 }
3978 _ => CompletionTriggerKind::INVOKED,
3979 };
3980 let completion_context = CompletionContext {
3981 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3982 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3983 Some(String::from(trigger))
3984 } else {
3985 None
3986 }
3987 }),
3988 trigger_kind,
3989 };
3990 let completions =
3991 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3992 let sort_completions = provider.sort_completions();
3993
3994 let id = post_inc(&mut self.next_completion_id);
3995 let task = cx.spawn_in(window, |editor, mut cx| {
3996 async move {
3997 editor.update(&mut cx, |this, _| {
3998 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3999 })?;
4000 let completions = completions.await.log_err();
4001 let menu = if let Some(completions) = completions {
4002 let mut menu = CompletionsMenu::new(
4003 id,
4004 sort_completions,
4005 show_completion_documentation,
4006 position,
4007 buffer.clone(),
4008 completions.into(),
4009 );
4010
4011 menu.filter(query.as_deref(), cx.background_executor().clone())
4012 .await;
4013
4014 menu.visible().then_some(menu)
4015 } else {
4016 None
4017 };
4018
4019 editor.update_in(&mut cx, |editor, window, cx| {
4020 match editor.context_menu.borrow().as_ref() {
4021 None => {}
4022 Some(CodeContextMenu::Completions(prev_menu)) => {
4023 if prev_menu.id > id {
4024 return;
4025 }
4026 }
4027 _ => return,
4028 }
4029
4030 if editor.focus_handle.is_focused(window) && menu.is_some() {
4031 let mut menu = menu.unwrap();
4032 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4033
4034 *editor.context_menu.borrow_mut() =
4035 Some(CodeContextMenu::Completions(menu));
4036
4037 if editor.show_edit_predictions_in_menu() {
4038 editor.update_visible_inline_completion(window, cx);
4039 } else {
4040 editor.discard_inline_completion(false, cx);
4041 }
4042
4043 cx.notify();
4044 } else if editor.completion_tasks.len() <= 1 {
4045 // If there are no more completion tasks and the last menu was
4046 // empty, we should hide it.
4047 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4048 // If it was already hidden and we don't show inline
4049 // completions in the menu, we should also show the
4050 // inline-completion when available.
4051 if was_hidden && editor.show_edit_predictions_in_menu() {
4052 editor.update_visible_inline_completion(window, cx);
4053 }
4054 }
4055 })?;
4056
4057 Ok::<_, anyhow::Error>(())
4058 }
4059 .log_err()
4060 });
4061
4062 self.completion_tasks.push((id, task));
4063 }
4064
4065 pub fn confirm_completion(
4066 &mut self,
4067 action: &ConfirmCompletion,
4068 window: &mut Window,
4069 cx: &mut Context<Self>,
4070 ) -> Option<Task<Result<()>>> {
4071 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4072 }
4073
4074 pub fn compose_completion(
4075 &mut self,
4076 action: &ComposeCompletion,
4077 window: &mut Window,
4078 cx: &mut Context<Self>,
4079 ) -> Option<Task<Result<()>>> {
4080 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4081 }
4082
4083 fn do_completion(
4084 &mut self,
4085 item_ix: Option<usize>,
4086 intent: CompletionIntent,
4087 window: &mut Window,
4088 cx: &mut Context<Editor>,
4089 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4090 use language::ToOffset as _;
4091
4092 let completions_menu =
4093 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4094 menu
4095 } else {
4096 return None;
4097 };
4098
4099 let entries = completions_menu.entries.borrow();
4100 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4101 if self.show_edit_predictions_in_menu() {
4102 self.discard_inline_completion(true, cx);
4103 }
4104 let candidate_id = mat.candidate_id;
4105 drop(entries);
4106
4107 let buffer_handle = completions_menu.buffer;
4108 let completion = completions_menu
4109 .completions
4110 .borrow()
4111 .get(candidate_id)?
4112 .clone();
4113 cx.stop_propagation();
4114
4115 let snippet;
4116 let text;
4117
4118 if completion.is_snippet() {
4119 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4120 text = snippet.as_ref().unwrap().text.clone();
4121 } else {
4122 snippet = None;
4123 text = completion.new_text.clone();
4124 };
4125 let selections = self.selections.all::<usize>(cx);
4126 let buffer = buffer_handle.read(cx);
4127 let old_range = completion.old_range.to_offset(buffer);
4128 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4129
4130 let newest_selection = self.selections.newest_anchor();
4131 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4132 return None;
4133 }
4134
4135 let lookbehind = newest_selection
4136 .start
4137 .text_anchor
4138 .to_offset(buffer)
4139 .saturating_sub(old_range.start);
4140 let lookahead = old_range
4141 .end
4142 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4143 let mut common_prefix_len = old_text
4144 .bytes()
4145 .zip(text.bytes())
4146 .take_while(|(a, b)| a == b)
4147 .count();
4148
4149 let snapshot = self.buffer.read(cx).snapshot(cx);
4150 let mut range_to_replace: Option<Range<isize>> = None;
4151 let mut ranges = Vec::new();
4152 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4153 for selection in &selections {
4154 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4155 let start = selection.start.saturating_sub(lookbehind);
4156 let end = selection.end + lookahead;
4157 if selection.id == newest_selection.id {
4158 range_to_replace = Some(
4159 ((start + common_prefix_len) as isize - selection.start as isize)
4160 ..(end as isize - selection.start as isize),
4161 );
4162 }
4163 ranges.push(start + common_prefix_len..end);
4164 } else {
4165 common_prefix_len = 0;
4166 ranges.clear();
4167 ranges.extend(selections.iter().map(|s| {
4168 if s.id == newest_selection.id {
4169 range_to_replace = Some(
4170 old_range.start.to_offset_utf16(&snapshot).0 as isize
4171 - selection.start as isize
4172 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4173 - selection.start as isize,
4174 );
4175 old_range.clone()
4176 } else {
4177 s.start..s.end
4178 }
4179 }));
4180 break;
4181 }
4182 if !self.linked_edit_ranges.is_empty() {
4183 let start_anchor = snapshot.anchor_before(selection.head());
4184 let end_anchor = snapshot.anchor_after(selection.tail());
4185 if let Some(ranges) = self
4186 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4187 {
4188 for (buffer, edits) in ranges {
4189 linked_edits.entry(buffer.clone()).or_default().extend(
4190 edits
4191 .into_iter()
4192 .map(|range| (range, text[common_prefix_len..].to_owned())),
4193 );
4194 }
4195 }
4196 }
4197 }
4198 let text = &text[common_prefix_len..];
4199
4200 cx.emit(EditorEvent::InputHandled {
4201 utf16_range_to_replace: range_to_replace,
4202 text: text.into(),
4203 });
4204
4205 self.transact(window, cx, |this, window, cx| {
4206 if let Some(mut snippet) = snippet {
4207 snippet.text = text.to_string();
4208 for tabstop in snippet
4209 .tabstops
4210 .iter_mut()
4211 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4212 {
4213 tabstop.start -= common_prefix_len as isize;
4214 tabstop.end -= common_prefix_len as isize;
4215 }
4216
4217 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4218 } else {
4219 this.buffer.update(cx, |buffer, cx| {
4220 buffer.edit(
4221 ranges.iter().map(|range| (range.clone(), text)),
4222 this.autoindent_mode.clone(),
4223 cx,
4224 );
4225 });
4226 }
4227 for (buffer, edits) in linked_edits {
4228 buffer.update(cx, |buffer, cx| {
4229 let snapshot = buffer.snapshot();
4230 let edits = edits
4231 .into_iter()
4232 .map(|(range, text)| {
4233 use text::ToPoint as TP;
4234 let end_point = TP::to_point(&range.end, &snapshot);
4235 let start_point = TP::to_point(&range.start, &snapshot);
4236 (start_point..end_point, text)
4237 })
4238 .sorted_by_key(|(range, _)| range.start)
4239 .collect::<Vec<_>>();
4240 buffer.edit(edits, None, cx);
4241 })
4242 }
4243
4244 this.refresh_inline_completion(true, false, window, cx);
4245 });
4246
4247 let show_new_completions_on_confirm = completion
4248 .confirm
4249 .as_ref()
4250 .map_or(false, |confirm| confirm(intent, window, cx));
4251 if show_new_completions_on_confirm {
4252 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4253 }
4254
4255 let provider = self.completion_provider.as_ref()?;
4256 drop(completion);
4257 let apply_edits = provider.apply_additional_edits_for_completion(
4258 buffer_handle,
4259 completions_menu.completions.clone(),
4260 candidate_id,
4261 true,
4262 cx,
4263 );
4264
4265 let editor_settings = EditorSettings::get_global(cx);
4266 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4267 // After the code completion is finished, users often want to know what signatures are needed.
4268 // so we should automatically call signature_help
4269 self.show_signature_help(&ShowSignatureHelp, window, cx);
4270 }
4271
4272 Some(cx.foreground_executor().spawn(async move {
4273 apply_edits.await?;
4274 Ok(())
4275 }))
4276 }
4277
4278 pub fn toggle_code_actions(
4279 &mut self,
4280 action: &ToggleCodeActions,
4281 window: &mut Window,
4282 cx: &mut Context<Self>,
4283 ) {
4284 let mut context_menu = self.context_menu.borrow_mut();
4285 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4286 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4287 // Toggle if we're selecting the same one
4288 *context_menu = None;
4289 cx.notify();
4290 return;
4291 } else {
4292 // Otherwise, clear it and start a new one
4293 *context_menu = None;
4294 cx.notify();
4295 }
4296 }
4297 drop(context_menu);
4298 let snapshot = self.snapshot(window, cx);
4299 let deployed_from_indicator = action.deployed_from_indicator;
4300 let mut task = self.code_actions_task.take();
4301 let action = action.clone();
4302 cx.spawn_in(window, |editor, mut cx| async move {
4303 while let Some(prev_task) = task {
4304 prev_task.await.log_err();
4305 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4306 }
4307
4308 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4309 if editor.focus_handle.is_focused(window) {
4310 let multibuffer_point = action
4311 .deployed_from_indicator
4312 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4313 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4314 let (buffer, buffer_row) = snapshot
4315 .buffer_snapshot
4316 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4317 .and_then(|(buffer_snapshot, range)| {
4318 editor
4319 .buffer
4320 .read(cx)
4321 .buffer(buffer_snapshot.remote_id())
4322 .map(|buffer| (buffer, range.start.row))
4323 })?;
4324 let (_, code_actions) = editor
4325 .available_code_actions
4326 .clone()
4327 .and_then(|(location, code_actions)| {
4328 let snapshot = location.buffer.read(cx).snapshot();
4329 let point_range = location.range.to_point(&snapshot);
4330 let point_range = point_range.start.row..=point_range.end.row;
4331 if point_range.contains(&buffer_row) {
4332 Some((location, code_actions))
4333 } else {
4334 None
4335 }
4336 })
4337 .unzip();
4338 let buffer_id = buffer.read(cx).remote_id();
4339 let tasks = editor
4340 .tasks
4341 .get(&(buffer_id, buffer_row))
4342 .map(|t| Arc::new(t.to_owned()));
4343 if tasks.is_none() && code_actions.is_none() {
4344 return None;
4345 }
4346
4347 editor.completion_tasks.clear();
4348 editor.discard_inline_completion(false, cx);
4349 let task_context =
4350 tasks
4351 .as_ref()
4352 .zip(editor.project.clone())
4353 .map(|(tasks, project)| {
4354 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4355 });
4356
4357 Some(cx.spawn_in(window, |editor, mut cx| async move {
4358 let task_context = match task_context {
4359 Some(task_context) => task_context.await,
4360 None => None,
4361 };
4362 let resolved_tasks =
4363 tasks.zip(task_context).map(|(tasks, task_context)| {
4364 Rc::new(ResolvedTasks {
4365 templates: tasks.resolve(&task_context).collect(),
4366 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4367 multibuffer_point.row,
4368 tasks.column,
4369 )),
4370 })
4371 });
4372 let spawn_straight_away = resolved_tasks
4373 .as_ref()
4374 .map_or(false, |tasks| tasks.templates.len() == 1)
4375 && code_actions
4376 .as_ref()
4377 .map_or(true, |actions| actions.is_empty());
4378 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4379 *editor.context_menu.borrow_mut() =
4380 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4381 buffer,
4382 actions: CodeActionContents {
4383 tasks: resolved_tasks,
4384 actions: code_actions,
4385 },
4386 selected_item: Default::default(),
4387 scroll_handle: UniformListScrollHandle::default(),
4388 deployed_from_indicator,
4389 }));
4390 if spawn_straight_away {
4391 if let Some(task) = editor.confirm_code_action(
4392 &ConfirmCodeAction { item_ix: Some(0) },
4393 window,
4394 cx,
4395 ) {
4396 cx.notify();
4397 return task;
4398 }
4399 }
4400 cx.notify();
4401 Task::ready(Ok(()))
4402 }) {
4403 task.await
4404 } else {
4405 Ok(())
4406 }
4407 }))
4408 } else {
4409 Some(Task::ready(Ok(())))
4410 }
4411 })?;
4412 if let Some(task) = spawned_test_task {
4413 task.await?;
4414 }
4415
4416 Ok::<_, anyhow::Error>(())
4417 })
4418 .detach_and_log_err(cx);
4419 }
4420
4421 pub fn confirm_code_action(
4422 &mut self,
4423 action: &ConfirmCodeAction,
4424 window: &mut Window,
4425 cx: &mut Context<Self>,
4426 ) -> Option<Task<Result<()>>> {
4427 let actions_menu =
4428 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4429 menu
4430 } else {
4431 return None;
4432 };
4433 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4434 let action = actions_menu.actions.get(action_ix)?;
4435 let title = action.label();
4436 let buffer = actions_menu.buffer;
4437 let workspace = self.workspace()?;
4438
4439 match action {
4440 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4441 workspace.update(cx, |workspace, cx| {
4442 workspace::tasks::schedule_resolved_task(
4443 workspace,
4444 task_source_kind,
4445 resolved_task,
4446 false,
4447 cx,
4448 );
4449
4450 Some(Task::ready(Ok(())))
4451 })
4452 }
4453 CodeActionsItem::CodeAction {
4454 excerpt_id,
4455 action,
4456 provider,
4457 } => {
4458 let apply_code_action =
4459 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4460 let workspace = workspace.downgrade();
4461 Some(cx.spawn_in(window, |editor, cx| async move {
4462 let project_transaction = apply_code_action.await?;
4463 Self::open_project_transaction(
4464 &editor,
4465 workspace,
4466 project_transaction,
4467 title,
4468 cx,
4469 )
4470 .await
4471 }))
4472 }
4473 }
4474 }
4475
4476 pub async fn open_project_transaction(
4477 this: &WeakEntity<Editor>,
4478 workspace: WeakEntity<Workspace>,
4479 transaction: ProjectTransaction,
4480 title: String,
4481 mut cx: AsyncWindowContext,
4482 ) -> Result<()> {
4483 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4484 cx.update(|_, cx| {
4485 entries.sort_unstable_by_key(|(buffer, _)| {
4486 buffer.read(cx).file().map(|f| f.path().clone())
4487 });
4488 })?;
4489
4490 // If the project transaction's edits are all contained within this editor, then
4491 // avoid opening a new editor to display them.
4492
4493 if let Some((buffer, transaction)) = entries.first() {
4494 if entries.len() == 1 {
4495 let excerpt = this.update(&mut cx, |editor, cx| {
4496 editor
4497 .buffer()
4498 .read(cx)
4499 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4500 })?;
4501 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4502 if excerpted_buffer == *buffer {
4503 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4504 let excerpt_range = excerpt_range.to_offset(buffer);
4505 buffer
4506 .edited_ranges_for_transaction::<usize>(transaction)
4507 .all(|range| {
4508 excerpt_range.start <= range.start
4509 && excerpt_range.end >= range.end
4510 })
4511 })?;
4512
4513 if all_edits_within_excerpt {
4514 return Ok(());
4515 }
4516 }
4517 }
4518 }
4519 } else {
4520 return Ok(());
4521 }
4522
4523 let mut ranges_to_highlight = Vec::new();
4524 let excerpt_buffer = cx.new(|cx| {
4525 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4526 for (buffer_handle, transaction) in &entries {
4527 let buffer = buffer_handle.read(cx);
4528 ranges_to_highlight.extend(
4529 multibuffer.push_excerpts_with_context_lines(
4530 buffer_handle.clone(),
4531 buffer
4532 .edited_ranges_for_transaction::<usize>(transaction)
4533 .collect(),
4534 DEFAULT_MULTIBUFFER_CONTEXT,
4535 cx,
4536 ),
4537 );
4538 }
4539 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4540 multibuffer
4541 })?;
4542
4543 workspace.update_in(&mut cx, |workspace, window, cx| {
4544 let project = workspace.project().clone();
4545 let editor = cx
4546 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4547 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4548 editor.update(cx, |editor, cx| {
4549 editor.highlight_background::<Self>(
4550 &ranges_to_highlight,
4551 |theme| theme.editor_highlighted_line_background,
4552 cx,
4553 );
4554 });
4555 })?;
4556
4557 Ok(())
4558 }
4559
4560 pub fn clear_code_action_providers(&mut self) {
4561 self.code_action_providers.clear();
4562 self.available_code_actions.take();
4563 }
4564
4565 pub fn add_code_action_provider(
4566 &mut self,
4567 provider: Rc<dyn CodeActionProvider>,
4568 window: &mut Window,
4569 cx: &mut Context<Self>,
4570 ) {
4571 if self
4572 .code_action_providers
4573 .iter()
4574 .any(|existing_provider| existing_provider.id() == provider.id())
4575 {
4576 return;
4577 }
4578
4579 self.code_action_providers.push(provider);
4580 self.refresh_code_actions(window, cx);
4581 }
4582
4583 pub fn remove_code_action_provider(
4584 &mut self,
4585 id: Arc<str>,
4586 window: &mut Window,
4587 cx: &mut Context<Self>,
4588 ) {
4589 self.code_action_providers
4590 .retain(|provider| provider.id() != id);
4591 self.refresh_code_actions(window, cx);
4592 }
4593
4594 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4595 let buffer = self.buffer.read(cx);
4596 let newest_selection = self.selections.newest_anchor().clone();
4597 if newest_selection.head().diff_base_anchor.is_some() {
4598 return None;
4599 }
4600 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4601 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4602 if start_buffer != end_buffer {
4603 return None;
4604 }
4605
4606 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4607 cx.background_executor()
4608 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4609 .await;
4610
4611 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4612 let providers = this.code_action_providers.clone();
4613 let tasks = this
4614 .code_action_providers
4615 .iter()
4616 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4617 .collect::<Vec<_>>();
4618 (providers, tasks)
4619 })?;
4620
4621 let mut actions = Vec::new();
4622 for (provider, provider_actions) in
4623 providers.into_iter().zip(future::join_all(tasks).await)
4624 {
4625 if let Some(provider_actions) = provider_actions.log_err() {
4626 actions.extend(provider_actions.into_iter().map(|action| {
4627 AvailableCodeAction {
4628 excerpt_id: newest_selection.start.excerpt_id,
4629 action,
4630 provider: provider.clone(),
4631 }
4632 }));
4633 }
4634 }
4635
4636 this.update(&mut cx, |this, cx| {
4637 this.available_code_actions = if actions.is_empty() {
4638 None
4639 } else {
4640 Some((
4641 Location {
4642 buffer: start_buffer,
4643 range: start..end,
4644 },
4645 actions.into(),
4646 ))
4647 };
4648 cx.notify();
4649 })
4650 }));
4651 None
4652 }
4653
4654 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4655 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4656 self.show_git_blame_inline = false;
4657
4658 self.show_git_blame_inline_delay_task =
4659 Some(cx.spawn_in(window, |this, mut cx| async move {
4660 cx.background_executor().timer(delay).await;
4661
4662 this.update(&mut cx, |this, cx| {
4663 this.show_git_blame_inline = true;
4664 cx.notify();
4665 })
4666 .log_err();
4667 }));
4668 }
4669 }
4670
4671 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4672 if self.pending_rename.is_some() {
4673 return None;
4674 }
4675
4676 let provider = self.semantics_provider.clone()?;
4677 let buffer = self.buffer.read(cx);
4678 let newest_selection = self.selections.newest_anchor().clone();
4679 let cursor_position = newest_selection.head();
4680 let (cursor_buffer, cursor_buffer_position) =
4681 buffer.text_anchor_for_position(cursor_position, cx)?;
4682 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4683 if cursor_buffer != tail_buffer {
4684 return None;
4685 }
4686 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4687 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4688 cx.background_executor()
4689 .timer(Duration::from_millis(debounce))
4690 .await;
4691
4692 let highlights = if let Some(highlights) = cx
4693 .update(|cx| {
4694 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4695 })
4696 .ok()
4697 .flatten()
4698 {
4699 highlights.await.log_err()
4700 } else {
4701 None
4702 };
4703
4704 if let Some(highlights) = highlights {
4705 this.update(&mut cx, |this, cx| {
4706 if this.pending_rename.is_some() {
4707 return;
4708 }
4709
4710 let buffer_id = cursor_position.buffer_id;
4711 let buffer = this.buffer.read(cx);
4712 if !buffer
4713 .text_anchor_for_position(cursor_position, cx)
4714 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4715 {
4716 return;
4717 }
4718
4719 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4720 let mut write_ranges = Vec::new();
4721 let mut read_ranges = Vec::new();
4722 for highlight in highlights {
4723 for (excerpt_id, excerpt_range) in
4724 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4725 {
4726 let start = highlight
4727 .range
4728 .start
4729 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4730 let end = highlight
4731 .range
4732 .end
4733 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4734 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4735 continue;
4736 }
4737
4738 let range = Anchor {
4739 buffer_id,
4740 excerpt_id,
4741 text_anchor: start,
4742 diff_base_anchor: None,
4743 }..Anchor {
4744 buffer_id,
4745 excerpt_id,
4746 text_anchor: end,
4747 diff_base_anchor: None,
4748 };
4749 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4750 write_ranges.push(range);
4751 } else {
4752 read_ranges.push(range);
4753 }
4754 }
4755 }
4756
4757 this.highlight_background::<DocumentHighlightRead>(
4758 &read_ranges,
4759 |theme| theme.editor_document_highlight_read_background,
4760 cx,
4761 );
4762 this.highlight_background::<DocumentHighlightWrite>(
4763 &write_ranges,
4764 |theme| theme.editor_document_highlight_write_background,
4765 cx,
4766 );
4767 cx.notify();
4768 })
4769 .log_err();
4770 }
4771 }));
4772 None
4773 }
4774
4775 pub fn refresh_selected_text_highlights(
4776 &mut self,
4777 window: &mut Window,
4778 cx: &mut Context<Editor>,
4779 ) {
4780 self.selection_highlight_task.take();
4781 if !EditorSettings::get_global(cx).selection_highlight {
4782 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4783 return;
4784 }
4785 if self.selections.count() != 1 || self.selections.line_mode {
4786 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4787 return;
4788 }
4789 let selection = self.selections.newest::<Point>(cx);
4790 if selection.is_empty() || selection.start.row != selection.end.row {
4791 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4792 return;
4793 }
4794 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4795 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4796 cx.background_executor()
4797 .timer(Duration::from_millis(debounce))
4798 .await;
4799 let Some(Some(matches_task)) = editor
4800 .update_in(&mut cx, |editor, _, cx| {
4801 if editor.selections.count() != 1 || editor.selections.line_mode {
4802 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4803 return None;
4804 }
4805 let selection = editor.selections.newest::<Point>(cx);
4806 if selection.is_empty() || selection.start.row != selection.end.row {
4807 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4808 return None;
4809 }
4810 let buffer = editor.buffer().read(cx).snapshot(cx);
4811 Some(cx.background_spawn(async move {
4812 let mut ranges = Vec::new();
4813 let query = buffer.text_for_range(selection.range()).collect::<String>();
4814 let selection_anchors = selection.range().to_anchors(&buffer);
4815 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4816 for (search_buffer, search_range, excerpt_id) in
4817 buffer.range_to_buffer_ranges(range)
4818 {
4819 ranges.extend(
4820 project::search::SearchQuery::text(
4821 query.clone(),
4822 false,
4823 false,
4824 false,
4825 Default::default(),
4826 Default::default(),
4827 None,
4828 )
4829 .unwrap()
4830 .search(search_buffer, Some(search_range.clone()))
4831 .await
4832 .into_iter()
4833 .filter_map(
4834 |match_range| {
4835 let start = search_buffer.anchor_after(
4836 search_range.start + match_range.start,
4837 );
4838 let end = search_buffer.anchor_before(
4839 search_range.start + match_range.end,
4840 );
4841 let range = Anchor::range_in_buffer(
4842 excerpt_id,
4843 search_buffer.remote_id(),
4844 start..end,
4845 );
4846 (range != selection_anchors).then_some(range)
4847 },
4848 ),
4849 );
4850 }
4851 }
4852 ranges
4853 }))
4854 })
4855 .log_err()
4856 else {
4857 return;
4858 };
4859 let matches = matches_task.await;
4860 editor
4861 .update_in(&mut cx, |editor, _, cx| {
4862 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4863 if !matches.is_empty() {
4864 editor.highlight_background::<SelectedTextHighlight>(
4865 &matches,
4866 |theme| theme.editor_document_highlight_bracket_background,
4867 cx,
4868 )
4869 }
4870 })
4871 .log_err();
4872 }));
4873 }
4874
4875 pub fn refresh_inline_completion(
4876 &mut self,
4877 debounce: bool,
4878 user_requested: bool,
4879 window: &mut Window,
4880 cx: &mut Context<Self>,
4881 ) -> Option<()> {
4882 let provider = self.edit_prediction_provider()?;
4883 let cursor = self.selections.newest_anchor().head();
4884 let (buffer, cursor_buffer_position) =
4885 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4886
4887 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4888 self.discard_inline_completion(false, cx);
4889 return None;
4890 }
4891
4892 if !user_requested
4893 && (!self.should_show_edit_predictions()
4894 || !self.is_focused(window)
4895 || buffer.read(cx).is_empty())
4896 {
4897 self.discard_inline_completion(false, cx);
4898 return None;
4899 }
4900
4901 self.update_visible_inline_completion(window, cx);
4902 provider.refresh(
4903 self.project.clone(),
4904 buffer,
4905 cursor_buffer_position,
4906 debounce,
4907 cx,
4908 );
4909 Some(())
4910 }
4911
4912 fn show_edit_predictions_in_menu(&self) -> bool {
4913 match self.edit_prediction_settings {
4914 EditPredictionSettings::Disabled => false,
4915 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4916 }
4917 }
4918
4919 pub fn edit_predictions_enabled(&self) -> bool {
4920 match self.edit_prediction_settings {
4921 EditPredictionSettings::Disabled => false,
4922 EditPredictionSettings::Enabled { .. } => true,
4923 }
4924 }
4925
4926 fn edit_prediction_requires_modifier(&self) -> bool {
4927 match self.edit_prediction_settings {
4928 EditPredictionSettings::Disabled => false,
4929 EditPredictionSettings::Enabled {
4930 preview_requires_modifier,
4931 ..
4932 } => preview_requires_modifier,
4933 }
4934 }
4935
4936 fn edit_prediction_settings_at_position(
4937 &self,
4938 buffer: &Entity<Buffer>,
4939 buffer_position: language::Anchor,
4940 cx: &App,
4941 ) -> EditPredictionSettings {
4942 if self.mode != EditorMode::Full
4943 || !self.show_inline_completions_override.unwrap_or(true)
4944 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4945 {
4946 return EditPredictionSettings::Disabled;
4947 }
4948
4949 let buffer = buffer.read(cx);
4950
4951 let file = buffer.file();
4952
4953 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4954 return EditPredictionSettings::Disabled;
4955 };
4956
4957 let by_provider = matches!(
4958 self.menu_inline_completions_policy,
4959 MenuInlineCompletionsPolicy::ByProvider
4960 );
4961
4962 let show_in_menu = by_provider
4963 && self
4964 .edit_prediction_provider
4965 .as_ref()
4966 .map_or(false, |provider| {
4967 provider.provider.show_completions_in_menu()
4968 });
4969
4970 let preview_requires_modifier =
4971 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4972
4973 EditPredictionSettings::Enabled {
4974 show_in_menu,
4975 preview_requires_modifier,
4976 }
4977 }
4978
4979 fn should_show_edit_predictions(&self) -> bool {
4980 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4981 }
4982
4983 pub fn edit_prediction_preview_is_active(&self) -> bool {
4984 matches!(
4985 self.edit_prediction_preview,
4986 EditPredictionPreview::Active { .. }
4987 )
4988 }
4989
4990 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4991 let cursor = self.selections.newest_anchor().head();
4992 if let Some((buffer, cursor_position)) =
4993 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4994 {
4995 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4996 } else {
4997 false
4998 }
4999 }
5000
5001 fn inline_completions_enabled_in_buffer(
5002 &self,
5003 buffer: &Entity<Buffer>,
5004 buffer_position: language::Anchor,
5005 cx: &App,
5006 ) -> bool {
5007 maybe!({
5008 let provider = self.edit_prediction_provider()?;
5009 if !provider.is_enabled(&buffer, buffer_position, cx) {
5010 return Some(false);
5011 }
5012 let buffer = buffer.read(cx);
5013 let Some(file) = buffer.file() else {
5014 return Some(true);
5015 };
5016 let settings = all_language_settings(Some(file), cx);
5017 Some(settings.inline_completions_enabled_for_path(file.path()))
5018 })
5019 .unwrap_or(false)
5020 }
5021
5022 fn cycle_inline_completion(
5023 &mut self,
5024 direction: Direction,
5025 window: &mut Window,
5026 cx: &mut Context<Self>,
5027 ) -> Option<()> {
5028 let provider = self.edit_prediction_provider()?;
5029 let cursor = self.selections.newest_anchor().head();
5030 let (buffer, cursor_buffer_position) =
5031 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5032 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5033 return None;
5034 }
5035
5036 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5037 self.update_visible_inline_completion(window, cx);
5038
5039 Some(())
5040 }
5041
5042 pub fn show_inline_completion(
5043 &mut self,
5044 _: &ShowEditPrediction,
5045 window: &mut Window,
5046 cx: &mut Context<Self>,
5047 ) {
5048 if !self.has_active_inline_completion() {
5049 self.refresh_inline_completion(false, true, window, cx);
5050 return;
5051 }
5052
5053 self.update_visible_inline_completion(window, cx);
5054 }
5055
5056 pub fn display_cursor_names(
5057 &mut self,
5058 _: &DisplayCursorNames,
5059 window: &mut Window,
5060 cx: &mut Context<Self>,
5061 ) {
5062 self.show_cursor_names(window, cx);
5063 }
5064
5065 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5066 self.show_cursor_names = true;
5067 cx.notify();
5068 cx.spawn_in(window, |this, mut cx| async move {
5069 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5070 this.update(&mut cx, |this, cx| {
5071 this.show_cursor_names = false;
5072 cx.notify()
5073 })
5074 .ok()
5075 })
5076 .detach();
5077 }
5078
5079 pub fn next_edit_prediction(
5080 &mut self,
5081 _: &NextEditPrediction,
5082 window: &mut Window,
5083 cx: &mut Context<Self>,
5084 ) {
5085 if self.has_active_inline_completion() {
5086 self.cycle_inline_completion(Direction::Next, window, cx);
5087 } else {
5088 let is_copilot_disabled = self
5089 .refresh_inline_completion(false, true, window, cx)
5090 .is_none();
5091 if is_copilot_disabled {
5092 cx.propagate();
5093 }
5094 }
5095 }
5096
5097 pub fn previous_edit_prediction(
5098 &mut self,
5099 _: &PreviousEditPrediction,
5100 window: &mut Window,
5101 cx: &mut Context<Self>,
5102 ) {
5103 if self.has_active_inline_completion() {
5104 self.cycle_inline_completion(Direction::Prev, window, cx);
5105 } else {
5106 let is_copilot_disabled = self
5107 .refresh_inline_completion(false, true, window, cx)
5108 .is_none();
5109 if is_copilot_disabled {
5110 cx.propagate();
5111 }
5112 }
5113 }
5114
5115 pub fn accept_edit_prediction(
5116 &mut self,
5117 _: &AcceptEditPrediction,
5118 window: &mut Window,
5119 cx: &mut Context<Self>,
5120 ) {
5121 if self.show_edit_predictions_in_menu() {
5122 self.hide_context_menu(window, cx);
5123 }
5124
5125 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5126 return;
5127 };
5128
5129 self.report_inline_completion_event(
5130 active_inline_completion.completion_id.clone(),
5131 true,
5132 cx,
5133 );
5134
5135 match &active_inline_completion.completion {
5136 InlineCompletion::Move { target, .. } => {
5137 let target = *target;
5138
5139 if let Some(position_map) = &self.last_position_map {
5140 if position_map
5141 .visible_row_range
5142 .contains(&target.to_display_point(&position_map.snapshot).row())
5143 || !self.edit_prediction_requires_modifier()
5144 {
5145 self.unfold_ranges(&[target..target], true, false, cx);
5146 // Note that this is also done in vim's handler of the Tab action.
5147 self.change_selections(
5148 Some(Autoscroll::newest()),
5149 window,
5150 cx,
5151 |selections| {
5152 selections.select_anchor_ranges([target..target]);
5153 },
5154 );
5155 self.clear_row_highlights::<EditPredictionPreview>();
5156
5157 self.edit_prediction_preview = EditPredictionPreview::Active {
5158 previous_scroll_position: None,
5159 };
5160 } else {
5161 self.edit_prediction_preview = EditPredictionPreview::Active {
5162 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5163 };
5164 self.highlight_rows::<EditPredictionPreview>(
5165 target..target,
5166 cx.theme().colors().editor_highlighted_line_background,
5167 true,
5168 cx,
5169 );
5170 self.request_autoscroll(Autoscroll::fit(), cx);
5171 }
5172 }
5173 }
5174 InlineCompletion::Edit { edits, .. } => {
5175 if let Some(provider) = self.edit_prediction_provider() {
5176 provider.accept(cx);
5177 }
5178
5179 let snapshot = self.buffer.read(cx).snapshot(cx);
5180 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5181
5182 self.buffer.update(cx, |buffer, cx| {
5183 buffer.edit(edits.iter().cloned(), None, cx)
5184 });
5185
5186 self.change_selections(None, window, cx, |s| {
5187 s.select_anchor_ranges([last_edit_end..last_edit_end])
5188 });
5189
5190 self.update_visible_inline_completion(window, cx);
5191 if self.active_inline_completion.is_none() {
5192 self.refresh_inline_completion(true, true, window, cx);
5193 }
5194
5195 cx.notify();
5196 }
5197 }
5198
5199 self.edit_prediction_requires_modifier_in_leading_space = false;
5200 }
5201
5202 pub fn accept_partial_inline_completion(
5203 &mut self,
5204 _: &AcceptPartialEditPrediction,
5205 window: &mut Window,
5206 cx: &mut Context<Self>,
5207 ) {
5208 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5209 return;
5210 };
5211 if self.selections.count() != 1 {
5212 return;
5213 }
5214
5215 self.report_inline_completion_event(
5216 active_inline_completion.completion_id.clone(),
5217 true,
5218 cx,
5219 );
5220
5221 match &active_inline_completion.completion {
5222 InlineCompletion::Move { target, .. } => {
5223 let target = *target;
5224 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5225 selections.select_anchor_ranges([target..target]);
5226 });
5227 }
5228 InlineCompletion::Edit { edits, .. } => {
5229 // Find an insertion that starts at the cursor position.
5230 let snapshot = self.buffer.read(cx).snapshot(cx);
5231 let cursor_offset = self.selections.newest::<usize>(cx).head();
5232 let insertion = edits.iter().find_map(|(range, text)| {
5233 let range = range.to_offset(&snapshot);
5234 if range.is_empty() && range.start == cursor_offset {
5235 Some(text)
5236 } else {
5237 None
5238 }
5239 });
5240
5241 if let Some(text) = insertion {
5242 let mut partial_completion = text
5243 .chars()
5244 .by_ref()
5245 .take_while(|c| c.is_alphabetic())
5246 .collect::<String>();
5247 if partial_completion.is_empty() {
5248 partial_completion = text
5249 .chars()
5250 .by_ref()
5251 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5252 .collect::<String>();
5253 }
5254
5255 cx.emit(EditorEvent::InputHandled {
5256 utf16_range_to_replace: None,
5257 text: partial_completion.clone().into(),
5258 });
5259
5260 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5261
5262 self.refresh_inline_completion(true, true, window, cx);
5263 cx.notify();
5264 } else {
5265 self.accept_edit_prediction(&Default::default(), window, cx);
5266 }
5267 }
5268 }
5269 }
5270
5271 fn discard_inline_completion(
5272 &mut self,
5273 should_report_inline_completion_event: bool,
5274 cx: &mut Context<Self>,
5275 ) -> bool {
5276 if should_report_inline_completion_event {
5277 let completion_id = self
5278 .active_inline_completion
5279 .as_ref()
5280 .and_then(|active_completion| active_completion.completion_id.clone());
5281
5282 self.report_inline_completion_event(completion_id, false, cx);
5283 }
5284
5285 if let Some(provider) = self.edit_prediction_provider() {
5286 provider.discard(cx);
5287 }
5288
5289 self.take_active_inline_completion(cx)
5290 }
5291
5292 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5293 let Some(provider) = self.edit_prediction_provider() else {
5294 return;
5295 };
5296
5297 let Some((_, buffer, _)) = self
5298 .buffer
5299 .read(cx)
5300 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5301 else {
5302 return;
5303 };
5304
5305 let extension = buffer
5306 .read(cx)
5307 .file()
5308 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5309
5310 let event_type = match accepted {
5311 true => "Edit Prediction Accepted",
5312 false => "Edit Prediction Discarded",
5313 };
5314 telemetry::event!(
5315 event_type,
5316 provider = provider.name(),
5317 prediction_id = id,
5318 suggestion_accepted = accepted,
5319 file_extension = extension,
5320 );
5321 }
5322
5323 pub fn has_active_inline_completion(&self) -> bool {
5324 self.active_inline_completion.is_some()
5325 }
5326
5327 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5328 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5329 return false;
5330 };
5331
5332 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5333 self.clear_highlights::<InlineCompletionHighlight>(cx);
5334 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5335 true
5336 }
5337
5338 /// Returns true when we're displaying the edit prediction popover below the cursor
5339 /// like we are not previewing and the LSP autocomplete menu is visible
5340 /// or we are in `when_holding_modifier` mode.
5341 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5342 if self.edit_prediction_preview_is_active()
5343 || !self.show_edit_predictions_in_menu()
5344 || !self.edit_predictions_enabled()
5345 {
5346 return false;
5347 }
5348
5349 if self.has_visible_completions_menu() {
5350 return true;
5351 }
5352
5353 has_completion && self.edit_prediction_requires_modifier()
5354 }
5355
5356 fn handle_modifiers_changed(
5357 &mut self,
5358 modifiers: Modifiers,
5359 position_map: &PositionMap,
5360 window: &mut Window,
5361 cx: &mut Context<Self>,
5362 ) {
5363 if self.show_edit_predictions_in_menu() {
5364 self.update_edit_prediction_preview(&modifiers, window, cx);
5365 }
5366
5367 self.update_selection_mode(&modifiers, position_map, window, cx);
5368
5369 let mouse_position = window.mouse_position();
5370 if !position_map.text_hitbox.is_hovered(window) {
5371 return;
5372 }
5373
5374 self.update_hovered_link(
5375 position_map.point_for_position(mouse_position),
5376 &position_map.snapshot,
5377 modifiers,
5378 window,
5379 cx,
5380 )
5381 }
5382
5383 fn update_selection_mode(
5384 &mut self,
5385 modifiers: &Modifiers,
5386 position_map: &PositionMap,
5387 window: &mut Window,
5388 cx: &mut Context<Self>,
5389 ) {
5390 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5391 return;
5392 }
5393
5394 let mouse_position = window.mouse_position();
5395 let point_for_position = position_map.point_for_position(mouse_position);
5396 let position = point_for_position.previous_valid;
5397
5398 self.select(
5399 SelectPhase::BeginColumnar {
5400 position,
5401 reset: false,
5402 goal_column: point_for_position.exact_unclipped.column(),
5403 },
5404 window,
5405 cx,
5406 );
5407 }
5408
5409 fn update_edit_prediction_preview(
5410 &mut self,
5411 modifiers: &Modifiers,
5412 window: &mut Window,
5413 cx: &mut Context<Self>,
5414 ) {
5415 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5416 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5417 return;
5418 };
5419
5420 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5421 if matches!(
5422 self.edit_prediction_preview,
5423 EditPredictionPreview::Inactive
5424 ) {
5425 self.edit_prediction_preview = EditPredictionPreview::Active {
5426 previous_scroll_position: None,
5427 };
5428
5429 self.update_visible_inline_completion(window, cx);
5430 cx.notify();
5431 }
5432 } else if let EditPredictionPreview::Active {
5433 previous_scroll_position,
5434 } = self.edit_prediction_preview
5435 {
5436 if let (Some(previous_scroll_position), Some(position_map)) =
5437 (previous_scroll_position, self.last_position_map.as_ref())
5438 {
5439 self.set_scroll_position(
5440 previous_scroll_position
5441 .scroll_position(&position_map.snapshot.display_snapshot),
5442 window,
5443 cx,
5444 );
5445 }
5446
5447 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5448 self.clear_row_highlights::<EditPredictionPreview>();
5449 self.update_visible_inline_completion(window, cx);
5450 cx.notify();
5451 }
5452 }
5453
5454 fn update_visible_inline_completion(
5455 &mut self,
5456 _window: &mut Window,
5457 cx: &mut Context<Self>,
5458 ) -> Option<()> {
5459 let selection = self.selections.newest_anchor();
5460 let cursor = selection.head();
5461 let multibuffer = self.buffer.read(cx).snapshot(cx);
5462 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5463 let excerpt_id = cursor.excerpt_id;
5464
5465 let show_in_menu = self.show_edit_predictions_in_menu();
5466 let completions_menu_has_precedence = !show_in_menu
5467 && (self.context_menu.borrow().is_some()
5468 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5469
5470 if completions_menu_has_precedence
5471 || !offset_selection.is_empty()
5472 || self
5473 .active_inline_completion
5474 .as_ref()
5475 .map_or(false, |completion| {
5476 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5477 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5478 !invalidation_range.contains(&offset_selection.head())
5479 })
5480 {
5481 self.discard_inline_completion(false, cx);
5482 return None;
5483 }
5484
5485 self.take_active_inline_completion(cx);
5486 let Some(provider) = self.edit_prediction_provider() else {
5487 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5488 return None;
5489 };
5490
5491 let (buffer, cursor_buffer_position) =
5492 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5493
5494 self.edit_prediction_settings =
5495 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5496
5497 self.edit_prediction_cursor_on_leading_whitespace =
5498 multibuffer.is_line_whitespace_upto(cursor);
5499
5500 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5501 let edits = inline_completion
5502 .edits
5503 .into_iter()
5504 .flat_map(|(range, new_text)| {
5505 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5506 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5507 Some((start..end, new_text))
5508 })
5509 .collect::<Vec<_>>();
5510 if edits.is_empty() {
5511 return None;
5512 }
5513
5514 let first_edit_start = edits.first().unwrap().0.start;
5515 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5516 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5517
5518 let last_edit_end = edits.last().unwrap().0.end;
5519 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5520 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5521
5522 let cursor_row = cursor.to_point(&multibuffer).row;
5523
5524 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5525
5526 let mut inlay_ids = Vec::new();
5527 let invalidation_row_range;
5528 let move_invalidation_row_range = if cursor_row < edit_start_row {
5529 Some(cursor_row..edit_end_row)
5530 } else if cursor_row > edit_end_row {
5531 Some(edit_start_row..cursor_row)
5532 } else {
5533 None
5534 };
5535 let is_move =
5536 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5537 let completion = if is_move {
5538 invalidation_row_range =
5539 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5540 let target = first_edit_start;
5541 InlineCompletion::Move { target, snapshot }
5542 } else {
5543 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5544 && !self.inline_completions_hidden_for_vim_mode;
5545
5546 if show_completions_in_buffer {
5547 if edits
5548 .iter()
5549 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5550 {
5551 let mut inlays = Vec::new();
5552 for (range, new_text) in &edits {
5553 let inlay = Inlay::inline_completion(
5554 post_inc(&mut self.next_inlay_id),
5555 range.start,
5556 new_text.as_str(),
5557 );
5558 inlay_ids.push(inlay.id);
5559 inlays.push(inlay);
5560 }
5561
5562 self.splice_inlays(&[], inlays, cx);
5563 } else {
5564 let background_color = cx.theme().status().deleted_background;
5565 self.highlight_text::<InlineCompletionHighlight>(
5566 edits.iter().map(|(range, _)| range.clone()).collect(),
5567 HighlightStyle {
5568 background_color: Some(background_color),
5569 ..Default::default()
5570 },
5571 cx,
5572 );
5573 }
5574 }
5575
5576 invalidation_row_range = edit_start_row..edit_end_row;
5577
5578 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5579 if provider.show_tab_accept_marker() {
5580 EditDisplayMode::TabAccept
5581 } else {
5582 EditDisplayMode::Inline
5583 }
5584 } else {
5585 EditDisplayMode::DiffPopover
5586 };
5587
5588 InlineCompletion::Edit {
5589 edits,
5590 edit_preview: inline_completion.edit_preview,
5591 display_mode,
5592 snapshot,
5593 }
5594 };
5595
5596 let invalidation_range = multibuffer
5597 .anchor_before(Point::new(invalidation_row_range.start, 0))
5598 ..multibuffer.anchor_after(Point::new(
5599 invalidation_row_range.end,
5600 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5601 ));
5602
5603 self.stale_inline_completion_in_menu = None;
5604 self.active_inline_completion = Some(InlineCompletionState {
5605 inlay_ids,
5606 completion,
5607 completion_id: inline_completion.id,
5608 invalidation_range,
5609 });
5610
5611 cx.notify();
5612
5613 Some(())
5614 }
5615
5616 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5617 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5618 }
5619
5620 fn render_code_actions_indicator(
5621 &self,
5622 _style: &EditorStyle,
5623 row: DisplayRow,
5624 is_active: bool,
5625 cx: &mut Context<Self>,
5626 ) -> Option<IconButton> {
5627 if self.available_code_actions.is_some() {
5628 Some(
5629 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5630 .shape(ui::IconButtonShape::Square)
5631 .icon_size(IconSize::XSmall)
5632 .icon_color(Color::Muted)
5633 .toggle_state(is_active)
5634 .tooltip({
5635 let focus_handle = self.focus_handle.clone();
5636 move |window, cx| {
5637 Tooltip::for_action_in(
5638 "Toggle Code Actions",
5639 &ToggleCodeActions {
5640 deployed_from_indicator: None,
5641 },
5642 &focus_handle,
5643 window,
5644 cx,
5645 )
5646 }
5647 })
5648 .on_click(cx.listener(move |editor, _e, window, cx| {
5649 window.focus(&editor.focus_handle(cx));
5650 editor.toggle_code_actions(
5651 &ToggleCodeActions {
5652 deployed_from_indicator: Some(row),
5653 },
5654 window,
5655 cx,
5656 );
5657 })),
5658 )
5659 } else {
5660 None
5661 }
5662 }
5663
5664 fn clear_tasks(&mut self) {
5665 self.tasks.clear()
5666 }
5667
5668 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5669 if self.tasks.insert(key, value).is_some() {
5670 // This case should hopefully be rare, but just in case...
5671 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5672 }
5673 }
5674
5675 fn build_tasks_context(
5676 project: &Entity<Project>,
5677 buffer: &Entity<Buffer>,
5678 buffer_row: u32,
5679 tasks: &Arc<RunnableTasks>,
5680 cx: &mut Context<Self>,
5681 ) -> Task<Option<task::TaskContext>> {
5682 let position = Point::new(buffer_row, tasks.column);
5683 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5684 let location = Location {
5685 buffer: buffer.clone(),
5686 range: range_start..range_start,
5687 };
5688 // Fill in the environmental variables from the tree-sitter captures
5689 let mut captured_task_variables = TaskVariables::default();
5690 for (capture_name, value) in tasks.extra_variables.clone() {
5691 captured_task_variables.insert(
5692 task::VariableName::Custom(capture_name.into()),
5693 value.clone(),
5694 );
5695 }
5696 project.update(cx, |project, cx| {
5697 project.task_store().update(cx, |task_store, cx| {
5698 task_store.task_context_for_location(captured_task_variables, location, cx)
5699 })
5700 })
5701 }
5702
5703 pub fn spawn_nearest_task(
5704 &mut self,
5705 action: &SpawnNearestTask,
5706 window: &mut Window,
5707 cx: &mut Context<Self>,
5708 ) {
5709 let Some((workspace, _)) = self.workspace.clone() else {
5710 return;
5711 };
5712 let Some(project) = self.project.clone() else {
5713 return;
5714 };
5715
5716 // Try to find a closest, enclosing node using tree-sitter that has a
5717 // task
5718 let Some((buffer, buffer_row, tasks)) = self
5719 .find_enclosing_node_task(cx)
5720 // Or find the task that's closest in row-distance.
5721 .or_else(|| self.find_closest_task(cx))
5722 else {
5723 return;
5724 };
5725
5726 let reveal_strategy = action.reveal;
5727 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5728 cx.spawn_in(window, |_, mut cx| async move {
5729 let context = task_context.await?;
5730 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5731
5732 let resolved = resolved_task.resolved.as_mut()?;
5733 resolved.reveal = reveal_strategy;
5734
5735 workspace
5736 .update(&mut cx, |workspace, cx| {
5737 workspace::tasks::schedule_resolved_task(
5738 workspace,
5739 task_source_kind,
5740 resolved_task,
5741 false,
5742 cx,
5743 );
5744 })
5745 .ok()
5746 })
5747 .detach();
5748 }
5749
5750 fn find_closest_task(
5751 &mut self,
5752 cx: &mut Context<Self>,
5753 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5754 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5755
5756 let ((buffer_id, row), tasks) = self
5757 .tasks
5758 .iter()
5759 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5760
5761 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5762 let tasks = Arc::new(tasks.to_owned());
5763 Some((buffer, *row, tasks))
5764 }
5765
5766 fn find_enclosing_node_task(
5767 &mut self,
5768 cx: &mut Context<Self>,
5769 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5770 let snapshot = self.buffer.read(cx).snapshot(cx);
5771 let offset = self.selections.newest::<usize>(cx).head();
5772 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5773 let buffer_id = excerpt.buffer().remote_id();
5774
5775 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5776 let mut cursor = layer.node().walk();
5777
5778 while cursor.goto_first_child_for_byte(offset).is_some() {
5779 if cursor.node().end_byte() == offset {
5780 cursor.goto_next_sibling();
5781 }
5782 }
5783
5784 // Ascend to the smallest ancestor that contains the range and has a task.
5785 loop {
5786 let node = cursor.node();
5787 let node_range = node.byte_range();
5788 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5789
5790 // Check if this node contains our offset
5791 if node_range.start <= offset && node_range.end >= offset {
5792 // If it contains offset, check for task
5793 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5794 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5795 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5796 }
5797 }
5798
5799 if !cursor.goto_parent() {
5800 break;
5801 }
5802 }
5803 None
5804 }
5805
5806 fn render_run_indicator(
5807 &self,
5808 _style: &EditorStyle,
5809 is_active: bool,
5810 row: DisplayRow,
5811 cx: &mut Context<Self>,
5812 ) -> IconButton {
5813 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5814 .shape(ui::IconButtonShape::Square)
5815 .icon_size(IconSize::XSmall)
5816 .icon_color(Color::Muted)
5817 .toggle_state(is_active)
5818 .on_click(cx.listener(move |editor, _e, window, cx| {
5819 window.focus(&editor.focus_handle(cx));
5820 editor.toggle_code_actions(
5821 &ToggleCodeActions {
5822 deployed_from_indicator: Some(row),
5823 },
5824 window,
5825 cx,
5826 );
5827 }))
5828 }
5829
5830 pub fn context_menu_visible(&self) -> bool {
5831 !self.edit_prediction_preview_is_active()
5832 && self
5833 .context_menu
5834 .borrow()
5835 .as_ref()
5836 .map_or(false, |menu| menu.visible())
5837 }
5838
5839 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5840 self.context_menu
5841 .borrow()
5842 .as_ref()
5843 .map(|menu| menu.origin())
5844 }
5845
5846 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5847 px(30.)
5848 }
5849
5850 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5851 if self.read_only(cx) {
5852 cx.theme().players().read_only()
5853 } else {
5854 self.style.as_ref().unwrap().local_player
5855 }
5856 }
5857
5858 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5859 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5860 let accept_keystroke = accept_binding.keystroke()?;
5861
5862 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5863
5864 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5865 Color::Accent
5866 } else {
5867 Color::Muted
5868 };
5869
5870 h_flex()
5871 .px_0p5()
5872 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5873 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5874 .text_size(TextSize::XSmall.rems(cx))
5875 .child(h_flex().children(ui::render_modifiers(
5876 &accept_keystroke.modifiers,
5877 PlatformStyle::platform(),
5878 Some(modifiers_color),
5879 Some(IconSize::XSmall.rems().into()),
5880 true,
5881 )))
5882 .when(is_platform_style_mac, |parent| {
5883 parent.child(accept_keystroke.key.clone())
5884 })
5885 .when(!is_platform_style_mac, |parent| {
5886 parent.child(
5887 Key::new(
5888 util::capitalize(&accept_keystroke.key),
5889 Some(Color::Default),
5890 )
5891 .size(Some(IconSize::XSmall.rems().into())),
5892 )
5893 })
5894 .into()
5895 }
5896
5897 fn render_edit_prediction_line_popover(
5898 &self,
5899 label: impl Into<SharedString>,
5900 icon: Option<IconName>,
5901 window: &mut Window,
5902 cx: &App,
5903 ) -> Option<Div> {
5904 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5905
5906 let result = h_flex()
5907 .py_0p5()
5908 .pl_1()
5909 .pr(padding_right)
5910 .gap_1()
5911 .rounded(px(6.))
5912 .border_1()
5913 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5914 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5915 .shadow_sm()
5916 .children(self.render_edit_prediction_accept_keybind(window, cx))
5917 .child(Label::new(label).size(LabelSize::Small))
5918 .when_some(icon, |element, icon| {
5919 element.child(
5920 div()
5921 .mt(px(1.5))
5922 .child(Icon::new(icon).size(IconSize::Small)),
5923 )
5924 });
5925
5926 Some(result)
5927 }
5928
5929 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5930 let accent_color = cx.theme().colors().text_accent;
5931 let editor_bg_color = cx.theme().colors().editor_background;
5932 editor_bg_color.blend(accent_color.opacity(0.1))
5933 }
5934
5935 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5936 let accent_color = cx.theme().colors().text_accent;
5937 let editor_bg_color = cx.theme().colors().editor_background;
5938 editor_bg_color.blend(accent_color.opacity(0.6))
5939 }
5940
5941 fn render_edit_prediction_cursor_popover(
5942 &self,
5943 min_width: Pixels,
5944 max_width: Pixels,
5945 cursor_point: Point,
5946 style: &EditorStyle,
5947 accept_keystroke: Option<&gpui::Keystroke>,
5948 _window: &Window,
5949 cx: &mut Context<Editor>,
5950 ) -> Option<AnyElement> {
5951 let provider = self.edit_prediction_provider.as_ref()?;
5952
5953 if provider.provider.needs_terms_acceptance(cx) {
5954 return Some(
5955 h_flex()
5956 .min_w(min_width)
5957 .flex_1()
5958 .px_2()
5959 .py_1()
5960 .gap_3()
5961 .elevation_2(cx)
5962 .hover(|style| style.bg(cx.theme().colors().element_hover))
5963 .id("accept-terms")
5964 .cursor_pointer()
5965 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5966 .on_click(cx.listener(|this, _event, window, cx| {
5967 cx.stop_propagation();
5968 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5969 window.dispatch_action(
5970 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5971 cx,
5972 );
5973 }))
5974 .child(
5975 h_flex()
5976 .flex_1()
5977 .gap_2()
5978 .child(Icon::new(IconName::ZedPredict))
5979 .child(Label::new("Accept Terms of Service"))
5980 .child(div().w_full())
5981 .child(
5982 Icon::new(IconName::ArrowUpRight)
5983 .color(Color::Muted)
5984 .size(IconSize::Small),
5985 )
5986 .into_any_element(),
5987 )
5988 .into_any(),
5989 );
5990 }
5991
5992 let is_refreshing = provider.provider.is_refreshing(cx);
5993
5994 fn pending_completion_container() -> Div {
5995 h_flex()
5996 .h_full()
5997 .flex_1()
5998 .gap_2()
5999 .child(Icon::new(IconName::ZedPredict))
6000 }
6001
6002 let completion = match &self.active_inline_completion {
6003 Some(completion) => match &completion.completion {
6004 InlineCompletion::Move {
6005 target, snapshot, ..
6006 } if !self.has_visible_completions_menu() => {
6007 use text::ToPoint as _;
6008
6009 return Some(
6010 h_flex()
6011 .px_2()
6012 .py_1()
6013 .gap_2()
6014 .elevation_2(cx)
6015 .border_color(cx.theme().colors().border)
6016 .rounded(px(6.))
6017 .rounded_tl(px(0.))
6018 .child(
6019 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6020 Icon::new(IconName::ZedPredictDown)
6021 } else {
6022 Icon::new(IconName::ZedPredictUp)
6023 },
6024 )
6025 .child(Label::new("Hold").size(LabelSize::Small))
6026 .child(h_flex().children(ui::render_modifiers(
6027 &accept_keystroke?.modifiers,
6028 PlatformStyle::platform(),
6029 Some(Color::Default),
6030 Some(IconSize::Small.rems().into()),
6031 false,
6032 )))
6033 .into_any(),
6034 );
6035 }
6036 _ => self.render_edit_prediction_cursor_popover_preview(
6037 completion,
6038 cursor_point,
6039 style,
6040 cx,
6041 )?,
6042 },
6043
6044 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6045 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6046 stale_completion,
6047 cursor_point,
6048 style,
6049 cx,
6050 )?,
6051
6052 None => {
6053 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6054 }
6055 },
6056
6057 None => pending_completion_container().child(Label::new("No Prediction")),
6058 };
6059
6060 let completion = if is_refreshing {
6061 completion
6062 .with_animation(
6063 "loading-completion",
6064 Animation::new(Duration::from_secs(2))
6065 .repeat()
6066 .with_easing(pulsating_between(0.4, 0.8)),
6067 |label, delta| label.opacity(delta),
6068 )
6069 .into_any_element()
6070 } else {
6071 completion.into_any_element()
6072 };
6073
6074 let has_completion = self.active_inline_completion.is_some();
6075
6076 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6077 Some(
6078 h_flex()
6079 .min_w(min_width)
6080 .max_w(max_width)
6081 .flex_1()
6082 .elevation_2(cx)
6083 .border_color(cx.theme().colors().border)
6084 .child(
6085 div()
6086 .flex_1()
6087 .py_1()
6088 .px_2()
6089 .overflow_hidden()
6090 .child(completion),
6091 )
6092 .when_some(accept_keystroke, |el, accept_keystroke| {
6093 if !accept_keystroke.modifiers.modified() {
6094 return el;
6095 }
6096
6097 el.child(
6098 h_flex()
6099 .h_full()
6100 .border_l_1()
6101 .rounded_r_lg()
6102 .border_color(cx.theme().colors().border)
6103 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6104 .gap_1()
6105 .py_1()
6106 .px_2()
6107 .child(
6108 h_flex()
6109 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6110 .when(is_platform_style_mac, |parent| parent.gap_1())
6111 .child(h_flex().children(ui::render_modifiers(
6112 &accept_keystroke.modifiers,
6113 PlatformStyle::platform(),
6114 Some(if !has_completion {
6115 Color::Muted
6116 } else {
6117 Color::Default
6118 }),
6119 None,
6120 false,
6121 ))),
6122 )
6123 .child(Label::new("Preview").into_any_element())
6124 .opacity(if has_completion { 1.0 } else { 0.4 }),
6125 )
6126 })
6127 .into_any(),
6128 )
6129 }
6130
6131 fn render_edit_prediction_cursor_popover_preview(
6132 &self,
6133 completion: &InlineCompletionState,
6134 cursor_point: Point,
6135 style: &EditorStyle,
6136 cx: &mut Context<Editor>,
6137 ) -> Option<Div> {
6138 use text::ToPoint as _;
6139
6140 fn render_relative_row_jump(
6141 prefix: impl Into<String>,
6142 current_row: u32,
6143 target_row: u32,
6144 ) -> Div {
6145 let (row_diff, arrow) = if target_row < current_row {
6146 (current_row - target_row, IconName::ArrowUp)
6147 } else {
6148 (target_row - current_row, IconName::ArrowDown)
6149 };
6150
6151 h_flex()
6152 .child(
6153 Label::new(format!("{}{}", prefix.into(), row_diff))
6154 .color(Color::Muted)
6155 .size(LabelSize::Small),
6156 )
6157 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6158 }
6159
6160 match &completion.completion {
6161 InlineCompletion::Move {
6162 target, snapshot, ..
6163 } => Some(
6164 h_flex()
6165 .px_2()
6166 .gap_2()
6167 .flex_1()
6168 .child(
6169 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6170 Icon::new(IconName::ZedPredictDown)
6171 } else {
6172 Icon::new(IconName::ZedPredictUp)
6173 },
6174 )
6175 .child(Label::new("Jump to Edit")),
6176 ),
6177
6178 InlineCompletion::Edit {
6179 edits,
6180 edit_preview,
6181 snapshot,
6182 display_mode: _,
6183 } => {
6184 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6185
6186 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6187 &snapshot,
6188 &edits,
6189 edit_preview.as_ref()?,
6190 true,
6191 cx,
6192 )
6193 .first_line_preview();
6194
6195 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6196 .with_highlights(&style.text, highlighted_edits.highlights);
6197
6198 let preview = h_flex()
6199 .gap_1()
6200 .min_w_16()
6201 .child(styled_text)
6202 .when(has_more_lines, |parent| parent.child("…"));
6203
6204 let left = if first_edit_row != cursor_point.row {
6205 render_relative_row_jump("", cursor_point.row, first_edit_row)
6206 .into_any_element()
6207 } else {
6208 Icon::new(IconName::ZedPredict).into_any_element()
6209 };
6210
6211 Some(
6212 h_flex()
6213 .h_full()
6214 .flex_1()
6215 .gap_2()
6216 .pr_1()
6217 .overflow_x_hidden()
6218 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6219 .child(left)
6220 .child(preview),
6221 )
6222 }
6223 }
6224 }
6225
6226 fn render_context_menu(
6227 &self,
6228 style: &EditorStyle,
6229 max_height_in_lines: u32,
6230 y_flipped: bool,
6231 window: &mut Window,
6232 cx: &mut Context<Editor>,
6233 ) -> Option<AnyElement> {
6234 let menu = self.context_menu.borrow();
6235 let menu = menu.as_ref()?;
6236 if !menu.visible() {
6237 return None;
6238 };
6239 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6240 }
6241
6242 fn render_context_menu_aside(
6243 &mut self,
6244 max_size: Size<Pixels>,
6245 window: &mut Window,
6246 cx: &mut Context<Editor>,
6247 ) -> Option<AnyElement> {
6248 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6249 if menu.visible() {
6250 menu.render_aside(self, max_size, window, cx)
6251 } else {
6252 None
6253 }
6254 })
6255 }
6256
6257 fn hide_context_menu(
6258 &mut self,
6259 window: &mut Window,
6260 cx: &mut Context<Self>,
6261 ) -> Option<CodeContextMenu> {
6262 cx.notify();
6263 self.completion_tasks.clear();
6264 let context_menu = self.context_menu.borrow_mut().take();
6265 self.stale_inline_completion_in_menu.take();
6266 self.update_visible_inline_completion(window, cx);
6267 context_menu
6268 }
6269
6270 fn show_snippet_choices(
6271 &mut self,
6272 choices: &Vec<String>,
6273 selection: Range<Anchor>,
6274 cx: &mut Context<Self>,
6275 ) {
6276 if selection.start.buffer_id.is_none() {
6277 return;
6278 }
6279 let buffer_id = selection.start.buffer_id.unwrap();
6280 let buffer = self.buffer().read(cx).buffer(buffer_id);
6281 let id = post_inc(&mut self.next_completion_id);
6282
6283 if let Some(buffer) = buffer {
6284 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6285 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6286 ));
6287 }
6288 }
6289
6290 pub fn insert_snippet(
6291 &mut self,
6292 insertion_ranges: &[Range<usize>],
6293 snippet: Snippet,
6294 window: &mut Window,
6295 cx: &mut Context<Self>,
6296 ) -> Result<()> {
6297 struct Tabstop<T> {
6298 is_end_tabstop: bool,
6299 ranges: Vec<Range<T>>,
6300 choices: Option<Vec<String>>,
6301 }
6302
6303 let tabstops = self.buffer.update(cx, |buffer, cx| {
6304 let snippet_text: Arc<str> = snippet.text.clone().into();
6305 buffer.edit(
6306 insertion_ranges
6307 .iter()
6308 .cloned()
6309 .map(|range| (range, snippet_text.clone())),
6310 Some(AutoindentMode::EachLine),
6311 cx,
6312 );
6313
6314 let snapshot = &*buffer.read(cx);
6315 let snippet = &snippet;
6316 snippet
6317 .tabstops
6318 .iter()
6319 .map(|tabstop| {
6320 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6321 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6322 });
6323 let mut tabstop_ranges = tabstop
6324 .ranges
6325 .iter()
6326 .flat_map(|tabstop_range| {
6327 let mut delta = 0_isize;
6328 insertion_ranges.iter().map(move |insertion_range| {
6329 let insertion_start = insertion_range.start as isize + delta;
6330 delta +=
6331 snippet.text.len() as isize - insertion_range.len() as isize;
6332
6333 let start = ((insertion_start + tabstop_range.start) as usize)
6334 .min(snapshot.len());
6335 let end = ((insertion_start + tabstop_range.end) as usize)
6336 .min(snapshot.len());
6337 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6338 })
6339 })
6340 .collect::<Vec<_>>();
6341 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6342
6343 Tabstop {
6344 is_end_tabstop,
6345 ranges: tabstop_ranges,
6346 choices: tabstop.choices.clone(),
6347 }
6348 })
6349 .collect::<Vec<_>>()
6350 });
6351 if let Some(tabstop) = tabstops.first() {
6352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6353 s.select_ranges(tabstop.ranges.iter().cloned());
6354 });
6355
6356 if let Some(choices) = &tabstop.choices {
6357 if let Some(selection) = tabstop.ranges.first() {
6358 self.show_snippet_choices(choices, selection.clone(), cx)
6359 }
6360 }
6361
6362 // If we're already at the last tabstop and it's at the end of the snippet,
6363 // we're done, we don't need to keep the state around.
6364 if !tabstop.is_end_tabstop {
6365 let choices = tabstops
6366 .iter()
6367 .map(|tabstop| tabstop.choices.clone())
6368 .collect();
6369
6370 let ranges = tabstops
6371 .into_iter()
6372 .map(|tabstop| tabstop.ranges)
6373 .collect::<Vec<_>>();
6374
6375 self.snippet_stack.push(SnippetState {
6376 active_index: 0,
6377 ranges,
6378 choices,
6379 });
6380 }
6381
6382 // Check whether the just-entered snippet ends with an auto-closable bracket.
6383 if self.autoclose_regions.is_empty() {
6384 let snapshot = self.buffer.read(cx).snapshot(cx);
6385 for selection in &mut self.selections.all::<Point>(cx) {
6386 let selection_head = selection.head();
6387 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6388 continue;
6389 };
6390
6391 let mut bracket_pair = None;
6392 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6393 let prev_chars = snapshot
6394 .reversed_chars_at(selection_head)
6395 .collect::<String>();
6396 for (pair, enabled) in scope.brackets() {
6397 if enabled
6398 && pair.close
6399 && prev_chars.starts_with(pair.start.as_str())
6400 && next_chars.starts_with(pair.end.as_str())
6401 {
6402 bracket_pair = Some(pair.clone());
6403 break;
6404 }
6405 }
6406 if let Some(pair) = bracket_pair {
6407 let start = snapshot.anchor_after(selection_head);
6408 let end = snapshot.anchor_after(selection_head);
6409 self.autoclose_regions.push(AutocloseRegion {
6410 selection_id: selection.id,
6411 range: start..end,
6412 pair,
6413 });
6414 }
6415 }
6416 }
6417 }
6418 Ok(())
6419 }
6420
6421 pub fn move_to_next_snippet_tabstop(
6422 &mut self,
6423 window: &mut Window,
6424 cx: &mut Context<Self>,
6425 ) -> bool {
6426 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6427 }
6428
6429 pub fn move_to_prev_snippet_tabstop(
6430 &mut self,
6431 window: &mut Window,
6432 cx: &mut Context<Self>,
6433 ) -> bool {
6434 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6435 }
6436
6437 pub fn move_to_snippet_tabstop(
6438 &mut self,
6439 bias: Bias,
6440 window: &mut Window,
6441 cx: &mut Context<Self>,
6442 ) -> bool {
6443 if let Some(mut snippet) = self.snippet_stack.pop() {
6444 match bias {
6445 Bias::Left => {
6446 if snippet.active_index > 0 {
6447 snippet.active_index -= 1;
6448 } else {
6449 self.snippet_stack.push(snippet);
6450 return false;
6451 }
6452 }
6453 Bias::Right => {
6454 if snippet.active_index + 1 < snippet.ranges.len() {
6455 snippet.active_index += 1;
6456 } else {
6457 self.snippet_stack.push(snippet);
6458 return false;
6459 }
6460 }
6461 }
6462 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6463 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6464 s.select_anchor_ranges(current_ranges.iter().cloned())
6465 });
6466
6467 if let Some(choices) = &snippet.choices[snippet.active_index] {
6468 if let Some(selection) = current_ranges.first() {
6469 self.show_snippet_choices(&choices, selection.clone(), cx);
6470 }
6471 }
6472
6473 // If snippet state is not at the last tabstop, push it back on the stack
6474 if snippet.active_index + 1 < snippet.ranges.len() {
6475 self.snippet_stack.push(snippet);
6476 }
6477 return true;
6478 }
6479 }
6480
6481 false
6482 }
6483
6484 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6485 self.transact(window, cx, |this, window, cx| {
6486 this.select_all(&SelectAll, window, cx);
6487 this.insert("", window, cx);
6488 });
6489 }
6490
6491 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6492 self.transact(window, cx, |this, window, cx| {
6493 this.select_autoclose_pair(window, cx);
6494 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6495 if !this.linked_edit_ranges.is_empty() {
6496 let selections = this.selections.all::<MultiBufferPoint>(cx);
6497 let snapshot = this.buffer.read(cx).snapshot(cx);
6498
6499 for selection in selections.iter() {
6500 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6501 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6502 if selection_start.buffer_id != selection_end.buffer_id {
6503 continue;
6504 }
6505 if let Some(ranges) =
6506 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6507 {
6508 for (buffer, entries) in ranges {
6509 linked_ranges.entry(buffer).or_default().extend(entries);
6510 }
6511 }
6512 }
6513 }
6514
6515 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6516 if !this.selections.line_mode {
6517 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6518 for selection in &mut selections {
6519 if selection.is_empty() {
6520 let old_head = selection.head();
6521 let mut new_head =
6522 movement::left(&display_map, old_head.to_display_point(&display_map))
6523 .to_point(&display_map);
6524 if let Some((buffer, line_buffer_range)) = display_map
6525 .buffer_snapshot
6526 .buffer_line_for_row(MultiBufferRow(old_head.row))
6527 {
6528 let indent_size =
6529 buffer.indent_size_for_line(line_buffer_range.start.row);
6530 let indent_len = match indent_size.kind {
6531 IndentKind::Space => {
6532 buffer.settings_at(line_buffer_range.start, cx).tab_size
6533 }
6534 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6535 };
6536 if old_head.column <= indent_size.len && old_head.column > 0 {
6537 let indent_len = indent_len.get();
6538 new_head = cmp::min(
6539 new_head,
6540 MultiBufferPoint::new(
6541 old_head.row,
6542 ((old_head.column - 1) / indent_len) * indent_len,
6543 ),
6544 );
6545 }
6546 }
6547
6548 selection.set_head(new_head, SelectionGoal::None);
6549 }
6550 }
6551 }
6552
6553 this.signature_help_state.set_backspace_pressed(true);
6554 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6555 s.select(selections)
6556 });
6557 this.insert("", window, cx);
6558 let empty_str: Arc<str> = Arc::from("");
6559 for (buffer, edits) in linked_ranges {
6560 let snapshot = buffer.read(cx).snapshot();
6561 use text::ToPoint as TP;
6562
6563 let edits = edits
6564 .into_iter()
6565 .map(|range| {
6566 let end_point = TP::to_point(&range.end, &snapshot);
6567 let mut start_point = TP::to_point(&range.start, &snapshot);
6568
6569 if end_point == start_point {
6570 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6571 .saturating_sub(1);
6572 start_point =
6573 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6574 };
6575
6576 (start_point..end_point, empty_str.clone())
6577 })
6578 .sorted_by_key(|(range, _)| range.start)
6579 .collect::<Vec<_>>();
6580 buffer.update(cx, |this, cx| {
6581 this.edit(edits, None, cx);
6582 })
6583 }
6584 this.refresh_inline_completion(true, false, window, cx);
6585 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6586 });
6587 }
6588
6589 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6590 self.transact(window, cx, |this, window, cx| {
6591 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6592 let line_mode = s.line_mode;
6593 s.move_with(|map, selection| {
6594 if selection.is_empty() && !line_mode {
6595 let cursor = movement::right(map, selection.head());
6596 selection.end = cursor;
6597 selection.reversed = true;
6598 selection.goal = SelectionGoal::None;
6599 }
6600 })
6601 });
6602 this.insert("", window, cx);
6603 this.refresh_inline_completion(true, false, window, cx);
6604 });
6605 }
6606
6607 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6608 if self.move_to_prev_snippet_tabstop(window, cx) {
6609 return;
6610 }
6611
6612 self.outdent(&Outdent, window, cx);
6613 }
6614
6615 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6616 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6617 return;
6618 }
6619
6620 let mut selections = self.selections.all_adjusted(cx);
6621 let buffer = self.buffer.read(cx);
6622 let snapshot = buffer.snapshot(cx);
6623 let rows_iter = selections.iter().map(|s| s.head().row);
6624 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6625
6626 let mut edits = Vec::new();
6627 let mut prev_edited_row = 0;
6628 let mut row_delta = 0;
6629 for selection in &mut selections {
6630 if selection.start.row != prev_edited_row {
6631 row_delta = 0;
6632 }
6633 prev_edited_row = selection.end.row;
6634
6635 // If the selection is non-empty, then increase the indentation of the selected lines.
6636 if !selection.is_empty() {
6637 row_delta =
6638 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6639 continue;
6640 }
6641
6642 // If the selection is empty and the cursor is in the leading whitespace before the
6643 // suggested indentation, then auto-indent the line.
6644 let cursor = selection.head();
6645 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6646 if let Some(suggested_indent) =
6647 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6648 {
6649 if cursor.column < suggested_indent.len
6650 && cursor.column <= current_indent.len
6651 && current_indent.len <= suggested_indent.len
6652 {
6653 selection.start = Point::new(cursor.row, suggested_indent.len);
6654 selection.end = selection.start;
6655 if row_delta == 0 {
6656 edits.extend(Buffer::edit_for_indent_size_adjustment(
6657 cursor.row,
6658 current_indent,
6659 suggested_indent,
6660 ));
6661 row_delta = suggested_indent.len - current_indent.len;
6662 }
6663 continue;
6664 }
6665 }
6666
6667 // Otherwise, insert a hard or soft tab.
6668 let settings = buffer.settings_at(cursor, cx);
6669 let tab_size = if settings.hard_tabs {
6670 IndentSize::tab()
6671 } else {
6672 let tab_size = settings.tab_size.get();
6673 let char_column = snapshot
6674 .text_for_range(Point::new(cursor.row, 0)..cursor)
6675 .flat_map(str::chars)
6676 .count()
6677 + row_delta as usize;
6678 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6679 IndentSize::spaces(chars_to_next_tab_stop)
6680 };
6681 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6682 selection.end = selection.start;
6683 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6684 row_delta += tab_size.len;
6685 }
6686
6687 self.transact(window, cx, |this, window, cx| {
6688 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6689 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6690 s.select(selections)
6691 });
6692 this.refresh_inline_completion(true, false, window, cx);
6693 });
6694 }
6695
6696 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6697 if self.read_only(cx) {
6698 return;
6699 }
6700 let mut selections = self.selections.all::<Point>(cx);
6701 let mut prev_edited_row = 0;
6702 let mut row_delta = 0;
6703 let mut edits = Vec::new();
6704 let buffer = self.buffer.read(cx);
6705 let snapshot = buffer.snapshot(cx);
6706 for selection in &mut selections {
6707 if selection.start.row != prev_edited_row {
6708 row_delta = 0;
6709 }
6710 prev_edited_row = selection.end.row;
6711
6712 row_delta =
6713 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6714 }
6715
6716 self.transact(window, cx, |this, window, cx| {
6717 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6718 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6719 s.select(selections)
6720 });
6721 });
6722 }
6723
6724 fn indent_selection(
6725 buffer: &MultiBuffer,
6726 snapshot: &MultiBufferSnapshot,
6727 selection: &mut Selection<Point>,
6728 edits: &mut Vec<(Range<Point>, String)>,
6729 delta_for_start_row: u32,
6730 cx: &App,
6731 ) -> u32 {
6732 let settings = buffer.settings_at(selection.start, cx);
6733 let tab_size = settings.tab_size.get();
6734 let indent_kind = if settings.hard_tabs {
6735 IndentKind::Tab
6736 } else {
6737 IndentKind::Space
6738 };
6739 let mut start_row = selection.start.row;
6740 let mut end_row = selection.end.row + 1;
6741
6742 // If a selection ends at the beginning of a line, don't indent
6743 // that last line.
6744 if selection.end.column == 0 && selection.end.row > selection.start.row {
6745 end_row -= 1;
6746 }
6747
6748 // Avoid re-indenting a row that has already been indented by a
6749 // previous selection, but still update this selection's column
6750 // to reflect that indentation.
6751 if delta_for_start_row > 0 {
6752 start_row += 1;
6753 selection.start.column += delta_for_start_row;
6754 if selection.end.row == selection.start.row {
6755 selection.end.column += delta_for_start_row;
6756 }
6757 }
6758
6759 let mut delta_for_end_row = 0;
6760 let has_multiple_rows = start_row + 1 != end_row;
6761 for row in start_row..end_row {
6762 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6763 let indent_delta = match (current_indent.kind, indent_kind) {
6764 (IndentKind::Space, IndentKind::Space) => {
6765 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6766 IndentSize::spaces(columns_to_next_tab_stop)
6767 }
6768 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6769 (_, IndentKind::Tab) => IndentSize::tab(),
6770 };
6771
6772 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6773 0
6774 } else {
6775 selection.start.column
6776 };
6777 let row_start = Point::new(row, start);
6778 edits.push((
6779 row_start..row_start,
6780 indent_delta.chars().collect::<String>(),
6781 ));
6782
6783 // Update this selection's endpoints to reflect the indentation.
6784 if row == selection.start.row {
6785 selection.start.column += indent_delta.len;
6786 }
6787 if row == selection.end.row {
6788 selection.end.column += indent_delta.len;
6789 delta_for_end_row = indent_delta.len;
6790 }
6791 }
6792
6793 if selection.start.row == selection.end.row {
6794 delta_for_start_row + delta_for_end_row
6795 } else {
6796 delta_for_end_row
6797 }
6798 }
6799
6800 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6801 if self.read_only(cx) {
6802 return;
6803 }
6804 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6805 let selections = self.selections.all::<Point>(cx);
6806 let mut deletion_ranges = Vec::new();
6807 let mut last_outdent = None;
6808 {
6809 let buffer = self.buffer.read(cx);
6810 let snapshot = buffer.snapshot(cx);
6811 for selection in &selections {
6812 let settings = buffer.settings_at(selection.start, cx);
6813 let tab_size = settings.tab_size.get();
6814 let mut rows = selection.spanned_rows(false, &display_map);
6815
6816 // Avoid re-outdenting a row that has already been outdented by a
6817 // previous selection.
6818 if let Some(last_row) = last_outdent {
6819 if last_row == rows.start {
6820 rows.start = rows.start.next_row();
6821 }
6822 }
6823 let has_multiple_rows = rows.len() > 1;
6824 for row in rows.iter_rows() {
6825 let indent_size = snapshot.indent_size_for_line(row);
6826 if indent_size.len > 0 {
6827 let deletion_len = match indent_size.kind {
6828 IndentKind::Space => {
6829 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6830 if columns_to_prev_tab_stop == 0 {
6831 tab_size
6832 } else {
6833 columns_to_prev_tab_stop
6834 }
6835 }
6836 IndentKind::Tab => 1,
6837 };
6838 let start = if has_multiple_rows
6839 || deletion_len > selection.start.column
6840 || indent_size.len < selection.start.column
6841 {
6842 0
6843 } else {
6844 selection.start.column - deletion_len
6845 };
6846 deletion_ranges.push(
6847 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6848 );
6849 last_outdent = Some(row);
6850 }
6851 }
6852 }
6853 }
6854
6855 self.transact(window, cx, |this, window, cx| {
6856 this.buffer.update(cx, |buffer, cx| {
6857 let empty_str: Arc<str> = Arc::default();
6858 buffer.edit(
6859 deletion_ranges
6860 .into_iter()
6861 .map(|range| (range, empty_str.clone())),
6862 None,
6863 cx,
6864 );
6865 });
6866 let selections = this.selections.all::<usize>(cx);
6867 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6868 s.select(selections)
6869 });
6870 });
6871 }
6872
6873 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6874 if self.read_only(cx) {
6875 return;
6876 }
6877 let selections = self
6878 .selections
6879 .all::<usize>(cx)
6880 .into_iter()
6881 .map(|s| s.range());
6882
6883 self.transact(window, cx, |this, window, cx| {
6884 this.buffer.update(cx, |buffer, cx| {
6885 buffer.autoindent_ranges(selections, cx);
6886 });
6887 let selections = this.selections.all::<usize>(cx);
6888 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6889 s.select(selections)
6890 });
6891 });
6892 }
6893
6894 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6895 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6896 let selections = self.selections.all::<Point>(cx);
6897
6898 let mut new_cursors = Vec::new();
6899 let mut edit_ranges = Vec::new();
6900 let mut selections = selections.iter().peekable();
6901 while let Some(selection) = selections.next() {
6902 let mut rows = selection.spanned_rows(false, &display_map);
6903 let goal_display_column = selection.head().to_display_point(&display_map).column();
6904
6905 // Accumulate contiguous regions of rows that we want to delete.
6906 while let Some(next_selection) = selections.peek() {
6907 let next_rows = next_selection.spanned_rows(false, &display_map);
6908 if next_rows.start <= rows.end {
6909 rows.end = next_rows.end;
6910 selections.next().unwrap();
6911 } else {
6912 break;
6913 }
6914 }
6915
6916 let buffer = &display_map.buffer_snapshot;
6917 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6918 let edit_end;
6919 let cursor_buffer_row;
6920 if buffer.max_point().row >= rows.end.0 {
6921 // If there's a line after the range, delete the \n from the end of the row range
6922 // and position the cursor on the next line.
6923 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6924 cursor_buffer_row = rows.end;
6925 } else {
6926 // If there isn't a line after the range, delete the \n from the line before the
6927 // start of the row range and position the cursor there.
6928 edit_start = edit_start.saturating_sub(1);
6929 edit_end = buffer.len();
6930 cursor_buffer_row = rows.start.previous_row();
6931 }
6932
6933 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6934 *cursor.column_mut() =
6935 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6936
6937 new_cursors.push((
6938 selection.id,
6939 buffer.anchor_after(cursor.to_point(&display_map)),
6940 ));
6941 edit_ranges.push(edit_start..edit_end);
6942 }
6943
6944 self.transact(window, cx, |this, window, cx| {
6945 let buffer = this.buffer.update(cx, |buffer, cx| {
6946 let empty_str: Arc<str> = Arc::default();
6947 buffer.edit(
6948 edit_ranges
6949 .into_iter()
6950 .map(|range| (range, empty_str.clone())),
6951 None,
6952 cx,
6953 );
6954 buffer.snapshot(cx)
6955 });
6956 let new_selections = new_cursors
6957 .into_iter()
6958 .map(|(id, cursor)| {
6959 let cursor = cursor.to_point(&buffer);
6960 Selection {
6961 id,
6962 start: cursor,
6963 end: cursor,
6964 reversed: false,
6965 goal: SelectionGoal::None,
6966 }
6967 })
6968 .collect();
6969
6970 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6971 s.select(new_selections);
6972 });
6973 });
6974 }
6975
6976 pub fn join_lines_impl(
6977 &mut self,
6978 insert_whitespace: bool,
6979 window: &mut Window,
6980 cx: &mut Context<Self>,
6981 ) {
6982 if self.read_only(cx) {
6983 return;
6984 }
6985 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6986 for selection in self.selections.all::<Point>(cx) {
6987 let start = MultiBufferRow(selection.start.row);
6988 // Treat single line selections as if they include the next line. Otherwise this action
6989 // would do nothing for single line selections individual cursors.
6990 let end = if selection.start.row == selection.end.row {
6991 MultiBufferRow(selection.start.row + 1)
6992 } else {
6993 MultiBufferRow(selection.end.row)
6994 };
6995
6996 if let Some(last_row_range) = row_ranges.last_mut() {
6997 if start <= last_row_range.end {
6998 last_row_range.end = end;
6999 continue;
7000 }
7001 }
7002 row_ranges.push(start..end);
7003 }
7004
7005 let snapshot = self.buffer.read(cx).snapshot(cx);
7006 let mut cursor_positions = Vec::new();
7007 for row_range in &row_ranges {
7008 let anchor = snapshot.anchor_before(Point::new(
7009 row_range.end.previous_row().0,
7010 snapshot.line_len(row_range.end.previous_row()),
7011 ));
7012 cursor_positions.push(anchor..anchor);
7013 }
7014
7015 self.transact(window, cx, |this, window, cx| {
7016 for row_range in row_ranges.into_iter().rev() {
7017 for row in row_range.iter_rows().rev() {
7018 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7019 let next_line_row = row.next_row();
7020 let indent = snapshot.indent_size_for_line(next_line_row);
7021 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7022
7023 let replace =
7024 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7025 " "
7026 } else {
7027 ""
7028 };
7029
7030 this.buffer.update(cx, |buffer, cx| {
7031 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7032 });
7033 }
7034 }
7035
7036 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7037 s.select_anchor_ranges(cursor_positions)
7038 });
7039 });
7040 }
7041
7042 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7043 self.join_lines_impl(true, window, cx);
7044 }
7045
7046 pub fn sort_lines_case_sensitive(
7047 &mut self,
7048 _: &SortLinesCaseSensitive,
7049 window: &mut Window,
7050 cx: &mut Context<Self>,
7051 ) {
7052 self.manipulate_lines(window, cx, |lines| lines.sort())
7053 }
7054
7055 pub fn sort_lines_case_insensitive(
7056 &mut self,
7057 _: &SortLinesCaseInsensitive,
7058 window: &mut Window,
7059 cx: &mut Context<Self>,
7060 ) {
7061 self.manipulate_lines(window, cx, |lines| {
7062 lines.sort_by_key(|line| line.to_lowercase())
7063 })
7064 }
7065
7066 pub fn unique_lines_case_insensitive(
7067 &mut self,
7068 _: &UniqueLinesCaseInsensitive,
7069 window: &mut Window,
7070 cx: &mut Context<Self>,
7071 ) {
7072 self.manipulate_lines(window, cx, |lines| {
7073 let mut seen = HashSet::default();
7074 lines.retain(|line| seen.insert(line.to_lowercase()));
7075 })
7076 }
7077
7078 pub fn unique_lines_case_sensitive(
7079 &mut self,
7080 _: &UniqueLinesCaseSensitive,
7081 window: &mut Window,
7082 cx: &mut Context<Self>,
7083 ) {
7084 self.manipulate_lines(window, cx, |lines| {
7085 let mut seen = HashSet::default();
7086 lines.retain(|line| seen.insert(*line));
7087 })
7088 }
7089
7090 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7091 let mut revert_changes = HashMap::default();
7092 let snapshot = self.snapshot(window, cx);
7093 for hunk in snapshot
7094 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7095 {
7096 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7097 }
7098 if !revert_changes.is_empty() {
7099 self.transact(window, cx, |editor, window, cx| {
7100 editor.revert(revert_changes, window, cx);
7101 });
7102 }
7103 }
7104
7105 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7106 let Some(project) = self.project.clone() else {
7107 return;
7108 };
7109 self.reload(project, window, cx)
7110 .detach_and_notify_err(window, cx);
7111 }
7112
7113 pub fn revert_selected_hunks(
7114 &mut self,
7115 _: &RevertSelectedHunks,
7116 window: &mut Window,
7117 cx: &mut Context<Self>,
7118 ) {
7119 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7120 self.discard_hunks_in_ranges(selections, window, cx);
7121 }
7122
7123 fn discard_hunks_in_ranges(
7124 &mut self,
7125 ranges: impl Iterator<Item = Range<Point>>,
7126 window: &mut Window,
7127 cx: &mut Context<Editor>,
7128 ) {
7129 let mut revert_changes = HashMap::default();
7130 let snapshot = self.snapshot(window, cx);
7131 for hunk in &snapshot.hunks_for_ranges(ranges) {
7132 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7133 }
7134 if !revert_changes.is_empty() {
7135 self.transact(window, cx, |editor, window, cx| {
7136 editor.revert(revert_changes, window, cx);
7137 });
7138 }
7139 }
7140
7141 pub fn open_active_item_in_terminal(
7142 &mut self,
7143 _: &OpenInTerminal,
7144 window: &mut Window,
7145 cx: &mut Context<Self>,
7146 ) {
7147 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7148 let project_path = buffer.read(cx).project_path(cx)?;
7149 let project = self.project.as_ref()?.read(cx);
7150 let entry = project.entry_for_path(&project_path, cx)?;
7151 let parent = match &entry.canonical_path {
7152 Some(canonical_path) => canonical_path.to_path_buf(),
7153 None => project.absolute_path(&project_path, cx)?,
7154 }
7155 .parent()?
7156 .to_path_buf();
7157 Some(parent)
7158 }) {
7159 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7160 }
7161 }
7162
7163 pub fn prepare_revert_change(
7164 &self,
7165 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7166 hunk: &MultiBufferDiffHunk,
7167 cx: &mut App,
7168 ) -> Option<()> {
7169 let buffer = self.buffer.read(cx);
7170 let diff = buffer.diff_for(hunk.buffer_id)?;
7171 let buffer = buffer.buffer(hunk.buffer_id)?;
7172 let buffer = buffer.read(cx);
7173 let original_text = diff
7174 .read(cx)
7175 .base_text()
7176 .as_ref()?
7177 .as_rope()
7178 .slice(hunk.diff_base_byte_range.clone());
7179 let buffer_snapshot = buffer.snapshot();
7180 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7181 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7182 probe
7183 .0
7184 .start
7185 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7186 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7187 }) {
7188 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7189 Some(())
7190 } else {
7191 None
7192 }
7193 }
7194
7195 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7196 self.manipulate_lines(window, cx, |lines| lines.reverse())
7197 }
7198
7199 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7200 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7201 }
7202
7203 fn manipulate_lines<Fn>(
7204 &mut self,
7205 window: &mut Window,
7206 cx: &mut Context<Self>,
7207 mut callback: Fn,
7208 ) where
7209 Fn: FnMut(&mut Vec<&str>),
7210 {
7211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7212 let buffer = self.buffer.read(cx).snapshot(cx);
7213
7214 let mut edits = Vec::new();
7215
7216 let selections = self.selections.all::<Point>(cx);
7217 let mut selections = selections.iter().peekable();
7218 let mut contiguous_row_selections = Vec::new();
7219 let mut new_selections = Vec::new();
7220 let mut added_lines = 0;
7221 let mut removed_lines = 0;
7222
7223 while let Some(selection) = selections.next() {
7224 let (start_row, end_row) = consume_contiguous_rows(
7225 &mut contiguous_row_selections,
7226 selection,
7227 &display_map,
7228 &mut selections,
7229 );
7230
7231 let start_point = Point::new(start_row.0, 0);
7232 let end_point = Point::new(
7233 end_row.previous_row().0,
7234 buffer.line_len(end_row.previous_row()),
7235 );
7236 let text = buffer
7237 .text_for_range(start_point..end_point)
7238 .collect::<String>();
7239
7240 let mut lines = text.split('\n').collect_vec();
7241
7242 let lines_before = lines.len();
7243 callback(&mut lines);
7244 let lines_after = lines.len();
7245
7246 edits.push((start_point..end_point, lines.join("\n")));
7247
7248 // Selections must change based on added and removed line count
7249 let start_row =
7250 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7251 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7252 new_selections.push(Selection {
7253 id: selection.id,
7254 start: start_row,
7255 end: end_row,
7256 goal: SelectionGoal::None,
7257 reversed: selection.reversed,
7258 });
7259
7260 if lines_after > lines_before {
7261 added_lines += lines_after - lines_before;
7262 } else if lines_before > lines_after {
7263 removed_lines += lines_before - lines_after;
7264 }
7265 }
7266
7267 self.transact(window, cx, |this, window, cx| {
7268 let buffer = this.buffer.update(cx, |buffer, cx| {
7269 buffer.edit(edits, None, cx);
7270 buffer.snapshot(cx)
7271 });
7272
7273 // Recalculate offsets on newly edited buffer
7274 let new_selections = new_selections
7275 .iter()
7276 .map(|s| {
7277 let start_point = Point::new(s.start.0, 0);
7278 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7279 Selection {
7280 id: s.id,
7281 start: buffer.point_to_offset(start_point),
7282 end: buffer.point_to_offset(end_point),
7283 goal: s.goal,
7284 reversed: s.reversed,
7285 }
7286 })
7287 .collect();
7288
7289 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7290 s.select(new_selections);
7291 });
7292
7293 this.request_autoscroll(Autoscroll::fit(), cx);
7294 });
7295 }
7296
7297 pub fn convert_to_upper_case(
7298 &mut self,
7299 _: &ConvertToUpperCase,
7300 window: &mut Window,
7301 cx: &mut Context<Self>,
7302 ) {
7303 self.manipulate_text(window, cx, |text| text.to_uppercase())
7304 }
7305
7306 pub fn convert_to_lower_case(
7307 &mut self,
7308 _: &ConvertToLowerCase,
7309 window: &mut Window,
7310 cx: &mut Context<Self>,
7311 ) {
7312 self.manipulate_text(window, cx, |text| text.to_lowercase())
7313 }
7314
7315 pub fn convert_to_title_case(
7316 &mut self,
7317 _: &ConvertToTitleCase,
7318 window: &mut Window,
7319 cx: &mut Context<Self>,
7320 ) {
7321 self.manipulate_text(window, cx, |text| {
7322 text.split('\n')
7323 .map(|line| line.to_case(Case::Title))
7324 .join("\n")
7325 })
7326 }
7327
7328 pub fn convert_to_snake_case(
7329 &mut self,
7330 _: &ConvertToSnakeCase,
7331 window: &mut Window,
7332 cx: &mut Context<Self>,
7333 ) {
7334 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7335 }
7336
7337 pub fn convert_to_kebab_case(
7338 &mut self,
7339 _: &ConvertToKebabCase,
7340 window: &mut Window,
7341 cx: &mut Context<Self>,
7342 ) {
7343 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7344 }
7345
7346 pub fn convert_to_upper_camel_case(
7347 &mut self,
7348 _: &ConvertToUpperCamelCase,
7349 window: &mut Window,
7350 cx: &mut Context<Self>,
7351 ) {
7352 self.manipulate_text(window, cx, |text| {
7353 text.split('\n')
7354 .map(|line| line.to_case(Case::UpperCamel))
7355 .join("\n")
7356 })
7357 }
7358
7359 pub fn convert_to_lower_camel_case(
7360 &mut self,
7361 _: &ConvertToLowerCamelCase,
7362 window: &mut Window,
7363 cx: &mut Context<Self>,
7364 ) {
7365 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7366 }
7367
7368 pub fn convert_to_opposite_case(
7369 &mut self,
7370 _: &ConvertToOppositeCase,
7371 window: &mut Window,
7372 cx: &mut Context<Self>,
7373 ) {
7374 self.manipulate_text(window, cx, |text| {
7375 text.chars()
7376 .fold(String::with_capacity(text.len()), |mut t, c| {
7377 if c.is_uppercase() {
7378 t.extend(c.to_lowercase());
7379 } else {
7380 t.extend(c.to_uppercase());
7381 }
7382 t
7383 })
7384 })
7385 }
7386
7387 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7388 where
7389 Fn: FnMut(&str) -> String,
7390 {
7391 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7392 let buffer = self.buffer.read(cx).snapshot(cx);
7393
7394 let mut new_selections = Vec::new();
7395 let mut edits = Vec::new();
7396 let mut selection_adjustment = 0i32;
7397
7398 for selection in self.selections.all::<usize>(cx) {
7399 let selection_is_empty = selection.is_empty();
7400
7401 let (start, end) = if selection_is_empty {
7402 let word_range = movement::surrounding_word(
7403 &display_map,
7404 selection.start.to_display_point(&display_map),
7405 );
7406 let start = word_range.start.to_offset(&display_map, Bias::Left);
7407 let end = word_range.end.to_offset(&display_map, Bias::Left);
7408 (start, end)
7409 } else {
7410 (selection.start, selection.end)
7411 };
7412
7413 let text = buffer.text_for_range(start..end).collect::<String>();
7414 let old_length = text.len() as i32;
7415 let text = callback(&text);
7416
7417 new_selections.push(Selection {
7418 start: (start as i32 - selection_adjustment) as usize,
7419 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7420 goal: SelectionGoal::None,
7421 ..selection
7422 });
7423
7424 selection_adjustment += old_length - text.len() as i32;
7425
7426 edits.push((start..end, text));
7427 }
7428
7429 self.transact(window, cx, |this, window, cx| {
7430 this.buffer.update(cx, |buffer, cx| {
7431 buffer.edit(edits, None, cx);
7432 });
7433
7434 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7435 s.select(new_selections);
7436 });
7437
7438 this.request_autoscroll(Autoscroll::fit(), cx);
7439 });
7440 }
7441
7442 pub fn duplicate(
7443 &mut self,
7444 upwards: bool,
7445 whole_lines: bool,
7446 window: &mut Window,
7447 cx: &mut Context<Self>,
7448 ) {
7449 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7450 let buffer = &display_map.buffer_snapshot;
7451 let selections = self.selections.all::<Point>(cx);
7452
7453 let mut edits = Vec::new();
7454 let mut selections_iter = selections.iter().peekable();
7455 while let Some(selection) = selections_iter.next() {
7456 let mut rows = selection.spanned_rows(false, &display_map);
7457 // duplicate line-wise
7458 if whole_lines || selection.start == selection.end {
7459 // Avoid duplicating the same lines twice.
7460 while let Some(next_selection) = selections_iter.peek() {
7461 let next_rows = next_selection.spanned_rows(false, &display_map);
7462 if next_rows.start < rows.end {
7463 rows.end = next_rows.end;
7464 selections_iter.next().unwrap();
7465 } else {
7466 break;
7467 }
7468 }
7469
7470 // Copy the text from the selected row region and splice it either at the start
7471 // or end of the region.
7472 let start = Point::new(rows.start.0, 0);
7473 let end = Point::new(
7474 rows.end.previous_row().0,
7475 buffer.line_len(rows.end.previous_row()),
7476 );
7477 let text = buffer
7478 .text_for_range(start..end)
7479 .chain(Some("\n"))
7480 .collect::<String>();
7481 let insert_location = if upwards {
7482 Point::new(rows.end.0, 0)
7483 } else {
7484 start
7485 };
7486 edits.push((insert_location..insert_location, text));
7487 } else {
7488 // duplicate character-wise
7489 let start = selection.start;
7490 let end = selection.end;
7491 let text = buffer.text_for_range(start..end).collect::<String>();
7492 edits.push((selection.end..selection.end, text));
7493 }
7494 }
7495
7496 self.transact(window, cx, |this, _, cx| {
7497 this.buffer.update(cx, |buffer, cx| {
7498 buffer.edit(edits, None, cx);
7499 });
7500
7501 this.request_autoscroll(Autoscroll::fit(), cx);
7502 });
7503 }
7504
7505 pub fn duplicate_line_up(
7506 &mut self,
7507 _: &DuplicateLineUp,
7508 window: &mut Window,
7509 cx: &mut Context<Self>,
7510 ) {
7511 self.duplicate(true, true, window, cx);
7512 }
7513
7514 pub fn duplicate_line_down(
7515 &mut self,
7516 _: &DuplicateLineDown,
7517 window: &mut Window,
7518 cx: &mut Context<Self>,
7519 ) {
7520 self.duplicate(false, true, window, cx);
7521 }
7522
7523 pub fn duplicate_selection(
7524 &mut self,
7525 _: &DuplicateSelection,
7526 window: &mut Window,
7527 cx: &mut Context<Self>,
7528 ) {
7529 self.duplicate(false, false, window, cx);
7530 }
7531
7532 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7533 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7534 let buffer = self.buffer.read(cx).snapshot(cx);
7535
7536 let mut edits = Vec::new();
7537 let mut unfold_ranges = Vec::new();
7538 let mut refold_creases = Vec::new();
7539
7540 let selections = self.selections.all::<Point>(cx);
7541 let mut selections = selections.iter().peekable();
7542 let mut contiguous_row_selections = Vec::new();
7543 let mut new_selections = Vec::new();
7544
7545 while let Some(selection) = selections.next() {
7546 // Find all the selections that span a contiguous row range
7547 let (start_row, end_row) = consume_contiguous_rows(
7548 &mut contiguous_row_selections,
7549 selection,
7550 &display_map,
7551 &mut selections,
7552 );
7553
7554 // Move the text spanned by the row range to be before the line preceding the row range
7555 if start_row.0 > 0 {
7556 let range_to_move = Point::new(
7557 start_row.previous_row().0,
7558 buffer.line_len(start_row.previous_row()),
7559 )
7560 ..Point::new(
7561 end_row.previous_row().0,
7562 buffer.line_len(end_row.previous_row()),
7563 );
7564 let insertion_point = display_map
7565 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7566 .0;
7567
7568 // Don't move lines across excerpts
7569 if buffer
7570 .excerpt_containing(insertion_point..range_to_move.end)
7571 .is_some()
7572 {
7573 let text = buffer
7574 .text_for_range(range_to_move.clone())
7575 .flat_map(|s| s.chars())
7576 .skip(1)
7577 .chain(['\n'])
7578 .collect::<String>();
7579
7580 edits.push((
7581 buffer.anchor_after(range_to_move.start)
7582 ..buffer.anchor_before(range_to_move.end),
7583 String::new(),
7584 ));
7585 let insertion_anchor = buffer.anchor_after(insertion_point);
7586 edits.push((insertion_anchor..insertion_anchor, text));
7587
7588 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7589
7590 // Move selections up
7591 new_selections.extend(contiguous_row_selections.drain(..).map(
7592 |mut selection| {
7593 selection.start.row -= row_delta;
7594 selection.end.row -= row_delta;
7595 selection
7596 },
7597 ));
7598
7599 // Move folds up
7600 unfold_ranges.push(range_to_move.clone());
7601 for fold in display_map.folds_in_range(
7602 buffer.anchor_before(range_to_move.start)
7603 ..buffer.anchor_after(range_to_move.end),
7604 ) {
7605 let mut start = fold.range.start.to_point(&buffer);
7606 let mut end = fold.range.end.to_point(&buffer);
7607 start.row -= row_delta;
7608 end.row -= row_delta;
7609 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7610 }
7611 }
7612 }
7613
7614 // If we didn't move line(s), preserve the existing selections
7615 new_selections.append(&mut contiguous_row_selections);
7616 }
7617
7618 self.transact(window, cx, |this, window, cx| {
7619 this.unfold_ranges(&unfold_ranges, true, true, cx);
7620 this.buffer.update(cx, |buffer, cx| {
7621 for (range, text) in edits {
7622 buffer.edit([(range, text)], None, cx);
7623 }
7624 });
7625 this.fold_creases(refold_creases, true, window, cx);
7626 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7627 s.select(new_selections);
7628 })
7629 });
7630 }
7631
7632 pub fn move_line_down(
7633 &mut self,
7634 _: &MoveLineDown,
7635 window: &mut Window,
7636 cx: &mut Context<Self>,
7637 ) {
7638 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7639 let buffer = self.buffer.read(cx).snapshot(cx);
7640
7641 let mut edits = Vec::new();
7642 let mut unfold_ranges = Vec::new();
7643 let mut refold_creases = Vec::new();
7644
7645 let selections = self.selections.all::<Point>(cx);
7646 let mut selections = selections.iter().peekable();
7647 let mut contiguous_row_selections = Vec::new();
7648 let mut new_selections = Vec::new();
7649
7650 while let Some(selection) = selections.next() {
7651 // Find all the selections that span a contiguous row range
7652 let (start_row, end_row) = consume_contiguous_rows(
7653 &mut contiguous_row_selections,
7654 selection,
7655 &display_map,
7656 &mut selections,
7657 );
7658
7659 // Move the text spanned by the row range to be after the last line of the row range
7660 if end_row.0 <= buffer.max_point().row {
7661 let range_to_move =
7662 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7663 let insertion_point = display_map
7664 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7665 .0;
7666
7667 // Don't move lines across excerpt boundaries
7668 if buffer
7669 .excerpt_containing(range_to_move.start..insertion_point)
7670 .is_some()
7671 {
7672 let mut text = String::from("\n");
7673 text.extend(buffer.text_for_range(range_to_move.clone()));
7674 text.pop(); // Drop trailing newline
7675 edits.push((
7676 buffer.anchor_after(range_to_move.start)
7677 ..buffer.anchor_before(range_to_move.end),
7678 String::new(),
7679 ));
7680 let insertion_anchor = buffer.anchor_after(insertion_point);
7681 edits.push((insertion_anchor..insertion_anchor, text));
7682
7683 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7684
7685 // Move selections down
7686 new_selections.extend(contiguous_row_selections.drain(..).map(
7687 |mut selection| {
7688 selection.start.row += row_delta;
7689 selection.end.row += row_delta;
7690 selection
7691 },
7692 ));
7693
7694 // Move folds down
7695 unfold_ranges.push(range_to_move.clone());
7696 for fold in display_map.folds_in_range(
7697 buffer.anchor_before(range_to_move.start)
7698 ..buffer.anchor_after(range_to_move.end),
7699 ) {
7700 let mut start = fold.range.start.to_point(&buffer);
7701 let mut end = fold.range.end.to_point(&buffer);
7702 start.row += row_delta;
7703 end.row += row_delta;
7704 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7705 }
7706 }
7707 }
7708
7709 // If we didn't move line(s), preserve the existing selections
7710 new_selections.append(&mut contiguous_row_selections);
7711 }
7712
7713 self.transact(window, cx, |this, window, cx| {
7714 this.unfold_ranges(&unfold_ranges, true, true, cx);
7715 this.buffer.update(cx, |buffer, cx| {
7716 for (range, text) in edits {
7717 buffer.edit([(range, text)], None, cx);
7718 }
7719 });
7720 this.fold_creases(refold_creases, true, window, cx);
7721 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7722 s.select(new_selections)
7723 });
7724 });
7725 }
7726
7727 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7728 let text_layout_details = &self.text_layout_details(window);
7729 self.transact(window, cx, |this, window, cx| {
7730 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7731 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7732 let line_mode = s.line_mode;
7733 s.move_with(|display_map, selection| {
7734 if !selection.is_empty() || line_mode {
7735 return;
7736 }
7737
7738 let mut head = selection.head();
7739 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7740 if head.column() == display_map.line_len(head.row()) {
7741 transpose_offset = display_map
7742 .buffer_snapshot
7743 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7744 }
7745
7746 if transpose_offset == 0 {
7747 return;
7748 }
7749
7750 *head.column_mut() += 1;
7751 head = display_map.clip_point(head, Bias::Right);
7752 let goal = SelectionGoal::HorizontalPosition(
7753 display_map
7754 .x_for_display_point(head, text_layout_details)
7755 .into(),
7756 );
7757 selection.collapse_to(head, goal);
7758
7759 let transpose_start = display_map
7760 .buffer_snapshot
7761 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7762 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7763 let transpose_end = display_map
7764 .buffer_snapshot
7765 .clip_offset(transpose_offset + 1, Bias::Right);
7766 if let Some(ch) =
7767 display_map.buffer_snapshot.chars_at(transpose_start).next()
7768 {
7769 edits.push((transpose_start..transpose_offset, String::new()));
7770 edits.push((transpose_end..transpose_end, ch.to_string()));
7771 }
7772 }
7773 });
7774 edits
7775 });
7776 this.buffer
7777 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7778 let selections = this.selections.all::<usize>(cx);
7779 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7780 s.select(selections);
7781 });
7782 });
7783 }
7784
7785 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7786 self.rewrap_impl(IsVimMode::No, cx)
7787 }
7788
7789 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7790 let buffer = self.buffer.read(cx).snapshot(cx);
7791 let selections = self.selections.all::<Point>(cx);
7792 let mut selections = selections.iter().peekable();
7793
7794 let mut edits = Vec::new();
7795 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7796
7797 while let Some(selection) = selections.next() {
7798 let mut start_row = selection.start.row;
7799 let mut end_row = selection.end.row;
7800
7801 // Skip selections that overlap with a range that has already been rewrapped.
7802 let selection_range = start_row..end_row;
7803 if rewrapped_row_ranges
7804 .iter()
7805 .any(|range| range.overlaps(&selection_range))
7806 {
7807 continue;
7808 }
7809
7810 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7811
7812 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7813 match language_scope.language_name().as_ref() {
7814 "Markdown" | "Plain Text" => {
7815 should_rewrap = true;
7816 }
7817 _ => {}
7818 }
7819 }
7820
7821 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7822
7823 // Since not all lines in the selection may be at the same indent
7824 // level, choose the indent size that is the most common between all
7825 // of the lines.
7826 //
7827 // If there is a tie, we use the deepest indent.
7828 let (indent_size, indent_end) = {
7829 let mut indent_size_occurrences = HashMap::default();
7830 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7831
7832 for row in start_row..=end_row {
7833 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7834 rows_by_indent_size.entry(indent).or_default().push(row);
7835 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7836 }
7837
7838 let indent_size = indent_size_occurrences
7839 .into_iter()
7840 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7841 .map(|(indent, _)| indent)
7842 .unwrap_or_default();
7843 let row = rows_by_indent_size[&indent_size][0];
7844 let indent_end = Point::new(row, indent_size.len);
7845
7846 (indent_size, indent_end)
7847 };
7848
7849 let mut line_prefix = indent_size.chars().collect::<String>();
7850
7851 if let Some(comment_prefix) =
7852 buffer
7853 .language_scope_at(selection.head())
7854 .and_then(|language| {
7855 language
7856 .line_comment_prefixes()
7857 .iter()
7858 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7859 .cloned()
7860 })
7861 {
7862 line_prefix.push_str(&comment_prefix);
7863 should_rewrap = true;
7864 }
7865
7866 if !should_rewrap {
7867 continue;
7868 }
7869
7870 if selection.is_empty() {
7871 'expand_upwards: while start_row > 0 {
7872 let prev_row = start_row - 1;
7873 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7874 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7875 {
7876 start_row = prev_row;
7877 } else {
7878 break 'expand_upwards;
7879 }
7880 }
7881
7882 'expand_downwards: while end_row < buffer.max_point().row {
7883 let next_row = end_row + 1;
7884 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7885 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7886 {
7887 end_row = next_row;
7888 } else {
7889 break 'expand_downwards;
7890 }
7891 }
7892 }
7893
7894 let start = Point::new(start_row, 0);
7895 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7896 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7897 let Some(lines_without_prefixes) = selection_text
7898 .lines()
7899 .map(|line| {
7900 line.strip_prefix(&line_prefix)
7901 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7902 .ok_or_else(|| {
7903 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7904 })
7905 })
7906 .collect::<Result<Vec<_>, _>>()
7907 .log_err()
7908 else {
7909 continue;
7910 };
7911
7912 let wrap_column = buffer
7913 .settings_at(Point::new(start_row, 0), cx)
7914 .preferred_line_length as usize;
7915 let wrapped_text = wrap_with_prefix(
7916 line_prefix,
7917 lines_without_prefixes.join(" "),
7918 wrap_column,
7919 tab_size,
7920 );
7921
7922 // TODO: should always use char-based diff while still supporting cursor behavior that
7923 // matches vim.
7924 let diff = match is_vim_mode {
7925 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7926 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7927 };
7928 let mut offset = start.to_offset(&buffer);
7929 let mut moved_since_edit = true;
7930
7931 for change in diff.iter_all_changes() {
7932 let value = change.value();
7933 match change.tag() {
7934 ChangeTag::Equal => {
7935 offset += value.len();
7936 moved_since_edit = true;
7937 }
7938 ChangeTag::Delete => {
7939 let start = buffer.anchor_after(offset);
7940 let end = buffer.anchor_before(offset + value.len());
7941
7942 if moved_since_edit {
7943 edits.push((start..end, String::new()));
7944 } else {
7945 edits.last_mut().unwrap().0.end = end;
7946 }
7947
7948 offset += value.len();
7949 moved_since_edit = false;
7950 }
7951 ChangeTag::Insert => {
7952 if moved_since_edit {
7953 let anchor = buffer.anchor_after(offset);
7954 edits.push((anchor..anchor, value.to_string()));
7955 } else {
7956 edits.last_mut().unwrap().1.push_str(value);
7957 }
7958
7959 moved_since_edit = false;
7960 }
7961 }
7962 }
7963
7964 rewrapped_row_ranges.push(start_row..=end_row);
7965 }
7966
7967 self.buffer
7968 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7969 }
7970
7971 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7972 let mut text = String::new();
7973 let buffer = self.buffer.read(cx).snapshot(cx);
7974 let mut selections = self.selections.all::<Point>(cx);
7975 let mut clipboard_selections = Vec::with_capacity(selections.len());
7976 {
7977 let max_point = buffer.max_point();
7978 let mut is_first = true;
7979 for selection in &mut selections {
7980 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7981 if is_entire_line {
7982 selection.start = Point::new(selection.start.row, 0);
7983 if !selection.is_empty() && selection.end.column == 0 {
7984 selection.end = cmp::min(max_point, selection.end);
7985 } else {
7986 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7987 }
7988 selection.goal = SelectionGoal::None;
7989 }
7990 if is_first {
7991 is_first = false;
7992 } else {
7993 text += "\n";
7994 }
7995 let mut len = 0;
7996 for chunk in buffer.text_for_range(selection.start..selection.end) {
7997 text.push_str(chunk);
7998 len += chunk.len();
7999 }
8000 clipboard_selections.push(ClipboardSelection {
8001 len,
8002 is_entire_line,
8003 first_line_indent: buffer
8004 .indent_size_for_line(MultiBufferRow(selection.start.row))
8005 .len,
8006 });
8007 }
8008 }
8009
8010 self.transact(window, cx, |this, window, cx| {
8011 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8012 s.select(selections);
8013 });
8014 this.insert("", window, cx);
8015 });
8016 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8017 }
8018
8019 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8020 let item = self.cut_common(window, cx);
8021 cx.write_to_clipboard(item);
8022 }
8023
8024 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8025 self.change_selections(None, window, cx, |s| {
8026 s.move_with(|snapshot, sel| {
8027 if sel.is_empty() {
8028 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8029 }
8030 });
8031 });
8032 let item = self.cut_common(window, cx);
8033 cx.set_global(KillRing(item))
8034 }
8035
8036 pub fn kill_ring_yank(
8037 &mut self,
8038 _: &KillRingYank,
8039 window: &mut Window,
8040 cx: &mut Context<Self>,
8041 ) {
8042 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8043 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8044 (kill_ring.text().to_string(), kill_ring.metadata_json())
8045 } else {
8046 return;
8047 }
8048 } else {
8049 return;
8050 };
8051 self.do_paste(&text, metadata, false, window, cx);
8052 }
8053
8054 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8055 let selections = self.selections.all::<Point>(cx);
8056 let buffer = self.buffer.read(cx).read(cx);
8057 let mut text = String::new();
8058
8059 let mut clipboard_selections = Vec::with_capacity(selections.len());
8060 {
8061 let max_point = buffer.max_point();
8062 let mut is_first = true;
8063 for selection in selections.iter() {
8064 let mut start = selection.start;
8065 let mut end = selection.end;
8066 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8067 if is_entire_line {
8068 start = Point::new(start.row, 0);
8069 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8070 }
8071 if is_first {
8072 is_first = false;
8073 } else {
8074 text += "\n";
8075 }
8076 let mut len = 0;
8077 for chunk in buffer.text_for_range(start..end) {
8078 text.push_str(chunk);
8079 len += chunk.len();
8080 }
8081 clipboard_selections.push(ClipboardSelection {
8082 len,
8083 is_entire_line,
8084 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8085 });
8086 }
8087 }
8088
8089 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8090 text,
8091 clipboard_selections,
8092 ));
8093 }
8094
8095 pub fn do_paste(
8096 &mut self,
8097 text: &String,
8098 clipboard_selections: Option<Vec<ClipboardSelection>>,
8099 handle_entire_lines: bool,
8100 window: &mut Window,
8101 cx: &mut Context<Self>,
8102 ) {
8103 if self.read_only(cx) {
8104 return;
8105 }
8106
8107 let clipboard_text = Cow::Borrowed(text);
8108
8109 self.transact(window, cx, |this, window, cx| {
8110 if let Some(mut clipboard_selections) = clipboard_selections {
8111 let old_selections = this.selections.all::<usize>(cx);
8112 let all_selections_were_entire_line =
8113 clipboard_selections.iter().all(|s| s.is_entire_line);
8114 let first_selection_indent_column =
8115 clipboard_selections.first().map(|s| s.first_line_indent);
8116 if clipboard_selections.len() != old_selections.len() {
8117 clipboard_selections.drain(..);
8118 }
8119 let cursor_offset = this.selections.last::<usize>(cx).head();
8120 let mut auto_indent_on_paste = true;
8121
8122 this.buffer.update(cx, |buffer, cx| {
8123 let snapshot = buffer.read(cx);
8124 auto_indent_on_paste =
8125 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8126
8127 let mut start_offset = 0;
8128 let mut edits = Vec::new();
8129 let mut original_indent_columns = Vec::new();
8130 for (ix, selection) in old_selections.iter().enumerate() {
8131 let to_insert;
8132 let entire_line;
8133 let original_indent_column;
8134 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8135 let end_offset = start_offset + clipboard_selection.len;
8136 to_insert = &clipboard_text[start_offset..end_offset];
8137 entire_line = clipboard_selection.is_entire_line;
8138 start_offset = end_offset + 1;
8139 original_indent_column = Some(clipboard_selection.first_line_indent);
8140 } else {
8141 to_insert = clipboard_text.as_str();
8142 entire_line = all_selections_were_entire_line;
8143 original_indent_column = first_selection_indent_column
8144 }
8145
8146 // If the corresponding selection was empty when this slice of the
8147 // clipboard text was written, then the entire line containing the
8148 // selection was copied. If this selection is also currently empty,
8149 // then paste the line before the current line of the buffer.
8150 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8151 let column = selection.start.to_point(&snapshot).column as usize;
8152 let line_start = selection.start - column;
8153 line_start..line_start
8154 } else {
8155 selection.range()
8156 };
8157
8158 edits.push((range, to_insert));
8159 original_indent_columns.extend(original_indent_column);
8160 }
8161 drop(snapshot);
8162
8163 buffer.edit(
8164 edits,
8165 if auto_indent_on_paste {
8166 Some(AutoindentMode::Block {
8167 original_indent_columns,
8168 })
8169 } else {
8170 None
8171 },
8172 cx,
8173 );
8174 });
8175
8176 let selections = this.selections.all::<usize>(cx);
8177 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8178 s.select(selections)
8179 });
8180 } else {
8181 this.insert(&clipboard_text, window, cx);
8182 }
8183 });
8184 }
8185
8186 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8187 if let Some(item) = cx.read_from_clipboard() {
8188 let entries = item.entries();
8189
8190 match entries.first() {
8191 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8192 // of all the pasted entries.
8193 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8194 .do_paste(
8195 clipboard_string.text(),
8196 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8197 true,
8198 window,
8199 cx,
8200 ),
8201 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8202 }
8203 }
8204 }
8205
8206 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8207 if self.read_only(cx) {
8208 return;
8209 }
8210
8211 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8212 if let Some((selections, _)) =
8213 self.selection_history.transaction(transaction_id).cloned()
8214 {
8215 self.change_selections(None, window, cx, |s| {
8216 s.select_anchors(selections.to_vec());
8217 });
8218 }
8219 self.request_autoscroll(Autoscroll::fit(), cx);
8220 self.unmark_text(window, cx);
8221 self.refresh_inline_completion(true, false, window, cx);
8222 cx.emit(EditorEvent::Edited { transaction_id });
8223 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8224 }
8225 }
8226
8227 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8228 if self.read_only(cx) {
8229 return;
8230 }
8231
8232 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8233 if let Some((_, Some(selections))) =
8234 self.selection_history.transaction(transaction_id).cloned()
8235 {
8236 self.change_selections(None, window, cx, |s| {
8237 s.select_anchors(selections.to_vec());
8238 });
8239 }
8240 self.request_autoscroll(Autoscroll::fit(), cx);
8241 self.unmark_text(window, cx);
8242 self.refresh_inline_completion(true, false, window, cx);
8243 cx.emit(EditorEvent::Edited { transaction_id });
8244 }
8245 }
8246
8247 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8248 self.buffer
8249 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8250 }
8251
8252 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8253 self.buffer
8254 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8255 }
8256
8257 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8259 let line_mode = s.line_mode;
8260 s.move_with(|map, selection| {
8261 let cursor = if selection.is_empty() && !line_mode {
8262 movement::left(map, selection.start)
8263 } else {
8264 selection.start
8265 };
8266 selection.collapse_to(cursor, SelectionGoal::None);
8267 });
8268 })
8269 }
8270
8271 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8273 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8274 })
8275 }
8276
8277 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8279 let line_mode = s.line_mode;
8280 s.move_with(|map, selection| {
8281 let cursor = if selection.is_empty() && !line_mode {
8282 movement::right(map, selection.end)
8283 } else {
8284 selection.end
8285 };
8286 selection.collapse_to(cursor, SelectionGoal::None)
8287 });
8288 })
8289 }
8290
8291 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8292 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8293 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8294 })
8295 }
8296
8297 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8298 if self.take_rename(true, window, cx).is_some() {
8299 return;
8300 }
8301
8302 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8303 cx.propagate();
8304 return;
8305 }
8306
8307 let text_layout_details = &self.text_layout_details(window);
8308 let selection_count = self.selections.count();
8309 let first_selection = self.selections.first_anchor();
8310
8311 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8312 let line_mode = s.line_mode;
8313 s.move_with(|map, selection| {
8314 if !selection.is_empty() && !line_mode {
8315 selection.goal = SelectionGoal::None;
8316 }
8317 let (cursor, goal) = movement::up(
8318 map,
8319 selection.start,
8320 selection.goal,
8321 false,
8322 text_layout_details,
8323 );
8324 selection.collapse_to(cursor, goal);
8325 });
8326 });
8327
8328 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8329 {
8330 cx.propagate();
8331 }
8332 }
8333
8334 pub fn move_up_by_lines(
8335 &mut self,
8336 action: &MoveUpByLines,
8337 window: &mut Window,
8338 cx: &mut Context<Self>,
8339 ) {
8340 if self.take_rename(true, window, cx).is_some() {
8341 return;
8342 }
8343
8344 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8345 cx.propagate();
8346 return;
8347 }
8348
8349 let text_layout_details = &self.text_layout_details(window);
8350
8351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8352 let line_mode = s.line_mode;
8353 s.move_with(|map, selection| {
8354 if !selection.is_empty() && !line_mode {
8355 selection.goal = SelectionGoal::None;
8356 }
8357 let (cursor, goal) = movement::up_by_rows(
8358 map,
8359 selection.start,
8360 action.lines,
8361 selection.goal,
8362 false,
8363 text_layout_details,
8364 );
8365 selection.collapse_to(cursor, goal);
8366 });
8367 })
8368 }
8369
8370 pub fn move_down_by_lines(
8371 &mut self,
8372 action: &MoveDownByLines,
8373 window: &mut Window,
8374 cx: &mut Context<Self>,
8375 ) {
8376 if self.take_rename(true, window, cx).is_some() {
8377 return;
8378 }
8379
8380 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8381 cx.propagate();
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 let line_mode = s.line_mode;
8389 s.move_with(|map, selection| {
8390 if !selection.is_empty() && !line_mode {
8391 selection.goal = SelectionGoal::None;
8392 }
8393 let (cursor, goal) = movement::down_by_rows(
8394 map,
8395 selection.start,
8396 action.lines,
8397 selection.goal,
8398 false,
8399 text_layout_details,
8400 );
8401 selection.collapse_to(cursor, goal);
8402 });
8403 })
8404 }
8405
8406 pub fn select_down_by_lines(
8407 &mut self,
8408 action: &SelectDownByLines,
8409 window: &mut Window,
8410 cx: &mut Context<Self>,
8411 ) {
8412 let text_layout_details = &self.text_layout_details(window);
8413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8414 s.move_heads_with(|map, head, goal| {
8415 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8416 })
8417 })
8418 }
8419
8420 pub fn select_up_by_lines(
8421 &mut self,
8422 action: &SelectUpByLines,
8423 window: &mut Window,
8424 cx: &mut Context<Self>,
8425 ) {
8426 let text_layout_details = &self.text_layout_details(window);
8427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8428 s.move_heads_with(|map, head, goal| {
8429 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8430 })
8431 })
8432 }
8433
8434 pub fn select_page_up(
8435 &mut self,
8436 _: &SelectPageUp,
8437 window: &mut Window,
8438 cx: &mut Context<Self>,
8439 ) {
8440 let Some(row_count) = self.visible_row_count() else {
8441 return;
8442 };
8443
8444 let text_layout_details = &self.text_layout_details(window);
8445
8446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8447 s.move_heads_with(|map, head, goal| {
8448 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8449 })
8450 })
8451 }
8452
8453 pub fn move_page_up(
8454 &mut self,
8455 action: &MovePageUp,
8456 window: &mut Window,
8457 cx: &mut Context<Self>,
8458 ) {
8459 if self.take_rename(true, window, cx).is_some() {
8460 return;
8461 }
8462
8463 if self
8464 .context_menu
8465 .borrow_mut()
8466 .as_mut()
8467 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8468 .unwrap_or(false)
8469 {
8470 return;
8471 }
8472
8473 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8474 cx.propagate();
8475 return;
8476 }
8477
8478 let Some(row_count) = self.visible_row_count() else {
8479 return;
8480 };
8481
8482 let autoscroll = if action.center_cursor {
8483 Autoscroll::center()
8484 } else {
8485 Autoscroll::fit()
8486 };
8487
8488 let text_layout_details = &self.text_layout_details(window);
8489
8490 self.change_selections(Some(autoscroll), window, cx, |s| {
8491 let line_mode = s.line_mode;
8492 s.move_with(|map, selection| {
8493 if !selection.is_empty() && !line_mode {
8494 selection.goal = SelectionGoal::None;
8495 }
8496 let (cursor, goal) = movement::up_by_rows(
8497 map,
8498 selection.end,
8499 row_count,
8500 selection.goal,
8501 false,
8502 text_layout_details,
8503 );
8504 selection.collapse_to(cursor, goal);
8505 });
8506 });
8507 }
8508
8509 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8510 let text_layout_details = &self.text_layout_details(window);
8511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8512 s.move_heads_with(|map, head, goal| {
8513 movement::up(map, head, goal, false, text_layout_details)
8514 })
8515 })
8516 }
8517
8518 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8519 self.take_rename(true, window, cx);
8520
8521 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8522 cx.propagate();
8523 return;
8524 }
8525
8526 let text_layout_details = &self.text_layout_details(window);
8527 let selection_count = self.selections.count();
8528 let first_selection = self.selections.first_anchor();
8529
8530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8531 let line_mode = s.line_mode;
8532 s.move_with(|map, selection| {
8533 if !selection.is_empty() && !line_mode {
8534 selection.goal = SelectionGoal::None;
8535 }
8536 let (cursor, goal) = movement::down(
8537 map,
8538 selection.end,
8539 selection.goal,
8540 false,
8541 text_layout_details,
8542 );
8543 selection.collapse_to(cursor, goal);
8544 });
8545 });
8546
8547 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8548 {
8549 cx.propagate();
8550 }
8551 }
8552
8553 pub fn select_page_down(
8554 &mut self,
8555 _: &SelectPageDown,
8556 window: &mut Window,
8557 cx: &mut Context<Self>,
8558 ) {
8559 let Some(row_count) = self.visible_row_count() else {
8560 return;
8561 };
8562
8563 let text_layout_details = &self.text_layout_details(window);
8564
8565 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8566 s.move_heads_with(|map, head, goal| {
8567 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8568 })
8569 })
8570 }
8571
8572 pub fn move_page_down(
8573 &mut self,
8574 action: &MovePageDown,
8575 window: &mut Window,
8576 cx: &mut Context<Self>,
8577 ) {
8578 if self.take_rename(true, window, cx).is_some() {
8579 return;
8580 }
8581
8582 if self
8583 .context_menu
8584 .borrow_mut()
8585 .as_mut()
8586 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8587 .unwrap_or(false)
8588 {
8589 return;
8590 }
8591
8592 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8593 cx.propagate();
8594 return;
8595 }
8596
8597 let Some(row_count) = self.visible_row_count() else {
8598 return;
8599 };
8600
8601 let autoscroll = if action.center_cursor {
8602 Autoscroll::center()
8603 } else {
8604 Autoscroll::fit()
8605 };
8606
8607 let text_layout_details = &self.text_layout_details(window);
8608 self.change_selections(Some(autoscroll), window, cx, |s| {
8609 let line_mode = s.line_mode;
8610 s.move_with(|map, selection| {
8611 if !selection.is_empty() && !line_mode {
8612 selection.goal = SelectionGoal::None;
8613 }
8614 let (cursor, goal) = movement::down_by_rows(
8615 map,
8616 selection.end,
8617 row_count,
8618 selection.goal,
8619 false,
8620 text_layout_details,
8621 );
8622 selection.collapse_to(cursor, goal);
8623 });
8624 });
8625 }
8626
8627 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8628 let text_layout_details = &self.text_layout_details(window);
8629 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8630 s.move_heads_with(|map, head, goal| {
8631 movement::down(map, head, goal, false, text_layout_details)
8632 })
8633 });
8634 }
8635
8636 pub fn context_menu_first(
8637 &mut self,
8638 _: &ContextMenuFirst,
8639 _window: &mut Window,
8640 cx: &mut Context<Self>,
8641 ) {
8642 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8643 context_menu.select_first(self.completion_provider.as_deref(), cx);
8644 }
8645 }
8646
8647 pub fn context_menu_prev(
8648 &mut self,
8649 _: &ContextMenuPrev,
8650 _window: &mut Window,
8651 cx: &mut Context<Self>,
8652 ) {
8653 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8654 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8655 }
8656 }
8657
8658 pub fn context_menu_next(
8659 &mut self,
8660 _: &ContextMenuNext,
8661 _window: &mut Window,
8662 cx: &mut Context<Self>,
8663 ) {
8664 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8665 context_menu.select_next(self.completion_provider.as_deref(), cx);
8666 }
8667 }
8668
8669 pub fn context_menu_last(
8670 &mut self,
8671 _: &ContextMenuLast,
8672 _window: &mut Window,
8673 cx: &mut Context<Self>,
8674 ) {
8675 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8676 context_menu.select_last(self.completion_provider.as_deref(), cx);
8677 }
8678 }
8679
8680 pub fn move_to_previous_word_start(
8681 &mut self,
8682 _: &MoveToPreviousWordStart,
8683 window: &mut Window,
8684 cx: &mut Context<Self>,
8685 ) {
8686 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8687 s.move_cursors_with(|map, head, _| {
8688 (
8689 movement::previous_word_start(map, head),
8690 SelectionGoal::None,
8691 )
8692 });
8693 })
8694 }
8695
8696 pub fn move_to_previous_subword_start(
8697 &mut self,
8698 _: &MoveToPreviousSubwordStart,
8699 window: &mut Window,
8700 cx: &mut Context<Self>,
8701 ) {
8702 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8703 s.move_cursors_with(|map, head, _| {
8704 (
8705 movement::previous_subword_start(map, head),
8706 SelectionGoal::None,
8707 )
8708 });
8709 })
8710 }
8711
8712 pub fn select_to_previous_word_start(
8713 &mut self,
8714 _: &SelectToPreviousWordStart,
8715 window: &mut Window,
8716 cx: &mut Context<Self>,
8717 ) {
8718 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8719 s.move_heads_with(|map, head, _| {
8720 (
8721 movement::previous_word_start(map, head),
8722 SelectionGoal::None,
8723 )
8724 });
8725 })
8726 }
8727
8728 pub fn select_to_previous_subword_start(
8729 &mut self,
8730 _: &SelectToPreviousSubwordStart,
8731 window: &mut Window,
8732 cx: &mut Context<Self>,
8733 ) {
8734 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8735 s.move_heads_with(|map, head, _| {
8736 (
8737 movement::previous_subword_start(map, head),
8738 SelectionGoal::None,
8739 )
8740 });
8741 })
8742 }
8743
8744 pub fn delete_to_previous_word_start(
8745 &mut self,
8746 action: &DeleteToPreviousWordStart,
8747 window: &mut Window,
8748 cx: &mut Context<Self>,
8749 ) {
8750 self.transact(window, cx, |this, window, cx| {
8751 this.select_autoclose_pair(window, cx);
8752 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8753 let line_mode = s.line_mode;
8754 s.move_with(|map, selection| {
8755 if selection.is_empty() && !line_mode {
8756 let cursor = if action.ignore_newlines {
8757 movement::previous_word_start(map, selection.head())
8758 } else {
8759 movement::previous_word_start_or_newline(map, selection.head())
8760 };
8761 selection.set_head(cursor, SelectionGoal::None);
8762 }
8763 });
8764 });
8765 this.insert("", window, cx);
8766 });
8767 }
8768
8769 pub fn delete_to_previous_subword_start(
8770 &mut self,
8771 _: &DeleteToPreviousSubwordStart,
8772 window: &mut Window,
8773 cx: &mut Context<Self>,
8774 ) {
8775 self.transact(window, cx, |this, window, cx| {
8776 this.select_autoclose_pair(window, cx);
8777 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8778 let line_mode = s.line_mode;
8779 s.move_with(|map, selection| {
8780 if selection.is_empty() && !line_mode {
8781 let cursor = movement::previous_subword_start(map, selection.head());
8782 selection.set_head(cursor, SelectionGoal::None);
8783 }
8784 });
8785 });
8786 this.insert("", window, cx);
8787 });
8788 }
8789
8790 pub fn move_to_next_word_end(
8791 &mut self,
8792 _: &MoveToNextWordEnd,
8793 window: &mut Window,
8794 cx: &mut Context<Self>,
8795 ) {
8796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8797 s.move_cursors_with(|map, head, _| {
8798 (movement::next_word_end(map, head), SelectionGoal::None)
8799 });
8800 })
8801 }
8802
8803 pub fn move_to_next_subword_end(
8804 &mut self,
8805 _: &MoveToNextSubwordEnd,
8806 window: &mut Window,
8807 cx: &mut Context<Self>,
8808 ) {
8809 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8810 s.move_cursors_with(|map, head, _| {
8811 (movement::next_subword_end(map, head), SelectionGoal::None)
8812 });
8813 })
8814 }
8815
8816 pub fn select_to_next_word_end(
8817 &mut self,
8818 _: &SelectToNextWordEnd,
8819 window: &mut Window,
8820 cx: &mut Context<Self>,
8821 ) {
8822 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8823 s.move_heads_with(|map, head, _| {
8824 (movement::next_word_end(map, head), SelectionGoal::None)
8825 });
8826 })
8827 }
8828
8829 pub fn select_to_next_subword_end(
8830 &mut self,
8831 _: &SelectToNextSubwordEnd,
8832 window: &mut Window,
8833 cx: &mut Context<Self>,
8834 ) {
8835 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8836 s.move_heads_with(|map, head, _| {
8837 (movement::next_subword_end(map, head), SelectionGoal::None)
8838 });
8839 })
8840 }
8841
8842 pub fn delete_to_next_word_end(
8843 &mut self,
8844 action: &DeleteToNextWordEnd,
8845 window: &mut Window,
8846 cx: &mut Context<Self>,
8847 ) {
8848 self.transact(window, cx, |this, window, cx| {
8849 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8850 let line_mode = s.line_mode;
8851 s.move_with(|map, selection| {
8852 if selection.is_empty() && !line_mode {
8853 let cursor = if action.ignore_newlines {
8854 movement::next_word_end(map, selection.head())
8855 } else {
8856 movement::next_word_end_or_newline(map, selection.head())
8857 };
8858 selection.set_head(cursor, SelectionGoal::None);
8859 }
8860 });
8861 });
8862 this.insert("", window, cx);
8863 });
8864 }
8865
8866 pub fn delete_to_next_subword_end(
8867 &mut self,
8868 _: &DeleteToNextSubwordEnd,
8869 window: &mut Window,
8870 cx: &mut Context<Self>,
8871 ) {
8872 self.transact(window, cx, |this, window, cx| {
8873 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8874 s.move_with(|map, selection| {
8875 if selection.is_empty() {
8876 let cursor = movement::next_subword_end(map, selection.head());
8877 selection.set_head(cursor, SelectionGoal::None);
8878 }
8879 });
8880 });
8881 this.insert("", window, cx);
8882 });
8883 }
8884
8885 pub fn move_to_beginning_of_line(
8886 &mut self,
8887 action: &MoveToBeginningOfLine,
8888 window: &mut Window,
8889 cx: &mut Context<Self>,
8890 ) {
8891 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8892 s.move_cursors_with(|map, head, _| {
8893 (
8894 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8895 SelectionGoal::None,
8896 )
8897 });
8898 })
8899 }
8900
8901 pub fn select_to_beginning_of_line(
8902 &mut self,
8903 action: &SelectToBeginningOfLine,
8904 window: &mut Window,
8905 cx: &mut Context<Self>,
8906 ) {
8907 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8908 s.move_heads_with(|map, head, _| {
8909 (
8910 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8911 SelectionGoal::None,
8912 )
8913 });
8914 });
8915 }
8916
8917 pub fn delete_to_beginning_of_line(
8918 &mut self,
8919 _: &DeleteToBeginningOfLine,
8920 window: &mut Window,
8921 cx: &mut Context<Self>,
8922 ) {
8923 self.transact(window, cx, |this, window, cx| {
8924 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8925 s.move_with(|_, selection| {
8926 selection.reversed = true;
8927 });
8928 });
8929
8930 this.select_to_beginning_of_line(
8931 &SelectToBeginningOfLine {
8932 stop_at_soft_wraps: false,
8933 },
8934 window,
8935 cx,
8936 );
8937 this.backspace(&Backspace, window, cx);
8938 });
8939 }
8940
8941 pub fn move_to_end_of_line(
8942 &mut self,
8943 action: &MoveToEndOfLine,
8944 window: &mut Window,
8945 cx: &mut Context<Self>,
8946 ) {
8947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8948 s.move_cursors_with(|map, head, _| {
8949 (
8950 movement::line_end(map, head, action.stop_at_soft_wraps),
8951 SelectionGoal::None,
8952 )
8953 });
8954 })
8955 }
8956
8957 pub fn select_to_end_of_line(
8958 &mut self,
8959 action: &SelectToEndOfLine,
8960 window: &mut Window,
8961 cx: &mut Context<Self>,
8962 ) {
8963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8964 s.move_heads_with(|map, head, _| {
8965 (
8966 movement::line_end(map, head, action.stop_at_soft_wraps),
8967 SelectionGoal::None,
8968 )
8969 });
8970 })
8971 }
8972
8973 pub fn delete_to_end_of_line(
8974 &mut self,
8975 _: &DeleteToEndOfLine,
8976 window: &mut Window,
8977 cx: &mut Context<Self>,
8978 ) {
8979 self.transact(window, cx, |this, window, cx| {
8980 this.select_to_end_of_line(
8981 &SelectToEndOfLine {
8982 stop_at_soft_wraps: false,
8983 },
8984 window,
8985 cx,
8986 );
8987 this.delete(&Delete, window, cx);
8988 });
8989 }
8990
8991 pub fn cut_to_end_of_line(
8992 &mut self,
8993 _: &CutToEndOfLine,
8994 window: &mut Window,
8995 cx: &mut Context<Self>,
8996 ) {
8997 self.transact(window, cx, |this, window, cx| {
8998 this.select_to_end_of_line(
8999 &SelectToEndOfLine {
9000 stop_at_soft_wraps: false,
9001 },
9002 window,
9003 cx,
9004 );
9005 this.cut(&Cut, window, cx);
9006 });
9007 }
9008
9009 pub fn move_to_start_of_paragraph(
9010 &mut self,
9011 _: &MoveToStartOfParagraph,
9012 window: &mut Window,
9013 cx: &mut Context<Self>,
9014 ) {
9015 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9016 cx.propagate();
9017 return;
9018 }
9019
9020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9021 s.move_with(|map, selection| {
9022 selection.collapse_to(
9023 movement::start_of_paragraph(map, selection.head(), 1),
9024 SelectionGoal::None,
9025 )
9026 });
9027 })
9028 }
9029
9030 pub fn move_to_end_of_paragraph(
9031 &mut self,
9032 _: &MoveToEndOfParagraph,
9033 window: &mut Window,
9034 cx: &mut Context<Self>,
9035 ) {
9036 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9037 cx.propagate();
9038 return;
9039 }
9040
9041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9042 s.move_with(|map, selection| {
9043 selection.collapse_to(
9044 movement::end_of_paragraph(map, selection.head(), 1),
9045 SelectionGoal::None,
9046 )
9047 });
9048 })
9049 }
9050
9051 pub fn select_to_start_of_paragraph(
9052 &mut self,
9053 _: &SelectToStartOfParagraph,
9054 window: &mut Window,
9055 cx: &mut Context<Self>,
9056 ) {
9057 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9058 cx.propagate();
9059 return;
9060 }
9061
9062 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9063 s.move_heads_with(|map, head, _| {
9064 (
9065 movement::start_of_paragraph(map, head, 1),
9066 SelectionGoal::None,
9067 )
9068 });
9069 })
9070 }
9071
9072 pub fn select_to_end_of_paragraph(
9073 &mut self,
9074 _: &SelectToEndOfParagraph,
9075 window: &mut Window,
9076 cx: &mut Context<Self>,
9077 ) {
9078 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9079 cx.propagate();
9080 return;
9081 }
9082
9083 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9084 s.move_heads_with(|map, head, _| {
9085 (
9086 movement::end_of_paragraph(map, head, 1),
9087 SelectionGoal::None,
9088 )
9089 });
9090 })
9091 }
9092
9093 pub fn move_to_beginning(
9094 &mut self,
9095 _: &MoveToBeginning,
9096 window: &mut Window,
9097 cx: &mut Context<Self>,
9098 ) {
9099 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9100 cx.propagate();
9101 return;
9102 }
9103
9104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9105 s.select_ranges(vec![0..0]);
9106 });
9107 }
9108
9109 pub fn select_to_beginning(
9110 &mut self,
9111 _: &SelectToBeginning,
9112 window: &mut Window,
9113 cx: &mut Context<Self>,
9114 ) {
9115 let mut selection = self.selections.last::<Point>(cx);
9116 selection.set_head(Point::zero(), SelectionGoal::None);
9117
9118 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9119 s.select(vec![selection]);
9120 });
9121 }
9122
9123 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9124 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9125 cx.propagate();
9126 return;
9127 }
9128
9129 let cursor = self.buffer.read(cx).read(cx).len();
9130 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9131 s.select_ranges(vec![cursor..cursor])
9132 });
9133 }
9134
9135 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9136 self.nav_history = nav_history;
9137 }
9138
9139 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9140 self.nav_history.as_ref()
9141 }
9142
9143 fn push_to_nav_history(
9144 &mut self,
9145 cursor_anchor: Anchor,
9146 new_position: Option<Point>,
9147 cx: &mut Context<Self>,
9148 ) {
9149 if let Some(nav_history) = self.nav_history.as_mut() {
9150 let buffer = self.buffer.read(cx).read(cx);
9151 let cursor_position = cursor_anchor.to_point(&buffer);
9152 let scroll_state = self.scroll_manager.anchor();
9153 let scroll_top_row = scroll_state.top_row(&buffer);
9154 drop(buffer);
9155
9156 if let Some(new_position) = new_position {
9157 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9158 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9159 return;
9160 }
9161 }
9162
9163 nav_history.push(
9164 Some(NavigationData {
9165 cursor_anchor,
9166 cursor_position,
9167 scroll_anchor: scroll_state,
9168 scroll_top_row,
9169 }),
9170 cx,
9171 );
9172 }
9173 }
9174
9175 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9176 let buffer = self.buffer.read(cx).snapshot(cx);
9177 let mut selection = self.selections.first::<usize>(cx);
9178 selection.set_head(buffer.len(), SelectionGoal::None);
9179 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9180 s.select(vec![selection]);
9181 });
9182 }
9183
9184 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9185 let end = self.buffer.read(cx).read(cx).len();
9186 self.change_selections(None, window, cx, |s| {
9187 s.select_ranges(vec![0..end]);
9188 });
9189 }
9190
9191 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9193 let mut selections = self.selections.all::<Point>(cx);
9194 let max_point = display_map.buffer_snapshot.max_point();
9195 for selection in &mut selections {
9196 let rows = selection.spanned_rows(true, &display_map);
9197 selection.start = Point::new(rows.start.0, 0);
9198 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9199 selection.reversed = false;
9200 }
9201 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9202 s.select(selections);
9203 });
9204 }
9205
9206 pub fn split_selection_into_lines(
9207 &mut self,
9208 _: &SplitSelectionIntoLines,
9209 window: &mut Window,
9210 cx: &mut Context<Self>,
9211 ) {
9212 let selections = self
9213 .selections
9214 .all::<Point>(cx)
9215 .into_iter()
9216 .map(|selection| selection.start..selection.end)
9217 .collect::<Vec<_>>();
9218 self.unfold_ranges(&selections, true, true, cx);
9219
9220 let mut new_selection_ranges = Vec::new();
9221 {
9222 let buffer = self.buffer.read(cx).read(cx);
9223 for selection in selections {
9224 for row in selection.start.row..selection.end.row {
9225 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9226 new_selection_ranges.push(cursor..cursor);
9227 }
9228
9229 let is_multiline_selection = selection.start.row != selection.end.row;
9230 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9231 // so this action feels more ergonomic when paired with other selection operations
9232 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9233 if !should_skip_last {
9234 new_selection_ranges.push(selection.end..selection.end);
9235 }
9236 }
9237 }
9238 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9239 s.select_ranges(new_selection_ranges);
9240 });
9241 }
9242
9243 pub fn add_selection_above(
9244 &mut self,
9245 _: &AddSelectionAbove,
9246 window: &mut Window,
9247 cx: &mut Context<Self>,
9248 ) {
9249 self.add_selection(true, window, cx);
9250 }
9251
9252 pub fn add_selection_below(
9253 &mut self,
9254 _: &AddSelectionBelow,
9255 window: &mut Window,
9256 cx: &mut Context<Self>,
9257 ) {
9258 self.add_selection(false, window, cx);
9259 }
9260
9261 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9263 let mut selections = self.selections.all::<Point>(cx);
9264 let text_layout_details = self.text_layout_details(window);
9265 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9266 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9267 let range = oldest_selection.display_range(&display_map).sorted();
9268
9269 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9270 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9271 let positions = start_x.min(end_x)..start_x.max(end_x);
9272
9273 selections.clear();
9274 let mut stack = Vec::new();
9275 for row in range.start.row().0..=range.end.row().0 {
9276 if let Some(selection) = self.selections.build_columnar_selection(
9277 &display_map,
9278 DisplayRow(row),
9279 &positions,
9280 oldest_selection.reversed,
9281 &text_layout_details,
9282 ) {
9283 stack.push(selection.id);
9284 selections.push(selection);
9285 }
9286 }
9287
9288 if above {
9289 stack.reverse();
9290 }
9291
9292 AddSelectionsState { above, stack }
9293 });
9294
9295 let last_added_selection = *state.stack.last().unwrap();
9296 let mut new_selections = Vec::new();
9297 if above == state.above {
9298 let end_row = if above {
9299 DisplayRow(0)
9300 } else {
9301 display_map.max_point().row()
9302 };
9303
9304 'outer: for selection in selections {
9305 if selection.id == last_added_selection {
9306 let range = selection.display_range(&display_map).sorted();
9307 debug_assert_eq!(range.start.row(), range.end.row());
9308 let mut row = range.start.row();
9309 let positions =
9310 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9311 px(start)..px(end)
9312 } else {
9313 let start_x =
9314 display_map.x_for_display_point(range.start, &text_layout_details);
9315 let end_x =
9316 display_map.x_for_display_point(range.end, &text_layout_details);
9317 start_x.min(end_x)..start_x.max(end_x)
9318 };
9319
9320 while row != end_row {
9321 if above {
9322 row.0 -= 1;
9323 } else {
9324 row.0 += 1;
9325 }
9326
9327 if let Some(new_selection) = self.selections.build_columnar_selection(
9328 &display_map,
9329 row,
9330 &positions,
9331 selection.reversed,
9332 &text_layout_details,
9333 ) {
9334 state.stack.push(new_selection.id);
9335 if above {
9336 new_selections.push(new_selection);
9337 new_selections.push(selection);
9338 } else {
9339 new_selections.push(selection);
9340 new_selections.push(new_selection);
9341 }
9342
9343 continue 'outer;
9344 }
9345 }
9346 }
9347
9348 new_selections.push(selection);
9349 }
9350 } else {
9351 new_selections = selections;
9352 new_selections.retain(|s| s.id != last_added_selection);
9353 state.stack.pop();
9354 }
9355
9356 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9357 s.select(new_selections);
9358 });
9359 if state.stack.len() > 1 {
9360 self.add_selections_state = Some(state);
9361 }
9362 }
9363
9364 pub fn select_next_match_internal(
9365 &mut self,
9366 display_map: &DisplaySnapshot,
9367 replace_newest: bool,
9368 autoscroll: Option<Autoscroll>,
9369 window: &mut Window,
9370 cx: &mut Context<Self>,
9371 ) -> Result<()> {
9372 fn select_next_match_ranges(
9373 this: &mut Editor,
9374 range: Range<usize>,
9375 replace_newest: bool,
9376 auto_scroll: Option<Autoscroll>,
9377 window: &mut Window,
9378 cx: &mut Context<Editor>,
9379 ) {
9380 this.unfold_ranges(&[range.clone()], false, true, cx);
9381 this.change_selections(auto_scroll, window, cx, |s| {
9382 if replace_newest {
9383 s.delete(s.newest_anchor().id);
9384 }
9385 s.insert_range(range.clone());
9386 });
9387 }
9388
9389 let buffer = &display_map.buffer_snapshot;
9390 let mut selections = self.selections.all::<usize>(cx);
9391 if let Some(mut select_next_state) = self.select_next_state.take() {
9392 let query = &select_next_state.query;
9393 if !select_next_state.done {
9394 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9395 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9396 let mut next_selected_range = None;
9397
9398 let bytes_after_last_selection =
9399 buffer.bytes_in_range(last_selection.end..buffer.len());
9400 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9401 let query_matches = query
9402 .stream_find_iter(bytes_after_last_selection)
9403 .map(|result| (last_selection.end, result))
9404 .chain(
9405 query
9406 .stream_find_iter(bytes_before_first_selection)
9407 .map(|result| (0, result)),
9408 );
9409
9410 for (start_offset, query_match) in query_matches {
9411 let query_match = query_match.unwrap(); // can only fail due to I/O
9412 let offset_range =
9413 start_offset + query_match.start()..start_offset + query_match.end();
9414 let display_range = offset_range.start.to_display_point(display_map)
9415 ..offset_range.end.to_display_point(display_map);
9416
9417 if !select_next_state.wordwise
9418 || (!movement::is_inside_word(display_map, display_range.start)
9419 && !movement::is_inside_word(display_map, display_range.end))
9420 {
9421 // TODO: This is n^2, because we might check all the selections
9422 if !selections
9423 .iter()
9424 .any(|selection| selection.range().overlaps(&offset_range))
9425 {
9426 next_selected_range = Some(offset_range);
9427 break;
9428 }
9429 }
9430 }
9431
9432 if let Some(next_selected_range) = next_selected_range {
9433 select_next_match_ranges(
9434 self,
9435 next_selected_range,
9436 replace_newest,
9437 autoscroll,
9438 window,
9439 cx,
9440 );
9441 } else {
9442 select_next_state.done = true;
9443 }
9444 }
9445
9446 self.select_next_state = Some(select_next_state);
9447 } else {
9448 let mut only_carets = true;
9449 let mut same_text_selected = true;
9450 let mut selected_text = None;
9451
9452 let mut selections_iter = selections.iter().peekable();
9453 while let Some(selection) = selections_iter.next() {
9454 if selection.start != selection.end {
9455 only_carets = false;
9456 }
9457
9458 if same_text_selected {
9459 if selected_text.is_none() {
9460 selected_text =
9461 Some(buffer.text_for_range(selection.range()).collect::<String>());
9462 }
9463
9464 if let Some(next_selection) = selections_iter.peek() {
9465 if next_selection.range().len() == selection.range().len() {
9466 let next_selected_text = buffer
9467 .text_for_range(next_selection.range())
9468 .collect::<String>();
9469 if Some(next_selected_text) != selected_text {
9470 same_text_selected = false;
9471 selected_text = None;
9472 }
9473 } else {
9474 same_text_selected = false;
9475 selected_text = None;
9476 }
9477 }
9478 }
9479 }
9480
9481 if only_carets {
9482 for selection in &mut selections {
9483 let word_range = movement::surrounding_word(
9484 display_map,
9485 selection.start.to_display_point(display_map),
9486 );
9487 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9488 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9489 selection.goal = SelectionGoal::None;
9490 selection.reversed = false;
9491 select_next_match_ranges(
9492 self,
9493 selection.start..selection.end,
9494 replace_newest,
9495 autoscroll,
9496 window,
9497 cx,
9498 );
9499 }
9500
9501 if selections.len() == 1 {
9502 let selection = selections
9503 .last()
9504 .expect("ensured that there's only one selection");
9505 let query = buffer
9506 .text_for_range(selection.start..selection.end)
9507 .collect::<String>();
9508 let is_empty = query.is_empty();
9509 let select_state = SelectNextState {
9510 query: AhoCorasick::new(&[query])?,
9511 wordwise: true,
9512 done: is_empty,
9513 };
9514 self.select_next_state = Some(select_state);
9515 } else {
9516 self.select_next_state = None;
9517 }
9518 } else if let Some(selected_text) = selected_text {
9519 self.select_next_state = Some(SelectNextState {
9520 query: AhoCorasick::new(&[selected_text])?,
9521 wordwise: false,
9522 done: false,
9523 });
9524 self.select_next_match_internal(
9525 display_map,
9526 replace_newest,
9527 autoscroll,
9528 window,
9529 cx,
9530 )?;
9531 }
9532 }
9533 Ok(())
9534 }
9535
9536 pub fn select_all_matches(
9537 &mut self,
9538 _action: &SelectAllMatches,
9539 window: &mut Window,
9540 cx: &mut Context<Self>,
9541 ) -> Result<()> {
9542 self.push_to_selection_history();
9543 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9544
9545 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9546 let Some(select_next_state) = self.select_next_state.as_mut() else {
9547 return Ok(());
9548 };
9549 if select_next_state.done {
9550 return Ok(());
9551 }
9552
9553 let mut new_selections = self.selections.all::<usize>(cx);
9554
9555 let buffer = &display_map.buffer_snapshot;
9556 let query_matches = select_next_state
9557 .query
9558 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9559
9560 for query_match in query_matches {
9561 let query_match = query_match.unwrap(); // can only fail due to I/O
9562 let offset_range = query_match.start()..query_match.end();
9563 let display_range = offset_range.start.to_display_point(&display_map)
9564 ..offset_range.end.to_display_point(&display_map);
9565
9566 if !select_next_state.wordwise
9567 || (!movement::is_inside_word(&display_map, display_range.start)
9568 && !movement::is_inside_word(&display_map, display_range.end))
9569 {
9570 self.selections.change_with(cx, |selections| {
9571 new_selections.push(Selection {
9572 id: selections.new_selection_id(),
9573 start: offset_range.start,
9574 end: offset_range.end,
9575 reversed: false,
9576 goal: SelectionGoal::None,
9577 });
9578 });
9579 }
9580 }
9581
9582 new_selections.sort_by_key(|selection| selection.start);
9583 let mut ix = 0;
9584 while ix + 1 < new_selections.len() {
9585 let current_selection = &new_selections[ix];
9586 let next_selection = &new_selections[ix + 1];
9587 if current_selection.range().overlaps(&next_selection.range()) {
9588 if current_selection.id < next_selection.id {
9589 new_selections.remove(ix + 1);
9590 } else {
9591 new_selections.remove(ix);
9592 }
9593 } else {
9594 ix += 1;
9595 }
9596 }
9597
9598 let reversed = self.selections.oldest::<usize>(cx).reversed;
9599
9600 for selection in new_selections.iter_mut() {
9601 selection.reversed = reversed;
9602 }
9603
9604 select_next_state.done = true;
9605 self.unfold_ranges(
9606 &new_selections
9607 .iter()
9608 .map(|selection| selection.range())
9609 .collect::<Vec<_>>(),
9610 false,
9611 false,
9612 cx,
9613 );
9614 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9615 selections.select(new_selections)
9616 });
9617
9618 Ok(())
9619 }
9620
9621 pub fn select_next(
9622 &mut self,
9623 action: &SelectNext,
9624 window: &mut Window,
9625 cx: &mut Context<Self>,
9626 ) -> Result<()> {
9627 self.push_to_selection_history();
9628 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9629 self.select_next_match_internal(
9630 &display_map,
9631 action.replace_newest,
9632 Some(Autoscroll::newest()),
9633 window,
9634 cx,
9635 )?;
9636 Ok(())
9637 }
9638
9639 pub fn select_previous(
9640 &mut self,
9641 action: &SelectPrevious,
9642 window: &mut Window,
9643 cx: &mut Context<Self>,
9644 ) -> Result<()> {
9645 self.push_to_selection_history();
9646 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9647 let buffer = &display_map.buffer_snapshot;
9648 let mut selections = self.selections.all::<usize>(cx);
9649 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9650 let query = &select_prev_state.query;
9651 if !select_prev_state.done {
9652 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9653 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9654 let mut next_selected_range = None;
9655 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9656 let bytes_before_last_selection =
9657 buffer.reversed_bytes_in_range(0..last_selection.start);
9658 let bytes_after_first_selection =
9659 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9660 let query_matches = query
9661 .stream_find_iter(bytes_before_last_selection)
9662 .map(|result| (last_selection.start, result))
9663 .chain(
9664 query
9665 .stream_find_iter(bytes_after_first_selection)
9666 .map(|result| (buffer.len(), result)),
9667 );
9668 for (end_offset, query_match) in query_matches {
9669 let query_match = query_match.unwrap(); // can only fail due to I/O
9670 let offset_range =
9671 end_offset - query_match.end()..end_offset - query_match.start();
9672 let display_range = offset_range.start.to_display_point(&display_map)
9673 ..offset_range.end.to_display_point(&display_map);
9674
9675 if !select_prev_state.wordwise
9676 || (!movement::is_inside_word(&display_map, display_range.start)
9677 && !movement::is_inside_word(&display_map, display_range.end))
9678 {
9679 next_selected_range = Some(offset_range);
9680 break;
9681 }
9682 }
9683
9684 if let Some(next_selected_range) = next_selected_range {
9685 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9686 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9687 if action.replace_newest {
9688 s.delete(s.newest_anchor().id);
9689 }
9690 s.insert_range(next_selected_range);
9691 });
9692 } else {
9693 select_prev_state.done = true;
9694 }
9695 }
9696
9697 self.select_prev_state = Some(select_prev_state);
9698 } else {
9699 let mut only_carets = true;
9700 let mut same_text_selected = true;
9701 let mut selected_text = None;
9702
9703 let mut selections_iter = selections.iter().peekable();
9704 while let Some(selection) = selections_iter.next() {
9705 if selection.start != selection.end {
9706 only_carets = false;
9707 }
9708
9709 if same_text_selected {
9710 if selected_text.is_none() {
9711 selected_text =
9712 Some(buffer.text_for_range(selection.range()).collect::<String>());
9713 }
9714
9715 if let Some(next_selection) = selections_iter.peek() {
9716 if next_selection.range().len() == selection.range().len() {
9717 let next_selected_text = buffer
9718 .text_for_range(next_selection.range())
9719 .collect::<String>();
9720 if Some(next_selected_text) != selected_text {
9721 same_text_selected = false;
9722 selected_text = None;
9723 }
9724 } else {
9725 same_text_selected = false;
9726 selected_text = None;
9727 }
9728 }
9729 }
9730 }
9731
9732 if only_carets {
9733 for selection in &mut selections {
9734 let word_range = movement::surrounding_word(
9735 &display_map,
9736 selection.start.to_display_point(&display_map),
9737 );
9738 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9739 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9740 selection.goal = SelectionGoal::None;
9741 selection.reversed = false;
9742 }
9743 if selections.len() == 1 {
9744 let selection = selections
9745 .last()
9746 .expect("ensured that there's only one selection");
9747 let query = buffer
9748 .text_for_range(selection.start..selection.end)
9749 .collect::<String>();
9750 let is_empty = query.is_empty();
9751 let select_state = SelectNextState {
9752 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9753 wordwise: true,
9754 done: is_empty,
9755 };
9756 self.select_prev_state = Some(select_state);
9757 } else {
9758 self.select_prev_state = None;
9759 }
9760
9761 self.unfold_ranges(
9762 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9763 false,
9764 true,
9765 cx,
9766 );
9767 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9768 s.select(selections);
9769 });
9770 } else if let Some(selected_text) = selected_text {
9771 self.select_prev_state = Some(SelectNextState {
9772 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9773 wordwise: false,
9774 done: false,
9775 });
9776 self.select_previous(action, window, cx)?;
9777 }
9778 }
9779 Ok(())
9780 }
9781
9782 pub fn toggle_comments(
9783 &mut self,
9784 action: &ToggleComments,
9785 window: &mut Window,
9786 cx: &mut Context<Self>,
9787 ) {
9788 if self.read_only(cx) {
9789 return;
9790 }
9791 let text_layout_details = &self.text_layout_details(window);
9792 self.transact(window, cx, |this, window, cx| {
9793 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9794 let mut edits = Vec::new();
9795 let mut selection_edit_ranges = Vec::new();
9796 let mut last_toggled_row = None;
9797 let snapshot = this.buffer.read(cx).read(cx);
9798 let empty_str: Arc<str> = Arc::default();
9799 let mut suffixes_inserted = Vec::new();
9800 let ignore_indent = action.ignore_indent;
9801
9802 fn comment_prefix_range(
9803 snapshot: &MultiBufferSnapshot,
9804 row: MultiBufferRow,
9805 comment_prefix: &str,
9806 comment_prefix_whitespace: &str,
9807 ignore_indent: bool,
9808 ) -> Range<Point> {
9809 let indent_size = if ignore_indent {
9810 0
9811 } else {
9812 snapshot.indent_size_for_line(row).len
9813 };
9814
9815 let start = Point::new(row.0, indent_size);
9816
9817 let mut line_bytes = snapshot
9818 .bytes_in_range(start..snapshot.max_point())
9819 .flatten()
9820 .copied();
9821
9822 // If this line currently begins with the line comment prefix, then record
9823 // the range containing the prefix.
9824 if line_bytes
9825 .by_ref()
9826 .take(comment_prefix.len())
9827 .eq(comment_prefix.bytes())
9828 {
9829 // Include any whitespace that matches the comment prefix.
9830 let matching_whitespace_len = line_bytes
9831 .zip(comment_prefix_whitespace.bytes())
9832 .take_while(|(a, b)| a == b)
9833 .count() as u32;
9834 let end = Point::new(
9835 start.row,
9836 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9837 );
9838 start..end
9839 } else {
9840 start..start
9841 }
9842 }
9843
9844 fn comment_suffix_range(
9845 snapshot: &MultiBufferSnapshot,
9846 row: MultiBufferRow,
9847 comment_suffix: &str,
9848 comment_suffix_has_leading_space: bool,
9849 ) -> Range<Point> {
9850 let end = Point::new(row.0, snapshot.line_len(row));
9851 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9852
9853 let mut line_end_bytes = snapshot
9854 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9855 .flatten()
9856 .copied();
9857
9858 let leading_space_len = if suffix_start_column > 0
9859 && line_end_bytes.next() == Some(b' ')
9860 && comment_suffix_has_leading_space
9861 {
9862 1
9863 } else {
9864 0
9865 };
9866
9867 // If this line currently begins with the line comment prefix, then record
9868 // the range containing the prefix.
9869 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9870 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9871 start..end
9872 } else {
9873 end..end
9874 }
9875 }
9876
9877 // TODO: Handle selections that cross excerpts
9878 for selection in &mut selections {
9879 let start_column = snapshot
9880 .indent_size_for_line(MultiBufferRow(selection.start.row))
9881 .len;
9882 let language = if let Some(language) =
9883 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9884 {
9885 language
9886 } else {
9887 continue;
9888 };
9889
9890 selection_edit_ranges.clear();
9891
9892 // If multiple selections contain a given row, avoid processing that
9893 // row more than once.
9894 let mut start_row = MultiBufferRow(selection.start.row);
9895 if last_toggled_row == Some(start_row) {
9896 start_row = start_row.next_row();
9897 }
9898 let end_row =
9899 if selection.end.row > selection.start.row && selection.end.column == 0 {
9900 MultiBufferRow(selection.end.row - 1)
9901 } else {
9902 MultiBufferRow(selection.end.row)
9903 };
9904 last_toggled_row = Some(end_row);
9905
9906 if start_row > end_row {
9907 continue;
9908 }
9909
9910 // If the language has line comments, toggle those.
9911 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9912
9913 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9914 if ignore_indent {
9915 full_comment_prefixes = full_comment_prefixes
9916 .into_iter()
9917 .map(|s| Arc::from(s.trim_end()))
9918 .collect();
9919 }
9920
9921 if !full_comment_prefixes.is_empty() {
9922 let first_prefix = full_comment_prefixes
9923 .first()
9924 .expect("prefixes is non-empty");
9925 let prefix_trimmed_lengths = full_comment_prefixes
9926 .iter()
9927 .map(|p| p.trim_end_matches(' ').len())
9928 .collect::<SmallVec<[usize; 4]>>();
9929
9930 let mut all_selection_lines_are_comments = true;
9931
9932 for row in start_row.0..=end_row.0 {
9933 let row = MultiBufferRow(row);
9934 if start_row < end_row && snapshot.is_line_blank(row) {
9935 continue;
9936 }
9937
9938 let prefix_range = full_comment_prefixes
9939 .iter()
9940 .zip(prefix_trimmed_lengths.iter().copied())
9941 .map(|(prefix, trimmed_prefix_len)| {
9942 comment_prefix_range(
9943 snapshot.deref(),
9944 row,
9945 &prefix[..trimmed_prefix_len],
9946 &prefix[trimmed_prefix_len..],
9947 ignore_indent,
9948 )
9949 })
9950 .max_by_key(|range| range.end.column - range.start.column)
9951 .expect("prefixes is non-empty");
9952
9953 if prefix_range.is_empty() {
9954 all_selection_lines_are_comments = false;
9955 }
9956
9957 selection_edit_ranges.push(prefix_range);
9958 }
9959
9960 if all_selection_lines_are_comments {
9961 edits.extend(
9962 selection_edit_ranges
9963 .iter()
9964 .cloned()
9965 .map(|range| (range, empty_str.clone())),
9966 );
9967 } else {
9968 let min_column = selection_edit_ranges
9969 .iter()
9970 .map(|range| range.start.column)
9971 .min()
9972 .unwrap_or(0);
9973 edits.extend(selection_edit_ranges.iter().map(|range| {
9974 let position = Point::new(range.start.row, min_column);
9975 (position..position, first_prefix.clone())
9976 }));
9977 }
9978 } else if let Some((full_comment_prefix, comment_suffix)) =
9979 language.block_comment_delimiters()
9980 {
9981 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9982 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9983 let prefix_range = comment_prefix_range(
9984 snapshot.deref(),
9985 start_row,
9986 comment_prefix,
9987 comment_prefix_whitespace,
9988 ignore_indent,
9989 );
9990 let suffix_range = comment_suffix_range(
9991 snapshot.deref(),
9992 end_row,
9993 comment_suffix.trim_start_matches(' '),
9994 comment_suffix.starts_with(' '),
9995 );
9996
9997 if prefix_range.is_empty() || suffix_range.is_empty() {
9998 edits.push((
9999 prefix_range.start..prefix_range.start,
10000 full_comment_prefix.clone(),
10001 ));
10002 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10003 suffixes_inserted.push((end_row, comment_suffix.len()));
10004 } else {
10005 edits.push((prefix_range, empty_str.clone()));
10006 edits.push((suffix_range, empty_str.clone()));
10007 }
10008 } else {
10009 continue;
10010 }
10011 }
10012
10013 drop(snapshot);
10014 this.buffer.update(cx, |buffer, cx| {
10015 buffer.edit(edits, None, cx);
10016 });
10017
10018 // Adjust selections so that they end before any comment suffixes that
10019 // were inserted.
10020 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10021 let mut selections = this.selections.all::<Point>(cx);
10022 let snapshot = this.buffer.read(cx).read(cx);
10023 for selection in &mut selections {
10024 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10025 match row.cmp(&MultiBufferRow(selection.end.row)) {
10026 Ordering::Less => {
10027 suffixes_inserted.next();
10028 continue;
10029 }
10030 Ordering::Greater => break,
10031 Ordering::Equal => {
10032 if selection.end.column == snapshot.line_len(row) {
10033 if selection.is_empty() {
10034 selection.start.column -= suffix_len as u32;
10035 }
10036 selection.end.column -= suffix_len as u32;
10037 }
10038 break;
10039 }
10040 }
10041 }
10042 }
10043
10044 drop(snapshot);
10045 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10046 s.select(selections)
10047 });
10048
10049 let selections = this.selections.all::<Point>(cx);
10050 let selections_on_single_row = selections.windows(2).all(|selections| {
10051 selections[0].start.row == selections[1].start.row
10052 && selections[0].end.row == selections[1].end.row
10053 && selections[0].start.row == selections[0].end.row
10054 });
10055 let selections_selecting = selections
10056 .iter()
10057 .any(|selection| selection.start != selection.end);
10058 let advance_downwards = action.advance_downwards
10059 && selections_on_single_row
10060 && !selections_selecting
10061 && !matches!(this.mode, EditorMode::SingleLine { .. });
10062
10063 if advance_downwards {
10064 let snapshot = this.buffer.read(cx).snapshot(cx);
10065
10066 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10067 s.move_cursors_with(|display_snapshot, display_point, _| {
10068 let mut point = display_point.to_point(display_snapshot);
10069 point.row += 1;
10070 point = snapshot.clip_point(point, Bias::Left);
10071 let display_point = point.to_display_point(display_snapshot);
10072 let goal = SelectionGoal::HorizontalPosition(
10073 display_snapshot
10074 .x_for_display_point(display_point, text_layout_details)
10075 .into(),
10076 );
10077 (display_point, goal)
10078 })
10079 });
10080 }
10081 });
10082 }
10083
10084 pub fn select_enclosing_symbol(
10085 &mut self,
10086 _: &SelectEnclosingSymbol,
10087 window: &mut Window,
10088 cx: &mut Context<Self>,
10089 ) {
10090 let buffer = self.buffer.read(cx).snapshot(cx);
10091 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10092
10093 fn update_selection(
10094 selection: &Selection<usize>,
10095 buffer_snap: &MultiBufferSnapshot,
10096 ) -> Option<Selection<usize>> {
10097 let cursor = selection.head();
10098 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10099 for symbol in symbols.iter().rev() {
10100 let start = symbol.range.start.to_offset(buffer_snap);
10101 let end = symbol.range.end.to_offset(buffer_snap);
10102 let new_range = start..end;
10103 if start < selection.start || end > selection.end {
10104 return Some(Selection {
10105 id: selection.id,
10106 start: new_range.start,
10107 end: new_range.end,
10108 goal: SelectionGoal::None,
10109 reversed: selection.reversed,
10110 });
10111 }
10112 }
10113 None
10114 }
10115
10116 let mut selected_larger_symbol = false;
10117 let new_selections = old_selections
10118 .iter()
10119 .map(|selection| match update_selection(selection, &buffer) {
10120 Some(new_selection) => {
10121 if new_selection.range() != selection.range() {
10122 selected_larger_symbol = true;
10123 }
10124 new_selection
10125 }
10126 None => selection.clone(),
10127 })
10128 .collect::<Vec<_>>();
10129
10130 if selected_larger_symbol {
10131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10132 s.select(new_selections);
10133 });
10134 }
10135 }
10136
10137 pub fn select_larger_syntax_node(
10138 &mut self,
10139 _: &SelectLargerSyntaxNode,
10140 window: &mut Window,
10141 cx: &mut Context<Self>,
10142 ) {
10143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10144 let buffer = self.buffer.read(cx).snapshot(cx);
10145 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10146
10147 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10148 let mut selected_larger_node = false;
10149 let new_selections = old_selections
10150 .iter()
10151 .map(|selection| {
10152 let old_range = selection.start..selection.end;
10153 let mut new_range = old_range.clone();
10154 let mut new_node = None;
10155 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10156 {
10157 new_node = Some(node);
10158 new_range = containing_range;
10159 if !display_map.intersects_fold(new_range.start)
10160 && !display_map.intersects_fold(new_range.end)
10161 {
10162 break;
10163 }
10164 }
10165
10166 if let Some(node) = new_node {
10167 // Log the ancestor, to support using this action as a way to explore TreeSitter
10168 // nodes. Parent and grandparent are also logged because this operation will not
10169 // visit nodes that have the same range as their parent.
10170 log::info!("Node: {node:?}");
10171 let parent = node.parent();
10172 log::info!("Parent: {parent:?}");
10173 let grandparent = parent.and_then(|x| x.parent());
10174 log::info!("Grandparent: {grandparent:?}");
10175 }
10176
10177 selected_larger_node |= new_range != old_range;
10178 Selection {
10179 id: selection.id,
10180 start: new_range.start,
10181 end: new_range.end,
10182 goal: SelectionGoal::None,
10183 reversed: selection.reversed,
10184 }
10185 })
10186 .collect::<Vec<_>>();
10187
10188 if selected_larger_node {
10189 stack.push(old_selections);
10190 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10191 s.select(new_selections);
10192 });
10193 }
10194 self.select_larger_syntax_node_stack = stack;
10195 }
10196
10197 pub fn select_smaller_syntax_node(
10198 &mut self,
10199 _: &SelectSmallerSyntaxNode,
10200 window: &mut Window,
10201 cx: &mut Context<Self>,
10202 ) {
10203 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10204 if let Some(selections) = stack.pop() {
10205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10206 s.select(selections.to_vec());
10207 });
10208 }
10209 self.select_larger_syntax_node_stack = stack;
10210 }
10211
10212 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10213 if !EditorSettings::get_global(cx).gutter.runnables {
10214 self.clear_tasks();
10215 return Task::ready(());
10216 }
10217 let project = self.project.as_ref().map(Entity::downgrade);
10218 cx.spawn_in(window, |this, mut cx| async move {
10219 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10220 let Some(project) = project.and_then(|p| p.upgrade()) else {
10221 return;
10222 };
10223 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10224 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10225 }) else {
10226 return;
10227 };
10228
10229 let hide_runnables = project
10230 .update(&mut cx, |project, cx| {
10231 // Do not display any test indicators in non-dev server remote projects.
10232 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10233 })
10234 .unwrap_or(true);
10235 if hide_runnables {
10236 return;
10237 }
10238 let new_rows =
10239 cx.background_spawn({
10240 let snapshot = display_snapshot.clone();
10241 async move {
10242 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10243 }
10244 })
10245 .await;
10246
10247 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10248 this.update(&mut cx, |this, _| {
10249 this.clear_tasks();
10250 for (key, value) in rows {
10251 this.insert_tasks(key, value);
10252 }
10253 })
10254 .ok();
10255 })
10256 }
10257 fn fetch_runnable_ranges(
10258 snapshot: &DisplaySnapshot,
10259 range: Range<Anchor>,
10260 ) -> Vec<language::RunnableRange> {
10261 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10262 }
10263
10264 fn runnable_rows(
10265 project: Entity<Project>,
10266 snapshot: DisplaySnapshot,
10267 runnable_ranges: Vec<RunnableRange>,
10268 mut cx: AsyncWindowContext,
10269 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10270 runnable_ranges
10271 .into_iter()
10272 .filter_map(|mut runnable| {
10273 let tasks = cx
10274 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10275 .ok()?;
10276 if tasks.is_empty() {
10277 return None;
10278 }
10279
10280 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10281
10282 let row = snapshot
10283 .buffer_snapshot
10284 .buffer_line_for_row(MultiBufferRow(point.row))?
10285 .1
10286 .start
10287 .row;
10288
10289 let context_range =
10290 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10291 Some((
10292 (runnable.buffer_id, row),
10293 RunnableTasks {
10294 templates: tasks,
10295 offset: MultiBufferOffset(runnable.run_range.start),
10296 context_range,
10297 column: point.column,
10298 extra_variables: runnable.extra_captures,
10299 },
10300 ))
10301 })
10302 .collect()
10303 }
10304
10305 fn templates_with_tags(
10306 project: &Entity<Project>,
10307 runnable: &mut Runnable,
10308 cx: &mut App,
10309 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10310 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10311 let (worktree_id, file) = project
10312 .buffer_for_id(runnable.buffer, cx)
10313 .and_then(|buffer| buffer.read(cx).file())
10314 .map(|file| (file.worktree_id(cx), file.clone()))
10315 .unzip();
10316
10317 (
10318 project.task_store().read(cx).task_inventory().cloned(),
10319 worktree_id,
10320 file,
10321 )
10322 });
10323
10324 let tags = mem::take(&mut runnable.tags);
10325 let mut tags: Vec<_> = tags
10326 .into_iter()
10327 .flat_map(|tag| {
10328 let tag = tag.0.clone();
10329 inventory
10330 .as_ref()
10331 .into_iter()
10332 .flat_map(|inventory| {
10333 inventory.read(cx).list_tasks(
10334 file.clone(),
10335 Some(runnable.language.clone()),
10336 worktree_id,
10337 cx,
10338 )
10339 })
10340 .filter(move |(_, template)| {
10341 template.tags.iter().any(|source_tag| source_tag == &tag)
10342 })
10343 })
10344 .sorted_by_key(|(kind, _)| kind.to_owned())
10345 .collect();
10346 if let Some((leading_tag_source, _)) = tags.first() {
10347 // Strongest source wins; if we have worktree tag binding, prefer that to
10348 // global and language bindings;
10349 // if we have a global binding, prefer that to language binding.
10350 let first_mismatch = tags
10351 .iter()
10352 .position(|(tag_source, _)| tag_source != leading_tag_source);
10353 if let Some(index) = first_mismatch {
10354 tags.truncate(index);
10355 }
10356 }
10357
10358 tags
10359 }
10360
10361 pub fn move_to_enclosing_bracket(
10362 &mut self,
10363 _: &MoveToEnclosingBracket,
10364 window: &mut Window,
10365 cx: &mut Context<Self>,
10366 ) {
10367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10368 s.move_offsets_with(|snapshot, selection| {
10369 let Some(enclosing_bracket_ranges) =
10370 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10371 else {
10372 return;
10373 };
10374
10375 let mut best_length = usize::MAX;
10376 let mut best_inside = false;
10377 let mut best_in_bracket_range = false;
10378 let mut best_destination = None;
10379 for (open, close) in enclosing_bracket_ranges {
10380 let close = close.to_inclusive();
10381 let length = close.end() - open.start;
10382 let inside = selection.start >= open.end && selection.end <= *close.start();
10383 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10384 || close.contains(&selection.head());
10385
10386 // If best is next to a bracket and current isn't, skip
10387 if !in_bracket_range && best_in_bracket_range {
10388 continue;
10389 }
10390
10391 // Prefer smaller lengths unless best is inside and current isn't
10392 if length > best_length && (best_inside || !inside) {
10393 continue;
10394 }
10395
10396 best_length = length;
10397 best_inside = inside;
10398 best_in_bracket_range = in_bracket_range;
10399 best_destination = Some(
10400 if close.contains(&selection.start) && close.contains(&selection.end) {
10401 if inside {
10402 open.end
10403 } else {
10404 open.start
10405 }
10406 } else if inside {
10407 *close.start()
10408 } else {
10409 *close.end()
10410 },
10411 );
10412 }
10413
10414 if let Some(destination) = best_destination {
10415 selection.collapse_to(destination, SelectionGoal::None);
10416 }
10417 })
10418 });
10419 }
10420
10421 pub fn undo_selection(
10422 &mut self,
10423 _: &UndoSelection,
10424 window: &mut Window,
10425 cx: &mut Context<Self>,
10426 ) {
10427 self.end_selection(window, cx);
10428 self.selection_history.mode = SelectionHistoryMode::Undoing;
10429 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10430 self.change_selections(None, window, cx, |s| {
10431 s.select_anchors(entry.selections.to_vec())
10432 });
10433 self.select_next_state = entry.select_next_state;
10434 self.select_prev_state = entry.select_prev_state;
10435 self.add_selections_state = entry.add_selections_state;
10436 self.request_autoscroll(Autoscroll::newest(), cx);
10437 }
10438 self.selection_history.mode = SelectionHistoryMode::Normal;
10439 }
10440
10441 pub fn redo_selection(
10442 &mut self,
10443 _: &RedoSelection,
10444 window: &mut Window,
10445 cx: &mut Context<Self>,
10446 ) {
10447 self.end_selection(window, cx);
10448 self.selection_history.mode = SelectionHistoryMode::Redoing;
10449 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10450 self.change_selections(None, window, cx, |s| {
10451 s.select_anchors(entry.selections.to_vec())
10452 });
10453 self.select_next_state = entry.select_next_state;
10454 self.select_prev_state = entry.select_prev_state;
10455 self.add_selections_state = entry.add_selections_state;
10456 self.request_autoscroll(Autoscroll::newest(), cx);
10457 }
10458 self.selection_history.mode = SelectionHistoryMode::Normal;
10459 }
10460
10461 pub fn expand_excerpts(
10462 &mut self,
10463 action: &ExpandExcerpts,
10464 _: &mut Window,
10465 cx: &mut Context<Self>,
10466 ) {
10467 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10468 }
10469
10470 pub fn expand_excerpts_down(
10471 &mut self,
10472 action: &ExpandExcerptsDown,
10473 _: &mut Window,
10474 cx: &mut Context<Self>,
10475 ) {
10476 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10477 }
10478
10479 pub fn expand_excerpts_up(
10480 &mut self,
10481 action: &ExpandExcerptsUp,
10482 _: &mut Window,
10483 cx: &mut Context<Self>,
10484 ) {
10485 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10486 }
10487
10488 pub fn expand_excerpts_for_direction(
10489 &mut self,
10490 lines: u32,
10491 direction: ExpandExcerptDirection,
10492
10493 cx: &mut Context<Self>,
10494 ) {
10495 let selections = self.selections.disjoint_anchors();
10496
10497 let lines = if lines == 0 {
10498 EditorSettings::get_global(cx).expand_excerpt_lines
10499 } else {
10500 lines
10501 };
10502
10503 self.buffer.update(cx, |buffer, cx| {
10504 let snapshot = buffer.snapshot(cx);
10505 let mut excerpt_ids = selections
10506 .iter()
10507 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10508 .collect::<Vec<_>>();
10509 excerpt_ids.sort();
10510 excerpt_ids.dedup();
10511 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10512 })
10513 }
10514
10515 pub fn expand_excerpt(
10516 &mut self,
10517 excerpt: ExcerptId,
10518 direction: ExpandExcerptDirection,
10519 cx: &mut Context<Self>,
10520 ) {
10521 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10522 self.buffer.update(cx, |buffer, cx| {
10523 buffer.expand_excerpts([excerpt], lines, direction, cx)
10524 })
10525 }
10526
10527 pub fn go_to_singleton_buffer_point(
10528 &mut self,
10529 point: Point,
10530 window: &mut Window,
10531 cx: &mut Context<Self>,
10532 ) {
10533 self.go_to_singleton_buffer_range(point..point, window, cx);
10534 }
10535
10536 pub fn go_to_singleton_buffer_range(
10537 &mut self,
10538 range: Range<Point>,
10539 window: &mut Window,
10540 cx: &mut Context<Self>,
10541 ) {
10542 let multibuffer = self.buffer().read(cx);
10543 let Some(buffer) = multibuffer.as_singleton() else {
10544 return;
10545 };
10546 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10547 return;
10548 };
10549 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10550 return;
10551 };
10552 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10553 s.select_anchor_ranges([start..end])
10554 });
10555 }
10556
10557 fn go_to_diagnostic(
10558 &mut self,
10559 _: &GoToDiagnostic,
10560 window: &mut Window,
10561 cx: &mut Context<Self>,
10562 ) {
10563 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10564 }
10565
10566 fn go_to_prev_diagnostic(
10567 &mut self,
10568 _: &GoToPrevDiagnostic,
10569 window: &mut Window,
10570 cx: &mut Context<Self>,
10571 ) {
10572 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10573 }
10574
10575 pub fn go_to_diagnostic_impl(
10576 &mut self,
10577 direction: Direction,
10578 window: &mut Window,
10579 cx: &mut Context<Self>,
10580 ) {
10581 let buffer = self.buffer.read(cx).snapshot(cx);
10582 let selection = self.selections.newest::<usize>(cx);
10583
10584 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10585 if direction == Direction::Next {
10586 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10587 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10588 return;
10589 };
10590 self.activate_diagnostics(
10591 buffer_id,
10592 popover.local_diagnostic.diagnostic.group_id,
10593 window,
10594 cx,
10595 );
10596 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10597 let primary_range_start = active_diagnostics.primary_range.start;
10598 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10599 let mut new_selection = s.newest_anchor().clone();
10600 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10601 s.select_anchors(vec![new_selection.clone()]);
10602 });
10603 self.refresh_inline_completion(false, true, window, cx);
10604 }
10605 return;
10606 }
10607 }
10608
10609 let active_group_id = self
10610 .active_diagnostics
10611 .as_ref()
10612 .map(|active_group| active_group.group_id);
10613 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10614 active_diagnostics
10615 .primary_range
10616 .to_offset(&buffer)
10617 .to_inclusive()
10618 });
10619 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10620 if active_primary_range.contains(&selection.head()) {
10621 *active_primary_range.start()
10622 } else {
10623 selection.head()
10624 }
10625 } else {
10626 selection.head()
10627 };
10628
10629 let snapshot = self.snapshot(window, cx);
10630 let primary_diagnostics_before = buffer
10631 .diagnostics_in_range::<usize>(0..search_start)
10632 .filter(|entry| entry.diagnostic.is_primary)
10633 .filter(|entry| entry.range.start != entry.range.end)
10634 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10635 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10636 .collect::<Vec<_>>();
10637 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10638 primary_diagnostics_before
10639 .iter()
10640 .position(|entry| entry.diagnostic.group_id == active_group_id)
10641 });
10642
10643 let primary_diagnostics_after = buffer
10644 .diagnostics_in_range::<usize>(search_start..buffer.len())
10645 .filter(|entry| entry.diagnostic.is_primary)
10646 .filter(|entry| entry.range.start != entry.range.end)
10647 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10648 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10649 .collect::<Vec<_>>();
10650 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10651 primary_diagnostics_after
10652 .iter()
10653 .enumerate()
10654 .rev()
10655 .find_map(|(i, entry)| {
10656 if entry.diagnostic.group_id == active_group_id {
10657 Some(i)
10658 } else {
10659 None
10660 }
10661 })
10662 });
10663
10664 let next_primary_diagnostic = match direction {
10665 Direction::Prev => primary_diagnostics_before
10666 .iter()
10667 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10668 .rev()
10669 .next(),
10670 Direction::Next => primary_diagnostics_after
10671 .iter()
10672 .skip(
10673 last_same_group_diagnostic_after
10674 .map(|index| index + 1)
10675 .unwrap_or(0),
10676 )
10677 .next(),
10678 };
10679
10680 // Cycle around to the start of the buffer, potentially moving back to the start of
10681 // the currently active diagnostic.
10682 let cycle_around = || match direction {
10683 Direction::Prev => primary_diagnostics_after
10684 .iter()
10685 .rev()
10686 .chain(primary_diagnostics_before.iter().rev())
10687 .next(),
10688 Direction::Next => primary_diagnostics_before
10689 .iter()
10690 .chain(primary_diagnostics_after.iter())
10691 .next(),
10692 };
10693
10694 if let Some((primary_range, group_id)) = next_primary_diagnostic
10695 .or_else(cycle_around)
10696 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10697 {
10698 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10699 return;
10700 };
10701 self.activate_diagnostics(buffer_id, group_id, window, cx);
10702 if self.active_diagnostics.is_some() {
10703 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704 s.select(vec![Selection {
10705 id: selection.id,
10706 start: primary_range.start,
10707 end: primary_range.start,
10708 reversed: false,
10709 goal: SelectionGoal::None,
10710 }]);
10711 });
10712 self.refresh_inline_completion(false, true, window, cx);
10713 }
10714 }
10715 }
10716
10717 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10718 let snapshot = self.snapshot(window, cx);
10719 let selection = self.selections.newest::<Point>(cx);
10720 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10721 }
10722
10723 fn go_to_hunk_after_position(
10724 &mut self,
10725 snapshot: &EditorSnapshot,
10726 position: Point,
10727 window: &mut Window,
10728 cx: &mut Context<Editor>,
10729 ) -> Option<MultiBufferDiffHunk> {
10730 let mut hunk = snapshot
10731 .buffer_snapshot
10732 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10733 .find(|hunk| hunk.row_range.start.0 > position.row);
10734 if hunk.is_none() {
10735 hunk = snapshot
10736 .buffer_snapshot
10737 .diff_hunks_in_range(Point::zero()..position)
10738 .find(|hunk| hunk.row_range.end.0 < position.row)
10739 }
10740 if let Some(hunk) = &hunk {
10741 let destination = Point::new(hunk.row_range.start.0, 0);
10742 self.unfold_ranges(&[destination..destination], false, false, cx);
10743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10744 s.select_ranges(vec![destination..destination]);
10745 });
10746 }
10747
10748 hunk
10749 }
10750
10751 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10752 let snapshot = self.snapshot(window, cx);
10753 let selection = self.selections.newest::<Point>(cx);
10754 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10755 }
10756
10757 fn go_to_hunk_before_position(
10758 &mut self,
10759 snapshot: &EditorSnapshot,
10760 position: Point,
10761 window: &mut Window,
10762 cx: &mut Context<Editor>,
10763 ) -> Option<MultiBufferDiffHunk> {
10764 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10765 if hunk.is_none() {
10766 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10767 }
10768 if let Some(hunk) = &hunk {
10769 let destination = Point::new(hunk.row_range.start.0, 0);
10770 self.unfold_ranges(&[destination..destination], false, false, cx);
10771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10772 s.select_ranges(vec![destination..destination]);
10773 });
10774 }
10775
10776 hunk
10777 }
10778
10779 pub fn go_to_definition(
10780 &mut self,
10781 _: &GoToDefinition,
10782 window: &mut Window,
10783 cx: &mut Context<Self>,
10784 ) -> Task<Result<Navigated>> {
10785 let definition =
10786 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10787 cx.spawn_in(window, |editor, mut cx| async move {
10788 if definition.await? == Navigated::Yes {
10789 return Ok(Navigated::Yes);
10790 }
10791 match editor.update_in(&mut cx, |editor, window, cx| {
10792 editor.find_all_references(&FindAllReferences, window, cx)
10793 })? {
10794 Some(references) => references.await,
10795 None => Ok(Navigated::No),
10796 }
10797 })
10798 }
10799
10800 pub fn go_to_declaration(
10801 &mut self,
10802 _: &GoToDeclaration,
10803 window: &mut Window,
10804 cx: &mut Context<Self>,
10805 ) -> Task<Result<Navigated>> {
10806 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10807 }
10808
10809 pub fn go_to_declaration_split(
10810 &mut self,
10811 _: &GoToDeclaration,
10812 window: &mut Window,
10813 cx: &mut Context<Self>,
10814 ) -> Task<Result<Navigated>> {
10815 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10816 }
10817
10818 pub fn go_to_implementation(
10819 &mut self,
10820 _: &GoToImplementation,
10821 window: &mut Window,
10822 cx: &mut Context<Self>,
10823 ) -> Task<Result<Navigated>> {
10824 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10825 }
10826
10827 pub fn go_to_implementation_split(
10828 &mut self,
10829 _: &GoToImplementationSplit,
10830 window: &mut Window,
10831 cx: &mut Context<Self>,
10832 ) -> Task<Result<Navigated>> {
10833 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10834 }
10835
10836 pub fn go_to_type_definition(
10837 &mut self,
10838 _: &GoToTypeDefinition,
10839 window: &mut Window,
10840 cx: &mut Context<Self>,
10841 ) -> Task<Result<Navigated>> {
10842 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10843 }
10844
10845 pub fn go_to_definition_split(
10846 &mut self,
10847 _: &GoToDefinitionSplit,
10848 window: &mut Window,
10849 cx: &mut Context<Self>,
10850 ) -> Task<Result<Navigated>> {
10851 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10852 }
10853
10854 pub fn go_to_type_definition_split(
10855 &mut self,
10856 _: &GoToTypeDefinitionSplit,
10857 window: &mut Window,
10858 cx: &mut Context<Self>,
10859 ) -> Task<Result<Navigated>> {
10860 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10861 }
10862
10863 fn go_to_definition_of_kind(
10864 &mut self,
10865 kind: GotoDefinitionKind,
10866 split: bool,
10867 window: &mut Window,
10868 cx: &mut Context<Self>,
10869 ) -> Task<Result<Navigated>> {
10870 let Some(provider) = self.semantics_provider.clone() else {
10871 return Task::ready(Ok(Navigated::No));
10872 };
10873 let head = self.selections.newest::<usize>(cx).head();
10874 let buffer = self.buffer.read(cx);
10875 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10876 text_anchor
10877 } else {
10878 return Task::ready(Ok(Navigated::No));
10879 };
10880
10881 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10882 return Task::ready(Ok(Navigated::No));
10883 };
10884
10885 cx.spawn_in(window, |editor, mut cx| async move {
10886 let definitions = definitions.await?;
10887 let navigated = editor
10888 .update_in(&mut cx, |editor, window, cx| {
10889 editor.navigate_to_hover_links(
10890 Some(kind),
10891 definitions
10892 .into_iter()
10893 .filter(|location| {
10894 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10895 })
10896 .map(HoverLink::Text)
10897 .collect::<Vec<_>>(),
10898 split,
10899 window,
10900 cx,
10901 )
10902 })?
10903 .await?;
10904 anyhow::Ok(navigated)
10905 })
10906 }
10907
10908 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10909 let selection = self.selections.newest_anchor();
10910 let head = selection.head();
10911 let tail = selection.tail();
10912
10913 let Some((buffer, start_position)) =
10914 self.buffer.read(cx).text_anchor_for_position(head, cx)
10915 else {
10916 return;
10917 };
10918
10919 let end_position = if head != tail {
10920 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10921 return;
10922 };
10923 Some(pos)
10924 } else {
10925 None
10926 };
10927
10928 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10929 let url = if let Some(end_pos) = end_position {
10930 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10931 } else {
10932 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10933 };
10934
10935 if let Some(url) = url {
10936 editor.update(&mut cx, |_, cx| {
10937 cx.open_url(&url);
10938 })
10939 } else {
10940 Ok(())
10941 }
10942 });
10943
10944 url_finder.detach();
10945 }
10946
10947 pub fn open_selected_filename(
10948 &mut self,
10949 _: &OpenSelectedFilename,
10950 window: &mut Window,
10951 cx: &mut Context<Self>,
10952 ) {
10953 let Some(workspace) = self.workspace() else {
10954 return;
10955 };
10956
10957 let position = self.selections.newest_anchor().head();
10958
10959 let Some((buffer, buffer_position)) =
10960 self.buffer.read(cx).text_anchor_for_position(position, cx)
10961 else {
10962 return;
10963 };
10964
10965 let project = self.project.clone();
10966
10967 cx.spawn_in(window, |_, mut cx| async move {
10968 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10969
10970 if let Some((_, path)) = result {
10971 workspace
10972 .update_in(&mut cx, |workspace, window, cx| {
10973 workspace.open_resolved_path(path, window, cx)
10974 })?
10975 .await?;
10976 }
10977 anyhow::Ok(())
10978 })
10979 .detach();
10980 }
10981
10982 pub(crate) fn navigate_to_hover_links(
10983 &mut self,
10984 kind: Option<GotoDefinitionKind>,
10985 mut definitions: Vec<HoverLink>,
10986 split: bool,
10987 window: &mut Window,
10988 cx: &mut Context<Editor>,
10989 ) -> Task<Result<Navigated>> {
10990 // If there is one definition, just open it directly
10991 if definitions.len() == 1 {
10992 let definition = definitions.pop().unwrap();
10993
10994 enum TargetTaskResult {
10995 Location(Option<Location>),
10996 AlreadyNavigated,
10997 }
10998
10999 let target_task = match definition {
11000 HoverLink::Text(link) => {
11001 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11002 }
11003 HoverLink::InlayHint(lsp_location, server_id) => {
11004 let computation =
11005 self.compute_target_location(lsp_location, server_id, window, cx);
11006 cx.background_spawn(async move {
11007 let location = computation.await?;
11008 Ok(TargetTaskResult::Location(location))
11009 })
11010 }
11011 HoverLink::Url(url) => {
11012 cx.open_url(&url);
11013 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11014 }
11015 HoverLink::File(path) => {
11016 if let Some(workspace) = self.workspace() {
11017 cx.spawn_in(window, |_, mut cx| async move {
11018 workspace
11019 .update_in(&mut cx, |workspace, window, cx| {
11020 workspace.open_resolved_path(path, window, cx)
11021 })?
11022 .await
11023 .map(|_| TargetTaskResult::AlreadyNavigated)
11024 })
11025 } else {
11026 Task::ready(Ok(TargetTaskResult::Location(None)))
11027 }
11028 }
11029 };
11030 cx.spawn_in(window, |editor, mut cx| async move {
11031 let target = match target_task.await.context("target resolution task")? {
11032 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11033 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11034 TargetTaskResult::Location(Some(target)) => target,
11035 };
11036
11037 editor.update_in(&mut cx, |editor, window, cx| {
11038 let Some(workspace) = editor.workspace() else {
11039 return Navigated::No;
11040 };
11041 let pane = workspace.read(cx).active_pane().clone();
11042
11043 let range = target.range.to_point(target.buffer.read(cx));
11044 let range = editor.range_for_match(&range);
11045 let range = collapse_multiline_range(range);
11046
11047 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11048 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11049 } else {
11050 window.defer(cx, move |window, cx| {
11051 let target_editor: Entity<Self> =
11052 workspace.update(cx, |workspace, cx| {
11053 let pane = if split {
11054 workspace.adjacent_pane(window, cx)
11055 } else {
11056 workspace.active_pane().clone()
11057 };
11058
11059 workspace.open_project_item(
11060 pane,
11061 target.buffer.clone(),
11062 true,
11063 true,
11064 window,
11065 cx,
11066 )
11067 });
11068 target_editor.update(cx, |target_editor, cx| {
11069 // When selecting a definition in a different buffer, disable the nav history
11070 // to avoid creating a history entry at the previous cursor location.
11071 pane.update(cx, |pane, _| pane.disable_history());
11072 target_editor.go_to_singleton_buffer_range(range, window, cx);
11073 pane.update(cx, |pane, _| pane.enable_history());
11074 });
11075 });
11076 }
11077 Navigated::Yes
11078 })
11079 })
11080 } else if !definitions.is_empty() {
11081 cx.spawn_in(window, |editor, mut cx| async move {
11082 let (title, location_tasks, workspace) = editor
11083 .update_in(&mut cx, |editor, window, cx| {
11084 let tab_kind = match kind {
11085 Some(GotoDefinitionKind::Implementation) => "Implementations",
11086 _ => "Definitions",
11087 };
11088 let title = definitions
11089 .iter()
11090 .find_map(|definition| match definition {
11091 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11092 let buffer = origin.buffer.read(cx);
11093 format!(
11094 "{} for {}",
11095 tab_kind,
11096 buffer
11097 .text_for_range(origin.range.clone())
11098 .collect::<String>()
11099 )
11100 }),
11101 HoverLink::InlayHint(_, _) => None,
11102 HoverLink::Url(_) => None,
11103 HoverLink::File(_) => None,
11104 })
11105 .unwrap_or(tab_kind.to_string());
11106 let location_tasks = definitions
11107 .into_iter()
11108 .map(|definition| match definition {
11109 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11110 HoverLink::InlayHint(lsp_location, server_id) => editor
11111 .compute_target_location(lsp_location, server_id, window, cx),
11112 HoverLink::Url(_) => Task::ready(Ok(None)),
11113 HoverLink::File(_) => Task::ready(Ok(None)),
11114 })
11115 .collect::<Vec<_>>();
11116 (title, location_tasks, editor.workspace().clone())
11117 })
11118 .context("location tasks preparation")?;
11119
11120 let locations = future::join_all(location_tasks)
11121 .await
11122 .into_iter()
11123 .filter_map(|location| location.transpose())
11124 .collect::<Result<_>>()
11125 .context("location tasks")?;
11126
11127 let Some(workspace) = workspace else {
11128 return Ok(Navigated::No);
11129 };
11130 let opened = workspace
11131 .update_in(&mut cx, |workspace, window, cx| {
11132 Self::open_locations_in_multibuffer(
11133 workspace,
11134 locations,
11135 title,
11136 split,
11137 MultibufferSelectionMode::First,
11138 window,
11139 cx,
11140 )
11141 })
11142 .ok();
11143
11144 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11145 })
11146 } else {
11147 Task::ready(Ok(Navigated::No))
11148 }
11149 }
11150
11151 fn compute_target_location(
11152 &self,
11153 lsp_location: lsp::Location,
11154 server_id: LanguageServerId,
11155 window: &mut Window,
11156 cx: &mut Context<Self>,
11157 ) -> Task<anyhow::Result<Option<Location>>> {
11158 let Some(project) = self.project.clone() else {
11159 return Task::ready(Ok(None));
11160 };
11161
11162 cx.spawn_in(window, move |editor, mut cx| async move {
11163 let location_task = editor.update(&mut cx, |_, cx| {
11164 project.update(cx, |project, cx| {
11165 let language_server_name = project
11166 .language_server_statuses(cx)
11167 .find(|(id, _)| server_id == *id)
11168 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11169 language_server_name.map(|language_server_name| {
11170 project.open_local_buffer_via_lsp(
11171 lsp_location.uri.clone(),
11172 server_id,
11173 language_server_name,
11174 cx,
11175 )
11176 })
11177 })
11178 })?;
11179 let location = match location_task {
11180 Some(task) => Some({
11181 let target_buffer_handle = task.await.context("open local buffer")?;
11182 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11183 let target_start = target_buffer
11184 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11185 let target_end = target_buffer
11186 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11187 target_buffer.anchor_after(target_start)
11188 ..target_buffer.anchor_before(target_end)
11189 })?;
11190 Location {
11191 buffer: target_buffer_handle,
11192 range,
11193 }
11194 }),
11195 None => None,
11196 };
11197 Ok(location)
11198 })
11199 }
11200
11201 pub fn find_all_references(
11202 &mut self,
11203 _: &FindAllReferences,
11204 window: &mut Window,
11205 cx: &mut Context<Self>,
11206 ) -> Option<Task<Result<Navigated>>> {
11207 let selection = self.selections.newest::<usize>(cx);
11208 let multi_buffer = self.buffer.read(cx);
11209 let head = selection.head();
11210
11211 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11212 let head_anchor = multi_buffer_snapshot.anchor_at(
11213 head,
11214 if head < selection.tail() {
11215 Bias::Right
11216 } else {
11217 Bias::Left
11218 },
11219 );
11220
11221 match self
11222 .find_all_references_task_sources
11223 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11224 {
11225 Ok(_) => {
11226 log::info!(
11227 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11228 );
11229 return None;
11230 }
11231 Err(i) => {
11232 self.find_all_references_task_sources.insert(i, head_anchor);
11233 }
11234 }
11235
11236 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11237 let workspace = self.workspace()?;
11238 let project = workspace.read(cx).project().clone();
11239 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11240 Some(cx.spawn_in(window, |editor, mut cx| async move {
11241 let _cleanup = defer({
11242 let mut cx = cx.clone();
11243 move || {
11244 let _ = editor.update(&mut cx, |editor, _| {
11245 if let Ok(i) =
11246 editor
11247 .find_all_references_task_sources
11248 .binary_search_by(|anchor| {
11249 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11250 })
11251 {
11252 editor.find_all_references_task_sources.remove(i);
11253 }
11254 });
11255 }
11256 });
11257
11258 let locations = references.await?;
11259 if locations.is_empty() {
11260 return anyhow::Ok(Navigated::No);
11261 }
11262
11263 workspace.update_in(&mut cx, |workspace, window, cx| {
11264 let title = locations
11265 .first()
11266 .as_ref()
11267 .map(|location| {
11268 let buffer = location.buffer.read(cx);
11269 format!(
11270 "References to `{}`",
11271 buffer
11272 .text_for_range(location.range.clone())
11273 .collect::<String>()
11274 )
11275 })
11276 .unwrap();
11277 Self::open_locations_in_multibuffer(
11278 workspace,
11279 locations,
11280 title,
11281 false,
11282 MultibufferSelectionMode::First,
11283 window,
11284 cx,
11285 );
11286 Navigated::Yes
11287 })
11288 }))
11289 }
11290
11291 /// Opens a multibuffer with the given project locations in it
11292 pub fn open_locations_in_multibuffer(
11293 workspace: &mut Workspace,
11294 mut locations: Vec<Location>,
11295 title: String,
11296 split: bool,
11297 multibuffer_selection_mode: MultibufferSelectionMode,
11298 window: &mut Window,
11299 cx: &mut Context<Workspace>,
11300 ) {
11301 // If there are multiple definitions, open them in a multibuffer
11302 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11303 let mut locations = locations.into_iter().peekable();
11304 let mut ranges = Vec::new();
11305 let capability = workspace.project().read(cx).capability();
11306
11307 let excerpt_buffer = cx.new(|cx| {
11308 let mut multibuffer = MultiBuffer::new(capability);
11309 while let Some(location) = locations.next() {
11310 let buffer = location.buffer.read(cx);
11311 let mut ranges_for_buffer = Vec::new();
11312 let range = location.range.to_offset(buffer);
11313 ranges_for_buffer.push(range.clone());
11314
11315 while let Some(next_location) = locations.peek() {
11316 if next_location.buffer == location.buffer {
11317 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11318 locations.next();
11319 } else {
11320 break;
11321 }
11322 }
11323
11324 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11325 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11326 location.buffer.clone(),
11327 ranges_for_buffer,
11328 DEFAULT_MULTIBUFFER_CONTEXT,
11329 cx,
11330 ))
11331 }
11332
11333 multibuffer.with_title(title)
11334 });
11335
11336 let editor = cx.new(|cx| {
11337 Editor::for_multibuffer(
11338 excerpt_buffer,
11339 Some(workspace.project().clone()),
11340 true,
11341 window,
11342 cx,
11343 )
11344 });
11345 editor.update(cx, |editor, cx| {
11346 match multibuffer_selection_mode {
11347 MultibufferSelectionMode::First => {
11348 if let Some(first_range) = ranges.first() {
11349 editor.change_selections(None, window, cx, |selections| {
11350 selections.clear_disjoint();
11351 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11352 });
11353 }
11354 editor.highlight_background::<Self>(
11355 &ranges,
11356 |theme| theme.editor_highlighted_line_background,
11357 cx,
11358 );
11359 }
11360 MultibufferSelectionMode::All => {
11361 editor.change_selections(None, window, cx, |selections| {
11362 selections.clear_disjoint();
11363 selections.select_anchor_ranges(ranges);
11364 });
11365 }
11366 }
11367 editor.register_buffers_with_language_servers(cx);
11368 });
11369
11370 let item = Box::new(editor);
11371 let item_id = item.item_id();
11372
11373 if split {
11374 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11375 } else {
11376 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11377 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11378 pane.close_current_preview_item(window, cx)
11379 } else {
11380 None
11381 }
11382 });
11383 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11384 }
11385 workspace.active_pane().update(cx, |pane, cx| {
11386 pane.set_preview_item_id(Some(item_id), cx);
11387 });
11388 }
11389
11390 pub fn rename(
11391 &mut self,
11392 _: &Rename,
11393 window: &mut Window,
11394 cx: &mut Context<Self>,
11395 ) -> Option<Task<Result<()>>> {
11396 use language::ToOffset as _;
11397
11398 let provider = self.semantics_provider.clone()?;
11399 let selection = self.selections.newest_anchor().clone();
11400 let (cursor_buffer, cursor_buffer_position) = self
11401 .buffer
11402 .read(cx)
11403 .text_anchor_for_position(selection.head(), cx)?;
11404 let (tail_buffer, cursor_buffer_position_end) = self
11405 .buffer
11406 .read(cx)
11407 .text_anchor_for_position(selection.tail(), cx)?;
11408 if tail_buffer != cursor_buffer {
11409 return None;
11410 }
11411
11412 let snapshot = cursor_buffer.read(cx).snapshot();
11413 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11414 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11415 let prepare_rename = provider
11416 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11417 .unwrap_or_else(|| Task::ready(Ok(None)));
11418 drop(snapshot);
11419
11420 Some(cx.spawn_in(window, |this, mut cx| async move {
11421 let rename_range = if let Some(range) = prepare_rename.await? {
11422 Some(range)
11423 } else {
11424 this.update(&mut cx, |this, cx| {
11425 let buffer = this.buffer.read(cx).snapshot(cx);
11426 let mut buffer_highlights = this
11427 .document_highlights_for_position(selection.head(), &buffer)
11428 .filter(|highlight| {
11429 highlight.start.excerpt_id == selection.head().excerpt_id
11430 && highlight.end.excerpt_id == selection.head().excerpt_id
11431 });
11432 buffer_highlights
11433 .next()
11434 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11435 })?
11436 };
11437 if let Some(rename_range) = rename_range {
11438 this.update_in(&mut cx, |this, window, cx| {
11439 let snapshot = cursor_buffer.read(cx).snapshot();
11440 let rename_buffer_range = rename_range.to_offset(&snapshot);
11441 let cursor_offset_in_rename_range =
11442 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11443 let cursor_offset_in_rename_range_end =
11444 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11445
11446 this.take_rename(false, window, cx);
11447 let buffer = this.buffer.read(cx).read(cx);
11448 let cursor_offset = selection.head().to_offset(&buffer);
11449 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11450 let rename_end = rename_start + rename_buffer_range.len();
11451 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11452 let mut old_highlight_id = None;
11453 let old_name: Arc<str> = buffer
11454 .chunks(rename_start..rename_end, true)
11455 .map(|chunk| {
11456 if old_highlight_id.is_none() {
11457 old_highlight_id = chunk.syntax_highlight_id;
11458 }
11459 chunk.text
11460 })
11461 .collect::<String>()
11462 .into();
11463
11464 drop(buffer);
11465
11466 // Position the selection in the rename editor so that it matches the current selection.
11467 this.show_local_selections = false;
11468 let rename_editor = cx.new(|cx| {
11469 let mut editor = Editor::single_line(window, cx);
11470 editor.buffer.update(cx, |buffer, cx| {
11471 buffer.edit([(0..0, old_name.clone())], None, cx)
11472 });
11473 let rename_selection_range = match cursor_offset_in_rename_range
11474 .cmp(&cursor_offset_in_rename_range_end)
11475 {
11476 Ordering::Equal => {
11477 editor.select_all(&SelectAll, window, cx);
11478 return editor;
11479 }
11480 Ordering::Less => {
11481 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11482 }
11483 Ordering::Greater => {
11484 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11485 }
11486 };
11487 if rename_selection_range.end > old_name.len() {
11488 editor.select_all(&SelectAll, window, cx);
11489 } else {
11490 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11491 s.select_ranges([rename_selection_range]);
11492 });
11493 }
11494 editor
11495 });
11496 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11497 if e == &EditorEvent::Focused {
11498 cx.emit(EditorEvent::FocusedIn)
11499 }
11500 })
11501 .detach();
11502
11503 let write_highlights =
11504 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11505 let read_highlights =
11506 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11507 let ranges = write_highlights
11508 .iter()
11509 .flat_map(|(_, ranges)| ranges.iter())
11510 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11511 .cloned()
11512 .collect();
11513
11514 this.highlight_text::<Rename>(
11515 ranges,
11516 HighlightStyle {
11517 fade_out: Some(0.6),
11518 ..Default::default()
11519 },
11520 cx,
11521 );
11522 let rename_focus_handle = rename_editor.focus_handle(cx);
11523 window.focus(&rename_focus_handle);
11524 let block_id = this.insert_blocks(
11525 [BlockProperties {
11526 style: BlockStyle::Flex,
11527 placement: BlockPlacement::Below(range.start),
11528 height: 1,
11529 render: Arc::new({
11530 let rename_editor = rename_editor.clone();
11531 move |cx: &mut BlockContext| {
11532 let mut text_style = cx.editor_style.text.clone();
11533 if let Some(highlight_style) = old_highlight_id
11534 .and_then(|h| h.style(&cx.editor_style.syntax))
11535 {
11536 text_style = text_style.highlight(highlight_style);
11537 }
11538 div()
11539 .block_mouse_down()
11540 .pl(cx.anchor_x)
11541 .child(EditorElement::new(
11542 &rename_editor,
11543 EditorStyle {
11544 background: cx.theme().system().transparent,
11545 local_player: cx.editor_style.local_player,
11546 text: text_style,
11547 scrollbar_width: cx.editor_style.scrollbar_width,
11548 syntax: cx.editor_style.syntax.clone(),
11549 status: cx.editor_style.status.clone(),
11550 inlay_hints_style: HighlightStyle {
11551 font_weight: Some(FontWeight::BOLD),
11552 ..make_inlay_hints_style(cx.app)
11553 },
11554 inline_completion_styles: make_suggestion_styles(
11555 cx.app,
11556 ),
11557 ..EditorStyle::default()
11558 },
11559 ))
11560 .into_any_element()
11561 }
11562 }),
11563 priority: 0,
11564 }],
11565 Some(Autoscroll::fit()),
11566 cx,
11567 )[0];
11568 this.pending_rename = Some(RenameState {
11569 range,
11570 old_name,
11571 editor: rename_editor,
11572 block_id,
11573 });
11574 })?;
11575 }
11576
11577 Ok(())
11578 }))
11579 }
11580
11581 pub fn confirm_rename(
11582 &mut self,
11583 _: &ConfirmRename,
11584 window: &mut Window,
11585 cx: &mut Context<Self>,
11586 ) -> Option<Task<Result<()>>> {
11587 let rename = self.take_rename(false, window, cx)?;
11588 let workspace = self.workspace()?.downgrade();
11589 let (buffer, start) = self
11590 .buffer
11591 .read(cx)
11592 .text_anchor_for_position(rename.range.start, cx)?;
11593 let (end_buffer, _) = self
11594 .buffer
11595 .read(cx)
11596 .text_anchor_for_position(rename.range.end, cx)?;
11597 if buffer != end_buffer {
11598 return None;
11599 }
11600
11601 let old_name = rename.old_name;
11602 let new_name = rename.editor.read(cx).text(cx);
11603
11604 let rename = self.semantics_provider.as_ref()?.perform_rename(
11605 &buffer,
11606 start,
11607 new_name.clone(),
11608 cx,
11609 )?;
11610
11611 Some(cx.spawn_in(window, |editor, mut cx| async move {
11612 let project_transaction = rename.await?;
11613 Self::open_project_transaction(
11614 &editor,
11615 workspace,
11616 project_transaction,
11617 format!("Rename: {} → {}", old_name, new_name),
11618 cx.clone(),
11619 )
11620 .await?;
11621
11622 editor.update(&mut cx, |editor, cx| {
11623 editor.refresh_document_highlights(cx);
11624 })?;
11625 Ok(())
11626 }))
11627 }
11628
11629 fn take_rename(
11630 &mut self,
11631 moving_cursor: bool,
11632 window: &mut Window,
11633 cx: &mut Context<Self>,
11634 ) -> Option<RenameState> {
11635 let rename = self.pending_rename.take()?;
11636 if rename.editor.focus_handle(cx).is_focused(window) {
11637 window.focus(&self.focus_handle);
11638 }
11639
11640 self.remove_blocks(
11641 [rename.block_id].into_iter().collect(),
11642 Some(Autoscroll::fit()),
11643 cx,
11644 );
11645 self.clear_highlights::<Rename>(cx);
11646 self.show_local_selections = true;
11647
11648 if moving_cursor {
11649 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11650 editor.selections.newest::<usize>(cx).head()
11651 });
11652
11653 // Update the selection to match the position of the selection inside
11654 // the rename editor.
11655 let snapshot = self.buffer.read(cx).read(cx);
11656 let rename_range = rename.range.to_offset(&snapshot);
11657 let cursor_in_editor = snapshot
11658 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11659 .min(rename_range.end);
11660 drop(snapshot);
11661
11662 self.change_selections(None, window, cx, |s| {
11663 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11664 });
11665 } else {
11666 self.refresh_document_highlights(cx);
11667 }
11668
11669 Some(rename)
11670 }
11671
11672 pub fn pending_rename(&self) -> Option<&RenameState> {
11673 self.pending_rename.as_ref()
11674 }
11675
11676 fn format(
11677 &mut self,
11678 _: &Format,
11679 window: &mut Window,
11680 cx: &mut Context<Self>,
11681 ) -> Option<Task<Result<()>>> {
11682 let project = match &self.project {
11683 Some(project) => project.clone(),
11684 None => return None,
11685 };
11686
11687 Some(self.perform_format(
11688 project,
11689 FormatTrigger::Manual,
11690 FormatTarget::Buffers,
11691 window,
11692 cx,
11693 ))
11694 }
11695
11696 fn format_selections(
11697 &mut self,
11698 _: &FormatSelections,
11699 window: &mut Window,
11700 cx: &mut Context<Self>,
11701 ) -> Option<Task<Result<()>>> {
11702 let project = match &self.project {
11703 Some(project) => project.clone(),
11704 None => return None,
11705 };
11706
11707 let ranges = self
11708 .selections
11709 .all_adjusted(cx)
11710 .into_iter()
11711 .map(|selection| selection.range())
11712 .collect_vec();
11713
11714 Some(self.perform_format(
11715 project,
11716 FormatTrigger::Manual,
11717 FormatTarget::Ranges(ranges),
11718 window,
11719 cx,
11720 ))
11721 }
11722
11723 fn perform_format(
11724 &mut self,
11725 project: Entity<Project>,
11726 trigger: FormatTrigger,
11727 target: FormatTarget,
11728 window: &mut Window,
11729 cx: &mut Context<Self>,
11730 ) -> Task<Result<()>> {
11731 let buffer = self.buffer.clone();
11732 let (buffers, target) = match target {
11733 FormatTarget::Buffers => {
11734 let mut buffers = buffer.read(cx).all_buffers();
11735 if trigger == FormatTrigger::Save {
11736 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11737 }
11738 (buffers, LspFormatTarget::Buffers)
11739 }
11740 FormatTarget::Ranges(selection_ranges) => {
11741 let multi_buffer = buffer.read(cx);
11742 let snapshot = multi_buffer.read(cx);
11743 let mut buffers = HashSet::default();
11744 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11745 BTreeMap::new();
11746 for selection_range in selection_ranges {
11747 for (buffer, buffer_range, _) in
11748 snapshot.range_to_buffer_ranges(selection_range)
11749 {
11750 let buffer_id = buffer.remote_id();
11751 let start = buffer.anchor_before(buffer_range.start);
11752 let end = buffer.anchor_after(buffer_range.end);
11753 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11754 buffer_id_to_ranges
11755 .entry(buffer_id)
11756 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11757 .or_insert_with(|| vec![start..end]);
11758 }
11759 }
11760 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11761 }
11762 };
11763
11764 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11765 let format = project.update(cx, |project, cx| {
11766 project.format(buffers, target, true, trigger, cx)
11767 });
11768
11769 cx.spawn_in(window, |_, mut cx| async move {
11770 let transaction = futures::select_biased! {
11771 () = timeout => {
11772 log::warn!("timed out waiting for formatting");
11773 None
11774 }
11775 transaction = format.log_err().fuse() => transaction,
11776 };
11777
11778 buffer
11779 .update(&mut cx, |buffer, cx| {
11780 if let Some(transaction) = transaction {
11781 if !buffer.is_singleton() {
11782 buffer.push_transaction(&transaction.0, cx);
11783 }
11784 }
11785
11786 cx.notify();
11787 })
11788 .ok();
11789
11790 Ok(())
11791 })
11792 }
11793
11794 fn restart_language_server(
11795 &mut self,
11796 _: &RestartLanguageServer,
11797 _: &mut Window,
11798 cx: &mut Context<Self>,
11799 ) {
11800 if let Some(project) = self.project.clone() {
11801 self.buffer.update(cx, |multi_buffer, cx| {
11802 project.update(cx, |project, cx| {
11803 project.restart_language_servers_for_buffers(
11804 multi_buffer.all_buffers().into_iter().collect(),
11805 cx,
11806 );
11807 });
11808 })
11809 }
11810 }
11811
11812 fn cancel_language_server_work(
11813 workspace: &mut Workspace,
11814 _: &actions::CancelLanguageServerWork,
11815 _: &mut Window,
11816 cx: &mut Context<Workspace>,
11817 ) {
11818 let project = workspace.project();
11819 let buffers = workspace
11820 .active_item(cx)
11821 .and_then(|item| item.act_as::<Editor>(cx))
11822 .map_or(HashSet::default(), |editor| {
11823 editor.read(cx).buffer.read(cx).all_buffers()
11824 });
11825 project.update(cx, |project, cx| {
11826 project.cancel_language_server_work_for_buffers(buffers, cx);
11827 });
11828 }
11829
11830 fn show_character_palette(
11831 &mut self,
11832 _: &ShowCharacterPalette,
11833 window: &mut Window,
11834 _: &mut Context<Self>,
11835 ) {
11836 window.show_character_palette();
11837 }
11838
11839 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11840 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11841 let buffer = self.buffer.read(cx).snapshot(cx);
11842 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11843 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11844 let is_valid = buffer
11845 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11846 .any(|entry| {
11847 entry.diagnostic.is_primary
11848 && !entry.range.is_empty()
11849 && entry.range.start == primary_range_start
11850 && entry.diagnostic.message == active_diagnostics.primary_message
11851 });
11852
11853 if is_valid != active_diagnostics.is_valid {
11854 active_diagnostics.is_valid = is_valid;
11855 let mut new_styles = HashMap::default();
11856 for (block_id, diagnostic) in &active_diagnostics.blocks {
11857 new_styles.insert(
11858 *block_id,
11859 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11860 );
11861 }
11862 self.display_map.update(cx, |display_map, _cx| {
11863 display_map.replace_blocks(new_styles)
11864 });
11865 }
11866 }
11867 }
11868
11869 fn activate_diagnostics(
11870 &mut self,
11871 buffer_id: BufferId,
11872 group_id: usize,
11873 window: &mut Window,
11874 cx: &mut Context<Self>,
11875 ) {
11876 self.dismiss_diagnostics(cx);
11877 let snapshot = self.snapshot(window, cx);
11878 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11879 let buffer = self.buffer.read(cx).snapshot(cx);
11880
11881 let mut primary_range = None;
11882 let mut primary_message = None;
11883 let diagnostic_group = buffer
11884 .diagnostic_group(buffer_id, group_id)
11885 .filter_map(|entry| {
11886 let start = entry.range.start;
11887 let end = entry.range.end;
11888 if snapshot.is_line_folded(MultiBufferRow(start.row))
11889 && (start.row == end.row
11890 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11891 {
11892 return None;
11893 }
11894 if entry.diagnostic.is_primary {
11895 primary_range = Some(entry.range.clone());
11896 primary_message = Some(entry.diagnostic.message.clone());
11897 }
11898 Some(entry)
11899 })
11900 .collect::<Vec<_>>();
11901 let primary_range = primary_range?;
11902 let primary_message = primary_message?;
11903
11904 let blocks = display_map
11905 .insert_blocks(
11906 diagnostic_group.iter().map(|entry| {
11907 let diagnostic = entry.diagnostic.clone();
11908 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11909 BlockProperties {
11910 style: BlockStyle::Fixed,
11911 placement: BlockPlacement::Below(
11912 buffer.anchor_after(entry.range.start),
11913 ),
11914 height: message_height,
11915 render: diagnostic_block_renderer(diagnostic, None, true, true),
11916 priority: 0,
11917 }
11918 }),
11919 cx,
11920 )
11921 .into_iter()
11922 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11923 .collect();
11924
11925 Some(ActiveDiagnosticGroup {
11926 primary_range: buffer.anchor_before(primary_range.start)
11927 ..buffer.anchor_after(primary_range.end),
11928 primary_message,
11929 group_id,
11930 blocks,
11931 is_valid: true,
11932 })
11933 });
11934 }
11935
11936 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11937 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11938 self.display_map.update(cx, |display_map, cx| {
11939 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11940 });
11941 cx.notify();
11942 }
11943 }
11944
11945 pub fn set_selections_from_remote(
11946 &mut self,
11947 selections: Vec<Selection<Anchor>>,
11948 pending_selection: Option<Selection<Anchor>>,
11949 window: &mut Window,
11950 cx: &mut Context<Self>,
11951 ) {
11952 let old_cursor_position = self.selections.newest_anchor().head();
11953 self.selections.change_with(cx, |s| {
11954 s.select_anchors(selections);
11955 if let Some(pending_selection) = pending_selection {
11956 s.set_pending(pending_selection, SelectMode::Character);
11957 } else {
11958 s.clear_pending();
11959 }
11960 });
11961 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11962 }
11963
11964 fn push_to_selection_history(&mut self) {
11965 self.selection_history.push(SelectionHistoryEntry {
11966 selections: self.selections.disjoint_anchors(),
11967 select_next_state: self.select_next_state.clone(),
11968 select_prev_state: self.select_prev_state.clone(),
11969 add_selections_state: self.add_selections_state.clone(),
11970 });
11971 }
11972
11973 pub fn transact(
11974 &mut self,
11975 window: &mut Window,
11976 cx: &mut Context<Self>,
11977 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11978 ) -> Option<TransactionId> {
11979 self.start_transaction_at(Instant::now(), window, cx);
11980 update(self, window, cx);
11981 self.end_transaction_at(Instant::now(), cx)
11982 }
11983
11984 pub fn start_transaction_at(
11985 &mut self,
11986 now: Instant,
11987 window: &mut Window,
11988 cx: &mut Context<Self>,
11989 ) {
11990 self.end_selection(window, cx);
11991 if let Some(tx_id) = self
11992 .buffer
11993 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11994 {
11995 self.selection_history
11996 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11997 cx.emit(EditorEvent::TransactionBegun {
11998 transaction_id: tx_id,
11999 })
12000 }
12001 }
12002
12003 pub fn end_transaction_at(
12004 &mut self,
12005 now: Instant,
12006 cx: &mut Context<Self>,
12007 ) -> Option<TransactionId> {
12008 if let Some(transaction_id) = self
12009 .buffer
12010 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12011 {
12012 if let Some((_, end_selections)) =
12013 self.selection_history.transaction_mut(transaction_id)
12014 {
12015 *end_selections = Some(self.selections.disjoint_anchors());
12016 } else {
12017 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12018 }
12019
12020 cx.emit(EditorEvent::Edited { transaction_id });
12021 Some(transaction_id)
12022 } else {
12023 None
12024 }
12025 }
12026
12027 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12028 if self.selection_mark_mode {
12029 self.change_selections(None, window, cx, |s| {
12030 s.move_with(|_, sel| {
12031 sel.collapse_to(sel.head(), SelectionGoal::None);
12032 });
12033 })
12034 }
12035 self.selection_mark_mode = true;
12036 cx.notify();
12037 }
12038
12039 pub fn swap_selection_ends(
12040 &mut self,
12041 _: &actions::SwapSelectionEnds,
12042 window: &mut Window,
12043 cx: &mut Context<Self>,
12044 ) {
12045 self.change_selections(None, window, cx, |s| {
12046 s.move_with(|_, sel| {
12047 if sel.start != sel.end {
12048 sel.reversed = !sel.reversed
12049 }
12050 });
12051 });
12052 self.request_autoscroll(Autoscroll::newest(), cx);
12053 cx.notify();
12054 }
12055
12056 pub fn toggle_fold(
12057 &mut self,
12058 _: &actions::ToggleFold,
12059 window: &mut Window,
12060 cx: &mut Context<Self>,
12061 ) {
12062 if self.is_singleton(cx) {
12063 let selection = self.selections.newest::<Point>(cx);
12064
12065 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12066 let range = if selection.is_empty() {
12067 let point = selection.head().to_display_point(&display_map);
12068 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12069 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12070 .to_point(&display_map);
12071 start..end
12072 } else {
12073 selection.range()
12074 };
12075 if display_map.folds_in_range(range).next().is_some() {
12076 self.unfold_lines(&Default::default(), window, cx)
12077 } else {
12078 self.fold(&Default::default(), window, cx)
12079 }
12080 } else {
12081 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12082 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12083 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12084 .map(|(snapshot, _, _)| snapshot.remote_id())
12085 .collect();
12086
12087 for buffer_id in buffer_ids {
12088 if self.is_buffer_folded(buffer_id, cx) {
12089 self.unfold_buffer(buffer_id, cx);
12090 } else {
12091 self.fold_buffer(buffer_id, cx);
12092 }
12093 }
12094 }
12095 }
12096
12097 pub fn toggle_fold_recursive(
12098 &mut self,
12099 _: &actions::ToggleFoldRecursive,
12100 window: &mut Window,
12101 cx: &mut Context<Self>,
12102 ) {
12103 let selection = self.selections.newest::<Point>(cx);
12104
12105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12106 let range = if selection.is_empty() {
12107 let point = selection.head().to_display_point(&display_map);
12108 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12109 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12110 .to_point(&display_map);
12111 start..end
12112 } else {
12113 selection.range()
12114 };
12115 if display_map.folds_in_range(range).next().is_some() {
12116 self.unfold_recursive(&Default::default(), window, cx)
12117 } else {
12118 self.fold_recursive(&Default::default(), window, cx)
12119 }
12120 }
12121
12122 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12123 if self.is_singleton(cx) {
12124 let mut to_fold = Vec::new();
12125 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12126 let selections = self.selections.all_adjusted(cx);
12127
12128 for selection in selections {
12129 let range = selection.range().sorted();
12130 let buffer_start_row = range.start.row;
12131
12132 if range.start.row != range.end.row {
12133 let mut found = false;
12134 let mut row = range.start.row;
12135 while row <= range.end.row {
12136 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12137 {
12138 found = true;
12139 row = crease.range().end.row + 1;
12140 to_fold.push(crease);
12141 } else {
12142 row += 1
12143 }
12144 }
12145 if found {
12146 continue;
12147 }
12148 }
12149
12150 for row in (0..=range.start.row).rev() {
12151 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12152 if crease.range().end.row >= buffer_start_row {
12153 to_fold.push(crease);
12154 if row <= range.start.row {
12155 break;
12156 }
12157 }
12158 }
12159 }
12160 }
12161
12162 self.fold_creases(to_fold, true, window, cx);
12163 } else {
12164 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12165
12166 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12167 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12168 .map(|(snapshot, _, _)| snapshot.remote_id())
12169 .collect();
12170 for buffer_id in buffer_ids {
12171 self.fold_buffer(buffer_id, cx);
12172 }
12173 }
12174 }
12175
12176 fn fold_at_level(
12177 &mut self,
12178 fold_at: &FoldAtLevel,
12179 window: &mut Window,
12180 cx: &mut Context<Self>,
12181 ) {
12182 if !self.buffer.read(cx).is_singleton() {
12183 return;
12184 }
12185
12186 let fold_at_level = fold_at.0;
12187 let snapshot = self.buffer.read(cx).snapshot(cx);
12188 let mut to_fold = Vec::new();
12189 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12190
12191 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12192 while start_row < end_row {
12193 match self
12194 .snapshot(window, cx)
12195 .crease_for_buffer_row(MultiBufferRow(start_row))
12196 {
12197 Some(crease) => {
12198 let nested_start_row = crease.range().start.row + 1;
12199 let nested_end_row = crease.range().end.row;
12200
12201 if current_level < fold_at_level {
12202 stack.push((nested_start_row, nested_end_row, current_level + 1));
12203 } else if current_level == fold_at_level {
12204 to_fold.push(crease);
12205 }
12206
12207 start_row = nested_end_row + 1;
12208 }
12209 None => start_row += 1,
12210 }
12211 }
12212 }
12213
12214 self.fold_creases(to_fold, true, window, cx);
12215 }
12216
12217 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12218 if self.buffer.read(cx).is_singleton() {
12219 let mut fold_ranges = Vec::new();
12220 let snapshot = self.buffer.read(cx).snapshot(cx);
12221
12222 for row in 0..snapshot.max_row().0 {
12223 if let Some(foldable_range) = self
12224 .snapshot(window, cx)
12225 .crease_for_buffer_row(MultiBufferRow(row))
12226 {
12227 fold_ranges.push(foldable_range);
12228 }
12229 }
12230
12231 self.fold_creases(fold_ranges, true, window, cx);
12232 } else {
12233 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12234 editor
12235 .update_in(&mut cx, |editor, _, cx| {
12236 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12237 editor.fold_buffer(buffer_id, cx);
12238 }
12239 })
12240 .ok();
12241 });
12242 }
12243 }
12244
12245 pub fn fold_function_bodies(
12246 &mut self,
12247 _: &actions::FoldFunctionBodies,
12248 window: &mut Window,
12249 cx: &mut Context<Self>,
12250 ) {
12251 let snapshot = self.buffer.read(cx).snapshot(cx);
12252
12253 let ranges = snapshot
12254 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12255 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12256 .collect::<Vec<_>>();
12257
12258 let creases = ranges
12259 .into_iter()
12260 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12261 .collect();
12262
12263 self.fold_creases(creases, true, window, cx);
12264 }
12265
12266 pub fn fold_recursive(
12267 &mut self,
12268 _: &actions::FoldRecursive,
12269 window: &mut Window,
12270 cx: &mut Context<Self>,
12271 ) {
12272 let mut to_fold = Vec::new();
12273 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12274 let selections = self.selections.all_adjusted(cx);
12275
12276 for selection in selections {
12277 let range = selection.range().sorted();
12278 let buffer_start_row = range.start.row;
12279
12280 if range.start.row != range.end.row {
12281 let mut found = false;
12282 for row in range.start.row..=range.end.row {
12283 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12284 found = true;
12285 to_fold.push(crease);
12286 }
12287 }
12288 if found {
12289 continue;
12290 }
12291 }
12292
12293 for row in (0..=range.start.row).rev() {
12294 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12295 if crease.range().end.row >= buffer_start_row {
12296 to_fold.push(crease);
12297 } else {
12298 break;
12299 }
12300 }
12301 }
12302 }
12303
12304 self.fold_creases(to_fold, true, window, cx);
12305 }
12306
12307 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12308 let buffer_row = fold_at.buffer_row;
12309 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12310
12311 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12312 let autoscroll = self
12313 .selections
12314 .all::<Point>(cx)
12315 .iter()
12316 .any(|selection| crease.range().overlaps(&selection.range()));
12317
12318 self.fold_creases(vec![crease], autoscroll, window, cx);
12319 }
12320 }
12321
12322 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12323 if self.is_singleton(cx) {
12324 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12325 let buffer = &display_map.buffer_snapshot;
12326 let selections = self.selections.all::<Point>(cx);
12327 let ranges = selections
12328 .iter()
12329 .map(|s| {
12330 let range = s.display_range(&display_map).sorted();
12331 let mut start = range.start.to_point(&display_map);
12332 let mut end = range.end.to_point(&display_map);
12333 start.column = 0;
12334 end.column = buffer.line_len(MultiBufferRow(end.row));
12335 start..end
12336 })
12337 .collect::<Vec<_>>();
12338
12339 self.unfold_ranges(&ranges, true, true, cx);
12340 } else {
12341 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12342 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12343 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12344 .map(|(snapshot, _, _)| snapshot.remote_id())
12345 .collect();
12346 for buffer_id in buffer_ids {
12347 self.unfold_buffer(buffer_id, cx);
12348 }
12349 }
12350 }
12351
12352 pub fn unfold_recursive(
12353 &mut self,
12354 _: &UnfoldRecursive,
12355 _window: &mut Window,
12356 cx: &mut Context<Self>,
12357 ) {
12358 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12359 let selections = self.selections.all::<Point>(cx);
12360 let ranges = selections
12361 .iter()
12362 .map(|s| {
12363 let mut range = s.display_range(&display_map).sorted();
12364 *range.start.column_mut() = 0;
12365 *range.end.column_mut() = display_map.line_len(range.end.row());
12366 let start = range.start.to_point(&display_map);
12367 let end = range.end.to_point(&display_map);
12368 start..end
12369 })
12370 .collect::<Vec<_>>();
12371
12372 self.unfold_ranges(&ranges, true, true, cx);
12373 }
12374
12375 pub fn unfold_at(
12376 &mut self,
12377 unfold_at: &UnfoldAt,
12378 _window: &mut Window,
12379 cx: &mut Context<Self>,
12380 ) {
12381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12382
12383 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12384 ..Point::new(
12385 unfold_at.buffer_row.0,
12386 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12387 );
12388
12389 let autoscroll = self
12390 .selections
12391 .all::<Point>(cx)
12392 .iter()
12393 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12394
12395 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12396 }
12397
12398 pub fn unfold_all(
12399 &mut self,
12400 _: &actions::UnfoldAll,
12401 _window: &mut Window,
12402 cx: &mut Context<Self>,
12403 ) {
12404 if self.buffer.read(cx).is_singleton() {
12405 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12406 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12407 } else {
12408 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12409 editor
12410 .update(&mut cx, |editor, cx| {
12411 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12412 editor.unfold_buffer(buffer_id, cx);
12413 }
12414 })
12415 .ok();
12416 });
12417 }
12418 }
12419
12420 pub fn fold_selected_ranges(
12421 &mut self,
12422 _: &FoldSelectedRanges,
12423 window: &mut Window,
12424 cx: &mut Context<Self>,
12425 ) {
12426 let selections = self.selections.all::<Point>(cx);
12427 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12428 let line_mode = self.selections.line_mode;
12429 let ranges = selections
12430 .into_iter()
12431 .map(|s| {
12432 if line_mode {
12433 let start = Point::new(s.start.row, 0);
12434 let end = Point::new(
12435 s.end.row,
12436 display_map
12437 .buffer_snapshot
12438 .line_len(MultiBufferRow(s.end.row)),
12439 );
12440 Crease::simple(start..end, display_map.fold_placeholder.clone())
12441 } else {
12442 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12443 }
12444 })
12445 .collect::<Vec<_>>();
12446 self.fold_creases(ranges, true, window, cx);
12447 }
12448
12449 pub fn fold_ranges<T: ToOffset + Clone>(
12450 &mut self,
12451 ranges: Vec<Range<T>>,
12452 auto_scroll: bool,
12453 window: &mut Window,
12454 cx: &mut Context<Self>,
12455 ) {
12456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12457 let ranges = ranges
12458 .into_iter()
12459 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12460 .collect::<Vec<_>>();
12461 self.fold_creases(ranges, auto_scroll, window, cx);
12462 }
12463
12464 pub fn fold_creases<T: ToOffset + Clone>(
12465 &mut self,
12466 creases: Vec<Crease<T>>,
12467 auto_scroll: bool,
12468 window: &mut Window,
12469 cx: &mut Context<Self>,
12470 ) {
12471 if creases.is_empty() {
12472 return;
12473 }
12474
12475 let mut buffers_affected = HashSet::default();
12476 let multi_buffer = self.buffer().read(cx);
12477 for crease in &creases {
12478 if let Some((_, buffer, _)) =
12479 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12480 {
12481 buffers_affected.insert(buffer.read(cx).remote_id());
12482 };
12483 }
12484
12485 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12486
12487 if auto_scroll {
12488 self.request_autoscroll(Autoscroll::fit(), cx);
12489 }
12490
12491 cx.notify();
12492
12493 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12494 // Clear diagnostics block when folding a range that contains it.
12495 let snapshot = self.snapshot(window, cx);
12496 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12497 drop(snapshot);
12498 self.active_diagnostics = Some(active_diagnostics);
12499 self.dismiss_diagnostics(cx);
12500 } else {
12501 self.active_diagnostics = Some(active_diagnostics);
12502 }
12503 }
12504
12505 self.scrollbar_marker_state.dirty = true;
12506 }
12507
12508 /// Removes any folds whose ranges intersect any of the given ranges.
12509 pub fn unfold_ranges<T: ToOffset + Clone>(
12510 &mut self,
12511 ranges: &[Range<T>],
12512 inclusive: bool,
12513 auto_scroll: bool,
12514 cx: &mut Context<Self>,
12515 ) {
12516 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12517 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12518 });
12519 }
12520
12521 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12522 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12523 return;
12524 }
12525 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12526 self.display_map
12527 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12528 cx.emit(EditorEvent::BufferFoldToggled {
12529 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12530 folded: true,
12531 });
12532 cx.notify();
12533 }
12534
12535 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12536 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12537 return;
12538 }
12539 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12540 self.display_map.update(cx, |display_map, cx| {
12541 display_map.unfold_buffer(buffer_id, cx);
12542 });
12543 cx.emit(EditorEvent::BufferFoldToggled {
12544 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12545 folded: false,
12546 });
12547 cx.notify();
12548 }
12549
12550 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12551 self.display_map.read(cx).is_buffer_folded(buffer)
12552 }
12553
12554 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12555 self.display_map.read(cx).folded_buffers()
12556 }
12557
12558 /// Removes any folds with the given ranges.
12559 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12560 &mut self,
12561 ranges: &[Range<T>],
12562 type_id: TypeId,
12563 auto_scroll: bool,
12564 cx: &mut Context<Self>,
12565 ) {
12566 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12567 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12568 });
12569 }
12570
12571 fn remove_folds_with<T: ToOffset + Clone>(
12572 &mut self,
12573 ranges: &[Range<T>],
12574 auto_scroll: bool,
12575 cx: &mut Context<Self>,
12576 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12577 ) {
12578 if ranges.is_empty() {
12579 return;
12580 }
12581
12582 let mut buffers_affected = HashSet::default();
12583 let multi_buffer = self.buffer().read(cx);
12584 for range in ranges {
12585 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12586 buffers_affected.insert(buffer.read(cx).remote_id());
12587 };
12588 }
12589
12590 self.display_map.update(cx, update);
12591
12592 if auto_scroll {
12593 self.request_autoscroll(Autoscroll::fit(), cx);
12594 }
12595
12596 cx.notify();
12597 self.scrollbar_marker_state.dirty = true;
12598 self.active_indent_guides_state.dirty = true;
12599 }
12600
12601 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12602 self.display_map.read(cx).fold_placeholder.clone()
12603 }
12604
12605 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12606 self.buffer.update(cx, |buffer, cx| {
12607 buffer.set_all_diff_hunks_expanded(cx);
12608 });
12609 }
12610
12611 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12612 self.distinguish_unstaged_diff_hunks = true;
12613 }
12614
12615 pub fn expand_all_diff_hunks(
12616 &mut self,
12617 _: &ExpandAllHunkDiffs,
12618 _window: &mut Window,
12619 cx: &mut Context<Self>,
12620 ) {
12621 self.buffer.update(cx, |buffer, cx| {
12622 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12623 });
12624 }
12625
12626 pub fn toggle_selected_diff_hunks(
12627 &mut self,
12628 _: &ToggleSelectedDiffHunks,
12629 _window: &mut Window,
12630 cx: &mut Context<Self>,
12631 ) {
12632 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12633 self.toggle_diff_hunks_in_ranges(ranges, cx);
12634 }
12635
12636 fn diff_hunks_in_ranges<'a>(
12637 &'a self,
12638 ranges: &'a [Range<Anchor>],
12639 buffer: &'a MultiBufferSnapshot,
12640 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12641 ranges.iter().flat_map(move |range| {
12642 let end_excerpt_id = range.end.excerpt_id;
12643 let range = range.to_point(buffer);
12644 let mut peek_end = range.end;
12645 if range.end.row < buffer.max_row().0 {
12646 peek_end = Point::new(range.end.row + 1, 0);
12647 }
12648 buffer
12649 .diff_hunks_in_range(range.start..peek_end)
12650 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12651 })
12652 }
12653
12654 pub fn has_stageable_diff_hunks_in_ranges(
12655 &self,
12656 ranges: &[Range<Anchor>],
12657 snapshot: &MultiBufferSnapshot,
12658 ) -> bool {
12659 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12660 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12661 }
12662
12663 pub fn toggle_staged_selected_diff_hunks(
12664 &mut self,
12665 _: &ToggleStagedSelectedDiffHunks,
12666 _window: &mut Window,
12667 cx: &mut Context<Self>,
12668 ) {
12669 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12670 self.stage_or_unstage_diff_hunks(&ranges, cx);
12671 }
12672
12673 pub fn stage_or_unstage_diff_hunks(
12674 &mut self,
12675 ranges: &[Range<Anchor>],
12676 cx: &mut Context<Self>,
12677 ) {
12678 let Some(project) = &self.project else {
12679 return;
12680 };
12681 let snapshot = self.buffer.read(cx).snapshot(cx);
12682 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12683
12684 let chunk_by = self
12685 .diff_hunks_in_ranges(&ranges, &snapshot)
12686 .chunk_by(|hunk| hunk.buffer_id);
12687 for (buffer_id, hunks) in &chunk_by {
12688 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12689 log::debug!("no buffer for id");
12690 continue;
12691 };
12692 let buffer = buffer.read(cx).snapshot();
12693 let Some((repo, path)) = project
12694 .read(cx)
12695 .repository_and_path_for_buffer_id(buffer_id, cx)
12696 else {
12697 log::debug!("no git repo for buffer id");
12698 continue;
12699 };
12700 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12701 log::debug!("no diff for buffer id");
12702 continue;
12703 };
12704 let Some(secondary_diff) = diff.secondary_diff() else {
12705 log::debug!("no secondary diff for buffer id");
12706 continue;
12707 };
12708
12709 let edits = diff.secondary_edits_for_stage_or_unstage(
12710 stage,
12711 hunks.map(|hunk| {
12712 (
12713 hunk.diff_base_byte_range.clone(),
12714 hunk.secondary_diff_base_byte_range.clone(),
12715 hunk.buffer_range.clone(),
12716 )
12717 }),
12718 &buffer,
12719 );
12720
12721 let index_base = secondary_diff.base_text().map_or_else(
12722 || Rope::from(""),
12723 |snapshot| snapshot.text.as_rope().clone(),
12724 );
12725 let index_buffer = cx.new(|cx| {
12726 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12727 });
12728 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12729 index_buffer.edit(edits, None, cx);
12730 index_buffer.snapshot().as_rope().to_string()
12731 });
12732 let new_index_text = if new_index_text.is_empty()
12733 && (diff.is_single_insertion
12734 || buffer
12735 .file()
12736 .map_or(false, |file| file.disk_state() == DiskState::New))
12737 {
12738 log::debug!("removing from index");
12739 None
12740 } else {
12741 Some(new_index_text)
12742 };
12743
12744 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12745 }
12746 }
12747
12748 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12749 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12750 self.buffer
12751 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12752 }
12753
12754 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12755 self.buffer.update(cx, |buffer, cx| {
12756 let ranges = vec![Anchor::min()..Anchor::max()];
12757 if !buffer.all_diff_hunks_expanded()
12758 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12759 {
12760 buffer.collapse_diff_hunks(ranges, cx);
12761 true
12762 } else {
12763 false
12764 }
12765 })
12766 }
12767
12768 fn toggle_diff_hunks_in_ranges(
12769 &mut self,
12770 ranges: Vec<Range<Anchor>>,
12771 cx: &mut Context<'_, Editor>,
12772 ) {
12773 self.buffer.update(cx, |buffer, cx| {
12774 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12775 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12776 })
12777 }
12778
12779 fn toggle_diff_hunks_in_ranges_narrow(
12780 &mut self,
12781 ranges: Vec<Range<Anchor>>,
12782 cx: &mut Context<'_, Editor>,
12783 ) {
12784 self.buffer.update(cx, |buffer, cx| {
12785 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12786 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12787 })
12788 }
12789
12790 pub(crate) fn apply_all_diff_hunks(
12791 &mut self,
12792 _: &ApplyAllDiffHunks,
12793 window: &mut Window,
12794 cx: &mut Context<Self>,
12795 ) {
12796 let buffers = self.buffer.read(cx).all_buffers();
12797 for branch_buffer in buffers {
12798 branch_buffer.update(cx, |branch_buffer, cx| {
12799 branch_buffer.merge_into_base(Vec::new(), cx);
12800 });
12801 }
12802
12803 if let Some(project) = self.project.clone() {
12804 self.save(true, project, window, cx).detach_and_log_err(cx);
12805 }
12806 }
12807
12808 pub(crate) fn apply_selected_diff_hunks(
12809 &mut self,
12810 _: &ApplyDiffHunk,
12811 window: &mut Window,
12812 cx: &mut Context<Self>,
12813 ) {
12814 let snapshot = self.snapshot(window, cx);
12815 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12816 let mut ranges_by_buffer = HashMap::default();
12817 self.transact(window, cx, |editor, _window, cx| {
12818 for hunk in hunks {
12819 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12820 ranges_by_buffer
12821 .entry(buffer.clone())
12822 .or_insert_with(Vec::new)
12823 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12824 }
12825 }
12826
12827 for (buffer, ranges) in ranges_by_buffer {
12828 buffer.update(cx, |buffer, cx| {
12829 buffer.merge_into_base(ranges, cx);
12830 });
12831 }
12832 });
12833
12834 if let Some(project) = self.project.clone() {
12835 self.save(true, project, window, cx).detach_and_log_err(cx);
12836 }
12837 }
12838
12839 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12840 if hovered != self.gutter_hovered {
12841 self.gutter_hovered = hovered;
12842 cx.notify();
12843 }
12844 }
12845
12846 pub fn insert_blocks(
12847 &mut self,
12848 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12849 autoscroll: Option<Autoscroll>,
12850 cx: &mut Context<Self>,
12851 ) -> Vec<CustomBlockId> {
12852 let blocks = self
12853 .display_map
12854 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12855 if let Some(autoscroll) = autoscroll {
12856 self.request_autoscroll(autoscroll, cx);
12857 }
12858 cx.notify();
12859 blocks
12860 }
12861
12862 pub fn resize_blocks(
12863 &mut self,
12864 heights: HashMap<CustomBlockId, u32>,
12865 autoscroll: Option<Autoscroll>,
12866 cx: &mut Context<Self>,
12867 ) {
12868 self.display_map
12869 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12870 if let Some(autoscroll) = autoscroll {
12871 self.request_autoscroll(autoscroll, cx);
12872 }
12873 cx.notify();
12874 }
12875
12876 pub fn replace_blocks(
12877 &mut self,
12878 renderers: HashMap<CustomBlockId, RenderBlock>,
12879 autoscroll: Option<Autoscroll>,
12880 cx: &mut Context<Self>,
12881 ) {
12882 self.display_map
12883 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12884 if let Some(autoscroll) = autoscroll {
12885 self.request_autoscroll(autoscroll, cx);
12886 }
12887 cx.notify();
12888 }
12889
12890 pub fn remove_blocks(
12891 &mut self,
12892 block_ids: HashSet<CustomBlockId>,
12893 autoscroll: Option<Autoscroll>,
12894 cx: &mut Context<Self>,
12895 ) {
12896 self.display_map.update(cx, |display_map, cx| {
12897 display_map.remove_blocks(block_ids, cx)
12898 });
12899 if let Some(autoscroll) = autoscroll {
12900 self.request_autoscroll(autoscroll, cx);
12901 }
12902 cx.notify();
12903 }
12904
12905 pub fn row_for_block(
12906 &self,
12907 block_id: CustomBlockId,
12908 cx: &mut Context<Self>,
12909 ) -> Option<DisplayRow> {
12910 self.display_map
12911 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12912 }
12913
12914 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12915 self.focused_block = Some(focused_block);
12916 }
12917
12918 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12919 self.focused_block.take()
12920 }
12921
12922 pub fn insert_creases(
12923 &mut self,
12924 creases: impl IntoIterator<Item = Crease<Anchor>>,
12925 cx: &mut Context<Self>,
12926 ) -> Vec<CreaseId> {
12927 self.display_map
12928 .update(cx, |map, cx| map.insert_creases(creases, cx))
12929 }
12930
12931 pub fn remove_creases(
12932 &mut self,
12933 ids: impl IntoIterator<Item = CreaseId>,
12934 cx: &mut Context<Self>,
12935 ) {
12936 self.display_map
12937 .update(cx, |map, cx| map.remove_creases(ids, cx));
12938 }
12939
12940 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12941 self.display_map
12942 .update(cx, |map, cx| map.snapshot(cx))
12943 .longest_row()
12944 }
12945
12946 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12947 self.display_map
12948 .update(cx, |map, cx| map.snapshot(cx))
12949 .max_point()
12950 }
12951
12952 pub fn text(&self, cx: &App) -> String {
12953 self.buffer.read(cx).read(cx).text()
12954 }
12955
12956 pub fn is_empty(&self, cx: &App) -> bool {
12957 self.buffer.read(cx).read(cx).is_empty()
12958 }
12959
12960 pub fn text_option(&self, cx: &App) -> Option<String> {
12961 let text = self.text(cx);
12962 let text = text.trim();
12963
12964 if text.is_empty() {
12965 return None;
12966 }
12967
12968 Some(text.to_string())
12969 }
12970
12971 pub fn set_text(
12972 &mut self,
12973 text: impl Into<Arc<str>>,
12974 window: &mut Window,
12975 cx: &mut Context<Self>,
12976 ) {
12977 self.transact(window, cx, |this, _, cx| {
12978 this.buffer
12979 .read(cx)
12980 .as_singleton()
12981 .expect("you can only call set_text on editors for singleton buffers")
12982 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12983 });
12984 }
12985
12986 pub fn display_text(&self, cx: &mut App) -> String {
12987 self.display_map
12988 .update(cx, |map, cx| map.snapshot(cx))
12989 .text()
12990 }
12991
12992 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12993 let mut wrap_guides = smallvec::smallvec![];
12994
12995 if self.show_wrap_guides == Some(false) {
12996 return wrap_guides;
12997 }
12998
12999 let settings = self.buffer.read(cx).settings_at(0, cx);
13000 if settings.show_wrap_guides {
13001 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13002 wrap_guides.push((soft_wrap as usize, true));
13003 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13004 wrap_guides.push((soft_wrap as usize, true));
13005 }
13006 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13007 }
13008
13009 wrap_guides
13010 }
13011
13012 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13013 let settings = self.buffer.read(cx).settings_at(0, cx);
13014 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13015 match mode {
13016 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13017 SoftWrap::None
13018 }
13019 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13020 language_settings::SoftWrap::PreferredLineLength => {
13021 SoftWrap::Column(settings.preferred_line_length)
13022 }
13023 language_settings::SoftWrap::Bounded => {
13024 SoftWrap::Bounded(settings.preferred_line_length)
13025 }
13026 }
13027 }
13028
13029 pub fn set_soft_wrap_mode(
13030 &mut self,
13031 mode: language_settings::SoftWrap,
13032
13033 cx: &mut Context<Self>,
13034 ) {
13035 self.soft_wrap_mode_override = Some(mode);
13036 cx.notify();
13037 }
13038
13039 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13040 self.text_style_refinement = Some(style);
13041 }
13042
13043 /// called by the Element so we know what style we were most recently rendered with.
13044 pub(crate) fn set_style(
13045 &mut self,
13046 style: EditorStyle,
13047 window: &mut Window,
13048 cx: &mut Context<Self>,
13049 ) {
13050 let rem_size = window.rem_size();
13051 self.display_map.update(cx, |map, cx| {
13052 map.set_font(
13053 style.text.font(),
13054 style.text.font_size.to_pixels(rem_size),
13055 cx,
13056 )
13057 });
13058 self.style = Some(style);
13059 }
13060
13061 pub fn style(&self) -> Option<&EditorStyle> {
13062 self.style.as_ref()
13063 }
13064
13065 // Called by the element. This method is not designed to be called outside of the editor
13066 // element's layout code because it does not notify when rewrapping is computed synchronously.
13067 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13068 self.display_map
13069 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13070 }
13071
13072 pub fn set_soft_wrap(&mut self) {
13073 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13074 }
13075
13076 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13077 if self.soft_wrap_mode_override.is_some() {
13078 self.soft_wrap_mode_override.take();
13079 } else {
13080 let soft_wrap = match self.soft_wrap_mode(cx) {
13081 SoftWrap::GitDiff => return,
13082 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13083 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13084 language_settings::SoftWrap::None
13085 }
13086 };
13087 self.soft_wrap_mode_override = Some(soft_wrap);
13088 }
13089 cx.notify();
13090 }
13091
13092 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13093 let Some(workspace) = self.workspace() else {
13094 return;
13095 };
13096 let fs = workspace.read(cx).app_state().fs.clone();
13097 let current_show = TabBarSettings::get_global(cx).show;
13098 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13099 setting.show = Some(!current_show);
13100 });
13101 }
13102
13103 pub fn toggle_indent_guides(
13104 &mut self,
13105 _: &ToggleIndentGuides,
13106 _: &mut Window,
13107 cx: &mut Context<Self>,
13108 ) {
13109 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13110 self.buffer
13111 .read(cx)
13112 .settings_at(0, cx)
13113 .indent_guides
13114 .enabled
13115 });
13116 self.show_indent_guides = Some(!currently_enabled);
13117 cx.notify();
13118 }
13119
13120 fn should_show_indent_guides(&self) -> Option<bool> {
13121 self.show_indent_guides
13122 }
13123
13124 pub fn toggle_line_numbers(
13125 &mut self,
13126 _: &ToggleLineNumbers,
13127 _: &mut Window,
13128 cx: &mut Context<Self>,
13129 ) {
13130 let mut editor_settings = EditorSettings::get_global(cx).clone();
13131 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13132 EditorSettings::override_global(editor_settings, cx);
13133 }
13134
13135 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13136 self.use_relative_line_numbers
13137 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13138 }
13139
13140 pub fn toggle_relative_line_numbers(
13141 &mut self,
13142 _: &ToggleRelativeLineNumbers,
13143 _: &mut Window,
13144 cx: &mut Context<Self>,
13145 ) {
13146 let is_relative = self.should_use_relative_line_numbers(cx);
13147 self.set_relative_line_number(Some(!is_relative), cx)
13148 }
13149
13150 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13151 self.use_relative_line_numbers = is_relative;
13152 cx.notify();
13153 }
13154
13155 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13156 self.show_gutter = show_gutter;
13157 cx.notify();
13158 }
13159
13160 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13161 self.show_scrollbars = show_scrollbars;
13162 cx.notify();
13163 }
13164
13165 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13166 self.show_line_numbers = Some(show_line_numbers);
13167 cx.notify();
13168 }
13169
13170 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13171 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13172 cx.notify();
13173 }
13174
13175 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13176 self.show_code_actions = Some(show_code_actions);
13177 cx.notify();
13178 }
13179
13180 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13181 self.show_runnables = Some(show_runnables);
13182 cx.notify();
13183 }
13184
13185 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13186 if self.display_map.read(cx).masked != masked {
13187 self.display_map.update(cx, |map, _| map.masked = masked);
13188 }
13189 cx.notify()
13190 }
13191
13192 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13193 self.show_wrap_guides = Some(show_wrap_guides);
13194 cx.notify();
13195 }
13196
13197 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13198 self.show_indent_guides = Some(show_indent_guides);
13199 cx.notify();
13200 }
13201
13202 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13203 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13204 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13205 if let Some(dir) = file.abs_path(cx).parent() {
13206 return Some(dir.to_owned());
13207 }
13208 }
13209
13210 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13211 return Some(project_path.path.to_path_buf());
13212 }
13213 }
13214
13215 None
13216 }
13217
13218 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13219 self.active_excerpt(cx)?
13220 .1
13221 .read(cx)
13222 .file()
13223 .and_then(|f| f.as_local())
13224 }
13225
13226 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13227 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13228 let buffer = buffer.read(cx);
13229 if let Some(project_path) = buffer.project_path(cx) {
13230 let project = self.project.as_ref()?.read(cx);
13231 project.absolute_path(&project_path, cx)
13232 } else {
13233 buffer
13234 .file()
13235 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13236 }
13237 })
13238 }
13239
13240 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13241 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13242 let project_path = buffer.read(cx).project_path(cx)?;
13243 let project = self.project.as_ref()?.read(cx);
13244 let entry = project.entry_for_path(&project_path, cx)?;
13245 let path = entry.path.to_path_buf();
13246 Some(path)
13247 })
13248 }
13249
13250 pub fn reveal_in_finder(
13251 &mut self,
13252 _: &RevealInFileManager,
13253 _window: &mut Window,
13254 cx: &mut Context<Self>,
13255 ) {
13256 if let Some(target) = self.target_file(cx) {
13257 cx.reveal_path(&target.abs_path(cx));
13258 }
13259 }
13260
13261 pub fn copy_path(
13262 &mut self,
13263 _: &zed_actions::workspace::CopyPath,
13264 _window: &mut Window,
13265 cx: &mut Context<Self>,
13266 ) {
13267 if let Some(path) = self.target_file_abs_path(cx) {
13268 if let Some(path) = path.to_str() {
13269 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13270 }
13271 }
13272 }
13273
13274 pub fn copy_relative_path(
13275 &mut self,
13276 _: &zed_actions::workspace::CopyRelativePath,
13277 _window: &mut Window,
13278 cx: &mut Context<Self>,
13279 ) {
13280 if let Some(path) = self.target_file_path(cx) {
13281 if let Some(path) = path.to_str() {
13282 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13283 }
13284 }
13285 }
13286
13287 pub fn copy_file_name_without_extension(
13288 &mut self,
13289 _: &CopyFileNameWithoutExtension,
13290 _: &mut Window,
13291 cx: &mut Context<Self>,
13292 ) {
13293 if let Some(file) = self.target_file(cx) {
13294 if let Some(file_stem) = file.path().file_stem() {
13295 if let Some(name) = file_stem.to_str() {
13296 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13297 }
13298 }
13299 }
13300 }
13301
13302 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13303 if let Some(file) = self.target_file(cx) {
13304 if let Some(file_name) = file.path().file_name() {
13305 if let Some(name) = file_name.to_str() {
13306 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13307 }
13308 }
13309 }
13310 }
13311
13312 pub fn toggle_git_blame(
13313 &mut self,
13314 _: &ToggleGitBlame,
13315 window: &mut Window,
13316 cx: &mut Context<Self>,
13317 ) {
13318 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13319
13320 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13321 self.start_git_blame(true, window, cx);
13322 }
13323
13324 cx.notify();
13325 }
13326
13327 pub fn toggle_git_blame_inline(
13328 &mut self,
13329 _: &ToggleGitBlameInline,
13330 window: &mut Window,
13331 cx: &mut Context<Self>,
13332 ) {
13333 self.toggle_git_blame_inline_internal(true, window, cx);
13334 cx.notify();
13335 }
13336
13337 pub fn git_blame_inline_enabled(&self) -> bool {
13338 self.git_blame_inline_enabled
13339 }
13340
13341 pub fn toggle_selection_menu(
13342 &mut self,
13343 _: &ToggleSelectionMenu,
13344 _: &mut Window,
13345 cx: &mut Context<Self>,
13346 ) {
13347 self.show_selection_menu = self
13348 .show_selection_menu
13349 .map(|show_selections_menu| !show_selections_menu)
13350 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13351
13352 cx.notify();
13353 }
13354
13355 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13356 self.show_selection_menu
13357 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13358 }
13359
13360 fn start_git_blame(
13361 &mut self,
13362 user_triggered: bool,
13363 window: &mut Window,
13364 cx: &mut Context<Self>,
13365 ) {
13366 if let Some(project) = self.project.as_ref() {
13367 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13368 return;
13369 };
13370
13371 if buffer.read(cx).file().is_none() {
13372 return;
13373 }
13374
13375 let focused = self.focus_handle(cx).contains_focused(window, cx);
13376
13377 let project = project.clone();
13378 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13379 self.blame_subscription =
13380 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13381 self.blame = Some(blame);
13382 }
13383 }
13384
13385 fn toggle_git_blame_inline_internal(
13386 &mut self,
13387 user_triggered: bool,
13388 window: &mut Window,
13389 cx: &mut Context<Self>,
13390 ) {
13391 if self.git_blame_inline_enabled {
13392 self.git_blame_inline_enabled = false;
13393 self.show_git_blame_inline = false;
13394 self.show_git_blame_inline_delay_task.take();
13395 } else {
13396 self.git_blame_inline_enabled = true;
13397 self.start_git_blame_inline(user_triggered, window, cx);
13398 }
13399
13400 cx.notify();
13401 }
13402
13403 fn start_git_blame_inline(
13404 &mut self,
13405 user_triggered: bool,
13406 window: &mut Window,
13407 cx: &mut Context<Self>,
13408 ) {
13409 self.start_git_blame(user_triggered, window, cx);
13410
13411 if ProjectSettings::get_global(cx)
13412 .git
13413 .inline_blame_delay()
13414 .is_some()
13415 {
13416 self.start_inline_blame_timer(window, cx);
13417 } else {
13418 self.show_git_blame_inline = true
13419 }
13420 }
13421
13422 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13423 self.blame.as_ref()
13424 }
13425
13426 pub fn show_git_blame_gutter(&self) -> bool {
13427 self.show_git_blame_gutter
13428 }
13429
13430 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13431 self.show_git_blame_gutter && self.has_blame_entries(cx)
13432 }
13433
13434 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13435 self.show_git_blame_inline
13436 && self.focus_handle.is_focused(window)
13437 && !self.newest_selection_head_on_empty_line(cx)
13438 && self.has_blame_entries(cx)
13439 }
13440
13441 fn has_blame_entries(&self, cx: &App) -> bool {
13442 self.blame()
13443 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13444 }
13445
13446 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13447 let cursor_anchor = self.selections.newest_anchor().head();
13448
13449 let snapshot = self.buffer.read(cx).snapshot(cx);
13450 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13451
13452 snapshot.line_len(buffer_row) == 0
13453 }
13454
13455 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13456 let buffer_and_selection = maybe!({
13457 let selection = self.selections.newest::<Point>(cx);
13458 let selection_range = selection.range();
13459
13460 let multi_buffer = self.buffer().read(cx);
13461 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13462 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13463
13464 let (buffer, range, _) = if selection.reversed {
13465 buffer_ranges.first()
13466 } else {
13467 buffer_ranges.last()
13468 }?;
13469
13470 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13471 ..text::ToPoint::to_point(&range.end, &buffer).row;
13472 Some((
13473 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13474 selection,
13475 ))
13476 });
13477
13478 let Some((buffer, selection)) = buffer_and_selection else {
13479 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13480 };
13481
13482 let Some(project) = self.project.as_ref() else {
13483 return Task::ready(Err(anyhow!("editor does not have project")));
13484 };
13485
13486 project.update(cx, |project, cx| {
13487 project.get_permalink_to_line(&buffer, selection, cx)
13488 })
13489 }
13490
13491 pub fn copy_permalink_to_line(
13492 &mut self,
13493 _: &CopyPermalinkToLine,
13494 window: &mut Window,
13495 cx: &mut Context<Self>,
13496 ) {
13497 let permalink_task = self.get_permalink_to_line(cx);
13498 let workspace = self.workspace();
13499
13500 cx.spawn_in(window, |_, mut cx| async move {
13501 match permalink_task.await {
13502 Ok(permalink) => {
13503 cx.update(|_, cx| {
13504 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13505 })
13506 .ok();
13507 }
13508 Err(err) => {
13509 let message = format!("Failed to copy permalink: {err}");
13510
13511 Err::<(), anyhow::Error>(err).log_err();
13512
13513 if let Some(workspace) = workspace {
13514 workspace
13515 .update_in(&mut cx, |workspace, _, cx| {
13516 struct CopyPermalinkToLine;
13517
13518 workspace.show_toast(
13519 Toast::new(
13520 NotificationId::unique::<CopyPermalinkToLine>(),
13521 message,
13522 ),
13523 cx,
13524 )
13525 })
13526 .ok();
13527 }
13528 }
13529 }
13530 })
13531 .detach();
13532 }
13533
13534 pub fn copy_file_location(
13535 &mut self,
13536 _: &CopyFileLocation,
13537 _: &mut Window,
13538 cx: &mut Context<Self>,
13539 ) {
13540 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13541 if let Some(file) = self.target_file(cx) {
13542 if let Some(path) = file.path().to_str() {
13543 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13544 }
13545 }
13546 }
13547
13548 pub fn open_permalink_to_line(
13549 &mut self,
13550 _: &OpenPermalinkToLine,
13551 window: &mut Window,
13552 cx: &mut Context<Self>,
13553 ) {
13554 let permalink_task = self.get_permalink_to_line(cx);
13555 let workspace = self.workspace();
13556
13557 cx.spawn_in(window, |_, mut cx| async move {
13558 match permalink_task.await {
13559 Ok(permalink) => {
13560 cx.update(|_, cx| {
13561 cx.open_url(permalink.as_ref());
13562 })
13563 .ok();
13564 }
13565 Err(err) => {
13566 let message = format!("Failed to open permalink: {err}");
13567
13568 Err::<(), anyhow::Error>(err).log_err();
13569
13570 if let Some(workspace) = workspace {
13571 workspace
13572 .update(&mut cx, |workspace, cx| {
13573 struct OpenPermalinkToLine;
13574
13575 workspace.show_toast(
13576 Toast::new(
13577 NotificationId::unique::<OpenPermalinkToLine>(),
13578 message,
13579 ),
13580 cx,
13581 )
13582 })
13583 .ok();
13584 }
13585 }
13586 }
13587 })
13588 .detach();
13589 }
13590
13591 pub fn insert_uuid_v4(
13592 &mut self,
13593 _: &InsertUuidV4,
13594 window: &mut Window,
13595 cx: &mut Context<Self>,
13596 ) {
13597 self.insert_uuid(UuidVersion::V4, window, cx);
13598 }
13599
13600 pub fn insert_uuid_v7(
13601 &mut self,
13602 _: &InsertUuidV7,
13603 window: &mut Window,
13604 cx: &mut Context<Self>,
13605 ) {
13606 self.insert_uuid(UuidVersion::V7, window, cx);
13607 }
13608
13609 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13610 self.transact(window, cx, |this, window, cx| {
13611 let edits = this
13612 .selections
13613 .all::<Point>(cx)
13614 .into_iter()
13615 .map(|selection| {
13616 let uuid = match version {
13617 UuidVersion::V4 => uuid::Uuid::new_v4(),
13618 UuidVersion::V7 => uuid::Uuid::now_v7(),
13619 };
13620
13621 (selection.range(), uuid.to_string())
13622 });
13623 this.edit(edits, cx);
13624 this.refresh_inline_completion(true, false, window, cx);
13625 });
13626 }
13627
13628 pub fn open_selections_in_multibuffer(
13629 &mut self,
13630 _: &OpenSelectionsInMultibuffer,
13631 window: &mut Window,
13632 cx: &mut Context<Self>,
13633 ) {
13634 let multibuffer = self.buffer.read(cx);
13635
13636 let Some(buffer) = multibuffer.as_singleton() else {
13637 return;
13638 };
13639
13640 let Some(workspace) = self.workspace() else {
13641 return;
13642 };
13643
13644 let locations = self
13645 .selections
13646 .disjoint_anchors()
13647 .iter()
13648 .map(|range| Location {
13649 buffer: buffer.clone(),
13650 range: range.start.text_anchor..range.end.text_anchor,
13651 })
13652 .collect::<Vec<_>>();
13653
13654 let title = multibuffer.title(cx).to_string();
13655
13656 cx.spawn_in(window, |_, mut cx| async move {
13657 workspace.update_in(&mut cx, |workspace, window, cx| {
13658 Self::open_locations_in_multibuffer(
13659 workspace,
13660 locations,
13661 format!("Selections for '{title}'"),
13662 false,
13663 MultibufferSelectionMode::All,
13664 window,
13665 cx,
13666 );
13667 })
13668 })
13669 .detach();
13670 }
13671
13672 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13673 /// last highlight added will be used.
13674 ///
13675 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13676 pub fn highlight_rows<T: 'static>(
13677 &mut self,
13678 range: Range<Anchor>,
13679 color: Hsla,
13680 should_autoscroll: bool,
13681 cx: &mut Context<Self>,
13682 ) {
13683 let snapshot = self.buffer().read(cx).snapshot(cx);
13684 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13685 let ix = row_highlights.binary_search_by(|highlight| {
13686 Ordering::Equal
13687 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13688 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13689 });
13690
13691 if let Err(mut ix) = ix {
13692 let index = post_inc(&mut self.highlight_order);
13693
13694 // If this range intersects with the preceding highlight, then merge it with
13695 // the preceding highlight. Otherwise insert a new highlight.
13696 let mut merged = false;
13697 if ix > 0 {
13698 let prev_highlight = &mut row_highlights[ix - 1];
13699 if prev_highlight
13700 .range
13701 .end
13702 .cmp(&range.start, &snapshot)
13703 .is_ge()
13704 {
13705 ix -= 1;
13706 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13707 prev_highlight.range.end = range.end;
13708 }
13709 merged = true;
13710 prev_highlight.index = index;
13711 prev_highlight.color = color;
13712 prev_highlight.should_autoscroll = should_autoscroll;
13713 }
13714 }
13715
13716 if !merged {
13717 row_highlights.insert(
13718 ix,
13719 RowHighlight {
13720 range: range.clone(),
13721 index,
13722 color,
13723 should_autoscroll,
13724 },
13725 );
13726 }
13727
13728 // If any of the following highlights intersect with this one, merge them.
13729 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13730 let highlight = &row_highlights[ix];
13731 if next_highlight
13732 .range
13733 .start
13734 .cmp(&highlight.range.end, &snapshot)
13735 .is_le()
13736 {
13737 if next_highlight
13738 .range
13739 .end
13740 .cmp(&highlight.range.end, &snapshot)
13741 .is_gt()
13742 {
13743 row_highlights[ix].range.end = next_highlight.range.end;
13744 }
13745 row_highlights.remove(ix + 1);
13746 } else {
13747 break;
13748 }
13749 }
13750 }
13751 }
13752
13753 /// Remove any highlighted row ranges of the given type that intersect the
13754 /// given ranges.
13755 pub fn remove_highlighted_rows<T: 'static>(
13756 &mut self,
13757 ranges_to_remove: Vec<Range<Anchor>>,
13758 cx: &mut Context<Self>,
13759 ) {
13760 let snapshot = self.buffer().read(cx).snapshot(cx);
13761 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13762 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13763 row_highlights.retain(|highlight| {
13764 while let Some(range_to_remove) = ranges_to_remove.peek() {
13765 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13766 Ordering::Less | Ordering::Equal => {
13767 ranges_to_remove.next();
13768 }
13769 Ordering::Greater => {
13770 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13771 Ordering::Less | Ordering::Equal => {
13772 return false;
13773 }
13774 Ordering::Greater => break,
13775 }
13776 }
13777 }
13778 }
13779
13780 true
13781 })
13782 }
13783
13784 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13785 pub fn clear_row_highlights<T: 'static>(&mut self) {
13786 self.highlighted_rows.remove(&TypeId::of::<T>());
13787 }
13788
13789 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13790 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13791 self.highlighted_rows
13792 .get(&TypeId::of::<T>())
13793 .map_or(&[] as &[_], |vec| vec.as_slice())
13794 .iter()
13795 .map(|highlight| (highlight.range.clone(), highlight.color))
13796 }
13797
13798 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13799 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13800 /// Allows to ignore certain kinds of highlights.
13801 pub fn highlighted_display_rows(
13802 &self,
13803 window: &mut Window,
13804 cx: &mut App,
13805 ) -> BTreeMap<DisplayRow, Background> {
13806 let snapshot = self.snapshot(window, cx);
13807 let mut used_highlight_orders = HashMap::default();
13808 self.highlighted_rows
13809 .iter()
13810 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13811 .fold(
13812 BTreeMap::<DisplayRow, Background>::new(),
13813 |mut unique_rows, highlight| {
13814 let start = highlight.range.start.to_display_point(&snapshot);
13815 let end = highlight.range.end.to_display_point(&snapshot);
13816 let start_row = start.row().0;
13817 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13818 && end.column() == 0
13819 {
13820 end.row().0.saturating_sub(1)
13821 } else {
13822 end.row().0
13823 };
13824 for row in start_row..=end_row {
13825 let used_index =
13826 used_highlight_orders.entry(row).or_insert(highlight.index);
13827 if highlight.index >= *used_index {
13828 *used_index = highlight.index;
13829 unique_rows.insert(DisplayRow(row), highlight.color.into());
13830 }
13831 }
13832 unique_rows
13833 },
13834 )
13835 }
13836
13837 pub fn highlighted_display_row_for_autoscroll(
13838 &self,
13839 snapshot: &DisplaySnapshot,
13840 ) -> Option<DisplayRow> {
13841 self.highlighted_rows
13842 .values()
13843 .flat_map(|highlighted_rows| highlighted_rows.iter())
13844 .filter_map(|highlight| {
13845 if highlight.should_autoscroll {
13846 Some(highlight.range.start.to_display_point(snapshot).row())
13847 } else {
13848 None
13849 }
13850 })
13851 .min()
13852 }
13853
13854 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13855 self.highlight_background::<SearchWithinRange>(
13856 ranges,
13857 |colors| colors.editor_document_highlight_read_background,
13858 cx,
13859 )
13860 }
13861
13862 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13863 self.breadcrumb_header = Some(new_header);
13864 }
13865
13866 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13867 self.clear_background_highlights::<SearchWithinRange>(cx);
13868 }
13869
13870 pub fn highlight_background<T: 'static>(
13871 &mut self,
13872 ranges: &[Range<Anchor>],
13873 color_fetcher: fn(&ThemeColors) -> Hsla,
13874 cx: &mut Context<Self>,
13875 ) {
13876 self.background_highlights
13877 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13878 self.scrollbar_marker_state.dirty = true;
13879 cx.notify();
13880 }
13881
13882 pub fn clear_background_highlights<T: 'static>(
13883 &mut self,
13884 cx: &mut Context<Self>,
13885 ) -> Option<BackgroundHighlight> {
13886 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13887 if !text_highlights.1.is_empty() {
13888 self.scrollbar_marker_state.dirty = true;
13889 cx.notify();
13890 }
13891 Some(text_highlights)
13892 }
13893
13894 pub fn highlight_gutter<T: 'static>(
13895 &mut self,
13896 ranges: &[Range<Anchor>],
13897 color_fetcher: fn(&App) -> Hsla,
13898 cx: &mut Context<Self>,
13899 ) {
13900 self.gutter_highlights
13901 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13902 cx.notify();
13903 }
13904
13905 pub fn clear_gutter_highlights<T: 'static>(
13906 &mut self,
13907 cx: &mut Context<Self>,
13908 ) -> Option<GutterHighlight> {
13909 cx.notify();
13910 self.gutter_highlights.remove(&TypeId::of::<T>())
13911 }
13912
13913 #[cfg(feature = "test-support")]
13914 pub fn all_text_background_highlights(
13915 &self,
13916 window: &mut Window,
13917 cx: &mut Context<Self>,
13918 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13919 let snapshot = self.snapshot(window, cx);
13920 let buffer = &snapshot.buffer_snapshot;
13921 let start = buffer.anchor_before(0);
13922 let end = buffer.anchor_after(buffer.len());
13923 let theme = cx.theme().colors();
13924 self.background_highlights_in_range(start..end, &snapshot, theme)
13925 }
13926
13927 #[cfg(feature = "test-support")]
13928 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13929 let snapshot = self.buffer().read(cx).snapshot(cx);
13930
13931 let highlights = self
13932 .background_highlights
13933 .get(&TypeId::of::<items::BufferSearchHighlights>());
13934
13935 if let Some((_color, ranges)) = highlights {
13936 ranges
13937 .iter()
13938 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13939 .collect_vec()
13940 } else {
13941 vec![]
13942 }
13943 }
13944
13945 fn document_highlights_for_position<'a>(
13946 &'a self,
13947 position: Anchor,
13948 buffer: &'a MultiBufferSnapshot,
13949 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13950 let read_highlights = self
13951 .background_highlights
13952 .get(&TypeId::of::<DocumentHighlightRead>())
13953 .map(|h| &h.1);
13954 let write_highlights = self
13955 .background_highlights
13956 .get(&TypeId::of::<DocumentHighlightWrite>())
13957 .map(|h| &h.1);
13958 let left_position = position.bias_left(buffer);
13959 let right_position = position.bias_right(buffer);
13960 read_highlights
13961 .into_iter()
13962 .chain(write_highlights)
13963 .flat_map(move |ranges| {
13964 let start_ix = match ranges.binary_search_by(|probe| {
13965 let cmp = probe.end.cmp(&left_position, buffer);
13966 if cmp.is_ge() {
13967 Ordering::Greater
13968 } else {
13969 Ordering::Less
13970 }
13971 }) {
13972 Ok(i) | Err(i) => i,
13973 };
13974
13975 ranges[start_ix..]
13976 .iter()
13977 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13978 })
13979 }
13980
13981 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13982 self.background_highlights
13983 .get(&TypeId::of::<T>())
13984 .map_or(false, |(_, highlights)| !highlights.is_empty())
13985 }
13986
13987 pub fn background_highlights_in_range(
13988 &self,
13989 search_range: Range<Anchor>,
13990 display_snapshot: &DisplaySnapshot,
13991 theme: &ThemeColors,
13992 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13993 let mut results = Vec::new();
13994 for (color_fetcher, ranges) in self.background_highlights.values() {
13995 let color = color_fetcher(theme);
13996 let start_ix = match ranges.binary_search_by(|probe| {
13997 let cmp = probe
13998 .end
13999 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14000 if cmp.is_gt() {
14001 Ordering::Greater
14002 } else {
14003 Ordering::Less
14004 }
14005 }) {
14006 Ok(i) | Err(i) => i,
14007 };
14008 for range in &ranges[start_ix..] {
14009 if range
14010 .start
14011 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14012 .is_ge()
14013 {
14014 break;
14015 }
14016
14017 let start = range.start.to_display_point(display_snapshot);
14018 let end = range.end.to_display_point(display_snapshot);
14019 results.push((start..end, color))
14020 }
14021 }
14022 results
14023 }
14024
14025 pub fn background_highlight_row_ranges<T: 'static>(
14026 &self,
14027 search_range: Range<Anchor>,
14028 display_snapshot: &DisplaySnapshot,
14029 count: usize,
14030 ) -> Vec<RangeInclusive<DisplayPoint>> {
14031 let mut results = Vec::new();
14032 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14033 return vec![];
14034 };
14035
14036 let start_ix = match ranges.binary_search_by(|probe| {
14037 let cmp = probe
14038 .end
14039 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14040 if cmp.is_gt() {
14041 Ordering::Greater
14042 } else {
14043 Ordering::Less
14044 }
14045 }) {
14046 Ok(i) | Err(i) => i,
14047 };
14048 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14049 if let (Some(start_display), Some(end_display)) = (start, end) {
14050 results.push(
14051 start_display.to_display_point(display_snapshot)
14052 ..=end_display.to_display_point(display_snapshot),
14053 );
14054 }
14055 };
14056 let mut start_row: Option<Point> = None;
14057 let mut end_row: Option<Point> = None;
14058 if ranges.len() > count {
14059 return Vec::new();
14060 }
14061 for range in &ranges[start_ix..] {
14062 if range
14063 .start
14064 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14065 .is_ge()
14066 {
14067 break;
14068 }
14069 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14070 if let Some(current_row) = &end_row {
14071 if end.row == current_row.row {
14072 continue;
14073 }
14074 }
14075 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14076 if start_row.is_none() {
14077 assert_eq!(end_row, None);
14078 start_row = Some(start);
14079 end_row = Some(end);
14080 continue;
14081 }
14082 if let Some(current_end) = end_row.as_mut() {
14083 if start.row > current_end.row + 1 {
14084 push_region(start_row, end_row);
14085 start_row = Some(start);
14086 end_row = Some(end);
14087 } else {
14088 // Merge two hunks.
14089 *current_end = end;
14090 }
14091 } else {
14092 unreachable!();
14093 }
14094 }
14095 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14096 push_region(start_row, end_row);
14097 results
14098 }
14099
14100 pub fn gutter_highlights_in_range(
14101 &self,
14102 search_range: Range<Anchor>,
14103 display_snapshot: &DisplaySnapshot,
14104 cx: &App,
14105 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14106 let mut results = Vec::new();
14107 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14108 let color = color_fetcher(cx);
14109 let start_ix = match ranges.binary_search_by(|probe| {
14110 let cmp = probe
14111 .end
14112 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14113 if cmp.is_gt() {
14114 Ordering::Greater
14115 } else {
14116 Ordering::Less
14117 }
14118 }) {
14119 Ok(i) | Err(i) => i,
14120 };
14121 for range in &ranges[start_ix..] {
14122 if range
14123 .start
14124 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14125 .is_ge()
14126 {
14127 break;
14128 }
14129
14130 let start = range.start.to_display_point(display_snapshot);
14131 let end = range.end.to_display_point(display_snapshot);
14132 results.push((start..end, color))
14133 }
14134 }
14135 results
14136 }
14137
14138 /// Get the text ranges corresponding to the redaction query
14139 pub fn redacted_ranges(
14140 &self,
14141 search_range: Range<Anchor>,
14142 display_snapshot: &DisplaySnapshot,
14143 cx: &App,
14144 ) -> Vec<Range<DisplayPoint>> {
14145 display_snapshot
14146 .buffer_snapshot
14147 .redacted_ranges(search_range, |file| {
14148 if let Some(file) = file {
14149 file.is_private()
14150 && EditorSettings::get(
14151 Some(SettingsLocation {
14152 worktree_id: file.worktree_id(cx),
14153 path: file.path().as_ref(),
14154 }),
14155 cx,
14156 )
14157 .redact_private_values
14158 } else {
14159 false
14160 }
14161 })
14162 .map(|range| {
14163 range.start.to_display_point(display_snapshot)
14164 ..range.end.to_display_point(display_snapshot)
14165 })
14166 .collect()
14167 }
14168
14169 pub fn highlight_text<T: 'static>(
14170 &mut self,
14171 ranges: Vec<Range<Anchor>>,
14172 style: HighlightStyle,
14173 cx: &mut Context<Self>,
14174 ) {
14175 self.display_map.update(cx, |map, _| {
14176 map.highlight_text(TypeId::of::<T>(), ranges, style)
14177 });
14178 cx.notify();
14179 }
14180
14181 pub(crate) fn highlight_inlays<T: 'static>(
14182 &mut self,
14183 highlights: Vec<InlayHighlight>,
14184 style: HighlightStyle,
14185 cx: &mut Context<Self>,
14186 ) {
14187 self.display_map.update(cx, |map, _| {
14188 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14189 });
14190 cx.notify();
14191 }
14192
14193 pub fn text_highlights<'a, T: 'static>(
14194 &'a self,
14195 cx: &'a App,
14196 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14197 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14198 }
14199
14200 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14201 let cleared = self
14202 .display_map
14203 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14204 if cleared {
14205 cx.notify();
14206 }
14207 }
14208
14209 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14210 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14211 && self.focus_handle.is_focused(window)
14212 }
14213
14214 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14215 self.show_cursor_when_unfocused = is_enabled;
14216 cx.notify();
14217 }
14218
14219 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14220 cx.notify();
14221 }
14222
14223 fn on_buffer_event(
14224 &mut self,
14225 multibuffer: &Entity<MultiBuffer>,
14226 event: &multi_buffer::Event,
14227 window: &mut Window,
14228 cx: &mut Context<Self>,
14229 ) {
14230 match event {
14231 multi_buffer::Event::Edited {
14232 singleton_buffer_edited,
14233 edited_buffer: buffer_edited,
14234 } => {
14235 self.scrollbar_marker_state.dirty = true;
14236 self.active_indent_guides_state.dirty = true;
14237 self.refresh_active_diagnostics(cx);
14238 self.refresh_code_actions(window, cx);
14239 if self.has_active_inline_completion() {
14240 self.update_visible_inline_completion(window, cx);
14241 }
14242 if let Some(buffer) = buffer_edited {
14243 let buffer_id = buffer.read(cx).remote_id();
14244 if !self.registered_buffers.contains_key(&buffer_id) {
14245 if let Some(project) = self.project.as_ref() {
14246 project.update(cx, |project, cx| {
14247 self.registered_buffers.insert(
14248 buffer_id,
14249 project.register_buffer_with_language_servers(&buffer, cx),
14250 );
14251 })
14252 }
14253 }
14254 }
14255 cx.emit(EditorEvent::BufferEdited);
14256 cx.emit(SearchEvent::MatchesInvalidated);
14257 if *singleton_buffer_edited {
14258 if let Some(project) = &self.project {
14259 #[allow(clippy::mutable_key_type)]
14260 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14261 multibuffer
14262 .all_buffers()
14263 .into_iter()
14264 .filter_map(|buffer| {
14265 buffer.update(cx, |buffer, cx| {
14266 let language = buffer.language()?;
14267 let should_discard = project.update(cx, |project, cx| {
14268 project.is_local()
14269 && !project.has_language_servers_for(buffer, cx)
14270 });
14271 should_discard.not().then_some(language.clone())
14272 })
14273 })
14274 .collect::<HashSet<_>>()
14275 });
14276 if !languages_affected.is_empty() {
14277 self.refresh_inlay_hints(
14278 InlayHintRefreshReason::BufferEdited(languages_affected),
14279 cx,
14280 );
14281 }
14282 }
14283 }
14284
14285 let Some(project) = &self.project else { return };
14286 let (telemetry, is_via_ssh) = {
14287 let project = project.read(cx);
14288 let telemetry = project.client().telemetry().clone();
14289 let is_via_ssh = project.is_via_ssh();
14290 (telemetry, is_via_ssh)
14291 };
14292 refresh_linked_ranges(self, window, cx);
14293 telemetry.log_edit_event("editor", is_via_ssh);
14294 }
14295 multi_buffer::Event::ExcerptsAdded {
14296 buffer,
14297 predecessor,
14298 excerpts,
14299 } => {
14300 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14301 let buffer_id = buffer.read(cx).remote_id();
14302 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14303 if let Some(project) = &self.project {
14304 get_uncommitted_diff_for_buffer(
14305 project,
14306 [buffer.clone()],
14307 self.buffer.clone(),
14308 cx,
14309 )
14310 .detach();
14311 }
14312 }
14313 cx.emit(EditorEvent::ExcerptsAdded {
14314 buffer: buffer.clone(),
14315 predecessor: *predecessor,
14316 excerpts: excerpts.clone(),
14317 });
14318 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14319 }
14320 multi_buffer::Event::ExcerptsRemoved { ids } => {
14321 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14322 let buffer = self.buffer.read(cx);
14323 self.registered_buffers
14324 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14325 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14326 }
14327 multi_buffer::Event::ExcerptsEdited { ids } => {
14328 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14329 }
14330 multi_buffer::Event::ExcerptsExpanded { ids } => {
14331 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14332 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14333 }
14334 multi_buffer::Event::Reparsed(buffer_id) => {
14335 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14336
14337 cx.emit(EditorEvent::Reparsed(*buffer_id));
14338 }
14339 multi_buffer::Event::DiffHunksToggled => {
14340 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14341 }
14342 multi_buffer::Event::LanguageChanged(buffer_id) => {
14343 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14344 cx.emit(EditorEvent::Reparsed(*buffer_id));
14345 cx.notify();
14346 }
14347 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14348 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14349 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14350 cx.emit(EditorEvent::TitleChanged)
14351 }
14352 // multi_buffer::Event::DiffBaseChanged => {
14353 // self.scrollbar_marker_state.dirty = true;
14354 // cx.emit(EditorEvent::DiffBaseChanged);
14355 // cx.notify();
14356 // }
14357 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14358 multi_buffer::Event::DiagnosticsUpdated => {
14359 self.refresh_active_diagnostics(cx);
14360 self.scrollbar_marker_state.dirty = true;
14361 cx.notify();
14362 }
14363 _ => {}
14364 };
14365 }
14366
14367 fn on_display_map_changed(
14368 &mut self,
14369 _: Entity<DisplayMap>,
14370 _: &mut Window,
14371 cx: &mut Context<Self>,
14372 ) {
14373 cx.notify();
14374 }
14375
14376 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14377 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14378 self.refresh_inline_completion(true, false, window, cx);
14379 self.refresh_inlay_hints(
14380 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14381 self.selections.newest_anchor().head(),
14382 &self.buffer.read(cx).snapshot(cx),
14383 cx,
14384 )),
14385 cx,
14386 );
14387
14388 let old_cursor_shape = self.cursor_shape;
14389
14390 {
14391 let editor_settings = EditorSettings::get_global(cx);
14392 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14393 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14394 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14395 }
14396
14397 if old_cursor_shape != self.cursor_shape {
14398 cx.emit(EditorEvent::CursorShapeChanged);
14399 }
14400
14401 let project_settings = ProjectSettings::get_global(cx);
14402 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14403
14404 if self.mode == EditorMode::Full {
14405 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14406 if self.git_blame_inline_enabled != inline_blame_enabled {
14407 self.toggle_git_blame_inline_internal(false, window, cx);
14408 }
14409 }
14410
14411 cx.notify();
14412 }
14413
14414 pub fn set_searchable(&mut self, searchable: bool) {
14415 self.searchable = searchable;
14416 }
14417
14418 pub fn searchable(&self) -> bool {
14419 self.searchable
14420 }
14421
14422 fn open_proposed_changes_editor(
14423 &mut self,
14424 _: &OpenProposedChangesEditor,
14425 window: &mut Window,
14426 cx: &mut Context<Self>,
14427 ) {
14428 let Some(workspace) = self.workspace() else {
14429 cx.propagate();
14430 return;
14431 };
14432
14433 let selections = self.selections.all::<usize>(cx);
14434 let multi_buffer = self.buffer.read(cx);
14435 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14436 let mut new_selections_by_buffer = HashMap::default();
14437 for selection in selections {
14438 for (buffer, range, _) in
14439 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14440 {
14441 let mut range = range.to_point(buffer);
14442 range.start.column = 0;
14443 range.end.column = buffer.line_len(range.end.row);
14444 new_selections_by_buffer
14445 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14446 .or_insert(Vec::new())
14447 .push(range)
14448 }
14449 }
14450
14451 let proposed_changes_buffers = new_selections_by_buffer
14452 .into_iter()
14453 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14454 .collect::<Vec<_>>();
14455 let proposed_changes_editor = cx.new(|cx| {
14456 ProposedChangesEditor::new(
14457 "Proposed changes",
14458 proposed_changes_buffers,
14459 self.project.clone(),
14460 window,
14461 cx,
14462 )
14463 });
14464
14465 window.defer(cx, move |window, cx| {
14466 workspace.update(cx, |workspace, cx| {
14467 workspace.active_pane().update(cx, |pane, cx| {
14468 pane.add_item(
14469 Box::new(proposed_changes_editor),
14470 true,
14471 true,
14472 None,
14473 window,
14474 cx,
14475 );
14476 });
14477 });
14478 });
14479 }
14480
14481 pub fn open_excerpts_in_split(
14482 &mut self,
14483 _: &OpenExcerptsSplit,
14484 window: &mut Window,
14485 cx: &mut Context<Self>,
14486 ) {
14487 self.open_excerpts_common(None, true, window, cx)
14488 }
14489
14490 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14491 self.open_excerpts_common(None, false, window, cx)
14492 }
14493
14494 fn open_excerpts_common(
14495 &mut self,
14496 jump_data: Option<JumpData>,
14497 split: bool,
14498 window: &mut Window,
14499 cx: &mut Context<Self>,
14500 ) {
14501 let Some(workspace) = self.workspace() else {
14502 cx.propagate();
14503 return;
14504 };
14505
14506 if self.buffer.read(cx).is_singleton() {
14507 cx.propagate();
14508 return;
14509 }
14510
14511 let mut new_selections_by_buffer = HashMap::default();
14512 match &jump_data {
14513 Some(JumpData::MultiBufferPoint {
14514 excerpt_id,
14515 position,
14516 anchor,
14517 line_offset_from_top,
14518 }) => {
14519 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14520 if let Some(buffer) = multi_buffer_snapshot
14521 .buffer_id_for_excerpt(*excerpt_id)
14522 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14523 {
14524 let buffer_snapshot = buffer.read(cx).snapshot();
14525 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14526 language::ToPoint::to_point(anchor, &buffer_snapshot)
14527 } else {
14528 buffer_snapshot.clip_point(*position, Bias::Left)
14529 };
14530 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14531 new_selections_by_buffer.insert(
14532 buffer,
14533 (
14534 vec![jump_to_offset..jump_to_offset],
14535 Some(*line_offset_from_top),
14536 ),
14537 );
14538 }
14539 }
14540 Some(JumpData::MultiBufferRow {
14541 row,
14542 line_offset_from_top,
14543 }) => {
14544 let point = MultiBufferPoint::new(row.0, 0);
14545 if let Some((buffer, buffer_point, _)) =
14546 self.buffer.read(cx).point_to_buffer_point(point, cx)
14547 {
14548 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14549 new_selections_by_buffer
14550 .entry(buffer)
14551 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14552 .0
14553 .push(buffer_offset..buffer_offset)
14554 }
14555 }
14556 None => {
14557 let selections = self.selections.all::<usize>(cx);
14558 let multi_buffer = self.buffer.read(cx);
14559 for selection in selections {
14560 for (buffer, mut range, _) in multi_buffer
14561 .snapshot(cx)
14562 .range_to_buffer_ranges(selection.range())
14563 {
14564 // When editing branch buffers, jump to the corresponding location
14565 // in their base buffer.
14566 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14567 let buffer = buffer_handle.read(cx);
14568 if let Some(base_buffer) = buffer.base_buffer() {
14569 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14570 buffer_handle = base_buffer;
14571 }
14572
14573 if selection.reversed {
14574 mem::swap(&mut range.start, &mut range.end);
14575 }
14576 new_selections_by_buffer
14577 .entry(buffer_handle)
14578 .or_insert((Vec::new(), None))
14579 .0
14580 .push(range)
14581 }
14582 }
14583 }
14584 }
14585
14586 if new_selections_by_buffer.is_empty() {
14587 return;
14588 }
14589
14590 // We defer the pane interaction because we ourselves are a workspace item
14591 // and activating a new item causes the pane to call a method on us reentrantly,
14592 // which panics if we're on the stack.
14593 window.defer(cx, move |window, cx| {
14594 workspace.update(cx, |workspace, cx| {
14595 let pane = if split {
14596 workspace.adjacent_pane(window, cx)
14597 } else {
14598 workspace.active_pane().clone()
14599 };
14600
14601 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14602 let editor = buffer
14603 .read(cx)
14604 .file()
14605 .is_none()
14606 .then(|| {
14607 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14608 // so `workspace.open_project_item` will never find them, always opening a new editor.
14609 // Instead, we try to activate the existing editor in the pane first.
14610 let (editor, pane_item_index) =
14611 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14612 let editor = item.downcast::<Editor>()?;
14613 let singleton_buffer =
14614 editor.read(cx).buffer().read(cx).as_singleton()?;
14615 if singleton_buffer == buffer {
14616 Some((editor, i))
14617 } else {
14618 None
14619 }
14620 })?;
14621 pane.update(cx, |pane, cx| {
14622 pane.activate_item(pane_item_index, true, true, window, cx)
14623 });
14624 Some(editor)
14625 })
14626 .flatten()
14627 .unwrap_or_else(|| {
14628 workspace.open_project_item::<Self>(
14629 pane.clone(),
14630 buffer,
14631 true,
14632 true,
14633 window,
14634 cx,
14635 )
14636 });
14637
14638 editor.update(cx, |editor, cx| {
14639 let autoscroll = match scroll_offset {
14640 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14641 None => Autoscroll::newest(),
14642 };
14643 let nav_history = editor.nav_history.take();
14644 editor.change_selections(Some(autoscroll), window, cx, |s| {
14645 s.select_ranges(ranges);
14646 });
14647 editor.nav_history = nav_history;
14648 });
14649 }
14650 })
14651 });
14652 }
14653
14654 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14655 let snapshot = self.buffer.read(cx).read(cx);
14656 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14657 Some(
14658 ranges
14659 .iter()
14660 .map(move |range| {
14661 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14662 })
14663 .collect(),
14664 )
14665 }
14666
14667 fn selection_replacement_ranges(
14668 &self,
14669 range: Range<OffsetUtf16>,
14670 cx: &mut App,
14671 ) -> Vec<Range<OffsetUtf16>> {
14672 let selections = self.selections.all::<OffsetUtf16>(cx);
14673 let newest_selection = selections
14674 .iter()
14675 .max_by_key(|selection| selection.id)
14676 .unwrap();
14677 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14678 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14679 let snapshot = self.buffer.read(cx).read(cx);
14680 selections
14681 .into_iter()
14682 .map(|mut selection| {
14683 selection.start.0 =
14684 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14685 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14686 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14687 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14688 })
14689 .collect()
14690 }
14691
14692 fn report_editor_event(
14693 &self,
14694 event_type: &'static str,
14695 file_extension: Option<String>,
14696 cx: &App,
14697 ) {
14698 if cfg!(any(test, feature = "test-support")) {
14699 return;
14700 }
14701
14702 let Some(project) = &self.project else { return };
14703
14704 // If None, we are in a file without an extension
14705 let file = self
14706 .buffer
14707 .read(cx)
14708 .as_singleton()
14709 .and_then(|b| b.read(cx).file());
14710 let file_extension = file_extension.or(file
14711 .as_ref()
14712 .and_then(|file| Path::new(file.file_name(cx)).extension())
14713 .and_then(|e| e.to_str())
14714 .map(|a| a.to_string()));
14715
14716 let vim_mode = cx
14717 .global::<SettingsStore>()
14718 .raw_user_settings()
14719 .get("vim_mode")
14720 == Some(&serde_json::Value::Bool(true));
14721
14722 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14723 let copilot_enabled = edit_predictions_provider
14724 == language::language_settings::EditPredictionProvider::Copilot;
14725 let copilot_enabled_for_language = self
14726 .buffer
14727 .read(cx)
14728 .settings_at(0, cx)
14729 .show_edit_predictions;
14730
14731 let project = project.read(cx);
14732 telemetry::event!(
14733 event_type,
14734 file_extension,
14735 vim_mode,
14736 copilot_enabled,
14737 copilot_enabled_for_language,
14738 edit_predictions_provider,
14739 is_via_ssh = project.is_via_ssh(),
14740 );
14741 }
14742
14743 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14744 /// with each line being an array of {text, highlight} objects.
14745 fn copy_highlight_json(
14746 &mut self,
14747 _: &CopyHighlightJson,
14748 window: &mut Window,
14749 cx: &mut Context<Self>,
14750 ) {
14751 #[derive(Serialize)]
14752 struct Chunk<'a> {
14753 text: String,
14754 highlight: Option<&'a str>,
14755 }
14756
14757 let snapshot = self.buffer.read(cx).snapshot(cx);
14758 let range = self
14759 .selected_text_range(false, window, cx)
14760 .and_then(|selection| {
14761 if selection.range.is_empty() {
14762 None
14763 } else {
14764 Some(selection.range)
14765 }
14766 })
14767 .unwrap_or_else(|| 0..snapshot.len());
14768
14769 let chunks = snapshot.chunks(range, true);
14770 let mut lines = Vec::new();
14771 let mut line: VecDeque<Chunk> = VecDeque::new();
14772
14773 let Some(style) = self.style.as_ref() else {
14774 return;
14775 };
14776
14777 for chunk in chunks {
14778 let highlight = chunk
14779 .syntax_highlight_id
14780 .and_then(|id| id.name(&style.syntax));
14781 let mut chunk_lines = chunk.text.split('\n').peekable();
14782 while let Some(text) = chunk_lines.next() {
14783 let mut merged_with_last_token = false;
14784 if let Some(last_token) = line.back_mut() {
14785 if last_token.highlight == highlight {
14786 last_token.text.push_str(text);
14787 merged_with_last_token = true;
14788 }
14789 }
14790
14791 if !merged_with_last_token {
14792 line.push_back(Chunk {
14793 text: text.into(),
14794 highlight,
14795 });
14796 }
14797
14798 if chunk_lines.peek().is_some() {
14799 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14800 line.pop_front();
14801 }
14802 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14803 line.pop_back();
14804 }
14805
14806 lines.push(mem::take(&mut line));
14807 }
14808 }
14809 }
14810
14811 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14812 return;
14813 };
14814 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14815 }
14816
14817 pub fn open_context_menu(
14818 &mut self,
14819 _: &OpenContextMenu,
14820 window: &mut Window,
14821 cx: &mut Context<Self>,
14822 ) {
14823 self.request_autoscroll(Autoscroll::newest(), cx);
14824 let position = self.selections.newest_display(cx).start;
14825 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14826 }
14827
14828 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14829 &self.inlay_hint_cache
14830 }
14831
14832 pub fn replay_insert_event(
14833 &mut self,
14834 text: &str,
14835 relative_utf16_range: Option<Range<isize>>,
14836 window: &mut Window,
14837 cx: &mut Context<Self>,
14838 ) {
14839 if !self.input_enabled {
14840 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14841 return;
14842 }
14843 if let Some(relative_utf16_range) = relative_utf16_range {
14844 let selections = self.selections.all::<OffsetUtf16>(cx);
14845 self.change_selections(None, window, cx, |s| {
14846 let new_ranges = selections.into_iter().map(|range| {
14847 let start = OffsetUtf16(
14848 range
14849 .head()
14850 .0
14851 .saturating_add_signed(relative_utf16_range.start),
14852 );
14853 let end = OffsetUtf16(
14854 range
14855 .head()
14856 .0
14857 .saturating_add_signed(relative_utf16_range.end),
14858 );
14859 start..end
14860 });
14861 s.select_ranges(new_ranges);
14862 });
14863 }
14864
14865 self.handle_input(text, window, cx);
14866 }
14867
14868 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14869 let Some(provider) = self.semantics_provider.as_ref() else {
14870 return false;
14871 };
14872
14873 let mut supports = false;
14874 self.buffer().update(cx, |this, cx| {
14875 this.for_each_buffer(|buffer| {
14876 supports |= provider.supports_inlay_hints(buffer, cx);
14877 });
14878 });
14879
14880 supports
14881 }
14882
14883 pub fn is_focused(&self, window: &Window) -> bool {
14884 self.focus_handle.is_focused(window)
14885 }
14886
14887 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14888 cx.emit(EditorEvent::Focused);
14889
14890 if let Some(descendant) = self
14891 .last_focused_descendant
14892 .take()
14893 .and_then(|descendant| descendant.upgrade())
14894 {
14895 window.focus(&descendant);
14896 } else {
14897 if let Some(blame) = self.blame.as_ref() {
14898 blame.update(cx, GitBlame::focus)
14899 }
14900
14901 self.blink_manager.update(cx, BlinkManager::enable);
14902 self.show_cursor_names(window, cx);
14903 self.buffer.update(cx, |buffer, cx| {
14904 buffer.finalize_last_transaction(cx);
14905 if self.leader_peer_id.is_none() {
14906 buffer.set_active_selections(
14907 &self.selections.disjoint_anchors(),
14908 self.selections.line_mode,
14909 self.cursor_shape,
14910 cx,
14911 );
14912 }
14913 });
14914 }
14915 }
14916
14917 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14918 cx.emit(EditorEvent::FocusedIn)
14919 }
14920
14921 fn handle_focus_out(
14922 &mut self,
14923 event: FocusOutEvent,
14924 _window: &mut Window,
14925 _cx: &mut Context<Self>,
14926 ) {
14927 if event.blurred != self.focus_handle {
14928 self.last_focused_descendant = Some(event.blurred);
14929 }
14930 }
14931
14932 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14933 self.blink_manager.update(cx, BlinkManager::disable);
14934 self.buffer
14935 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14936
14937 if let Some(blame) = self.blame.as_ref() {
14938 blame.update(cx, GitBlame::blur)
14939 }
14940 if !self.hover_state.focused(window, cx) {
14941 hide_hover(self, cx);
14942 }
14943 if !self
14944 .context_menu
14945 .borrow()
14946 .as_ref()
14947 .is_some_and(|context_menu| context_menu.focused(window, cx))
14948 {
14949 self.hide_context_menu(window, cx);
14950 }
14951 self.discard_inline_completion(false, cx);
14952 cx.emit(EditorEvent::Blurred);
14953 cx.notify();
14954 }
14955
14956 pub fn register_action<A: Action>(
14957 &mut self,
14958 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14959 ) -> Subscription {
14960 let id = self.next_editor_action_id.post_inc();
14961 let listener = Arc::new(listener);
14962 self.editor_actions.borrow_mut().insert(
14963 id,
14964 Box::new(move |window, _| {
14965 let listener = listener.clone();
14966 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14967 let action = action.downcast_ref().unwrap();
14968 if phase == DispatchPhase::Bubble {
14969 listener(action, window, cx)
14970 }
14971 })
14972 }),
14973 );
14974
14975 let editor_actions = self.editor_actions.clone();
14976 Subscription::new(move || {
14977 editor_actions.borrow_mut().remove(&id);
14978 })
14979 }
14980
14981 pub fn file_header_size(&self) -> u32 {
14982 FILE_HEADER_HEIGHT
14983 }
14984
14985 pub fn revert(
14986 &mut self,
14987 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14988 window: &mut Window,
14989 cx: &mut Context<Self>,
14990 ) {
14991 self.buffer().update(cx, |multi_buffer, cx| {
14992 for (buffer_id, changes) in revert_changes {
14993 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14994 buffer.update(cx, |buffer, cx| {
14995 buffer.edit(
14996 changes.into_iter().map(|(range, text)| {
14997 (range, text.to_string().map(Arc::<str>::from))
14998 }),
14999 None,
15000 cx,
15001 );
15002 });
15003 }
15004 }
15005 });
15006 self.change_selections(None, window, cx, |selections| selections.refresh());
15007 }
15008
15009 pub fn to_pixel_point(
15010 &self,
15011 source: multi_buffer::Anchor,
15012 editor_snapshot: &EditorSnapshot,
15013 window: &mut Window,
15014 ) -> Option<gpui::Point<Pixels>> {
15015 let source_point = source.to_display_point(editor_snapshot);
15016 self.display_to_pixel_point(source_point, editor_snapshot, window)
15017 }
15018
15019 pub fn display_to_pixel_point(
15020 &self,
15021 source: DisplayPoint,
15022 editor_snapshot: &EditorSnapshot,
15023 window: &mut Window,
15024 ) -> Option<gpui::Point<Pixels>> {
15025 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15026 let text_layout_details = self.text_layout_details(window);
15027 let scroll_top = text_layout_details
15028 .scroll_anchor
15029 .scroll_position(editor_snapshot)
15030 .y;
15031
15032 if source.row().as_f32() < scroll_top.floor() {
15033 return None;
15034 }
15035 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15036 let source_y = line_height * (source.row().as_f32() - scroll_top);
15037 Some(gpui::Point::new(source_x, source_y))
15038 }
15039
15040 pub fn has_visible_completions_menu(&self) -> bool {
15041 !self.edit_prediction_preview_is_active()
15042 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15043 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15044 })
15045 }
15046
15047 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15048 self.addons
15049 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15050 }
15051
15052 pub fn unregister_addon<T: Addon>(&mut self) {
15053 self.addons.remove(&std::any::TypeId::of::<T>());
15054 }
15055
15056 pub fn addon<T: Addon>(&self) -> Option<&T> {
15057 let type_id = std::any::TypeId::of::<T>();
15058 self.addons
15059 .get(&type_id)
15060 .and_then(|item| item.to_any().downcast_ref::<T>())
15061 }
15062
15063 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15064 let text_layout_details = self.text_layout_details(window);
15065 let style = &text_layout_details.editor_style;
15066 let font_id = window.text_system().resolve_font(&style.text.font());
15067 let font_size = style.text.font_size.to_pixels(window.rem_size());
15068 let line_height = style.text.line_height_in_pixels(window.rem_size());
15069 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15070
15071 gpui::Size::new(em_width, line_height)
15072 }
15073
15074 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15075 self.load_diff_task.clone()
15076 }
15077
15078 fn read_selections_from_db(
15079 &mut self,
15080 item_id: u64,
15081 workspace_id: WorkspaceId,
15082 window: &mut Window,
15083 cx: &mut Context<Editor>,
15084 ) {
15085 if !self.is_singleton(cx)
15086 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15087 {
15088 return;
15089 }
15090 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15091 return;
15092 };
15093 if selections.is_empty() {
15094 return;
15095 }
15096
15097 let snapshot = self.buffer.read(cx).snapshot(cx);
15098 self.change_selections(None, window, cx, |s| {
15099 s.select_ranges(selections.into_iter().map(|(start, end)| {
15100 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15101 }));
15102 });
15103 }
15104}
15105
15106fn get_uncommitted_diff_for_buffer(
15107 project: &Entity<Project>,
15108 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15109 buffer: Entity<MultiBuffer>,
15110 cx: &mut App,
15111) -> Task<()> {
15112 let mut tasks = Vec::new();
15113 project.update(cx, |project, cx| {
15114 for buffer in buffers {
15115 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15116 }
15117 });
15118 cx.spawn(|mut cx| async move {
15119 let diffs = futures::future::join_all(tasks).await;
15120 buffer
15121 .update(&mut cx, |buffer, cx| {
15122 for diff in diffs.into_iter().flatten() {
15123 buffer.add_diff(diff, cx);
15124 }
15125 })
15126 .ok();
15127 })
15128}
15129
15130fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15131 let tab_size = tab_size.get() as usize;
15132 let mut width = offset;
15133
15134 for ch in text.chars() {
15135 width += if ch == '\t' {
15136 tab_size - (width % tab_size)
15137 } else {
15138 1
15139 };
15140 }
15141
15142 width - offset
15143}
15144
15145#[cfg(test)]
15146mod tests {
15147 use super::*;
15148
15149 #[test]
15150 fn test_string_size_with_expanded_tabs() {
15151 let nz = |val| NonZeroU32::new(val).unwrap();
15152 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15153 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15154 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15155 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15156 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15157 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15158 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15159 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15160 }
15161}
15162
15163/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15164struct WordBreakingTokenizer<'a> {
15165 input: &'a str,
15166}
15167
15168impl<'a> WordBreakingTokenizer<'a> {
15169 fn new(input: &'a str) -> Self {
15170 Self { input }
15171 }
15172}
15173
15174fn is_char_ideographic(ch: char) -> bool {
15175 use unicode_script::Script::*;
15176 use unicode_script::UnicodeScript;
15177 matches!(ch.script(), Han | Tangut | Yi)
15178}
15179
15180fn is_grapheme_ideographic(text: &str) -> bool {
15181 text.chars().any(is_char_ideographic)
15182}
15183
15184fn is_grapheme_whitespace(text: &str) -> bool {
15185 text.chars().any(|x| x.is_whitespace())
15186}
15187
15188fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15189 text.chars().next().map_or(false, |ch| {
15190 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15191 })
15192}
15193
15194#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15195struct WordBreakToken<'a> {
15196 token: &'a str,
15197 grapheme_len: usize,
15198 is_whitespace: bool,
15199}
15200
15201impl<'a> Iterator for WordBreakingTokenizer<'a> {
15202 /// Yields a span, the count of graphemes in the token, and whether it was
15203 /// whitespace. Note that it also breaks at word boundaries.
15204 type Item = WordBreakToken<'a>;
15205
15206 fn next(&mut self) -> Option<Self::Item> {
15207 use unicode_segmentation::UnicodeSegmentation;
15208 if self.input.is_empty() {
15209 return None;
15210 }
15211
15212 let mut iter = self.input.graphemes(true).peekable();
15213 let mut offset = 0;
15214 let mut graphemes = 0;
15215 if let Some(first_grapheme) = iter.next() {
15216 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15217 offset += first_grapheme.len();
15218 graphemes += 1;
15219 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15220 if let Some(grapheme) = iter.peek().copied() {
15221 if should_stay_with_preceding_ideograph(grapheme) {
15222 offset += grapheme.len();
15223 graphemes += 1;
15224 }
15225 }
15226 } else {
15227 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15228 let mut next_word_bound = words.peek().copied();
15229 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15230 next_word_bound = words.next();
15231 }
15232 while let Some(grapheme) = iter.peek().copied() {
15233 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15234 break;
15235 };
15236 if is_grapheme_whitespace(grapheme) != is_whitespace {
15237 break;
15238 };
15239 offset += grapheme.len();
15240 graphemes += 1;
15241 iter.next();
15242 }
15243 }
15244 let token = &self.input[..offset];
15245 self.input = &self.input[offset..];
15246 if is_whitespace {
15247 Some(WordBreakToken {
15248 token: " ",
15249 grapheme_len: 1,
15250 is_whitespace: true,
15251 })
15252 } else {
15253 Some(WordBreakToken {
15254 token,
15255 grapheme_len: graphemes,
15256 is_whitespace: false,
15257 })
15258 }
15259 } else {
15260 None
15261 }
15262 }
15263}
15264
15265#[test]
15266fn test_word_breaking_tokenizer() {
15267 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15268 ("", &[]),
15269 (" ", &[(" ", 1, true)]),
15270 ("Ʒ", &[("Ʒ", 1, false)]),
15271 ("Ǽ", &[("Ǽ", 1, false)]),
15272 ("⋑", &[("⋑", 1, false)]),
15273 ("⋑⋑", &[("⋑⋑", 2, false)]),
15274 (
15275 "原理,进而",
15276 &[
15277 ("原", 1, false),
15278 ("理,", 2, false),
15279 ("进", 1, false),
15280 ("而", 1, false),
15281 ],
15282 ),
15283 (
15284 "hello world",
15285 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15286 ),
15287 (
15288 "hello, world",
15289 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15290 ),
15291 (
15292 " hello world",
15293 &[
15294 (" ", 1, true),
15295 ("hello", 5, false),
15296 (" ", 1, true),
15297 ("world", 5, false),
15298 ],
15299 ),
15300 (
15301 "这是什么 \n 钢笔",
15302 &[
15303 ("这", 1, false),
15304 ("是", 1, false),
15305 ("什", 1, false),
15306 ("么", 1, false),
15307 (" ", 1, true),
15308 ("钢", 1, false),
15309 ("笔", 1, false),
15310 ],
15311 ),
15312 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15313 ];
15314
15315 for (input, result) in tests {
15316 assert_eq!(
15317 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15318 result
15319 .iter()
15320 .copied()
15321 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15322 token,
15323 grapheme_len,
15324 is_whitespace,
15325 })
15326 .collect::<Vec<_>>()
15327 );
15328 }
15329}
15330
15331fn wrap_with_prefix(
15332 line_prefix: String,
15333 unwrapped_text: String,
15334 wrap_column: usize,
15335 tab_size: NonZeroU32,
15336) -> String {
15337 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15338 let mut wrapped_text = String::new();
15339 let mut current_line = line_prefix.clone();
15340
15341 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15342 let mut current_line_len = line_prefix_len;
15343 for WordBreakToken {
15344 token,
15345 grapheme_len,
15346 is_whitespace,
15347 } in tokenizer
15348 {
15349 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15350 wrapped_text.push_str(current_line.trim_end());
15351 wrapped_text.push('\n');
15352 current_line.truncate(line_prefix.len());
15353 current_line_len = line_prefix_len;
15354 if !is_whitespace {
15355 current_line.push_str(token);
15356 current_line_len += grapheme_len;
15357 }
15358 } else if !is_whitespace {
15359 current_line.push_str(token);
15360 current_line_len += grapheme_len;
15361 } else if current_line_len != line_prefix_len {
15362 current_line.push(' ');
15363 current_line_len += 1;
15364 }
15365 }
15366
15367 if !current_line.is_empty() {
15368 wrapped_text.push_str(¤t_line);
15369 }
15370 wrapped_text
15371}
15372
15373#[test]
15374fn test_wrap_with_prefix() {
15375 assert_eq!(
15376 wrap_with_prefix(
15377 "# ".to_string(),
15378 "abcdefg".to_string(),
15379 4,
15380 NonZeroU32::new(4).unwrap()
15381 ),
15382 "# abcdefg"
15383 );
15384 assert_eq!(
15385 wrap_with_prefix(
15386 "".to_string(),
15387 "\thello world".to_string(),
15388 8,
15389 NonZeroU32::new(4).unwrap()
15390 ),
15391 "hello\nworld"
15392 );
15393 assert_eq!(
15394 wrap_with_prefix(
15395 "// ".to_string(),
15396 "xx \nyy zz aa bb cc".to_string(),
15397 12,
15398 NonZeroU32::new(4).unwrap()
15399 ),
15400 "// xx yy zz\n// aa bb cc"
15401 );
15402 assert_eq!(
15403 wrap_with_prefix(
15404 String::new(),
15405 "这是什么 \n 钢笔".to_string(),
15406 3,
15407 NonZeroU32::new(4).unwrap()
15408 ),
15409 "这是什\n么 钢\n笔"
15410 );
15411}
15412
15413pub trait CollaborationHub {
15414 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15415 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15416 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15417}
15418
15419impl CollaborationHub for Entity<Project> {
15420 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15421 self.read(cx).collaborators()
15422 }
15423
15424 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15425 self.read(cx).user_store().read(cx).participant_indices()
15426 }
15427
15428 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15429 let this = self.read(cx);
15430 let user_ids = this.collaborators().values().map(|c| c.user_id);
15431 this.user_store().read_with(cx, |user_store, cx| {
15432 user_store.participant_names(user_ids, cx)
15433 })
15434 }
15435}
15436
15437pub trait SemanticsProvider {
15438 fn hover(
15439 &self,
15440 buffer: &Entity<Buffer>,
15441 position: text::Anchor,
15442 cx: &mut App,
15443 ) -> Option<Task<Vec<project::Hover>>>;
15444
15445 fn inlay_hints(
15446 &self,
15447 buffer_handle: Entity<Buffer>,
15448 range: Range<text::Anchor>,
15449 cx: &mut App,
15450 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15451
15452 fn resolve_inlay_hint(
15453 &self,
15454 hint: InlayHint,
15455 buffer_handle: Entity<Buffer>,
15456 server_id: LanguageServerId,
15457 cx: &mut App,
15458 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15459
15460 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15461
15462 fn document_highlights(
15463 &self,
15464 buffer: &Entity<Buffer>,
15465 position: text::Anchor,
15466 cx: &mut App,
15467 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15468
15469 fn definitions(
15470 &self,
15471 buffer: &Entity<Buffer>,
15472 position: text::Anchor,
15473 kind: GotoDefinitionKind,
15474 cx: &mut App,
15475 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15476
15477 fn range_for_rename(
15478 &self,
15479 buffer: &Entity<Buffer>,
15480 position: text::Anchor,
15481 cx: &mut App,
15482 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15483
15484 fn perform_rename(
15485 &self,
15486 buffer: &Entity<Buffer>,
15487 position: text::Anchor,
15488 new_name: String,
15489 cx: &mut App,
15490 ) -> Option<Task<Result<ProjectTransaction>>>;
15491}
15492
15493pub trait CompletionProvider {
15494 fn completions(
15495 &self,
15496 buffer: &Entity<Buffer>,
15497 buffer_position: text::Anchor,
15498 trigger: CompletionContext,
15499 window: &mut Window,
15500 cx: &mut Context<Editor>,
15501 ) -> Task<Result<Vec<Completion>>>;
15502
15503 fn resolve_completions(
15504 &self,
15505 buffer: Entity<Buffer>,
15506 completion_indices: Vec<usize>,
15507 completions: Rc<RefCell<Box<[Completion]>>>,
15508 cx: &mut Context<Editor>,
15509 ) -> Task<Result<bool>>;
15510
15511 fn apply_additional_edits_for_completion(
15512 &self,
15513 _buffer: Entity<Buffer>,
15514 _completions: Rc<RefCell<Box<[Completion]>>>,
15515 _completion_index: usize,
15516 _push_to_history: bool,
15517 _cx: &mut Context<Editor>,
15518 ) -> Task<Result<Option<language::Transaction>>> {
15519 Task::ready(Ok(None))
15520 }
15521
15522 fn is_completion_trigger(
15523 &self,
15524 buffer: &Entity<Buffer>,
15525 position: language::Anchor,
15526 text: &str,
15527 trigger_in_words: bool,
15528 cx: &mut Context<Editor>,
15529 ) -> bool;
15530
15531 fn sort_completions(&self) -> bool {
15532 true
15533 }
15534}
15535
15536pub trait CodeActionProvider {
15537 fn id(&self) -> Arc<str>;
15538
15539 fn code_actions(
15540 &self,
15541 buffer: &Entity<Buffer>,
15542 range: Range<text::Anchor>,
15543 window: &mut Window,
15544 cx: &mut App,
15545 ) -> Task<Result<Vec<CodeAction>>>;
15546
15547 fn apply_code_action(
15548 &self,
15549 buffer_handle: Entity<Buffer>,
15550 action: CodeAction,
15551 excerpt_id: ExcerptId,
15552 push_to_history: bool,
15553 window: &mut Window,
15554 cx: &mut App,
15555 ) -> Task<Result<ProjectTransaction>>;
15556}
15557
15558impl CodeActionProvider for Entity<Project> {
15559 fn id(&self) -> Arc<str> {
15560 "project".into()
15561 }
15562
15563 fn code_actions(
15564 &self,
15565 buffer: &Entity<Buffer>,
15566 range: Range<text::Anchor>,
15567 _window: &mut Window,
15568 cx: &mut App,
15569 ) -> Task<Result<Vec<CodeAction>>> {
15570 self.update(cx, |project, cx| {
15571 project.code_actions(buffer, range, None, cx)
15572 })
15573 }
15574
15575 fn apply_code_action(
15576 &self,
15577 buffer_handle: Entity<Buffer>,
15578 action: CodeAction,
15579 _excerpt_id: ExcerptId,
15580 push_to_history: bool,
15581 _window: &mut Window,
15582 cx: &mut App,
15583 ) -> Task<Result<ProjectTransaction>> {
15584 self.update(cx, |project, cx| {
15585 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15586 })
15587 }
15588}
15589
15590fn snippet_completions(
15591 project: &Project,
15592 buffer: &Entity<Buffer>,
15593 buffer_position: text::Anchor,
15594 cx: &mut App,
15595) -> Task<Result<Vec<Completion>>> {
15596 let language = buffer.read(cx).language_at(buffer_position);
15597 let language_name = language.as_ref().map(|language| language.lsp_id());
15598 let snippet_store = project.snippets().read(cx);
15599 let snippets = snippet_store.snippets_for(language_name, cx);
15600
15601 if snippets.is_empty() {
15602 return Task::ready(Ok(vec![]));
15603 }
15604 let snapshot = buffer.read(cx).text_snapshot();
15605 let chars: String = snapshot
15606 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15607 .collect();
15608
15609 let scope = language.map(|language| language.default_scope());
15610 let executor = cx.background_executor().clone();
15611
15612 cx.background_spawn(async move {
15613 let classifier = CharClassifier::new(scope).for_completion(true);
15614 let mut last_word = chars
15615 .chars()
15616 .take_while(|c| classifier.is_word(*c))
15617 .collect::<String>();
15618 last_word = last_word.chars().rev().collect();
15619
15620 if last_word.is_empty() {
15621 return Ok(vec![]);
15622 }
15623
15624 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15625 let to_lsp = |point: &text::Anchor| {
15626 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15627 point_to_lsp(end)
15628 };
15629 let lsp_end = to_lsp(&buffer_position);
15630
15631 let candidates = snippets
15632 .iter()
15633 .enumerate()
15634 .flat_map(|(ix, snippet)| {
15635 snippet
15636 .prefix
15637 .iter()
15638 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15639 })
15640 .collect::<Vec<StringMatchCandidate>>();
15641
15642 let mut matches = fuzzy::match_strings(
15643 &candidates,
15644 &last_word,
15645 last_word.chars().any(|c| c.is_uppercase()),
15646 100,
15647 &Default::default(),
15648 executor,
15649 )
15650 .await;
15651
15652 // Remove all candidates where the query's start does not match the start of any word in the candidate
15653 if let Some(query_start) = last_word.chars().next() {
15654 matches.retain(|string_match| {
15655 split_words(&string_match.string).any(|word| {
15656 // Check that the first codepoint of the word as lowercase matches the first
15657 // codepoint of the query as lowercase
15658 word.chars()
15659 .flat_map(|codepoint| codepoint.to_lowercase())
15660 .zip(query_start.to_lowercase())
15661 .all(|(word_cp, query_cp)| word_cp == query_cp)
15662 })
15663 });
15664 }
15665
15666 let matched_strings = matches
15667 .into_iter()
15668 .map(|m| m.string)
15669 .collect::<HashSet<_>>();
15670
15671 let result: Vec<Completion> = snippets
15672 .into_iter()
15673 .filter_map(|snippet| {
15674 let matching_prefix = snippet
15675 .prefix
15676 .iter()
15677 .find(|prefix| matched_strings.contains(*prefix))?;
15678 let start = as_offset - last_word.len();
15679 let start = snapshot.anchor_before(start);
15680 let range = start..buffer_position;
15681 let lsp_start = to_lsp(&start);
15682 let lsp_range = lsp::Range {
15683 start: lsp_start,
15684 end: lsp_end,
15685 };
15686 Some(Completion {
15687 old_range: range,
15688 new_text: snippet.body.clone(),
15689 resolved: false,
15690 label: CodeLabel {
15691 text: matching_prefix.clone(),
15692 runs: vec![],
15693 filter_range: 0..matching_prefix.len(),
15694 },
15695 server_id: LanguageServerId(usize::MAX),
15696 documentation: snippet
15697 .description
15698 .clone()
15699 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15700 lsp_completion: lsp::CompletionItem {
15701 label: snippet.prefix.first().unwrap().clone(),
15702 kind: Some(CompletionItemKind::SNIPPET),
15703 label_details: snippet.description.as_ref().map(|description| {
15704 lsp::CompletionItemLabelDetails {
15705 detail: Some(description.clone()),
15706 description: None,
15707 }
15708 }),
15709 insert_text_format: Some(InsertTextFormat::SNIPPET),
15710 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15711 lsp::InsertReplaceEdit {
15712 new_text: snippet.body.clone(),
15713 insert: lsp_range,
15714 replace: lsp_range,
15715 },
15716 )),
15717 filter_text: Some(snippet.body.clone()),
15718 sort_text: Some(char::MAX.to_string()),
15719 ..Default::default()
15720 },
15721 confirm: None,
15722 })
15723 })
15724 .collect();
15725
15726 Ok(result)
15727 })
15728}
15729
15730impl CompletionProvider for Entity<Project> {
15731 fn completions(
15732 &self,
15733 buffer: &Entity<Buffer>,
15734 buffer_position: text::Anchor,
15735 options: CompletionContext,
15736 _window: &mut Window,
15737 cx: &mut Context<Editor>,
15738 ) -> Task<Result<Vec<Completion>>> {
15739 self.update(cx, |project, cx| {
15740 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15741 let project_completions = project.completions(buffer, buffer_position, options, cx);
15742 cx.background_spawn(async move {
15743 let mut completions = project_completions.await?;
15744 let snippets_completions = snippets.await?;
15745 completions.extend(snippets_completions);
15746 Ok(completions)
15747 })
15748 })
15749 }
15750
15751 fn resolve_completions(
15752 &self,
15753 buffer: Entity<Buffer>,
15754 completion_indices: Vec<usize>,
15755 completions: Rc<RefCell<Box<[Completion]>>>,
15756 cx: &mut Context<Editor>,
15757 ) -> Task<Result<bool>> {
15758 self.update(cx, |project, cx| {
15759 project.lsp_store().update(cx, |lsp_store, cx| {
15760 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15761 })
15762 })
15763 }
15764
15765 fn apply_additional_edits_for_completion(
15766 &self,
15767 buffer: Entity<Buffer>,
15768 completions: Rc<RefCell<Box<[Completion]>>>,
15769 completion_index: usize,
15770 push_to_history: bool,
15771 cx: &mut Context<Editor>,
15772 ) -> Task<Result<Option<language::Transaction>>> {
15773 self.update(cx, |project, cx| {
15774 project.lsp_store().update(cx, |lsp_store, cx| {
15775 lsp_store.apply_additional_edits_for_completion(
15776 buffer,
15777 completions,
15778 completion_index,
15779 push_to_history,
15780 cx,
15781 )
15782 })
15783 })
15784 }
15785
15786 fn is_completion_trigger(
15787 &self,
15788 buffer: &Entity<Buffer>,
15789 position: language::Anchor,
15790 text: &str,
15791 trigger_in_words: bool,
15792 cx: &mut Context<Editor>,
15793 ) -> bool {
15794 let mut chars = text.chars();
15795 let char = if let Some(char) = chars.next() {
15796 char
15797 } else {
15798 return false;
15799 };
15800 if chars.next().is_some() {
15801 return false;
15802 }
15803
15804 let buffer = buffer.read(cx);
15805 let snapshot = buffer.snapshot();
15806 if !snapshot.settings_at(position, cx).show_completions_on_input {
15807 return false;
15808 }
15809 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15810 if trigger_in_words && classifier.is_word(char) {
15811 return true;
15812 }
15813
15814 buffer.completion_triggers().contains(text)
15815 }
15816}
15817
15818impl SemanticsProvider for Entity<Project> {
15819 fn hover(
15820 &self,
15821 buffer: &Entity<Buffer>,
15822 position: text::Anchor,
15823 cx: &mut App,
15824 ) -> Option<Task<Vec<project::Hover>>> {
15825 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15826 }
15827
15828 fn document_highlights(
15829 &self,
15830 buffer: &Entity<Buffer>,
15831 position: text::Anchor,
15832 cx: &mut App,
15833 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15834 Some(self.update(cx, |project, cx| {
15835 project.document_highlights(buffer, position, cx)
15836 }))
15837 }
15838
15839 fn definitions(
15840 &self,
15841 buffer: &Entity<Buffer>,
15842 position: text::Anchor,
15843 kind: GotoDefinitionKind,
15844 cx: &mut App,
15845 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15846 Some(self.update(cx, |project, cx| match kind {
15847 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15848 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15849 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15850 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15851 }))
15852 }
15853
15854 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15855 // TODO: make this work for remote projects
15856 self.update(cx, |this, cx| {
15857 buffer.update(cx, |buffer, cx| {
15858 this.any_language_server_supports_inlay_hints(buffer, cx)
15859 })
15860 })
15861 }
15862
15863 fn inlay_hints(
15864 &self,
15865 buffer_handle: Entity<Buffer>,
15866 range: Range<text::Anchor>,
15867 cx: &mut App,
15868 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15869 Some(self.update(cx, |project, cx| {
15870 project.inlay_hints(buffer_handle, range, cx)
15871 }))
15872 }
15873
15874 fn resolve_inlay_hint(
15875 &self,
15876 hint: InlayHint,
15877 buffer_handle: Entity<Buffer>,
15878 server_id: LanguageServerId,
15879 cx: &mut App,
15880 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15881 Some(self.update(cx, |project, cx| {
15882 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15883 }))
15884 }
15885
15886 fn range_for_rename(
15887 &self,
15888 buffer: &Entity<Buffer>,
15889 position: text::Anchor,
15890 cx: &mut App,
15891 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15892 Some(self.update(cx, |project, cx| {
15893 let buffer = buffer.clone();
15894 let task = project.prepare_rename(buffer.clone(), position, cx);
15895 cx.spawn(|_, mut cx| async move {
15896 Ok(match task.await? {
15897 PrepareRenameResponse::Success(range) => Some(range),
15898 PrepareRenameResponse::InvalidPosition => None,
15899 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15900 // Fallback on using TreeSitter info to determine identifier range
15901 buffer.update(&mut cx, |buffer, _| {
15902 let snapshot = buffer.snapshot();
15903 let (range, kind) = snapshot.surrounding_word(position);
15904 if kind != Some(CharKind::Word) {
15905 return None;
15906 }
15907 Some(
15908 snapshot.anchor_before(range.start)
15909 ..snapshot.anchor_after(range.end),
15910 )
15911 })?
15912 }
15913 })
15914 })
15915 }))
15916 }
15917
15918 fn perform_rename(
15919 &self,
15920 buffer: &Entity<Buffer>,
15921 position: text::Anchor,
15922 new_name: String,
15923 cx: &mut App,
15924 ) -> Option<Task<Result<ProjectTransaction>>> {
15925 Some(self.update(cx, |project, cx| {
15926 project.perform_rename(buffer.clone(), position, new_name, cx)
15927 }))
15928 }
15929}
15930
15931fn inlay_hint_settings(
15932 location: Anchor,
15933 snapshot: &MultiBufferSnapshot,
15934 cx: &mut Context<Editor>,
15935) -> InlayHintSettings {
15936 let file = snapshot.file_at(location);
15937 let language = snapshot.language_at(location).map(|l| l.name());
15938 language_settings(language, file, cx).inlay_hints
15939}
15940
15941fn consume_contiguous_rows(
15942 contiguous_row_selections: &mut Vec<Selection<Point>>,
15943 selection: &Selection<Point>,
15944 display_map: &DisplaySnapshot,
15945 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15946) -> (MultiBufferRow, MultiBufferRow) {
15947 contiguous_row_selections.push(selection.clone());
15948 let start_row = MultiBufferRow(selection.start.row);
15949 let mut end_row = ending_row(selection, display_map);
15950
15951 while let Some(next_selection) = selections.peek() {
15952 if next_selection.start.row <= end_row.0 {
15953 end_row = ending_row(next_selection, display_map);
15954 contiguous_row_selections.push(selections.next().unwrap().clone());
15955 } else {
15956 break;
15957 }
15958 }
15959 (start_row, end_row)
15960}
15961
15962fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15963 if next_selection.end.column > 0 || next_selection.is_empty() {
15964 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15965 } else {
15966 MultiBufferRow(next_selection.end.row)
15967 }
15968}
15969
15970impl EditorSnapshot {
15971 pub fn remote_selections_in_range<'a>(
15972 &'a self,
15973 range: &'a Range<Anchor>,
15974 collaboration_hub: &dyn CollaborationHub,
15975 cx: &'a App,
15976 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15977 let participant_names = collaboration_hub.user_names(cx);
15978 let participant_indices = collaboration_hub.user_participant_indices(cx);
15979 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15980 let collaborators_by_replica_id = collaborators_by_peer_id
15981 .iter()
15982 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15983 .collect::<HashMap<_, _>>();
15984 self.buffer_snapshot
15985 .selections_in_range(range, false)
15986 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15987 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15988 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15989 let user_name = participant_names.get(&collaborator.user_id).cloned();
15990 Some(RemoteSelection {
15991 replica_id,
15992 selection,
15993 cursor_shape,
15994 line_mode,
15995 participant_index,
15996 peer_id: collaborator.peer_id,
15997 user_name,
15998 })
15999 })
16000 }
16001
16002 pub fn hunks_for_ranges(
16003 &self,
16004 ranges: impl Iterator<Item = Range<Point>>,
16005 ) -> Vec<MultiBufferDiffHunk> {
16006 let mut hunks = Vec::new();
16007 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16008 HashMap::default();
16009 for query_range in ranges {
16010 let query_rows =
16011 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16012 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16013 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16014 ) {
16015 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16016 // when the caret is just above or just below the deleted hunk.
16017 let allow_adjacent = hunk.status().is_removed();
16018 let related_to_selection = if allow_adjacent {
16019 hunk.row_range.overlaps(&query_rows)
16020 || hunk.row_range.start == query_rows.end
16021 || hunk.row_range.end == query_rows.start
16022 } else {
16023 hunk.row_range.overlaps(&query_rows)
16024 };
16025 if related_to_selection {
16026 if !processed_buffer_rows
16027 .entry(hunk.buffer_id)
16028 .or_default()
16029 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16030 {
16031 continue;
16032 }
16033 hunks.push(hunk);
16034 }
16035 }
16036 }
16037
16038 hunks
16039 }
16040
16041 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16042 self.display_snapshot.buffer_snapshot.language_at(position)
16043 }
16044
16045 pub fn is_focused(&self) -> bool {
16046 self.is_focused
16047 }
16048
16049 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16050 self.placeholder_text.as_ref()
16051 }
16052
16053 pub fn scroll_position(&self) -> gpui::Point<f32> {
16054 self.scroll_anchor.scroll_position(&self.display_snapshot)
16055 }
16056
16057 fn gutter_dimensions(
16058 &self,
16059 font_id: FontId,
16060 font_size: Pixels,
16061 max_line_number_width: Pixels,
16062 cx: &App,
16063 ) -> Option<GutterDimensions> {
16064 if !self.show_gutter {
16065 return None;
16066 }
16067
16068 let descent = cx.text_system().descent(font_id, font_size);
16069 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16070 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16071
16072 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16073 matches!(
16074 ProjectSettings::get_global(cx).git.git_gutter,
16075 Some(GitGutterSetting::TrackedFiles)
16076 )
16077 });
16078 let gutter_settings = EditorSettings::get_global(cx).gutter;
16079 let show_line_numbers = self
16080 .show_line_numbers
16081 .unwrap_or(gutter_settings.line_numbers);
16082 let line_gutter_width = if show_line_numbers {
16083 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16084 let min_width_for_number_on_gutter = em_advance * 4.0;
16085 max_line_number_width.max(min_width_for_number_on_gutter)
16086 } else {
16087 0.0.into()
16088 };
16089
16090 let show_code_actions = self
16091 .show_code_actions
16092 .unwrap_or(gutter_settings.code_actions);
16093
16094 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16095
16096 let git_blame_entries_width =
16097 self.git_blame_gutter_max_author_length
16098 .map(|max_author_length| {
16099 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16100
16101 /// The number of characters to dedicate to gaps and margins.
16102 const SPACING_WIDTH: usize = 4;
16103
16104 let max_char_count = max_author_length
16105 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16106 + ::git::SHORT_SHA_LENGTH
16107 + MAX_RELATIVE_TIMESTAMP.len()
16108 + SPACING_WIDTH;
16109
16110 em_advance * max_char_count
16111 });
16112
16113 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16114 left_padding += if show_code_actions || show_runnables {
16115 em_width * 3.0
16116 } else if show_git_gutter && show_line_numbers {
16117 em_width * 2.0
16118 } else if show_git_gutter || show_line_numbers {
16119 em_width
16120 } else {
16121 px(0.)
16122 };
16123
16124 let right_padding = if gutter_settings.folds && show_line_numbers {
16125 em_width * 4.0
16126 } else if gutter_settings.folds {
16127 em_width * 3.0
16128 } else if show_line_numbers {
16129 em_width
16130 } else {
16131 px(0.)
16132 };
16133
16134 Some(GutterDimensions {
16135 left_padding,
16136 right_padding,
16137 width: line_gutter_width + left_padding + right_padding,
16138 margin: -descent,
16139 git_blame_entries_width,
16140 })
16141 }
16142
16143 pub fn render_crease_toggle(
16144 &self,
16145 buffer_row: MultiBufferRow,
16146 row_contains_cursor: bool,
16147 editor: Entity<Editor>,
16148 window: &mut Window,
16149 cx: &mut App,
16150 ) -> Option<AnyElement> {
16151 let folded = self.is_line_folded(buffer_row);
16152 let mut is_foldable = false;
16153
16154 if let Some(crease) = self
16155 .crease_snapshot
16156 .query_row(buffer_row, &self.buffer_snapshot)
16157 {
16158 is_foldable = true;
16159 match crease {
16160 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16161 if let Some(render_toggle) = render_toggle {
16162 let toggle_callback =
16163 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16164 if folded {
16165 editor.update(cx, |editor, cx| {
16166 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16167 });
16168 } else {
16169 editor.update(cx, |editor, cx| {
16170 editor.unfold_at(
16171 &crate::UnfoldAt { buffer_row },
16172 window,
16173 cx,
16174 )
16175 });
16176 }
16177 });
16178 return Some((render_toggle)(
16179 buffer_row,
16180 folded,
16181 toggle_callback,
16182 window,
16183 cx,
16184 ));
16185 }
16186 }
16187 }
16188 }
16189
16190 is_foldable |= self.starts_indent(buffer_row);
16191
16192 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16193 Some(
16194 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16195 .toggle_state(folded)
16196 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16197 if folded {
16198 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16199 } else {
16200 this.fold_at(&FoldAt { buffer_row }, window, cx);
16201 }
16202 }))
16203 .into_any_element(),
16204 )
16205 } else {
16206 None
16207 }
16208 }
16209
16210 pub fn render_crease_trailer(
16211 &self,
16212 buffer_row: MultiBufferRow,
16213 window: &mut Window,
16214 cx: &mut App,
16215 ) -> Option<AnyElement> {
16216 let folded = self.is_line_folded(buffer_row);
16217 if let Crease::Inline { render_trailer, .. } = self
16218 .crease_snapshot
16219 .query_row(buffer_row, &self.buffer_snapshot)?
16220 {
16221 let render_trailer = render_trailer.as_ref()?;
16222 Some(render_trailer(buffer_row, folded, window, cx))
16223 } else {
16224 None
16225 }
16226 }
16227}
16228
16229impl Deref for EditorSnapshot {
16230 type Target = DisplaySnapshot;
16231
16232 fn deref(&self) -> &Self::Target {
16233 &self.display_snapshot
16234 }
16235}
16236
16237#[derive(Clone, Debug, PartialEq, Eq)]
16238pub enum EditorEvent {
16239 InputIgnored {
16240 text: Arc<str>,
16241 },
16242 InputHandled {
16243 utf16_range_to_replace: Option<Range<isize>>,
16244 text: Arc<str>,
16245 },
16246 ExcerptsAdded {
16247 buffer: Entity<Buffer>,
16248 predecessor: ExcerptId,
16249 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16250 },
16251 ExcerptsRemoved {
16252 ids: Vec<ExcerptId>,
16253 },
16254 BufferFoldToggled {
16255 ids: Vec<ExcerptId>,
16256 folded: bool,
16257 },
16258 ExcerptsEdited {
16259 ids: Vec<ExcerptId>,
16260 },
16261 ExcerptsExpanded {
16262 ids: Vec<ExcerptId>,
16263 },
16264 BufferEdited,
16265 Edited {
16266 transaction_id: clock::Lamport,
16267 },
16268 Reparsed(BufferId),
16269 Focused,
16270 FocusedIn,
16271 Blurred,
16272 DirtyChanged,
16273 Saved,
16274 TitleChanged,
16275 DiffBaseChanged,
16276 SelectionsChanged {
16277 local: bool,
16278 },
16279 ScrollPositionChanged {
16280 local: bool,
16281 autoscroll: bool,
16282 },
16283 Closed,
16284 TransactionUndone {
16285 transaction_id: clock::Lamport,
16286 },
16287 TransactionBegun {
16288 transaction_id: clock::Lamport,
16289 },
16290 Reloaded,
16291 CursorShapeChanged,
16292}
16293
16294impl EventEmitter<EditorEvent> for Editor {}
16295
16296impl Focusable for Editor {
16297 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16298 self.focus_handle.clone()
16299 }
16300}
16301
16302impl Render for Editor {
16303 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16304 let settings = ThemeSettings::get_global(cx);
16305
16306 let mut text_style = match self.mode {
16307 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16308 color: cx.theme().colors().editor_foreground,
16309 font_family: settings.ui_font.family.clone(),
16310 font_features: settings.ui_font.features.clone(),
16311 font_fallbacks: settings.ui_font.fallbacks.clone(),
16312 font_size: rems(0.875).into(),
16313 font_weight: settings.ui_font.weight,
16314 line_height: relative(settings.buffer_line_height.value()),
16315 ..Default::default()
16316 },
16317 EditorMode::Full => TextStyle {
16318 color: cx.theme().colors().editor_foreground,
16319 font_family: settings.buffer_font.family.clone(),
16320 font_features: settings.buffer_font.features.clone(),
16321 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16322 font_size: settings.buffer_font_size(cx).into(),
16323 font_weight: settings.buffer_font.weight,
16324 line_height: relative(settings.buffer_line_height.value()),
16325 ..Default::default()
16326 },
16327 };
16328 if let Some(text_style_refinement) = &self.text_style_refinement {
16329 text_style.refine(text_style_refinement)
16330 }
16331
16332 let background = match self.mode {
16333 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16334 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16335 EditorMode::Full => cx.theme().colors().editor_background,
16336 };
16337
16338 EditorElement::new(
16339 &cx.entity(),
16340 EditorStyle {
16341 background,
16342 local_player: cx.theme().players().local(),
16343 text: text_style,
16344 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16345 syntax: cx.theme().syntax().clone(),
16346 status: cx.theme().status().clone(),
16347 inlay_hints_style: make_inlay_hints_style(cx),
16348 inline_completion_styles: make_suggestion_styles(cx),
16349 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16350 },
16351 )
16352 }
16353}
16354
16355impl EntityInputHandler for Editor {
16356 fn text_for_range(
16357 &mut self,
16358 range_utf16: Range<usize>,
16359 adjusted_range: &mut Option<Range<usize>>,
16360 _: &mut Window,
16361 cx: &mut Context<Self>,
16362 ) -> Option<String> {
16363 let snapshot = self.buffer.read(cx).read(cx);
16364 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16365 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16366 if (start.0..end.0) != range_utf16 {
16367 adjusted_range.replace(start.0..end.0);
16368 }
16369 Some(snapshot.text_for_range(start..end).collect())
16370 }
16371
16372 fn selected_text_range(
16373 &mut self,
16374 ignore_disabled_input: bool,
16375 _: &mut Window,
16376 cx: &mut Context<Self>,
16377 ) -> Option<UTF16Selection> {
16378 // Prevent the IME menu from appearing when holding down an alphabetic key
16379 // while input is disabled.
16380 if !ignore_disabled_input && !self.input_enabled {
16381 return None;
16382 }
16383
16384 let selection = self.selections.newest::<OffsetUtf16>(cx);
16385 let range = selection.range();
16386
16387 Some(UTF16Selection {
16388 range: range.start.0..range.end.0,
16389 reversed: selection.reversed,
16390 })
16391 }
16392
16393 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16394 let snapshot = self.buffer.read(cx).read(cx);
16395 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16396 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16397 }
16398
16399 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16400 self.clear_highlights::<InputComposition>(cx);
16401 self.ime_transaction.take();
16402 }
16403
16404 fn replace_text_in_range(
16405 &mut self,
16406 range_utf16: Option<Range<usize>>,
16407 text: &str,
16408 window: &mut Window,
16409 cx: &mut Context<Self>,
16410 ) {
16411 if !self.input_enabled {
16412 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16413 return;
16414 }
16415
16416 self.transact(window, cx, |this, window, cx| {
16417 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16418 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16419 Some(this.selection_replacement_ranges(range_utf16, cx))
16420 } else {
16421 this.marked_text_ranges(cx)
16422 };
16423
16424 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16425 let newest_selection_id = this.selections.newest_anchor().id;
16426 this.selections
16427 .all::<OffsetUtf16>(cx)
16428 .iter()
16429 .zip(ranges_to_replace.iter())
16430 .find_map(|(selection, range)| {
16431 if selection.id == newest_selection_id {
16432 Some(
16433 (range.start.0 as isize - selection.head().0 as isize)
16434 ..(range.end.0 as isize - selection.head().0 as isize),
16435 )
16436 } else {
16437 None
16438 }
16439 })
16440 });
16441
16442 cx.emit(EditorEvent::InputHandled {
16443 utf16_range_to_replace: range_to_replace,
16444 text: text.into(),
16445 });
16446
16447 if let Some(new_selected_ranges) = new_selected_ranges {
16448 this.change_selections(None, window, cx, |selections| {
16449 selections.select_ranges(new_selected_ranges)
16450 });
16451 this.backspace(&Default::default(), window, cx);
16452 }
16453
16454 this.handle_input(text, window, cx);
16455 });
16456
16457 if let Some(transaction) = self.ime_transaction {
16458 self.buffer.update(cx, |buffer, cx| {
16459 buffer.group_until_transaction(transaction, cx);
16460 });
16461 }
16462
16463 self.unmark_text(window, cx);
16464 }
16465
16466 fn replace_and_mark_text_in_range(
16467 &mut self,
16468 range_utf16: Option<Range<usize>>,
16469 text: &str,
16470 new_selected_range_utf16: Option<Range<usize>>,
16471 window: &mut Window,
16472 cx: &mut Context<Self>,
16473 ) {
16474 if !self.input_enabled {
16475 return;
16476 }
16477
16478 let transaction = self.transact(window, cx, |this, window, cx| {
16479 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16480 let snapshot = this.buffer.read(cx).read(cx);
16481 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16482 for marked_range in &mut marked_ranges {
16483 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16484 marked_range.start.0 += relative_range_utf16.start;
16485 marked_range.start =
16486 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16487 marked_range.end =
16488 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16489 }
16490 }
16491 Some(marked_ranges)
16492 } else if let Some(range_utf16) = range_utf16 {
16493 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16494 Some(this.selection_replacement_ranges(range_utf16, cx))
16495 } else {
16496 None
16497 };
16498
16499 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16500 let newest_selection_id = this.selections.newest_anchor().id;
16501 this.selections
16502 .all::<OffsetUtf16>(cx)
16503 .iter()
16504 .zip(ranges_to_replace.iter())
16505 .find_map(|(selection, range)| {
16506 if selection.id == newest_selection_id {
16507 Some(
16508 (range.start.0 as isize - selection.head().0 as isize)
16509 ..(range.end.0 as isize - selection.head().0 as isize),
16510 )
16511 } else {
16512 None
16513 }
16514 })
16515 });
16516
16517 cx.emit(EditorEvent::InputHandled {
16518 utf16_range_to_replace: range_to_replace,
16519 text: text.into(),
16520 });
16521
16522 if let Some(ranges) = ranges_to_replace {
16523 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16524 }
16525
16526 let marked_ranges = {
16527 let snapshot = this.buffer.read(cx).read(cx);
16528 this.selections
16529 .disjoint_anchors()
16530 .iter()
16531 .map(|selection| {
16532 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16533 })
16534 .collect::<Vec<_>>()
16535 };
16536
16537 if text.is_empty() {
16538 this.unmark_text(window, cx);
16539 } else {
16540 this.highlight_text::<InputComposition>(
16541 marked_ranges.clone(),
16542 HighlightStyle {
16543 underline: Some(UnderlineStyle {
16544 thickness: px(1.),
16545 color: None,
16546 wavy: false,
16547 }),
16548 ..Default::default()
16549 },
16550 cx,
16551 );
16552 }
16553
16554 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16555 let use_autoclose = this.use_autoclose;
16556 let use_auto_surround = this.use_auto_surround;
16557 this.set_use_autoclose(false);
16558 this.set_use_auto_surround(false);
16559 this.handle_input(text, window, cx);
16560 this.set_use_autoclose(use_autoclose);
16561 this.set_use_auto_surround(use_auto_surround);
16562
16563 if let Some(new_selected_range) = new_selected_range_utf16 {
16564 let snapshot = this.buffer.read(cx).read(cx);
16565 let new_selected_ranges = marked_ranges
16566 .into_iter()
16567 .map(|marked_range| {
16568 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16569 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16570 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16571 snapshot.clip_offset_utf16(new_start, Bias::Left)
16572 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16573 })
16574 .collect::<Vec<_>>();
16575
16576 drop(snapshot);
16577 this.change_selections(None, window, cx, |selections| {
16578 selections.select_ranges(new_selected_ranges)
16579 });
16580 }
16581 });
16582
16583 self.ime_transaction = self.ime_transaction.or(transaction);
16584 if let Some(transaction) = self.ime_transaction {
16585 self.buffer.update(cx, |buffer, cx| {
16586 buffer.group_until_transaction(transaction, cx);
16587 });
16588 }
16589
16590 if self.text_highlights::<InputComposition>(cx).is_none() {
16591 self.ime_transaction.take();
16592 }
16593 }
16594
16595 fn bounds_for_range(
16596 &mut self,
16597 range_utf16: Range<usize>,
16598 element_bounds: gpui::Bounds<Pixels>,
16599 window: &mut Window,
16600 cx: &mut Context<Self>,
16601 ) -> Option<gpui::Bounds<Pixels>> {
16602 let text_layout_details = self.text_layout_details(window);
16603 let gpui::Size {
16604 width: em_width,
16605 height: line_height,
16606 } = self.character_size(window);
16607
16608 let snapshot = self.snapshot(window, cx);
16609 let scroll_position = snapshot.scroll_position();
16610 let scroll_left = scroll_position.x * em_width;
16611
16612 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16613 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16614 + self.gutter_dimensions.width
16615 + self.gutter_dimensions.margin;
16616 let y = line_height * (start.row().as_f32() - scroll_position.y);
16617
16618 Some(Bounds {
16619 origin: element_bounds.origin + point(x, y),
16620 size: size(em_width, line_height),
16621 })
16622 }
16623
16624 fn character_index_for_point(
16625 &mut self,
16626 point: gpui::Point<Pixels>,
16627 _window: &mut Window,
16628 _cx: &mut Context<Self>,
16629 ) -> Option<usize> {
16630 let position_map = self.last_position_map.as_ref()?;
16631 if !position_map.text_hitbox.contains(&point) {
16632 return None;
16633 }
16634 let display_point = position_map.point_for_position(point).previous_valid;
16635 let anchor = position_map
16636 .snapshot
16637 .display_point_to_anchor(display_point, Bias::Left);
16638 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16639 Some(utf16_offset.0)
16640 }
16641}
16642
16643trait SelectionExt {
16644 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16645 fn spanned_rows(
16646 &self,
16647 include_end_if_at_line_start: bool,
16648 map: &DisplaySnapshot,
16649 ) -> Range<MultiBufferRow>;
16650}
16651
16652impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16653 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16654 let start = self
16655 .start
16656 .to_point(&map.buffer_snapshot)
16657 .to_display_point(map);
16658 let end = self
16659 .end
16660 .to_point(&map.buffer_snapshot)
16661 .to_display_point(map);
16662 if self.reversed {
16663 end..start
16664 } else {
16665 start..end
16666 }
16667 }
16668
16669 fn spanned_rows(
16670 &self,
16671 include_end_if_at_line_start: bool,
16672 map: &DisplaySnapshot,
16673 ) -> Range<MultiBufferRow> {
16674 let start = self.start.to_point(&map.buffer_snapshot);
16675 let mut end = self.end.to_point(&map.buffer_snapshot);
16676 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16677 end.row -= 1;
16678 }
16679
16680 let buffer_start = map.prev_line_boundary(start).0;
16681 let buffer_end = map.next_line_boundary(end).0;
16682 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16683 }
16684}
16685
16686impl<T: InvalidationRegion> InvalidationStack<T> {
16687 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16688 where
16689 S: Clone + ToOffset,
16690 {
16691 while let Some(region) = self.last() {
16692 let all_selections_inside_invalidation_ranges =
16693 if selections.len() == region.ranges().len() {
16694 selections
16695 .iter()
16696 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16697 .all(|(selection, invalidation_range)| {
16698 let head = selection.head().to_offset(buffer);
16699 invalidation_range.start <= head && invalidation_range.end >= head
16700 })
16701 } else {
16702 false
16703 };
16704
16705 if all_selections_inside_invalidation_ranges {
16706 break;
16707 } else {
16708 self.pop();
16709 }
16710 }
16711 }
16712}
16713
16714impl<T> Default for InvalidationStack<T> {
16715 fn default() -> Self {
16716 Self(Default::default())
16717 }
16718}
16719
16720impl<T> Deref for InvalidationStack<T> {
16721 type Target = Vec<T>;
16722
16723 fn deref(&self) -> &Self::Target {
16724 &self.0
16725 }
16726}
16727
16728impl<T> DerefMut for InvalidationStack<T> {
16729 fn deref_mut(&mut self) -> &mut Self::Target {
16730 &mut self.0
16731 }
16732}
16733
16734impl InvalidationRegion for SnippetState {
16735 fn ranges(&self) -> &[Range<Anchor>] {
16736 &self.ranges[self.active_index]
16737 }
16738}
16739
16740pub fn diagnostic_block_renderer(
16741 diagnostic: Diagnostic,
16742 max_message_rows: Option<u8>,
16743 allow_closing: bool,
16744 _is_valid: bool,
16745) -> RenderBlock {
16746 let (text_without_backticks, code_ranges) =
16747 highlight_diagnostic_message(&diagnostic, max_message_rows);
16748
16749 Arc::new(move |cx: &mut BlockContext| {
16750 let group_id: SharedString = cx.block_id.to_string().into();
16751
16752 let mut text_style = cx.window.text_style().clone();
16753 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16754 let theme_settings = ThemeSettings::get_global(cx);
16755 text_style.font_family = theme_settings.buffer_font.family.clone();
16756 text_style.font_style = theme_settings.buffer_font.style;
16757 text_style.font_features = theme_settings.buffer_font.features.clone();
16758 text_style.font_weight = theme_settings.buffer_font.weight;
16759
16760 let multi_line_diagnostic = diagnostic.message.contains('\n');
16761
16762 let buttons = |diagnostic: &Diagnostic| {
16763 if multi_line_diagnostic {
16764 v_flex()
16765 } else {
16766 h_flex()
16767 }
16768 .when(allow_closing, |div| {
16769 div.children(diagnostic.is_primary.then(|| {
16770 IconButton::new("close-block", IconName::XCircle)
16771 .icon_color(Color::Muted)
16772 .size(ButtonSize::Compact)
16773 .style(ButtonStyle::Transparent)
16774 .visible_on_hover(group_id.clone())
16775 .on_click(move |_click, window, cx| {
16776 window.dispatch_action(Box::new(Cancel), cx)
16777 })
16778 .tooltip(|window, cx| {
16779 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16780 })
16781 }))
16782 })
16783 .child(
16784 IconButton::new("copy-block", IconName::Copy)
16785 .icon_color(Color::Muted)
16786 .size(ButtonSize::Compact)
16787 .style(ButtonStyle::Transparent)
16788 .visible_on_hover(group_id.clone())
16789 .on_click({
16790 let message = diagnostic.message.clone();
16791 move |_click, _, cx| {
16792 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16793 }
16794 })
16795 .tooltip(Tooltip::text("Copy diagnostic message")),
16796 )
16797 };
16798
16799 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16800 AvailableSpace::min_size(),
16801 cx.window,
16802 cx.app,
16803 );
16804
16805 h_flex()
16806 .id(cx.block_id)
16807 .group(group_id.clone())
16808 .relative()
16809 .size_full()
16810 .block_mouse_down()
16811 .pl(cx.gutter_dimensions.width)
16812 .w(cx.max_width - cx.gutter_dimensions.full_width())
16813 .child(
16814 div()
16815 .flex()
16816 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16817 .flex_shrink(),
16818 )
16819 .child(buttons(&diagnostic))
16820 .child(div().flex().flex_shrink_0().child(
16821 StyledText::new(text_without_backticks.clone()).with_highlights(
16822 &text_style,
16823 code_ranges.iter().map(|range| {
16824 (
16825 range.clone(),
16826 HighlightStyle {
16827 font_weight: Some(FontWeight::BOLD),
16828 ..Default::default()
16829 },
16830 )
16831 }),
16832 ),
16833 ))
16834 .into_any_element()
16835 })
16836}
16837
16838fn inline_completion_edit_text(
16839 current_snapshot: &BufferSnapshot,
16840 edits: &[(Range<Anchor>, String)],
16841 edit_preview: &EditPreview,
16842 include_deletions: bool,
16843 cx: &App,
16844) -> HighlightedText {
16845 let edits = edits
16846 .iter()
16847 .map(|(anchor, text)| {
16848 (
16849 anchor.start.text_anchor..anchor.end.text_anchor,
16850 text.clone(),
16851 )
16852 })
16853 .collect::<Vec<_>>();
16854
16855 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16856}
16857
16858pub fn highlight_diagnostic_message(
16859 diagnostic: &Diagnostic,
16860 mut max_message_rows: Option<u8>,
16861) -> (SharedString, Vec<Range<usize>>) {
16862 let mut text_without_backticks = String::new();
16863 let mut code_ranges = Vec::new();
16864
16865 if let Some(source) = &diagnostic.source {
16866 text_without_backticks.push_str(source);
16867 code_ranges.push(0..source.len());
16868 text_without_backticks.push_str(": ");
16869 }
16870
16871 let mut prev_offset = 0;
16872 let mut in_code_block = false;
16873 let has_row_limit = max_message_rows.is_some();
16874 let mut newline_indices = diagnostic
16875 .message
16876 .match_indices('\n')
16877 .filter(|_| has_row_limit)
16878 .map(|(ix, _)| ix)
16879 .fuse()
16880 .peekable();
16881
16882 for (quote_ix, _) in diagnostic
16883 .message
16884 .match_indices('`')
16885 .chain([(diagnostic.message.len(), "")])
16886 {
16887 let mut first_newline_ix = None;
16888 let mut last_newline_ix = None;
16889 while let Some(newline_ix) = newline_indices.peek() {
16890 if *newline_ix < quote_ix {
16891 if first_newline_ix.is_none() {
16892 first_newline_ix = Some(*newline_ix);
16893 }
16894 last_newline_ix = Some(*newline_ix);
16895
16896 if let Some(rows_left) = &mut max_message_rows {
16897 if *rows_left == 0 {
16898 break;
16899 } else {
16900 *rows_left -= 1;
16901 }
16902 }
16903 let _ = newline_indices.next();
16904 } else {
16905 break;
16906 }
16907 }
16908 let prev_len = text_without_backticks.len();
16909 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16910 text_without_backticks.push_str(new_text);
16911 if in_code_block {
16912 code_ranges.push(prev_len..text_without_backticks.len());
16913 }
16914 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16915 in_code_block = !in_code_block;
16916 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16917 text_without_backticks.push_str("...");
16918 break;
16919 }
16920 }
16921
16922 (text_without_backticks.into(), code_ranges)
16923}
16924
16925fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16926 match severity {
16927 DiagnosticSeverity::ERROR => colors.error,
16928 DiagnosticSeverity::WARNING => colors.warning,
16929 DiagnosticSeverity::INFORMATION => colors.info,
16930 DiagnosticSeverity::HINT => colors.info,
16931 _ => colors.ignored,
16932 }
16933}
16934
16935pub fn styled_runs_for_code_label<'a>(
16936 label: &'a CodeLabel,
16937 syntax_theme: &'a theme::SyntaxTheme,
16938) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16939 let fade_out = HighlightStyle {
16940 fade_out: Some(0.35),
16941 ..Default::default()
16942 };
16943
16944 let mut prev_end = label.filter_range.end;
16945 label
16946 .runs
16947 .iter()
16948 .enumerate()
16949 .flat_map(move |(ix, (range, highlight_id))| {
16950 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16951 style
16952 } else {
16953 return Default::default();
16954 };
16955 let mut muted_style = style;
16956 muted_style.highlight(fade_out);
16957
16958 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16959 if range.start >= label.filter_range.end {
16960 if range.start > prev_end {
16961 runs.push((prev_end..range.start, fade_out));
16962 }
16963 runs.push((range.clone(), muted_style));
16964 } else if range.end <= label.filter_range.end {
16965 runs.push((range.clone(), style));
16966 } else {
16967 runs.push((range.start..label.filter_range.end, style));
16968 runs.push((label.filter_range.end..range.end, muted_style));
16969 }
16970 prev_end = cmp::max(prev_end, range.end);
16971
16972 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16973 runs.push((prev_end..label.text.len(), fade_out));
16974 }
16975
16976 runs
16977 })
16978}
16979
16980pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16981 let mut prev_index = 0;
16982 let mut prev_codepoint: Option<char> = None;
16983 text.char_indices()
16984 .chain([(text.len(), '\0')])
16985 .filter_map(move |(index, codepoint)| {
16986 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16987 let is_boundary = index == text.len()
16988 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16989 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16990 if is_boundary {
16991 let chunk = &text[prev_index..index];
16992 prev_index = index;
16993 Some(chunk)
16994 } else {
16995 None
16996 }
16997 })
16998}
16999
17000pub trait RangeToAnchorExt: Sized {
17001 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17002
17003 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17004 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17005 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17006 }
17007}
17008
17009impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17010 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17011 let start_offset = self.start.to_offset(snapshot);
17012 let end_offset = self.end.to_offset(snapshot);
17013 if start_offset == end_offset {
17014 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17015 } else {
17016 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17017 }
17018 }
17019}
17020
17021pub trait RowExt {
17022 fn as_f32(&self) -> f32;
17023
17024 fn next_row(&self) -> Self;
17025
17026 fn previous_row(&self) -> Self;
17027
17028 fn minus(&self, other: Self) -> u32;
17029}
17030
17031impl RowExt for DisplayRow {
17032 fn as_f32(&self) -> f32 {
17033 self.0 as f32
17034 }
17035
17036 fn next_row(&self) -> Self {
17037 Self(self.0 + 1)
17038 }
17039
17040 fn previous_row(&self) -> Self {
17041 Self(self.0.saturating_sub(1))
17042 }
17043
17044 fn minus(&self, other: Self) -> u32 {
17045 self.0 - other.0
17046 }
17047}
17048
17049impl RowExt for MultiBufferRow {
17050 fn as_f32(&self) -> f32 {
17051 self.0 as f32
17052 }
17053
17054 fn next_row(&self) -> Self {
17055 Self(self.0 + 1)
17056 }
17057
17058 fn previous_row(&self) -> Self {
17059 Self(self.0.saturating_sub(1))
17060 }
17061
17062 fn minus(&self, other: Self) -> u32 {
17063 self.0 - other.0
17064 }
17065}
17066
17067trait RowRangeExt {
17068 type Row;
17069
17070 fn len(&self) -> usize;
17071
17072 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17073}
17074
17075impl RowRangeExt for Range<MultiBufferRow> {
17076 type Row = MultiBufferRow;
17077
17078 fn len(&self) -> usize {
17079 (self.end.0 - self.start.0) as usize
17080 }
17081
17082 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17083 (self.start.0..self.end.0).map(MultiBufferRow)
17084 }
17085}
17086
17087impl RowRangeExt for Range<DisplayRow> {
17088 type Row = DisplayRow;
17089
17090 fn len(&self) -> usize {
17091 (self.end.0 - self.start.0) as usize
17092 }
17093
17094 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17095 (self.start.0..self.end.0).map(DisplayRow)
17096 }
17097}
17098
17099/// If select range has more than one line, we
17100/// just point the cursor to range.start.
17101fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17102 if range.start.row == range.end.row {
17103 range
17104 } else {
17105 range.start..range.start
17106 }
17107}
17108pub struct KillRing(ClipboardItem);
17109impl Global for KillRing {}
17110
17111const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17112
17113fn all_edits_insertions_or_deletions(
17114 edits: &Vec<(Range<Anchor>, String)>,
17115 snapshot: &MultiBufferSnapshot,
17116) -> bool {
17117 let mut all_insertions = true;
17118 let mut all_deletions = true;
17119
17120 for (range, new_text) in edits.iter() {
17121 let range_is_empty = range.to_offset(&snapshot).is_empty();
17122 let text_is_empty = new_text.is_empty();
17123
17124 if range_is_empty != text_is_empty {
17125 if range_is_empty {
17126 all_deletions = false;
17127 } else {
17128 all_insertions = false;
17129 }
17130 } else {
17131 return false;
17132 }
17133
17134 if !all_insertions && !all_deletions {
17135 return false;
17136 }
17137 }
17138 all_insertions || all_deletions
17139}