1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
84 ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
85 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
86 InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
87 Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
88 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
89 WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
103 HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
104 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
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::{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
209pub fn render_parsed_markdown(
210 element_id: impl Into<ElementId>,
211 parsed: &language::ParsedMarkdown,
212 editor_style: &EditorStyle,
213 workspace: Option<WeakEntity<Workspace>>,
214 cx: &mut App,
215) -> InteractiveText {
216 let code_span_background_color = cx
217 .theme()
218 .colors()
219 .editor_document_highlight_read_background;
220
221 let highlights = gpui::combine_highlights(
222 parsed.highlights.iter().filter_map(|(range, highlight)| {
223 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
224 Some((range.clone(), highlight))
225 }),
226 parsed
227 .regions
228 .iter()
229 .zip(&parsed.region_ranges)
230 .filter_map(|(region, range)| {
231 if region.code {
232 Some((
233 range.clone(),
234 HighlightStyle {
235 background_color: Some(code_span_background_color),
236 ..Default::default()
237 },
238 ))
239 } else {
240 None
241 }
242 }),
243 );
244
245 let mut links = Vec::new();
246 let mut link_ranges = Vec::new();
247 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
248 if let Some(link) = region.link.clone() {
249 links.push(link);
250 link_ranges.push(range.clone());
251 }
252 }
253
254 InteractiveText::new(
255 element_id,
256 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
257 )
258 .on_click(
259 link_ranges,
260 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
261 markdown::Link::Web { url } => cx.open_url(url),
262 markdown::Link::Path { path } => {
263 if let Some(workspace) = &workspace {
264 _ = workspace.update(cx, |workspace, cx| {
265 workspace
266 .open_abs_path(path.clone(), false, window, cx)
267 .detach();
268 });
269 }
270 }
271 },
272 )
273}
274
275#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
276pub enum InlayId {
277 InlineCompletion(usize),
278 Hint(usize),
279}
280
281impl InlayId {
282 fn id(&self) -> usize {
283 match self {
284 Self::InlineCompletion(id) => *id,
285 Self::Hint(id) => *id,
286 }
287 }
288}
289
290enum DocumentHighlightRead {}
291enum DocumentHighlightWrite {}
292enum InputComposition {}
293enum SelectedTextHighlight {}
294
295#[derive(Debug, Copy, Clone, PartialEq, Eq)]
296pub enum Navigated {
297 Yes,
298 No,
299}
300
301impl Navigated {
302 pub fn from_bool(yes: bool) -> Navigated {
303 if yes {
304 Navigated::Yes
305 } else {
306 Navigated::No
307 }
308 }
309}
310
311pub fn init_settings(cx: &mut App) {
312 EditorSettings::register(cx);
313}
314
315pub fn init(cx: &mut App) {
316 init_settings(cx);
317
318 workspace::register_project_item::<Editor>(cx);
319 workspace::FollowableViewRegistry::register::<Editor>(cx);
320 workspace::register_serializable_item::<Editor>(cx);
321
322 cx.observe_new(
323 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
324 workspace.register_action(Editor::new_file);
325 workspace.register_action(Editor::new_file_vertical);
326 workspace.register_action(Editor::new_file_horizontal);
327 workspace.register_action(Editor::cancel_language_server_work);
328 },
329 )
330 .detach();
331
332 cx.on_action(move |_: &workspace::NewFile, cx| {
333 let app_state = workspace::AppState::global(cx);
334 if let Some(app_state) = app_state.upgrade() {
335 workspace::open_new(
336 Default::default(),
337 app_state,
338 cx,
339 |workspace, window, cx| {
340 Editor::new_file(workspace, &Default::default(), window, cx)
341 },
342 )
343 .detach();
344 }
345 });
346 cx.on_action(move |_: &workspace::NewWindow, cx| {
347 let app_state = workspace::AppState::global(cx);
348 if let Some(app_state) = app_state.upgrade() {
349 workspace::open_new(
350 Default::default(),
351 app_state,
352 cx,
353 |workspace, window, cx| {
354 cx.activate(true);
355 Editor::new_file(workspace, &Default::default(), window, cx)
356 },
357 )
358 .detach();
359 }
360 });
361}
362
363pub struct SearchWithinRange;
364
365trait InvalidationRegion {
366 fn ranges(&self) -> &[Range<Anchor>];
367}
368
369#[derive(Clone, Debug, PartialEq)]
370pub enum SelectPhase {
371 Begin {
372 position: DisplayPoint,
373 add: bool,
374 click_count: usize,
375 },
376 BeginColumnar {
377 position: DisplayPoint,
378 reset: bool,
379 goal_column: u32,
380 },
381 Extend {
382 position: DisplayPoint,
383 click_count: usize,
384 },
385 Update {
386 position: DisplayPoint,
387 goal_column: u32,
388 scroll_delta: gpui::Point<f32>,
389 },
390 End,
391}
392
393#[derive(Clone, Debug)]
394pub enum SelectMode {
395 Character,
396 Word(Range<Anchor>),
397 Line(Range<Anchor>),
398 All,
399}
400
401#[derive(Copy, Clone, PartialEq, Eq, Debug)]
402pub enum EditorMode {
403 SingleLine { auto_width: bool },
404 AutoHeight { max_lines: usize },
405 Full,
406}
407
408#[derive(Copy, Clone, Debug)]
409pub enum SoftWrap {
410 /// Prefer not to wrap at all.
411 ///
412 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
413 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
414 GitDiff,
415 /// Prefer a single line generally, unless an overly long line is encountered.
416 None,
417 /// Soft wrap lines that exceed the editor width.
418 EditorWidth,
419 /// Soft wrap lines at the preferred line length.
420 Column(u32),
421 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
422 Bounded(u32),
423}
424
425#[derive(Clone)]
426pub struct EditorStyle {
427 pub background: Hsla,
428 pub local_player: PlayerColor,
429 pub text: TextStyle,
430 pub scrollbar_width: Pixels,
431 pub syntax: Arc<SyntaxTheme>,
432 pub status: StatusColors,
433 pub inlay_hints_style: HighlightStyle,
434 pub inline_completion_styles: InlineCompletionStyles,
435 pub unnecessary_code_fade: f32,
436}
437
438impl Default for EditorStyle {
439 fn default() -> Self {
440 Self {
441 background: Hsla::default(),
442 local_player: PlayerColor::default(),
443 text: TextStyle::default(),
444 scrollbar_width: Pixels::default(),
445 syntax: Default::default(),
446 // HACK: Status colors don't have a real default.
447 // We should look into removing the status colors from the editor
448 // style and retrieve them directly from the theme.
449 status: StatusColors::dark(),
450 inlay_hints_style: HighlightStyle::default(),
451 inline_completion_styles: InlineCompletionStyles {
452 insertion: HighlightStyle::default(),
453 whitespace: HighlightStyle::default(),
454 },
455 unnecessary_code_fade: Default::default(),
456 }
457 }
458}
459
460pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
461 let show_background = language_settings::language_settings(None, None, cx)
462 .inlay_hints
463 .show_background;
464
465 HighlightStyle {
466 color: Some(cx.theme().status().hint),
467 background_color: show_background.then(|| cx.theme().status().hint_background),
468 ..HighlightStyle::default()
469 }
470}
471
472pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
473 InlineCompletionStyles {
474 insertion: HighlightStyle {
475 color: Some(cx.theme().status().predictive),
476 ..HighlightStyle::default()
477 },
478 whitespace: HighlightStyle {
479 background_color: Some(cx.theme().status().created_background),
480 ..HighlightStyle::default()
481 },
482 }
483}
484
485type CompletionId = usize;
486
487pub(crate) enum EditDisplayMode {
488 TabAccept,
489 DiffPopover,
490 Inline,
491}
492
493enum InlineCompletion {
494 Edit {
495 edits: Vec<(Range<Anchor>, String)>,
496 edit_preview: Option<EditPreview>,
497 display_mode: EditDisplayMode,
498 snapshot: BufferSnapshot,
499 },
500 Move {
501 target: Anchor,
502 snapshot: BufferSnapshot,
503 },
504}
505
506struct InlineCompletionState {
507 inlay_ids: Vec<InlayId>,
508 completion: InlineCompletion,
509 completion_id: Option<SharedString>,
510 invalidation_range: Range<Anchor>,
511}
512
513enum EditPredictionSettings {
514 Disabled,
515 Enabled {
516 show_in_menu: bool,
517 preview_requires_modifier: bool,
518 },
519}
520
521enum InlineCompletionHighlight {}
522
523pub enum MenuInlineCompletionsPolicy {
524 Never,
525 ByProvider,
526}
527
528pub enum EditPredictionPreview {
529 /// Modifier is not pressed
530 Inactive,
531 /// Modifier pressed
532 Active {
533 previous_scroll_position: Option<ScrollAnchor>,
534 },
535}
536
537#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
538struct EditorActionId(usize);
539
540impl EditorActionId {
541 pub fn post_inc(&mut self) -> Self {
542 let answer = self.0;
543
544 *self = Self(answer + 1);
545
546 Self(answer)
547 }
548}
549
550// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
551// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
552
553type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
554type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
555
556#[derive(Default)]
557struct ScrollbarMarkerState {
558 scrollbar_size: Size<Pixels>,
559 dirty: bool,
560 markers: Arc<[PaintQuad]>,
561 pending_refresh: Option<Task<Result<()>>>,
562}
563
564impl ScrollbarMarkerState {
565 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
566 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
567 }
568}
569
570#[derive(Clone, Debug)]
571struct RunnableTasks {
572 templates: Vec<(TaskSourceKind, TaskTemplate)>,
573 offset: MultiBufferOffset,
574 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
575 column: u32,
576 // Values of all named captures, including those starting with '_'
577 extra_variables: HashMap<String, String>,
578 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
579 context_range: Range<BufferOffset>,
580}
581
582impl RunnableTasks {
583 fn resolve<'a>(
584 &'a self,
585 cx: &'a task::TaskContext,
586 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
587 self.templates.iter().filter_map(|(kind, template)| {
588 template
589 .resolve_task(&kind.to_id_base(), cx)
590 .map(|task| (kind.clone(), task))
591 })
592 }
593}
594
595#[derive(Clone)]
596struct ResolvedTasks {
597 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
598 position: Anchor,
599}
600#[derive(Copy, Clone, Debug)]
601struct MultiBufferOffset(usize);
602#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
603struct BufferOffset(usize);
604
605// Addons allow storing per-editor state in other crates (e.g. Vim)
606pub trait Addon: 'static {
607 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
608
609 fn render_buffer_header_controls(
610 &self,
611 _: &ExcerptInfo,
612 _: &Window,
613 _: &App,
614 ) -> Option<AnyElement> {
615 None
616 }
617
618 fn to_any(&self) -> &dyn std::any::Any;
619}
620
621#[derive(Debug, Copy, Clone, PartialEq, Eq)]
622pub enum IsVimMode {
623 Yes,
624 No,
625}
626
627/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
628///
629/// See the [module level documentation](self) for more information.
630pub struct Editor {
631 focus_handle: FocusHandle,
632 last_focused_descendant: Option<WeakFocusHandle>,
633 /// The text buffer being edited
634 buffer: Entity<MultiBuffer>,
635 /// Map of how text in the buffer should be displayed.
636 /// Handles soft wraps, folds, fake inlay text insertions, etc.
637 pub display_map: Entity<DisplayMap>,
638 pub selections: SelectionsCollection,
639 pub scroll_manager: ScrollManager,
640 /// When inline assist editors are linked, they all render cursors because
641 /// typing enters text into each of them, even the ones that aren't focused.
642 pub(crate) show_cursor_when_unfocused: bool,
643 columnar_selection_tail: Option<Anchor>,
644 add_selections_state: Option<AddSelectionsState>,
645 select_next_state: Option<SelectNextState>,
646 select_prev_state: Option<SelectNextState>,
647 selection_history: SelectionHistory,
648 autoclose_regions: Vec<AutocloseRegion>,
649 snippet_stack: InvalidationStack<SnippetState>,
650 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
651 ime_transaction: Option<TransactionId>,
652 active_diagnostics: Option<ActiveDiagnosticGroup>,
653 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
654
655 // TODO: make this a access method
656 pub project: Option<Entity<Project>>,
657 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
658 completion_provider: Option<Box<dyn CompletionProvider>>,
659 collaboration_hub: Option<Box<dyn CollaborationHub>>,
660 blink_manager: Entity<BlinkManager>,
661 show_cursor_names: bool,
662 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
663 pub show_local_selections: bool,
664 mode: EditorMode,
665 show_breadcrumbs: bool,
666 show_gutter: bool,
667 show_scrollbars: bool,
668 show_line_numbers: Option<bool>,
669 use_relative_line_numbers: Option<bool>,
670 show_git_diff_gutter: Option<bool>,
671 show_code_actions: Option<bool>,
672 show_runnables: Option<bool>,
673 show_wrap_guides: Option<bool>,
674 show_indent_guides: Option<bool>,
675 placeholder_text: Option<Arc<str>>,
676 highlight_order: usize,
677 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
678 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
679 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
680 scrollbar_marker_state: ScrollbarMarkerState,
681 active_indent_guides_state: ActiveIndentGuidesState,
682 nav_history: Option<ItemNavHistory>,
683 context_menu: RefCell<Option<CodeContextMenu>>,
684 mouse_context_menu: Option<MouseContextMenu>,
685 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
686 signature_help_state: SignatureHelpState,
687 auto_signature_help: Option<bool>,
688 find_all_references_task_sources: Vec<Anchor>,
689 next_completion_id: CompletionId,
690 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
691 code_actions_task: Option<Task<Result<()>>>,
692 selection_highlight_task: Option<Task<()>>,
693 document_highlights_task: Option<Task<()>>,
694 linked_editing_range_task: Option<Task<Option<()>>>,
695 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
696 pending_rename: Option<RenameState>,
697 searchable: bool,
698 cursor_shape: CursorShape,
699 current_line_highlight: Option<CurrentLineHighlight>,
700 collapse_matches: bool,
701 autoindent_mode: Option<AutoindentMode>,
702 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
703 input_enabled: bool,
704 use_modal_editing: bool,
705 read_only: bool,
706 leader_peer_id: Option<PeerId>,
707 remote_id: Option<ViewId>,
708 hover_state: HoverState,
709 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
710 gutter_hovered: bool,
711 hovered_link_state: Option<HoveredLinkState>,
712 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
713 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
714 active_inline_completion: Option<InlineCompletionState>,
715 /// Used to prevent flickering as the user types while the menu is open
716 stale_inline_completion_in_menu: Option<InlineCompletionState>,
717 edit_prediction_settings: EditPredictionSettings,
718 inline_completions_hidden_for_vim_mode: bool,
719 show_inline_completions_override: Option<bool>,
720 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
721 edit_prediction_preview: EditPredictionPreview,
722 edit_prediction_cursor_on_leading_whitespace: bool,
723 edit_prediction_requires_modifier_in_leading_space: bool,
724 inlay_hint_cache: InlayHintCache,
725 next_inlay_id: usize,
726 _subscriptions: Vec<Subscription>,
727 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
728 gutter_dimensions: GutterDimensions,
729 style: Option<EditorStyle>,
730 text_style_refinement: Option<TextStyleRefinement>,
731 next_editor_action_id: EditorActionId,
732 editor_actions:
733 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
734 use_autoclose: bool,
735 use_auto_surround: bool,
736 auto_replace_emoji_shortcode: bool,
737 show_git_blame_gutter: bool,
738 show_git_blame_inline: bool,
739 show_git_blame_inline_delay_task: Option<Task<()>>,
740 distinguish_unstaged_diff_hunks: bool,
741 git_blame_inline_enabled: bool,
742 serialize_dirty_buffers: bool,
743 show_selection_menu: Option<bool>,
744 blame: Option<Entity<GitBlame>>,
745 blame_subscription: Option<Subscription>,
746 custom_context_menu: Option<
747 Box<
748 dyn 'static
749 + Fn(
750 &mut Self,
751 DisplayPoint,
752 &mut Window,
753 &mut Context<Self>,
754 ) -> Option<Entity<ui::ContextMenu>>,
755 >,
756 >,
757 last_bounds: Option<Bounds<Pixels>>,
758 last_position_map: Option<Rc<PositionMap>>,
759 expect_bounds_change: Option<Bounds<Pixels>>,
760 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
761 tasks_update_task: Option<Task<()>>,
762 in_project_search: bool,
763 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
764 breadcrumb_header: Option<String>,
765 focused_block: Option<FocusedBlock>,
766 next_scroll_position: NextScrollCursorCenterTopBottom,
767 addons: HashMap<TypeId, Box<dyn Addon>>,
768 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
769 load_diff_task: Option<Shared<Task<()>>>,
770 selection_mark_mode: bool,
771 toggle_fold_multiple_buffers: Task<()>,
772 _scroll_cursor_center_top_bottom_task: Task<()>,
773 serialize_selections: Task<()>,
774}
775
776#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
777enum NextScrollCursorCenterTopBottom {
778 #[default]
779 Center,
780 Top,
781 Bottom,
782}
783
784impl NextScrollCursorCenterTopBottom {
785 fn next(&self) -> Self {
786 match self {
787 Self::Center => Self::Top,
788 Self::Top => Self::Bottom,
789 Self::Bottom => Self::Center,
790 }
791 }
792}
793
794#[derive(Clone)]
795pub struct EditorSnapshot {
796 pub mode: EditorMode,
797 show_gutter: bool,
798 show_line_numbers: Option<bool>,
799 show_git_diff_gutter: Option<bool>,
800 show_code_actions: Option<bool>,
801 show_runnables: Option<bool>,
802 git_blame_gutter_max_author_length: Option<usize>,
803 pub display_snapshot: DisplaySnapshot,
804 pub placeholder_text: Option<Arc<str>>,
805 is_focused: bool,
806 scroll_anchor: ScrollAnchor,
807 ongoing_scroll: OngoingScroll,
808 current_line_highlight: CurrentLineHighlight,
809 gutter_hovered: bool,
810}
811
812const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
813
814#[derive(Default, Debug, Clone, Copy)]
815pub struct GutterDimensions {
816 pub left_padding: Pixels,
817 pub right_padding: Pixels,
818 pub width: Pixels,
819 pub margin: Pixels,
820 pub git_blame_entries_width: Option<Pixels>,
821}
822
823impl GutterDimensions {
824 /// The full width of the space taken up by the gutter.
825 pub fn full_width(&self) -> Pixels {
826 self.margin + self.width
827 }
828
829 /// The width of the space reserved for the fold indicators,
830 /// use alongside 'justify_end' and `gutter_width` to
831 /// right align content with the line numbers
832 pub fn fold_area_width(&self) -> Pixels {
833 self.margin + self.right_padding
834 }
835}
836
837#[derive(Debug)]
838pub struct RemoteSelection {
839 pub replica_id: ReplicaId,
840 pub selection: Selection<Anchor>,
841 pub cursor_shape: CursorShape,
842 pub peer_id: PeerId,
843 pub line_mode: bool,
844 pub participant_index: Option<ParticipantIndex>,
845 pub user_name: Option<SharedString>,
846}
847
848#[derive(Clone, Debug)]
849struct SelectionHistoryEntry {
850 selections: Arc<[Selection<Anchor>]>,
851 select_next_state: Option<SelectNextState>,
852 select_prev_state: Option<SelectNextState>,
853 add_selections_state: Option<AddSelectionsState>,
854}
855
856enum SelectionHistoryMode {
857 Normal,
858 Undoing,
859 Redoing,
860}
861
862#[derive(Clone, PartialEq, Eq, Hash)]
863struct HoveredCursor {
864 replica_id: u16,
865 selection_id: usize,
866}
867
868impl Default for SelectionHistoryMode {
869 fn default() -> Self {
870 Self::Normal
871 }
872}
873
874#[derive(Default)]
875struct SelectionHistory {
876 #[allow(clippy::type_complexity)]
877 selections_by_transaction:
878 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
879 mode: SelectionHistoryMode,
880 undo_stack: VecDeque<SelectionHistoryEntry>,
881 redo_stack: VecDeque<SelectionHistoryEntry>,
882}
883
884impl SelectionHistory {
885 fn insert_transaction(
886 &mut self,
887 transaction_id: TransactionId,
888 selections: Arc<[Selection<Anchor>]>,
889 ) {
890 self.selections_by_transaction
891 .insert(transaction_id, (selections, None));
892 }
893
894 #[allow(clippy::type_complexity)]
895 fn transaction(
896 &self,
897 transaction_id: TransactionId,
898 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
899 self.selections_by_transaction.get(&transaction_id)
900 }
901
902 #[allow(clippy::type_complexity)]
903 fn transaction_mut(
904 &mut self,
905 transaction_id: TransactionId,
906 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
907 self.selections_by_transaction.get_mut(&transaction_id)
908 }
909
910 fn push(&mut self, entry: SelectionHistoryEntry) {
911 if !entry.selections.is_empty() {
912 match self.mode {
913 SelectionHistoryMode::Normal => {
914 self.push_undo(entry);
915 self.redo_stack.clear();
916 }
917 SelectionHistoryMode::Undoing => self.push_redo(entry),
918 SelectionHistoryMode::Redoing => self.push_undo(entry),
919 }
920 }
921 }
922
923 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
924 if self
925 .undo_stack
926 .back()
927 .map_or(true, |e| e.selections != entry.selections)
928 {
929 self.undo_stack.push_back(entry);
930 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
931 self.undo_stack.pop_front();
932 }
933 }
934 }
935
936 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
937 if self
938 .redo_stack
939 .back()
940 .map_or(true, |e| e.selections != entry.selections)
941 {
942 self.redo_stack.push_back(entry);
943 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
944 self.redo_stack.pop_front();
945 }
946 }
947 }
948}
949
950struct RowHighlight {
951 index: usize,
952 range: Range<Anchor>,
953 color: Hsla,
954 should_autoscroll: bool,
955}
956
957#[derive(Clone, Debug)]
958struct AddSelectionsState {
959 above: bool,
960 stack: Vec<usize>,
961}
962
963#[derive(Clone)]
964struct SelectNextState {
965 query: AhoCorasick,
966 wordwise: bool,
967 done: bool,
968}
969
970impl std::fmt::Debug for SelectNextState {
971 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
972 f.debug_struct(std::any::type_name::<Self>())
973 .field("wordwise", &self.wordwise)
974 .field("done", &self.done)
975 .finish()
976 }
977}
978
979#[derive(Debug)]
980struct AutocloseRegion {
981 selection_id: usize,
982 range: Range<Anchor>,
983 pair: BracketPair,
984}
985
986#[derive(Debug)]
987struct SnippetState {
988 ranges: Vec<Vec<Range<Anchor>>>,
989 active_index: usize,
990 choices: Vec<Option<Vec<String>>>,
991}
992
993#[doc(hidden)]
994pub struct RenameState {
995 pub range: Range<Anchor>,
996 pub old_name: Arc<str>,
997 pub editor: Entity<Editor>,
998 block_id: CustomBlockId,
999}
1000
1001struct InvalidationStack<T>(Vec<T>);
1002
1003struct RegisteredInlineCompletionProvider {
1004 provider: Arc<dyn InlineCompletionProviderHandle>,
1005 _subscription: Subscription,
1006}
1007
1008#[derive(Debug)]
1009struct ActiveDiagnosticGroup {
1010 primary_range: Range<Anchor>,
1011 primary_message: String,
1012 group_id: usize,
1013 blocks: HashMap<CustomBlockId, Diagnostic>,
1014 is_valid: bool,
1015}
1016
1017#[derive(Serialize, Deserialize, Clone, Debug)]
1018pub struct ClipboardSelection {
1019 pub len: usize,
1020 pub is_entire_line: bool,
1021 pub first_line_indent: u32,
1022}
1023
1024#[derive(Debug)]
1025pub(crate) struct NavigationData {
1026 cursor_anchor: Anchor,
1027 cursor_position: Point,
1028 scroll_anchor: ScrollAnchor,
1029 scroll_top_row: u32,
1030}
1031
1032#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1033pub enum GotoDefinitionKind {
1034 Symbol,
1035 Declaration,
1036 Type,
1037 Implementation,
1038}
1039
1040#[derive(Debug, Clone)]
1041enum InlayHintRefreshReason {
1042 Toggle(bool),
1043 SettingsChange(InlayHintSettings),
1044 NewLinesShown,
1045 BufferEdited(HashSet<Arc<Language>>),
1046 RefreshRequested,
1047 ExcerptsRemoved(Vec<ExcerptId>),
1048}
1049
1050impl InlayHintRefreshReason {
1051 fn description(&self) -> &'static str {
1052 match self {
1053 Self::Toggle(_) => "toggle",
1054 Self::SettingsChange(_) => "settings change",
1055 Self::NewLinesShown => "new lines shown",
1056 Self::BufferEdited(_) => "buffer edited",
1057 Self::RefreshRequested => "refresh requested",
1058 Self::ExcerptsRemoved(_) => "excerpts removed",
1059 }
1060 }
1061}
1062
1063pub enum FormatTarget {
1064 Buffers,
1065 Ranges(Vec<Range<MultiBufferPoint>>),
1066}
1067
1068pub(crate) struct FocusedBlock {
1069 id: BlockId,
1070 focus_handle: WeakFocusHandle,
1071}
1072
1073#[derive(Clone)]
1074enum JumpData {
1075 MultiBufferRow {
1076 row: MultiBufferRow,
1077 line_offset_from_top: u32,
1078 },
1079 MultiBufferPoint {
1080 excerpt_id: ExcerptId,
1081 position: Point,
1082 anchor: text::Anchor,
1083 line_offset_from_top: u32,
1084 },
1085}
1086
1087pub enum MultibufferSelectionMode {
1088 First,
1089 All,
1090}
1091
1092impl Editor {
1093 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1094 let buffer = cx.new(|cx| Buffer::local("", cx));
1095 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1096 Self::new(
1097 EditorMode::SingleLine { auto_width: false },
1098 buffer,
1099 None,
1100 false,
1101 window,
1102 cx,
1103 )
1104 }
1105
1106 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1107 let buffer = cx.new(|cx| Buffer::local("", cx));
1108 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1109 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1110 }
1111
1112 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1113 let buffer = cx.new(|cx| Buffer::local("", cx));
1114 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1115 Self::new(
1116 EditorMode::SingleLine { auto_width: true },
1117 buffer,
1118 None,
1119 false,
1120 window,
1121 cx,
1122 )
1123 }
1124
1125 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1126 let buffer = cx.new(|cx| Buffer::local("", cx));
1127 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1128 Self::new(
1129 EditorMode::AutoHeight { max_lines },
1130 buffer,
1131 None,
1132 false,
1133 window,
1134 cx,
1135 )
1136 }
1137
1138 pub fn for_buffer(
1139 buffer: Entity<Buffer>,
1140 project: Option<Entity<Project>>,
1141 window: &mut Window,
1142 cx: &mut Context<Self>,
1143 ) -> Self {
1144 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1145 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1146 }
1147
1148 pub fn for_multibuffer(
1149 buffer: Entity<MultiBuffer>,
1150 project: Option<Entity<Project>>,
1151 show_excerpt_controls: bool,
1152 window: &mut Window,
1153 cx: &mut Context<Self>,
1154 ) -> Self {
1155 Self::new(
1156 EditorMode::Full,
1157 buffer,
1158 project,
1159 show_excerpt_controls,
1160 window,
1161 cx,
1162 )
1163 }
1164
1165 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1166 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1167 let mut clone = Self::new(
1168 self.mode,
1169 self.buffer.clone(),
1170 self.project.clone(),
1171 show_excerpt_controls,
1172 window,
1173 cx,
1174 );
1175 self.display_map.update(cx, |display_map, cx| {
1176 let snapshot = display_map.snapshot(cx);
1177 clone.display_map.update(cx, |display_map, cx| {
1178 display_map.set_state(&snapshot, cx);
1179 });
1180 });
1181 clone.selections.clone_state(&self.selections);
1182 clone.scroll_manager.clone_state(&self.scroll_manager);
1183 clone.searchable = self.searchable;
1184 clone
1185 }
1186
1187 pub fn new(
1188 mode: EditorMode,
1189 buffer: Entity<MultiBuffer>,
1190 project: Option<Entity<Project>>,
1191 show_excerpt_controls: bool,
1192 window: &mut Window,
1193 cx: &mut Context<Self>,
1194 ) -> Self {
1195 let style = window.text_style();
1196 let font_size = style.font_size.to_pixels(window.rem_size());
1197 let editor = cx.entity().downgrade();
1198 let fold_placeholder = FoldPlaceholder {
1199 constrain_width: true,
1200 render: Arc::new(move |fold_id, fold_range, _, cx| {
1201 let editor = editor.clone();
1202 div()
1203 .id(fold_id)
1204 .bg(cx.theme().colors().ghost_element_background)
1205 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1206 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1207 .rounded_sm()
1208 .size_full()
1209 .cursor_pointer()
1210 .child("⋯")
1211 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1212 .on_click(move |_, _window, cx| {
1213 editor
1214 .update(cx, |editor, cx| {
1215 editor.unfold_ranges(
1216 &[fold_range.start..fold_range.end],
1217 true,
1218 false,
1219 cx,
1220 );
1221 cx.stop_propagation();
1222 })
1223 .ok();
1224 })
1225 .into_any()
1226 }),
1227 merge_adjacent: true,
1228 ..Default::default()
1229 };
1230 let display_map = cx.new(|cx| {
1231 DisplayMap::new(
1232 buffer.clone(),
1233 style.font(),
1234 font_size,
1235 None,
1236 show_excerpt_controls,
1237 FILE_HEADER_HEIGHT,
1238 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1239 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1240 fold_placeholder,
1241 cx,
1242 )
1243 });
1244
1245 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1246
1247 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1248
1249 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1250 .then(|| language_settings::SoftWrap::None);
1251
1252 let mut project_subscriptions = Vec::new();
1253 if mode == EditorMode::Full {
1254 if let Some(project) = project.as_ref() {
1255 if buffer.read(cx).is_singleton() {
1256 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1257 cx.emit(EditorEvent::TitleChanged);
1258 }));
1259 }
1260 project_subscriptions.push(cx.subscribe_in(
1261 project,
1262 window,
1263 |editor, _, event, window, cx| {
1264 if let project::Event::RefreshInlayHints = event {
1265 editor
1266 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1267 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1268 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1269 let focus_handle = editor.focus_handle(cx);
1270 if focus_handle.is_focused(window) {
1271 let snapshot = buffer.read(cx).snapshot();
1272 for (range, snippet) in snippet_edits {
1273 let editor_range =
1274 language::range_from_lsp(*range).to_offset(&snapshot);
1275 editor
1276 .insert_snippet(
1277 &[editor_range],
1278 snippet.clone(),
1279 window,
1280 cx,
1281 )
1282 .ok();
1283 }
1284 }
1285 }
1286 }
1287 },
1288 ));
1289 if let Some(task_inventory) = project
1290 .read(cx)
1291 .task_store()
1292 .read(cx)
1293 .task_inventory()
1294 .cloned()
1295 {
1296 project_subscriptions.push(cx.observe_in(
1297 &task_inventory,
1298 window,
1299 |editor, _, window, cx| {
1300 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1301 },
1302 ));
1303 }
1304 }
1305 }
1306
1307 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1308
1309 let inlay_hint_settings =
1310 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1311 let focus_handle = cx.focus_handle();
1312 cx.on_focus(&focus_handle, window, Self::handle_focus)
1313 .detach();
1314 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1315 .detach();
1316 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1317 .detach();
1318 cx.on_blur(&focus_handle, window, Self::handle_blur)
1319 .detach();
1320
1321 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1322 Some(false)
1323 } else {
1324 None
1325 };
1326
1327 let mut code_action_providers = Vec::new();
1328 let mut load_uncommitted_diff = None;
1329 if let Some(project) = project.clone() {
1330 load_uncommitted_diff = Some(
1331 get_uncommitted_diff_for_buffer(
1332 &project,
1333 buffer.read(cx).all_buffers(),
1334 buffer.clone(),
1335 cx,
1336 )
1337 .shared(),
1338 );
1339 code_action_providers.push(Rc::new(project) as Rc<_>);
1340 }
1341
1342 let mut this = Self {
1343 focus_handle,
1344 show_cursor_when_unfocused: false,
1345 last_focused_descendant: None,
1346 buffer: buffer.clone(),
1347 display_map: display_map.clone(),
1348 selections,
1349 scroll_manager: ScrollManager::new(cx),
1350 columnar_selection_tail: None,
1351 add_selections_state: None,
1352 select_next_state: None,
1353 select_prev_state: None,
1354 selection_history: Default::default(),
1355 autoclose_regions: Default::default(),
1356 snippet_stack: Default::default(),
1357 select_larger_syntax_node_stack: Vec::new(),
1358 ime_transaction: Default::default(),
1359 active_diagnostics: None,
1360 soft_wrap_mode_override,
1361 completion_provider: project.clone().map(|project| Box::new(project) as _),
1362 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1363 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1364 project,
1365 blink_manager: blink_manager.clone(),
1366 show_local_selections: true,
1367 show_scrollbars: true,
1368 mode,
1369 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1370 show_gutter: mode == EditorMode::Full,
1371 show_line_numbers: None,
1372 use_relative_line_numbers: None,
1373 show_git_diff_gutter: None,
1374 show_code_actions: None,
1375 show_runnables: None,
1376 show_wrap_guides: None,
1377 show_indent_guides,
1378 placeholder_text: None,
1379 highlight_order: 0,
1380 highlighted_rows: HashMap::default(),
1381 background_highlights: Default::default(),
1382 gutter_highlights: TreeMap::default(),
1383 scrollbar_marker_state: ScrollbarMarkerState::default(),
1384 active_indent_guides_state: ActiveIndentGuidesState::default(),
1385 nav_history: None,
1386 context_menu: RefCell::new(None),
1387 mouse_context_menu: None,
1388 completion_tasks: Default::default(),
1389 signature_help_state: SignatureHelpState::default(),
1390 auto_signature_help: None,
1391 find_all_references_task_sources: Vec::new(),
1392 next_completion_id: 0,
1393 next_inlay_id: 0,
1394 code_action_providers,
1395 available_code_actions: Default::default(),
1396 code_actions_task: Default::default(),
1397 selection_highlight_task: Default::default(),
1398 document_highlights_task: Default::default(),
1399 linked_editing_range_task: Default::default(),
1400 pending_rename: Default::default(),
1401 searchable: true,
1402 cursor_shape: EditorSettings::get_global(cx)
1403 .cursor_shape
1404 .unwrap_or_default(),
1405 current_line_highlight: None,
1406 autoindent_mode: Some(AutoindentMode::EachLine),
1407 collapse_matches: false,
1408 workspace: None,
1409 input_enabled: true,
1410 use_modal_editing: mode == EditorMode::Full,
1411 read_only: false,
1412 use_autoclose: true,
1413 use_auto_surround: true,
1414 auto_replace_emoji_shortcode: false,
1415 leader_peer_id: None,
1416 remote_id: None,
1417 hover_state: Default::default(),
1418 pending_mouse_down: None,
1419 hovered_link_state: Default::default(),
1420 edit_prediction_provider: None,
1421 active_inline_completion: None,
1422 stale_inline_completion_in_menu: None,
1423 edit_prediction_preview: EditPredictionPreview::Inactive,
1424 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1425
1426 gutter_hovered: false,
1427 pixel_position_of_newest_cursor: None,
1428 last_bounds: None,
1429 last_position_map: None,
1430 expect_bounds_change: None,
1431 gutter_dimensions: GutterDimensions::default(),
1432 style: None,
1433 show_cursor_names: false,
1434 hovered_cursors: Default::default(),
1435 next_editor_action_id: EditorActionId::default(),
1436 editor_actions: Rc::default(),
1437 inline_completions_hidden_for_vim_mode: false,
1438 show_inline_completions_override: None,
1439 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1440 edit_prediction_settings: EditPredictionSettings::Disabled,
1441 edit_prediction_cursor_on_leading_whitespace: false,
1442 edit_prediction_requires_modifier_in_leading_space: true,
1443 custom_context_menu: None,
1444 show_git_blame_gutter: false,
1445 show_git_blame_inline: false,
1446 distinguish_unstaged_diff_hunks: false,
1447 show_selection_menu: None,
1448 show_git_blame_inline_delay_task: None,
1449 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1450 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1451 .session
1452 .restore_unsaved_buffers,
1453 blame: None,
1454 blame_subscription: None,
1455 tasks: Default::default(),
1456 _subscriptions: vec![
1457 cx.observe(&buffer, Self::on_buffer_changed),
1458 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1459 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1460 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1461 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1462 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1463 cx.observe_window_activation(window, |editor, window, cx| {
1464 let active = window.is_window_active();
1465 editor.blink_manager.update(cx, |blink_manager, cx| {
1466 if active {
1467 blink_manager.enable(cx);
1468 } else {
1469 blink_manager.disable(cx);
1470 }
1471 });
1472 }),
1473 ],
1474 tasks_update_task: None,
1475 linked_edit_ranges: Default::default(),
1476 in_project_search: false,
1477 previous_search_ranges: None,
1478 breadcrumb_header: None,
1479 focused_block: None,
1480 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1481 addons: HashMap::default(),
1482 registered_buffers: HashMap::default(),
1483 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1484 selection_mark_mode: false,
1485 toggle_fold_multiple_buffers: Task::ready(()),
1486 serialize_selections: Task::ready(()),
1487 text_style_refinement: None,
1488 load_diff_task: load_uncommitted_diff,
1489 };
1490 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1491 this._subscriptions.extend(project_subscriptions);
1492
1493 this.end_selection(window, cx);
1494 this.scroll_manager.show_scrollbar(window, cx);
1495
1496 if mode == EditorMode::Full {
1497 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1498 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1499
1500 if this.git_blame_inline_enabled {
1501 this.git_blame_inline_enabled = true;
1502 this.start_git_blame_inline(false, window, cx);
1503 }
1504
1505 if let Some(buffer) = buffer.read(cx).as_singleton() {
1506 if let Some(project) = this.project.as_ref() {
1507 let handle = project.update(cx, |project, cx| {
1508 project.register_buffer_with_language_servers(&buffer, cx)
1509 });
1510 this.registered_buffers
1511 .insert(buffer.read(cx).remote_id(), handle);
1512 }
1513 }
1514 }
1515
1516 this.report_editor_event("Editor Opened", None, cx);
1517 this
1518 }
1519
1520 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1521 self.mouse_context_menu
1522 .as_ref()
1523 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1524 }
1525
1526 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1527 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1528 }
1529
1530 fn key_context_internal(
1531 &self,
1532 has_active_edit_prediction: bool,
1533 window: &Window,
1534 cx: &App,
1535 ) -> KeyContext {
1536 let mut key_context = KeyContext::new_with_defaults();
1537 key_context.add("Editor");
1538 let mode = match self.mode {
1539 EditorMode::SingleLine { .. } => "single_line",
1540 EditorMode::AutoHeight { .. } => "auto_height",
1541 EditorMode::Full => "full",
1542 };
1543
1544 if EditorSettings::jupyter_enabled(cx) {
1545 key_context.add("jupyter");
1546 }
1547
1548 key_context.set("mode", mode);
1549 if self.pending_rename.is_some() {
1550 key_context.add("renaming");
1551 }
1552
1553 match self.context_menu.borrow().as_ref() {
1554 Some(CodeContextMenu::Completions(_)) => {
1555 key_context.add("menu");
1556 key_context.add("showing_completions");
1557 }
1558 Some(CodeContextMenu::CodeActions(_)) => {
1559 key_context.add("menu");
1560 key_context.add("showing_code_actions")
1561 }
1562 None => {}
1563 }
1564
1565 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1566 if !self.focus_handle(cx).contains_focused(window, cx)
1567 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1568 {
1569 for addon in self.addons.values() {
1570 addon.extend_key_context(&mut key_context, cx)
1571 }
1572 }
1573
1574 if let Some(extension) = self
1575 .buffer
1576 .read(cx)
1577 .as_singleton()
1578 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1579 {
1580 key_context.set("extension", extension.to_string());
1581 }
1582
1583 if has_active_edit_prediction {
1584 if self.edit_prediction_in_conflict() {
1585 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1586 } else {
1587 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1588 key_context.add("copilot_suggestion");
1589 }
1590 }
1591
1592 if self.selection_mark_mode {
1593 key_context.add("selection_mode");
1594 }
1595
1596 key_context
1597 }
1598
1599 pub fn edit_prediction_in_conflict(&self) -> bool {
1600 if !self.show_edit_predictions_in_menu() {
1601 return false;
1602 }
1603
1604 let showing_completions = self
1605 .context_menu
1606 .borrow()
1607 .as_ref()
1608 .map_or(false, |context| {
1609 matches!(context, CodeContextMenu::Completions(_))
1610 });
1611
1612 showing_completions
1613 || self.edit_prediction_requires_modifier()
1614 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1615 // bindings to insert tab characters.
1616 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1617 }
1618
1619 pub fn accept_edit_prediction_keybind(
1620 &self,
1621 window: &Window,
1622 cx: &App,
1623 ) -> AcceptEditPredictionBinding {
1624 let key_context = self.key_context_internal(true, window, cx);
1625 let in_conflict = self.edit_prediction_in_conflict();
1626
1627 AcceptEditPredictionBinding(
1628 window
1629 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1630 .into_iter()
1631 .filter(|binding| {
1632 !in_conflict
1633 || binding
1634 .keystrokes()
1635 .first()
1636 .map_or(false, |keystroke| keystroke.modifiers.modified())
1637 })
1638 .rev()
1639 .min_by_key(|binding| {
1640 binding
1641 .keystrokes()
1642 .first()
1643 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1644 }),
1645 )
1646 }
1647
1648 pub fn new_file(
1649 workspace: &mut Workspace,
1650 _: &workspace::NewFile,
1651 window: &mut Window,
1652 cx: &mut Context<Workspace>,
1653 ) {
1654 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1655 "Failed to create buffer",
1656 window,
1657 cx,
1658 |e, _, _| match e.error_code() {
1659 ErrorCode::RemoteUpgradeRequired => Some(format!(
1660 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1661 e.error_tag("required").unwrap_or("the latest version")
1662 )),
1663 _ => None,
1664 },
1665 );
1666 }
1667
1668 pub fn new_in_workspace(
1669 workspace: &mut Workspace,
1670 window: &mut Window,
1671 cx: &mut Context<Workspace>,
1672 ) -> Task<Result<Entity<Editor>>> {
1673 let project = workspace.project().clone();
1674 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1675
1676 cx.spawn_in(window, |workspace, mut cx| async move {
1677 let buffer = create.await?;
1678 workspace.update_in(&mut cx, |workspace, window, cx| {
1679 let editor =
1680 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1681 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1682 editor
1683 })
1684 })
1685 }
1686
1687 fn new_file_vertical(
1688 workspace: &mut Workspace,
1689 _: &workspace::NewFileSplitVertical,
1690 window: &mut Window,
1691 cx: &mut Context<Workspace>,
1692 ) {
1693 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1694 }
1695
1696 fn new_file_horizontal(
1697 workspace: &mut Workspace,
1698 _: &workspace::NewFileSplitHorizontal,
1699 window: &mut Window,
1700 cx: &mut Context<Workspace>,
1701 ) {
1702 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1703 }
1704
1705 fn new_file_in_direction(
1706 workspace: &mut Workspace,
1707 direction: SplitDirection,
1708 window: &mut Window,
1709 cx: &mut Context<Workspace>,
1710 ) {
1711 let project = workspace.project().clone();
1712 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1713
1714 cx.spawn_in(window, |workspace, mut cx| async move {
1715 let buffer = create.await?;
1716 workspace.update_in(&mut cx, move |workspace, window, cx| {
1717 workspace.split_item(
1718 direction,
1719 Box::new(
1720 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1721 ),
1722 window,
1723 cx,
1724 )
1725 })?;
1726 anyhow::Ok(())
1727 })
1728 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1729 match e.error_code() {
1730 ErrorCode::RemoteUpgradeRequired => Some(format!(
1731 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1732 e.error_tag("required").unwrap_or("the latest version")
1733 )),
1734 _ => None,
1735 }
1736 });
1737 }
1738
1739 pub fn leader_peer_id(&self) -> Option<PeerId> {
1740 self.leader_peer_id
1741 }
1742
1743 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1744 &self.buffer
1745 }
1746
1747 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1748 self.workspace.as_ref()?.0.upgrade()
1749 }
1750
1751 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1752 self.buffer().read(cx).title(cx)
1753 }
1754
1755 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1756 let git_blame_gutter_max_author_length = self
1757 .render_git_blame_gutter(cx)
1758 .then(|| {
1759 if let Some(blame) = self.blame.as_ref() {
1760 let max_author_length =
1761 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1762 Some(max_author_length)
1763 } else {
1764 None
1765 }
1766 })
1767 .flatten();
1768
1769 EditorSnapshot {
1770 mode: self.mode,
1771 show_gutter: self.show_gutter,
1772 show_line_numbers: self.show_line_numbers,
1773 show_git_diff_gutter: self.show_git_diff_gutter,
1774 show_code_actions: self.show_code_actions,
1775 show_runnables: self.show_runnables,
1776 git_blame_gutter_max_author_length,
1777 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1778 scroll_anchor: self.scroll_manager.anchor(),
1779 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1780 placeholder_text: self.placeholder_text.clone(),
1781 is_focused: self.focus_handle.is_focused(window),
1782 current_line_highlight: self
1783 .current_line_highlight
1784 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1785 gutter_hovered: self.gutter_hovered,
1786 }
1787 }
1788
1789 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1790 self.buffer.read(cx).language_at(point, cx)
1791 }
1792
1793 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1794 self.buffer.read(cx).read(cx).file_at(point).cloned()
1795 }
1796
1797 pub fn active_excerpt(
1798 &self,
1799 cx: &App,
1800 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1801 self.buffer
1802 .read(cx)
1803 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1804 }
1805
1806 pub fn mode(&self) -> EditorMode {
1807 self.mode
1808 }
1809
1810 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1811 self.collaboration_hub.as_deref()
1812 }
1813
1814 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1815 self.collaboration_hub = Some(hub);
1816 }
1817
1818 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1819 self.in_project_search = in_project_search;
1820 }
1821
1822 pub fn set_custom_context_menu(
1823 &mut self,
1824 f: impl 'static
1825 + Fn(
1826 &mut Self,
1827 DisplayPoint,
1828 &mut Window,
1829 &mut Context<Self>,
1830 ) -> Option<Entity<ui::ContextMenu>>,
1831 ) {
1832 self.custom_context_menu = Some(Box::new(f))
1833 }
1834
1835 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1836 self.completion_provider = provider;
1837 }
1838
1839 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1840 self.semantics_provider.clone()
1841 }
1842
1843 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1844 self.semantics_provider = provider;
1845 }
1846
1847 pub fn set_edit_prediction_provider<T>(
1848 &mut self,
1849 provider: Option<Entity<T>>,
1850 window: &mut Window,
1851 cx: &mut Context<Self>,
1852 ) where
1853 T: EditPredictionProvider,
1854 {
1855 self.edit_prediction_provider =
1856 provider.map(|provider| RegisteredInlineCompletionProvider {
1857 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1858 if this.focus_handle.is_focused(window) {
1859 this.update_visible_inline_completion(window, cx);
1860 }
1861 }),
1862 provider: Arc::new(provider),
1863 });
1864 self.refresh_inline_completion(false, false, window, cx);
1865 }
1866
1867 pub fn placeholder_text(&self) -> Option<&str> {
1868 self.placeholder_text.as_deref()
1869 }
1870
1871 pub fn set_placeholder_text(
1872 &mut self,
1873 placeholder_text: impl Into<Arc<str>>,
1874 cx: &mut Context<Self>,
1875 ) {
1876 let placeholder_text = Some(placeholder_text.into());
1877 if self.placeholder_text != placeholder_text {
1878 self.placeholder_text = placeholder_text;
1879 cx.notify();
1880 }
1881 }
1882
1883 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1884 self.cursor_shape = cursor_shape;
1885
1886 // Disrupt blink for immediate user feedback that the cursor shape has changed
1887 self.blink_manager.update(cx, BlinkManager::show_cursor);
1888
1889 cx.notify();
1890 }
1891
1892 pub fn set_current_line_highlight(
1893 &mut self,
1894 current_line_highlight: Option<CurrentLineHighlight>,
1895 ) {
1896 self.current_line_highlight = current_line_highlight;
1897 }
1898
1899 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1900 self.collapse_matches = collapse_matches;
1901 }
1902
1903 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1904 let buffers = self.buffer.read(cx).all_buffers();
1905 let Some(project) = self.project.as_ref() else {
1906 return;
1907 };
1908 project.update(cx, |project, cx| {
1909 for buffer in buffers {
1910 self.registered_buffers
1911 .entry(buffer.read(cx).remote_id())
1912 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1913 }
1914 })
1915 }
1916
1917 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1918 if self.collapse_matches {
1919 return range.start..range.start;
1920 }
1921 range.clone()
1922 }
1923
1924 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1925 if self.display_map.read(cx).clip_at_line_ends != clip {
1926 self.display_map
1927 .update(cx, |map, _| map.clip_at_line_ends = clip);
1928 }
1929 }
1930
1931 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1932 self.input_enabled = input_enabled;
1933 }
1934
1935 pub fn set_inline_completions_hidden_for_vim_mode(
1936 &mut self,
1937 hidden: bool,
1938 window: &mut Window,
1939 cx: &mut Context<Self>,
1940 ) {
1941 if hidden != self.inline_completions_hidden_for_vim_mode {
1942 self.inline_completions_hidden_for_vim_mode = hidden;
1943 if hidden {
1944 self.update_visible_inline_completion(window, cx);
1945 } else {
1946 self.refresh_inline_completion(true, false, window, cx);
1947 }
1948 }
1949 }
1950
1951 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1952 self.menu_inline_completions_policy = value;
1953 }
1954
1955 pub fn set_autoindent(&mut self, autoindent: bool) {
1956 if autoindent {
1957 self.autoindent_mode = Some(AutoindentMode::EachLine);
1958 } else {
1959 self.autoindent_mode = None;
1960 }
1961 }
1962
1963 pub fn read_only(&self, cx: &App) -> bool {
1964 self.read_only || self.buffer.read(cx).read_only()
1965 }
1966
1967 pub fn set_read_only(&mut self, read_only: bool) {
1968 self.read_only = read_only;
1969 }
1970
1971 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1972 self.use_autoclose = autoclose;
1973 }
1974
1975 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1976 self.use_auto_surround = auto_surround;
1977 }
1978
1979 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1980 self.auto_replace_emoji_shortcode = auto_replace;
1981 }
1982
1983 pub fn toggle_inline_completions(
1984 &mut self,
1985 _: &ToggleEditPrediction,
1986 window: &mut Window,
1987 cx: &mut Context<Self>,
1988 ) {
1989 if self.show_inline_completions_override.is_some() {
1990 self.set_show_edit_predictions(None, window, cx);
1991 } else {
1992 let show_edit_predictions = !self.edit_predictions_enabled();
1993 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1994 }
1995 }
1996
1997 pub fn set_show_edit_predictions(
1998 &mut self,
1999 show_edit_predictions: Option<bool>,
2000 window: &mut Window,
2001 cx: &mut Context<Self>,
2002 ) {
2003 self.show_inline_completions_override = show_edit_predictions;
2004 self.refresh_inline_completion(false, true, window, cx);
2005 }
2006
2007 fn inline_completions_disabled_in_scope(
2008 &self,
2009 buffer: &Entity<Buffer>,
2010 buffer_position: language::Anchor,
2011 cx: &App,
2012 ) -> bool {
2013 let snapshot = buffer.read(cx).snapshot();
2014 let settings = snapshot.settings_at(buffer_position, cx);
2015
2016 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2017 return false;
2018 };
2019
2020 scope.override_name().map_or(false, |scope_name| {
2021 settings
2022 .edit_predictions_disabled_in
2023 .iter()
2024 .any(|s| s == scope_name)
2025 })
2026 }
2027
2028 pub fn set_use_modal_editing(&mut self, to: bool) {
2029 self.use_modal_editing = to;
2030 }
2031
2032 pub fn use_modal_editing(&self) -> bool {
2033 self.use_modal_editing
2034 }
2035
2036 fn selections_did_change(
2037 &mut self,
2038 local: bool,
2039 old_cursor_position: &Anchor,
2040 show_completions: bool,
2041 window: &mut Window,
2042 cx: &mut Context<Self>,
2043 ) {
2044 window.invalidate_character_coordinates();
2045
2046 // Copy selections to primary selection buffer
2047 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2048 if local {
2049 let selections = self.selections.all::<usize>(cx);
2050 let buffer_handle = self.buffer.read(cx).read(cx);
2051
2052 let mut text = String::new();
2053 for (index, selection) in selections.iter().enumerate() {
2054 let text_for_selection = buffer_handle
2055 .text_for_range(selection.start..selection.end)
2056 .collect::<String>();
2057
2058 text.push_str(&text_for_selection);
2059 if index != selections.len() - 1 {
2060 text.push('\n');
2061 }
2062 }
2063
2064 if !text.is_empty() {
2065 cx.write_to_primary(ClipboardItem::new_string(text));
2066 }
2067 }
2068
2069 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2070 self.buffer.update(cx, |buffer, cx| {
2071 buffer.set_active_selections(
2072 &self.selections.disjoint_anchors(),
2073 self.selections.line_mode,
2074 self.cursor_shape,
2075 cx,
2076 )
2077 });
2078 }
2079 let display_map = self
2080 .display_map
2081 .update(cx, |display_map, cx| display_map.snapshot(cx));
2082 let buffer = &display_map.buffer_snapshot;
2083 self.add_selections_state = None;
2084 self.select_next_state = None;
2085 self.select_prev_state = None;
2086 self.select_larger_syntax_node_stack.clear();
2087 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2088 self.snippet_stack
2089 .invalidate(&self.selections.disjoint_anchors(), buffer);
2090 self.take_rename(false, window, cx);
2091
2092 let new_cursor_position = self.selections.newest_anchor().head();
2093
2094 self.push_to_nav_history(
2095 *old_cursor_position,
2096 Some(new_cursor_position.to_point(buffer)),
2097 cx,
2098 );
2099
2100 if local {
2101 let new_cursor_position = self.selections.newest_anchor().head();
2102 let mut context_menu = self.context_menu.borrow_mut();
2103 let completion_menu = match context_menu.as_ref() {
2104 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2105 _ => {
2106 *context_menu = None;
2107 None
2108 }
2109 };
2110 if let Some(buffer_id) = new_cursor_position.buffer_id {
2111 if !self.registered_buffers.contains_key(&buffer_id) {
2112 if let Some(project) = self.project.as_ref() {
2113 project.update(cx, |project, cx| {
2114 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2115 return;
2116 };
2117 self.registered_buffers.insert(
2118 buffer_id,
2119 project.register_buffer_with_language_servers(&buffer, cx),
2120 );
2121 })
2122 }
2123 }
2124 }
2125
2126 if let Some(completion_menu) = completion_menu {
2127 let cursor_position = new_cursor_position.to_offset(buffer);
2128 let (word_range, kind) =
2129 buffer.surrounding_word(completion_menu.initial_position, true);
2130 if kind == Some(CharKind::Word)
2131 && word_range.to_inclusive().contains(&cursor_position)
2132 {
2133 let mut completion_menu = completion_menu.clone();
2134 drop(context_menu);
2135
2136 let query = Self::completion_query(buffer, cursor_position);
2137 cx.spawn(move |this, mut cx| async move {
2138 completion_menu
2139 .filter(query.as_deref(), cx.background_executor().clone())
2140 .await;
2141
2142 this.update(&mut cx, |this, cx| {
2143 let mut context_menu = this.context_menu.borrow_mut();
2144 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2145 else {
2146 return;
2147 };
2148
2149 if menu.id > completion_menu.id {
2150 return;
2151 }
2152
2153 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2154 drop(context_menu);
2155 cx.notify();
2156 })
2157 })
2158 .detach();
2159
2160 if show_completions {
2161 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2162 }
2163 } else {
2164 drop(context_menu);
2165 self.hide_context_menu(window, cx);
2166 }
2167 } else {
2168 drop(context_menu);
2169 }
2170
2171 hide_hover(self, cx);
2172
2173 if old_cursor_position.to_display_point(&display_map).row()
2174 != new_cursor_position.to_display_point(&display_map).row()
2175 {
2176 self.available_code_actions.take();
2177 }
2178 self.refresh_code_actions(window, cx);
2179 self.refresh_document_highlights(cx);
2180 self.refresh_selected_text_highlights(window, cx);
2181 refresh_matching_bracket_highlights(self, window, cx);
2182 self.update_visible_inline_completion(window, cx);
2183 self.edit_prediction_requires_modifier_in_leading_space = true;
2184 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2185 if self.git_blame_inline_enabled {
2186 self.start_inline_blame_timer(window, cx);
2187 }
2188 }
2189
2190 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2191 cx.emit(EditorEvent::SelectionsChanged { local });
2192
2193 let selections = &self.selections.disjoint;
2194 if selections.len() == 1 {
2195 cx.emit(SearchEvent::ActiveMatchChanged)
2196 }
2197 if local
2198 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2199 {
2200 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2201 let background_executor = cx.background_executor().clone();
2202 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2203 let snapshot = self.buffer().read(cx).snapshot(cx);
2204 let selections = selections.clone();
2205 self.serialize_selections = cx.background_spawn(async move {
2206 background_executor.timer(Duration::from_millis(100)).await;
2207 let selections = selections
2208 .iter()
2209 .map(|selection| {
2210 (
2211 selection.start.to_offset(&snapshot),
2212 selection.end.to_offset(&snapshot),
2213 )
2214 })
2215 .collect();
2216 DB.save_editor_selections(editor_id, workspace_id, selections)
2217 .await
2218 .context("persisting editor selections")
2219 .log_err();
2220 });
2221 }
2222 }
2223
2224 cx.notify();
2225 }
2226
2227 pub fn change_selections<R>(
2228 &mut self,
2229 autoscroll: Option<Autoscroll>,
2230 window: &mut Window,
2231 cx: &mut Context<Self>,
2232 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2233 ) -> R {
2234 self.change_selections_inner(autoscroll, true, window, cx, change)
2235 }
2236
2237 fn change_selections_inner<R>(
2238 &mut self,
2239 autoscroll: Option<Autoscroll>,
2240 request_completions: bool,
2241 window: &mut Window,
2242 cx: &mut Context<Self>,
2243 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2244 ) -> R {
2245 let old_cursor_position = self.selections.newest_anchor().head();
2246 self.push_to_selection_history();
2247
2248 let (changed, result) = self.selections.change_with(cx, change);
2249
2250 if changed {
2251 if let Some(autoscroll) = autoscroll {
2252 self.request_autoscroll(autoscroll, cx);
2253 }
2254 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2255
2256 if self.should_open_signature_help_automatically(
2257 &old_cursor_position,
2258 self.signature_help_state.backspace_pressed(),
2259 cx,
2260 ) {
2261 self.show_signature_help(&ShowSignatureHelp, window, cx);
2262 }
2263 self.signature_help_state.set_backspace_pressed(false);
2264 }
2265
2266 result
2267 }
2268
2269 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2270 where
2271 I: IntoIterator<Item = (Range<S>, T)>,
2272 S: ToOffset,
2273 T: Into<Arc<str>>,
2274 {
2275 if self.read_only(cx) {
2276 return;
2277 }
2278
2279 self.buffer
2280 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2281 }
2282
2283 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2284 where
2285 I: IntoIterator<Item = (Range<S>, T)>,
2286 S: ToOffset,
2287 T: Into<Arc<str>>,
2288 {
2289 if self.read_only(cx) {
2290 return;
2291 }
2292
2293 self.buffer.update(cx, |buffer, cx| {
2294 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2295 });
2296 }
2297
2298 pub fn edit_with_block_indent<I, S, T>(
2299 &mut self,
2300 edits: I,
2301 original_indent_columns: Vec<u32>,
2302 cx: &mut Context<Self>,
2303 ) where
2304 I: IntoIterator<Item = (Range<S>, T)>,
2305 S: ToOffset,
2306 T: Into<Arc<str>>,
2307 {
2308 if self.read_only(cx) {
2309 return;
2310 }
2311
2312 self.buffer.update(cx, |buffer, cx| {
2313 buffer.edit(
2314 edits,
2315 Some(AutoindentMode::Block {
2316 original_indent_columns,
2317 }),
2318 cx,
2319 )
2320 });
2321 }
2322
2323 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2324 self.hide_context_menu(window, cx);
2325
2326 match phase {
2327 SelectPhase::Begin {
2328 position,
2329 add,
2330 click_count,
2331 } => self.begin_selection(position, add, click_count, window, cx),
2332 SelectPhase::BeginColumnar {
2333 position,
2334 goal_column,
2335 reset,
2336 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2337 SelectPhase::Extend {
2338 position,
2339 click_count,
2340 } => self.extend_selection(position, click_count, window, cx),
2341 SelectPhase::Update {
2342 position,
2343 goal_column,
2344 scroll_delta,
2345 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2346 SelectPhase::End => self.end_selection(window, cx),
2347 }
2348 }
2349
2350 fn extend_selection(
2351 &mut self,
2352 position: DisplayPoint,
2353 click_count: usize,
2354 window: &mut Window,
2355 cx: &mut Context<Self>,
2356 ) {
2357 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2358 let tail = self.selections.newest::<usize>(cx).tail();
2359 self.begin_selection(position, false, click_count, window, cx);
2360
2361 let position = position.to_offset(&display_map, Bias::Left);
2362 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2363
2364 let mut pending_selection = self
2365 .selections
2366 .pending_anchor()
2367 .expect("extend_selection not called with pending selection");
2368 if position >= tail {
2369 pending_selection.start = tail_anchor;
2370 } else {
2371 pending_selection.end = tail_anchor;
2372 pending_selection.reversed = true;
2373 }
2374
2375 let mut pending_mode = self.selections.pending_mode().unwrap();
2376 match &mut pending_mode {
2377 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2378 _ => {}
2379 }
2380
2381 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2382 s.set_pending(pending_selection, pending_mode)
2383 });
2384 }
2385
2386 fn begin_selection(
2387 &mut self,
2388 position: DisplayPoint,
2389 add: bool,
2390 click_count: usize,
2391 window: &mut Window,
2392 cx: &mut Context<Self>,
2393 ) {
2394 if !self.focus_handle.is_focused(window) {
2395 self.last_focused_descendant = None;
2396 window.focus(&self.focus_handle);
2397 }
2398
2399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2400 let buffer = &display_map.buffer_snapshot;
2401 let newest_selection = self.selections.newest_anchor().clone();
2402 let position = display_map.clip_point(position, Bias::Left);
2403
2404 let start;
2405 let end;
2406 let mode;
2407 let mut auto_scroll;
2408 match click_count {
2409 1 => {
2410 start = buffer.anchor_before(position.to_point(&display_map));
2411 end = start;
2412 mode = SelectMode::Character;
2413 auto_scroll = true;
2414 }
2415 2 => {
2416 let range = movement::surrounding_word(&display_map, position);
2417 start = buffer.anchor_before(range.start.to_point(&display_map));
2418 end = buffer.anchor_before(range.end.to_point(&display_map));
2419 mode = SelectMode::Word(start..end);
2420 auto_scroll = true;
2421 }
2422 3 => {
2423 let position = display_map
2424 .clip_point(position, Bias::Left)
2425 .to_point(&display_map);
2426 let line_start = display_map.prev_line_boundary(position).0;
2427 let next_line_start = buffer.clip_point(
2428 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2429 Bias::Left,
2430 );
2431 start = buffer.anchor_before(line_start);
2432 end = buffer.anchor_before(next_line_start);
2433 mode = SelectMode::Line(start..end);
2434 auto_scroll = true;
2435 }
2436 _ => {
2437 start = buffer.anchor_before(0);
2438 end = buffer.anchor_before(buffer.len());
2439 mode = SelectMode::All;
2440 auto_scroll = false;
2441 }
2442 }
2443 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2444
2445 let point_to_delete: Option<usize> = {
2446 let selected_points: Vec<Selection<Point>> =
2447 self.selections.disjoint_in_range(start..end, cx);
2448
2449 if !add || click_count > 1 {
2450 None
2451 } else if !selected_points.is_empty() {
2452 Some(selected_points[0].id)
2453 } else {
2454 let clicked_point_already_selected =
2455 self.selections.disjoint.iter().find(|selection| {
2456 selection.start.to_point(buffer) == start.to_point(buffer)
2457 || selection.end.to_point(buffer) == end.to_point(buffer)
2458 });
2459
2460 clicked_point_already_selected.map(|selection| selection.id)
2461 }
2462 };
2463
2464 let selections_count = self.selections.count();
2465
2466 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2467 if let Some(point_to_delete) = point_to_delete {
2468 s.delete(point_to_delete);
2469
2470 if selections_count == 1 {
2471 s.set_pending_anchor_range(start..end, mode);
2472 }
2473 } else {
2474 if !add {
2475 s.clear_disjoint();
2476 } else if click_count > 1 {
2477 s.delete(newest_selection.id)
2478 }
2479
2480 s.set_pending_anchor_range(start..end, mode);
2481 }
2482 });
2483 }
2484
2485 fn begin_columnar_selection(
2486 &mut self,
2487 position: DisplayPoint,
2488 goal_column: u32,
2489 reset: bool,
2490 window: &mut Window,
2491 cx: &mut Context<Self>,
2492 ) {
2493 if !self.focus_handle.is_focused(window) {
2494 self.last_focused_descendant = None;
2495 window.focus(&self.focus_handle);
2496 }
2497
2498 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2499
2500 if reset {
2501 let pointer_position = display_map
2502 .buffer_snapshot
2503 .anchor_before(position.to_point(&display_map));
2504
2505 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2506 s.clear_disjoint();
2507 s.set_pending_anchor_range(
2508 pointer_position..pointer_position,
2509 SelectMode::Character,
2510 );
2511 });
2512 }
2513
2514 let tail = self.selections.newest::<Point>(cx).tail();
2515 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2516
2517 if !reset {
2518 self.select_columns(
2519 tail.to_display_point(&display_map),
2520 position,
2521 goal_column,
2522 &display_map,
2523 window,
2524 cx,
2525 );
2526 }
2527 }
2528
2529 fn update_selection(
2530 &mut self,
2531 position: DisplayPoint,
2532 goal_column: u32,
2533 scroll_delta: gpui::Point<f32>,
2534 window: &mut Window,
2535 cx: &mut Context<Self>,
2536 ) {
2537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2538
2539 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2540 let tail = tail.to_display_point(&display_map);
2541 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2542 } else if let Some(mut pending) = self.selections.pending_anchor() {
2543 let buffer = self.buffer.read(cx).snapshot(cx);
2544 let head;
2545 let tail;
2546 let mode = self.selections.pending_mode().unwrap();
2547 match &mode {
2548 SelectMode::Character => {
2549 head = position.to_point(&display_map);
2550 tail = pending.tail().to_point(&buffer);
2551 }
2552 SelectMode::Word(original_range) => {
2553 let original_display_range = original_range.start.to_display_point(&display_map)
2554 ..original_range.end.to_display_point(&display_map);
2555 let original_buffer_range = original_display_range.start.to_point(&display_map)
2556 ..original_display_range.end.to_point(&display_map);
2557 if movement::is_inside_word(&display_map, position)
2558 || original_display_range.contains(&position)
2559 {
2560 let word_range = movement::surrounding_word(&display_map, position);
2561 if word_range.start < original_display_range.start {
2562 head = word_range.start.to_point(&display_map);
2563 } else {
2564 head = word_range.end.to_point(&display_map);
2565 }
2566 } else {
2567 head = position.to_point(&display_map);
2568 }
2569
2570 if head <= original_buffer_range.start {
2571 tail = original_buffer_range.end;
2572 } else {
2573 tail = original_buffer_range.start;
2574 }
2575 }
2576 SelectMode::Line(original_range) => {
2577 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2578
2579 let position = display_map
2580 .clip_point(position, Bias::Left)
2581 .to_point(&display_map);
2582 let line_start = display_map.prev_line_boundary(position).0;
2583 let next_line_start = buffer.clip_point(
2584 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2585 Bias::Left,
2586 );
2587
2588 if line_start < original_range.start {
2589 head = line_start
2590 } else {
2591 head = next_line_start
2592 }
2593
2594 if head <= original_range.start {
2595 tail = original_range.end;
2596 } else {
2597 tail = original_range.start;
2598 }
2599 }
2600 SelectMode::All => {
2601 return;
2602 }
2603 };
2604
2605 if head < tail {
2606 pending.start = buffer.anchor_before(head);
2607 pending.end = buffer.anchor_before(tail);
2608 pending.reversed = true;
2609 } else {
2610 pending.start = buffer.anchor_before(tail);
2611 pending.end = buffer.anchor_before(head);
2612 pending.reversed = false;
2613 }
2614
2615 self.change_selections(None, window, cx, |s| {
2616 s.set_pending(pending, mode);
2617 });
2618 } else {
2619 log::error!("update_selection dispatched with no pending selection");
2620 return;
2621 }
2622
2623 self.apply_scroll_delta(scroll_delta, window, cx);
2624 cx.notify();
2625 }
2626
2627 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2628 self.columnar_selection_tail.take();
2629 if self.selections.pending_anchor().is_some() {
2630 let selections = self.selections.all::<usize>(cx);
2631 self.change_selections(None, window, cx, |s| {
2632 s.select(selections);
2633 s.clear_pending();
2634 });
2635 }
2636 }
2637
2638 fn select_columns(
2639 &mut self,
2640 tail: DisplayPoint,
2641 head: DisplayPoint,
2642 goal_column: u32,
2643 display_map: &DisplaySnapshot,
2644 window: &mut Window,
2645 cx: &mut Context<Self>,
2646 ) {
2647 let start_row = cmp::min(tail.row(), head.row());
2648 let end_row = cmp::max(tail.row(), head.row());
2649 let start_column = cmp::min(tail.column(), goal_column);
2650 let end_column = cmp::max(tail.column(), goal_column);
2651 let reversed = start_column < tail.column();
2652
2653 let selection_ranges = (start_row.0..=end_row.0)
2654 .map(DisplayRow)
2655 .filter_map(|row| {
2656 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2657 let start = display_map
2658 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2659 .to_point(display_map);
2660 let end = display_map
2661 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2662 .to_point(display_map);
2663 if reversed {
2664 Some(end..start)
2665 } else {
2666 Some(start..end)
2667 }
2668 } else {
2669 None
2670 }
2671 })
2672 .collect::<Vec<_>>();
2673
2674 self.change_selections(None, window, cx, |s| {
2675 s.select_ranges(selection_ranges);
2676 });
2677 cx.notify();
2678 }
2679
2680 pub fn has_pending_nonempty_selection(&self) -> bool {
2681 let pending_nonempty_selection = match self.selections.pending_anchor() {
2682 Some(Selection { start, end, .. }) => start != end,
2683 None => false,
2684 };
2685
2686 pending_nonempty_selection
2687 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2688 }
2689
2690 pub fn has_pending_selection(&self) -> bool {
2691 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2692 }
2693
2694 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2695 self.selection_mark_mode = false;
2696
2697 if self.clear_expanded_diff_hunks(cx) {
2698 cx.notify();
2699 return;
2700 }
2701 if self.dismiss_menus_and_popups(true, window, cx) {
2702 return;
2703 }
2704
2705 if self.mode == EditorMode::Full
2706 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2707 {
2708 return;
2709 }
2710
2711 cx.propagate();
2712 }
2713
2714 pub fn dismiss_menus_and_popups(
2715 &mut self,
2716 is_user_requested: bool,
2717 window: &mut Window,
2718 cx: &mut Context<Self>,
2719 ) -> bool {
2720 if self.take_rename(false, window, cx).is_some() {
2721 return true;
2722 }
2723
2724 if hide_hover(self, cx) {
2725 return true;
2726 }
2727
2728 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2729 return true;
2730 }
2731
2732 if self.hide_context_menu(window, cx).is_some() {
2733 return true;
2734 }
2735
2736 if self.mouse_context_menu.take().is_some() {
2737 return true;
2738 }
2739
2740 if is_user_requested && self.discard_inline_completion(true, cx) {
2741 return true;
2742 }
2743
2744 if self.snippet_stack.pop().is_some() {
2745 return true;
2746 }
2747
2748 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2749 self.dismiss_diagnostics(cx);
2750 return true;
2751 }
2752
2753 false
2754 }
2755
2756 fn linked_editing_ranges_for(
2757 &self,
2758 selection: Range<text::Anchor>,
2759 cx: &App,
2760 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2761 if self.linked_edit_ranges.is_empty() {
2762 return None;
2763 }
2764 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2765 selection.end.buffer_id.and_then(|end_buffer_id| {
2766 if selection.start.buffer_id != Some(end_buffer_id) {
2767 return None;
2768 }
2769 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2770 let snapshot = buffer.read(cx).snapshot();
2771 self.linked_edit_ranges
2772 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2773 .map(|ranges| (ranges, snapshot, buffer))
2774 })?;
2775 use text::ToOffset as TO;
2776 // find offset from the start of current range to current cursor position
2777 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2778
2779 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2780 let start_difference = start_offset - start_byte_offset;
2781 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2782 let end_difference = end_offset - start_byte_offset;
2783 // Current range has associated linked ranges.
2784 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2785 for range in linked_ranges.iter() {
2786 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2787 let end_offset = start_offset + end_difference;
2788 let start_offset = start_offset + start_difference;
2789 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2790 continue;
2791 }
2792 if self.selections.disjoint_anchor_ranges().any(|s| {
2793 if s.start.buffer_id != selection.start.buffer_id
2794 || s.end.buffer_id != selection.end.buffer_id
2795 {
2796 return false;
2797 }
2798 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2799 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2800 }) {
2801 continue;
2802 }
2803 let start = buffer_snapshot.anchor_after(start_offset);
2804 let end = buffer_snapshot.anchor_after(end_offset);
2805 linked_edits
2806 .entry(buffer.clone())
2807 .or_default()
2808 .push(start..end);
2809 }
2810 Some(linked_edits)
2811 }
2812
2813 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2814 let text: Arc<str> = text.into();
2815
2816 if self.read_only(cx) {
2817 return;
2818 }
2819
2820 let selections = self.selections.all_adjusted(cx);
2821 let mut bracket_inserted = false;
2822 let mut edits = Vec::new();
2823 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2824 let mut new_selections = Vec::with_capacity(selections.len());
2825 let mut new_autoclose_regions = Vec::new();
2826 let snapshot = self.buffer.read(cx).read(cx);
2827
2828 for (selection, autoclose_region) in
2829 self.selections_with_autoclose_regions(selections, &snapshot)
2830 {
2831 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2832 // Determine if the inserted text matches the opening or closing
2833 // bracket of any of this language's bracket pairs.
2834 let mut bracket_pair = None;
2835 let mut is_bracket_pair_start = false;
2836 let mut is_bracket_pair_end = false;
2837 if !text.is_empty() {
2838 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2839 // and they are removing the character that triggered IME popup.
2840 for (pair, enabled) in scope.brackets() {
2841 if !pair.close && !pair.surround {
2842 continue;
2843 }
2844
2845 if enabled && pair.start.ends_with(text.as_ref()) {
2846 let prefix_len = pair.start.len() - text.len();
2847 let preceding_text_matches_prefix = prefix_len == 0
2848 || (selection.start.column >= (prefix_len as u32)
2849 && snapshot.contains_str_at(
2850 Point::new(
2851 selection.start.row,
2852 selection.start.column - (prefix_len as u32),
2853 ),
2854 &pair.start[..prefix_len],
2855 ));
2856 if preceding_text_matches_prefix {
2857 bracket_pair = Some(pair.clone());
2858 is_bracket_pair_start = true;
2859 break;
2860 }
2861 }
2862 if pair.end.as_str() == text.as_ref() {
2863 bracket_pair = Some(pair.clone());
2864 is_bracket_pair_end = true;
2865 break;
2866 }
2867 }
2868 }
2869
2870 if let Some(bracket_pair) = bracket_pair {
2871 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2872 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2873 let auto_surround =
2874 self.use_auto_surround && snapshot_settings.use_auto_surround;
2875 if selection.is_empty() {
2876 if is_bracket_pair_start {
2877 // If the inserted text is a suffix of an opening bracket and the
2878 // selection is preceded by the rest of the opening bracket, then
2879 // insert the closing bracket.
2880 let following_text_allows_autoclose = snapshot
2881 .chars_at(selection.start)
2882 .next()
2883 .map_or(true, |c| scope.should_autoclose_before(c));
2884
2885 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2886 && bracket_pair.start.len() == 1
2887 {
2888 let target = bracket_pair.start.chars().next().unwrap();
2889 let current_line_count = snapshot
2890 .reversed_chars_at(selection.start)
2891 .take_while(|&c| c != '\n')
2892 .filter(|&c| c == target)
2893 .count();
2894 current_line_count % 2 == 1
2895 } else {
2896 false
2897 };
2898
2899 if autoclose
2900 && bracket_pair.close
2901 && following_text_allows_autoclose
2902 && !is_closing_quote
2903 {
2904 let anchor = snapshot.anchor_before(selection.end);
2905 new_selections.push((selection.map(|_| anchor), text.len()));
2906 new_autoclose_regions.push((
2907 anchor,
2908 text.len(),
2909 selection.id,
2910 bracket_pair.clone(),
2911 ));
2912 edits.push((
2913 selection.range(),
2914 format!("{}{}", text, bracket_pair.end).into(),
2915 ));
2916 bracket_inserted = true;
2917 continue;
2918 }
2919 }
2920
2921 if let Some(region) = autoclose_region {
2922 // If the selection is followed by an auto-inserted closing bracket,
2923 // then don't insert that closing bracket again; just move the selection
2924 // past the closing bracket.
2925 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2926 && text.as_ref() == region.pair.end.as_str();
2927 if should_skip {
2928 let anchor = snapshot.anchor_after(selection.end);
2929 new_selections
2930 .push((selection.map(|_| anchor), region.pair.end.len()));
2931 continue;
2932 }
2933 }
2934
2935 let always_treat_brackets_as_autoclosed = snapshot
2936 .settings_at(selection.start, cx)
2937 .always_treat_brackets_as_autoclosed;
2938 if always_treat_brackets_as_autoclosed
2939 && is_bracket_pair_end
2940 && snapshot.contains_str_at(selection.end, text.as_ref())
2941 {
2942 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2943 // and the inserted text is a closing bracket and the selection is followed
2944 // by the closing bracket then move the selection past the closing bracket.
2945 let anchor = snapshot.anchor_after(selection.end);
2946 new_selections.push((selection.map(|_| anchor), text.len()));
2947 continue;
2948 }
2949 }
2950 // If an opening bracket is 1 character long and is typed while
2951 // text is selected, then surround that text with the bracket pair.
2952 else if auto_surround
2953 && bracket_pair.surround
2954 && is_bracket_pair_start
2955 && bracket_pair.start.chars().count() == 1
2956 {
2957 edits.push((selection.start..selection.start, text.clone()));
2958 edits.push((
2959 selection.end..selection.end,
2960 bracket_pair.end.as_str().into(),
2961 ));
2962 bracket_inserted = true;
2963 new_selections.push((
2964 Selection {
2965 id: selection.id,
2966 start: snapshot.anchor_after(selection.start),
2967 end: snapshot.anchor_before(selection.end),
2968 reversed: selection.reversed,
2969 goal: selection.goal,
2970 },
2971 0,
2972 ));
2973 continue;
2974 }
2975 }
2976 }
2977
2978 if self.auto_replace_emoji_shortcode
2979 && selection.is_empty()
2980 && text.as_ref().ends_with(':')
2981 {
2982 if let Some(possible_emoji_short_code) =
2983 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2984 {
2985 if !possible_emoji_short_code.is_empty() {
2986 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2987 let emoji_shortcode_start = Point::new(
2988 selection.start.row,
2989 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2990 );
2991
2992 // Remove shortcode from buffer
2993 edits.push((
2994 emoji_shortcode_start..selection.start,
2995 "".to_string().into(),
2996 ));
2997 new_selections.push((
2998 Selection {
2999 id: selection.id,
3000 start: snapshot.anchor_after(emoji_shortcode_start),
3001 end: snapshot.anchor_before(selection.start),
3002 reversed: selection.reversed,
3003 goal: selection.goal,
3004 },
3005 0,
3006 ));
3007
3008 // Insert emoji
3009 let selection_start_anchor = snapshot.anchor_after(selection.start);
3010 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3011 edits.push((selection.start..selection.end, emoji.to_string().into()));
3012
3013 continue;
3014 }
3015 }
3016 }
3017 }
3018
3019 // If not handling any auto-close operation, then just replace the selected
3020 // text with the given input and move the selection to the end of the
3021 // newly inserted text.
3022 let anchor = snapshot.anchor_after(selection.end);
3023 if !self.linked_edit_ranges.is_empty() {
3024 let start_anchor = snapshot.anchor_before(selection.start);
3025
3026 let is_word_char = text.chars().next().map_or(true, |char| {
3027 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3028 classifier.is_word(char)
3029 });
3030
3031 if is_word_char {
3032 if let Some(ranges) = self
3033 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3034 {
3035 for (buffer, edits) in ranges {
3036 linked_edits
3037 .entry(buffer.clone())
3038 .or_default()
3039 .extend(edits.into_iter().map(|range| (range, text.clone())));
3040 }
3041 }
3042 }
3043 }
3044
3045 new_selections.push((selection.map(|_| anchor), 0));
3046 edits.push((selection.start..selection.end, text.clone()));
3047 }
3048
3049 drop(snapshot);
3050
3051 self.transact(window, cx, |this, window, cx| {
3052 this.buffer.update(cx, |buffer, cx| {
3053 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3054 });
3055 for (buffer, edits) in linked_edits {
3056 buffer.update(cx, |buffer, cx| {
3057 let snapshot = buffer.snapshot();
3058 let edits = edits
3059 .into_iter()
3060 .map(|(range, text)| {
3061 use text::ToPoint as TP;
3062 let end_point = TP::to_point(&range.end, &snapshot);
3063 let start_point = TP::to_point(&range.start, &snapshot);
3064 (start_point..end_point, text)
3065 })
3066 .sorted_by_key(|(range, _)| range.start)
3067 .collect::<Vec<_>>();
3068 buffer.edit(edits, None, cx);
3069 })
3070 }
3071 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3072 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3073 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3074 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3075 .zip(new_selection_deltas)
3076 .map(|(selection, delta)| Selection {
3077 id: selection.id,
3078 start: selection.start + delta,
3079 end: selection.end + delta,
3080 reversed: selection.reversed,
3081 goal: SelectionGoal::None,
3082 })
3083 .collect::<Vec<_>>();
3084
3085 let mut i = 0;
3086 for (position, delta, selection_id, pair) in new_autoclose_regions {
3087 let position = position.to_offset(&map.buffer_snapshot) + delta;
3088 let start = map.buffer_snapshot.anchor_before(position);
3089 let end = map.buffer_snapshot.anchor_after(position);
3090 while let Some(existing_state) = this.autoclose_regions.get(i) {
3091 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3092 Ordering::Less => i += 1,
3093 Ordering::Greater => break,
3094 Ordering::Equal => {
3095 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3096 Ordering::Less => i += 1,
3097 Ordering::Equal => break,
3098 Ordering::Greater => break,
3099 }
3100 }
3101 }
3102 }
3103 this.autoclose_regions.insert(
3104 i,
3105 AutocloseRegion {
3106 selection_id,
3107 range: start..end,
3108 pair,
3109 },
3110 );
3111 }
3112
3113 let had_active_inline_completion = this.has_active_inline_completion();
3114 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3115 s.select(new_selections)
3116 });
3117
3118 if !bracket_inserted {
3119 if let Some(on_type_format_task) =
3120 this.trigger_on_type_formatting(text.to_string(), window, cx)
3121 {
3122 on_type_format_task.detach_and_log_err(cx);
3123 }
3124 }
3125
3126 let editor_settings = EditorSettings::get_global(cx);
3127 if bracket_inserted
3128 && (editor_settings.auto_signature_help
3129 || editor_settings.show_signature_help_after_edits)
3130 {
3131 this.show_signature_help(&ShowSignatureHelp, window, cx);
3132 }
3133
3134 let trigger_in_words =
3135 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3136 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3137 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3138 this.refresh_inline_completion(true, false, window, cx);
3139 });
3140 }
3141
3142 fn find_possible_emoji_shortcode_at_position(
3143 snapshot: &MultiBufferSnapshot,
3144 position: Point,
3145 ) -> Option<String> {
3146 let mut chars = Vec::new();
3147 let mut found_colon = false;
3148 for char in snapshot.reversed_chars_at(position).take(100) {
3149 // Found a possible emoji shortcode in the middle of the buffer
3150 if found_colon {
3151 if char.is_whitespace() {
3152 chars.reverse();
3153 return Some(chars.iter().collect());
3154 }
3155 // If the previous character is not a whitespace, we are in the middle of a word
3156 // and we only want to complete the shortcode if the word is made up of other emojis
3157 let mut containing_word = String::new();
3158 for ch in snapshot
3159 .reversed_chars_at(position)
3160 .skip(chars.len() + 1)
3161 .take(100)
3162 {
3163 if ch.is_whitespace() {
3164 break;
3165 }
3166 containing_word.push(ch);
3167 }
3168 let containing_word = containing_word.chars().rev().collect::<String>();
3169 if util::word_consists_of_emojis(containing_word.as_str()) {
3170 chars.reverse();
3171 return Some(chars.iter().collect());
3172 }
3173 }
3174
3175 if char.is_whitespace() || !char.is_ascii() {
3176 return None;
3177 }
3178 if char == ':' {
3179 found_colon = true;
3180 } else {
3181 chars.push(char);
3182 }
3183 }
3184 // Found a possible emoji shortcode at the beginning of the buffer
3185 chars.reverse();
3186 Some(chars.iter().collect())
3187 }
3188
3189 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3190 self.transact(window, cx, |this, window, cx| {
3191 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3192 let selections = this.selections.all::<usize>(cx);
3193 let multi_buffer = this.buffer.read(cx);
3194 let buffer = multi_buffer.snapshot(cx);
3195 selections
3196 .iter()
3197 .map(|selection| {
3198 let start_point = selection.start.to_point(&buffer);
3199 let mut indent =
3200 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3201 indent.len = cmp::min(indent.len, start_point.column);
3202 let start = selection.start;
3203 let end = selection.end;
3204 let selection_is_empty = start == end;
3205 let language_scope = buffer.language_scope_at(start);
3206 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3207 &language_scope
3208 {
3209 let leading_whitespace_len = buffer
3210 .reversed_chars_at(start)
3211 .take_while(|c| c.is_whitespace() && *c != '\n')
3212 .map(|c| c.len_utf8())
3213 .sum::<usize>();
3214
3215 let trailing_whitespace_len = buffer
3216 .chars_at(end)
3217 .take_while(|c| c.is_whitespace() && *c != '\n')
3218 .map(|c| c.len_utf8())
3219 .sum::<usize>();
3220
3221 let insert_extra_newline =
3222 language.brackets().any(|(pair, enabled)| {
3223 let pair_start = pair.start.trim_end();
3224 let pair_end = pair.end.trim_start();
3225
3226 enabled
3227 && pair.newline
3228 && buffer.contains_str_at(
3229 end + trailing_whitespace_len,
3230 pair_end,
3231 )
3232 && buffer.contains_str_at(
3233 (start - leading_whitespace_len)
3234 .saturating_sub(pair_start.len()),
3235 pair_start,
3236 )
3237 });
3238
3239 // Comment extension on newline is allowed only for cursor selections
3240 let comment_delimiter = maybe!({
3241 if !selection_is_empty {
3242 return None;
3243 }
3244
3245 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3246 return None;
3247 }
3248
3249 let delimiters = language.line_comment_prefixes();
3250 let max_len_of_delimiter =
3251 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3252 let (snapshot, range) =
3253 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3254
3255 let mut index_of_first_non_whitespace = 0;
3256 let comment_candidate = snapshot
3257 .chars_for_range(range)
3258 .skip_while(|c| {
3259 let should_skip = c.is_whitespace();
3260 if should_skip {
3261 index_of_first_non_whitespace += 1;
3262 }
3263 should_skip
3264 })
3265 .take(max_len_of_delimiter)
3266 .collect::<String>();
3267 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3268 comment_candidate.starts_with(comment_prefix.as_ref())
3269 })?;
3270 let cursor_is_placed_after_comment_marker =
3271 index_of_first_non_whitespace + comment_prefix.len()
3272 <= start_point.column as usize;
3273 if cursor_is_placed_after_comment_marker {
3274 Some(comment_prefix.clone())
3275 } else {
3276 None
3277 }
3278 });
3279 (comment_delimiter, insert_extra_newline)
3280 } else {
3281 (None, false)
3282 };
3283
3284 let capacity_for_delimiter = comment_delimiter
3285 .as_deref()
3286 .map(str::len)
3287 .unwrap_or_default();
3288 let mut new_text =
3289 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3290 new_text.push('\n');
3291 new_text.extend(indent.chars());
3292 if let Some(delimiter) = &comment_delimiter {
3293 new_text.push_str(delimiter);
3294 }
3295 if insert_extra_newline {
3296 new_text = new_text.repeat(2);
3297 }
3298
3299 let anchor = buffer.anchor_after(end);
3300 let new_selection = selection.map(|_| anchor);
3301 (
3302 (start..end, new_text),
3303 (insert_extra_newline, new_selection),
3304 )
3305 })
3306 .unzip()
3307 };
3308
3309 this.edit_with_autoindent(edits, cx);
3310 let buffer = this.buffer.read(cx).snapshot(cx);
3311 let new_selections = selection_fixup_info
3312 .into_iter()
3313 .map(|(extra_newline_inserted, new_selection)| {
3314 let mut cursor = new_selection.end.to_point(&buffer);
3315 if extra_newline_inserted {
3316 cursor.row -= 1;
3317 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3318 }
3319 new_selection.map(|_| cursor)
3320 })
3321 .collect();
3322
3323 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3324 s.select(new_selections)
3325 });
3326 this.refresh_inline_completion(true, false, window, cx);
3327 });
3328 }
3329
3330 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3331 let buffer = self.buffer.read(cx);
3332 let snapshot = buffer.snapshot(cx);
3333
3334 let mut edits = Vec::new();
3335 let mut rows = Vec::new();
3336
3337 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3338 let cursor = selection.head();
3339 let row = cursor.row;
3340
3341 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3342
3343 let newline = "\n".to_string();
3344 edits.push((start_of_line..start_of_line, newline));
3345
3346 rows.push(row + rows_inserted as u32);
3347 }
3348
3349 self.transact(window, cx, |editor, window, cx| {
3350 editor.edit(edits, cx);
3351
3352 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3353 let mut index = 0;
3354 s.move_cursors_with(|map, _, _| {
3355 let row = rows[index];
3356 index += 1;
3357
3358 let point = Point::new(row, 0);
3359 let boundary = map.next_line_boundary(point).1;
3360 let clipped = map.clip_point(boundary, Bias::Left);
3361
3362 (clipped, SelectionGoal::None)
3363 });
3364 });
3365
3366 let mut indent_edits = Vec::new();
3367 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3368 for row in rows {
3369 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3370 for (row, indent) in indents {
3371 if indent.len == 0 {
3372 continue;
3373 }
3374
3375 let text = match indent.kind {
3376 IndentKind::Space => " ".repeat(indent.len as usize),
3377 IndentKind::Tab => "\t".repeat(indent.len as usize),
3378 };
3379 let point = Point::new(row.0, 0);
3380 indent_edits.push((point..point, text));
3381 }
3382 }
3383 editor.edit(indent_edits, cx);
3384 });
3385 }
3386
3387 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3388 let buffer = self.buffer.read(cx);
3389 let snapshot = buffer.snapshot(cx);
3390
3391 let mut edits = Vec::new();
3392 let mut rows = Vec::new();
3393 let mut rows_inserted = 0;
3394
3395 for selection in self.selections.all_adjusted(cx) {
3396 let cursor = selection.head();
3397 let row = cursor.row;
3398
3399 let point = Point::new(row + 1, 0);
3400 let start_of_line = snapshot.clip_point(point, Bias::Left);
3401
3402 let newline = "\n".to_string();
3403 edits.push((start_of_line..start_of_line, newline));
3404
3405 rows_inserted += 1;
3406 rows.push(row + rows_inserted);
3407 }
3408
3409 self.transact(window, cx, |editor, window, cx| {
3410 editor.edit(edits, cx);
3411
3412 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3413 let mut index = 0;
3414 s.move_cursors_with(|map, _, _| {
3415 let row = rows[index];
3416 index += 1;
3417
3418 let point = Point::new(row, 0);
3419 let boundary = map.next_line_boundary(point).1;
3420 let clipped = map.clip_point(boundary, Bias::Left);
3421
3422 (clipped, SelectionGoal::None)
3423 });
3424 });
3425
3426 let mut indent_edits = Vec::new();
3427 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3428 for row in rows {
3429 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3430 for (row, indent) in indents {
3431 if indent.len == 0 {
3432 continue;
3433 }
3434
3435 let text = match indent.kind {
3436 IndentKind::Space => " ".repeat(indent.len as usize),
3437 IndentKind::Tab => "\t".repeat(indent.len as usize),
3438 };
3439 let point = Point::new(row.0, 0);
3440 indent_edits.push((point..point, text));
3441 }
3442 }
3443 editor.edit(indent_edits, cx);
3444 });
3445 }
3446
3447 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3448 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3449 original_indent_columns: Vec::new(),
3450 });
3451 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3452 }
3453
3454 fn insert_with_autoindent_mode(
3455 &mut self,
3456 text: &str,
3457 autoindent_mode: Option<AutoindentMode>,
3458 window: &mut Window,
3459 cx: &mut Context<Self>,
3460 ) {
3461 if self.read_only(cx) {
3462 return;
3463 }
3464
3465 let text: Arc<str> = text.into();
3466 self.transact(window, cx, |this, window, cx| {
3467 let old_selections = this.selections.all_adjusted(cx);
3468 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3469 let anchors = {
3470 let snapshot = buffer.read(cx);
3471 old_selections
3472 .iter()
3473 .map(|s| {
3474 let anchor = snapshot.anchor_after(s.head());
3475 s.map(|_| anchor)
3476 })
3477 .collect::<Vec<_>>()
3478 };
3479 buffer.edit(
3480 old_selections
3481 .iter()
3482 .map(|s| (s.start..s.end, text.clone())),
3483 autoindent_mode,
3484 cx,
3485 );
3486 anchors
3487 });
3488
3489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3490 s.select_anchors(selection_anchors);
3491 });
3492
3493 cx.notify();
3494 });
3495 }
3496
3497 fn trigger_completion_on_input(
3498 &mut self,
3499 text: &str,
3500 trigger_in_words: bool,
3501 window: &mut Window,
3502 cx: &mut Context<Self>,
3503 ) {
3504 if self.is_completion_trigger(text, trigger_in_words, cx) {
3505 self.show_completions(
3506 &ShowCompletions {
3507 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3508 },
3509 window,
3510 cx,
3511 );
3512 } else {
3513 self.hide_context_menu(window, cx);
3514 }
3515 }
3516
3517 fn is_completion_trigger(
3518 &self,
3519 text: &str,
3520 trigger_in_words: bool,
3521 cx: &mut Context<Self>,
3522 ) -> bool {
3523 let position = self.selections.newest_anchor().head();
3524 let multibuffer = self.buffer.read(cx);
3525 let Some(buffer) = position
3526 .buffer_id
3527 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3528 else {
3529 return false;
3530 };
3531
3532 if let Some(completion_provider) = &self.completion_provider {
3533 completion_provider.is_completion_trigger(
3534 &buffer,
3535 position.text_anchor,
3536 text,
3537 trigger_in_words,
3538 cx,
3539 )
3540 } else {
3541 false
3542 }
3543 }
3544
3545 /// If any empty selections is touching the start of its innermost containing autoclose
3546 /// region, expand it to select the brackets.
3547 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3548 let selections = self.selections.all::<usize>(cx);
3549 let buffer = self.buffer.read(cx).read(cx);
3550 let new_selections = self
3551 .selections_with_autoclose_regions(selections, &buffer)
3552 .map(|(mut selection, region)| {
3553 if !selection.is_empty() {
3554 return selection;
3555 }
3556
3557 if let Some(region) = region {
3558 let mut range = region.range.to_offset(&buffer);
3559 if selection.start == range.start && range.start >= region.pair.start.len() {
3560 range.start -= region.pair.start.len();
3561 if buffer.contains_str_at(range.start, ®ion.pair.start)
3562 && buffer.contains_str_at(range.end, ®ion.pair.end)
3563 {
3564 range.end += region.pair.end.len();
3565 selection.start = range.start;
3566 selection.end = range.end;
3567
3568 return selection;
3569 }
3570 }
3571 }
3572
3573 let always_treat_brackets_as_autoclosed = buffer
3574 .settings_at(selection.start, cx)
3575 .always_treat_brackets_as_autoclosed;
3576
3577 if !always_treat_brackets_as_autoclosed {
3578 return selection;
3579 }
3580
3581 if let Some(scope) = buffer.language_scope_at(selection.start) {
3582 for (pair, enabled) in scope.brackets() {
3583 if !enabled || !pair.close {
3584 continue;
3585 }
3586
3587 if buffer.contains_str_at(selection.start, &pair.end) {
3588 let pair_start_len = pair.start.len();
3589 if buffer.contains_str_at(
3590 selection.start.saturating_sub(pair_start_len),
3591 &pair.start,
3592 ) {
3593 selection.start -= pair_start_len;
3594 selection.end += pair.end.len();
3595
3596 return selection;
3597 }
3598 }
3599 }
3600 }
3601
3602 selection
3603 })
3604 .collect();
3605
3606 drop(buffer);
3607 self.change_selections(None, window, cx, |selections| {
3608 selections.select(new_selections)
3609 });
3610 }
3611
3612 /// Iterate the given selections, and for each one, find the smallest surrounding
3613 /// autoclose region. This uses the ordering of the selections and the autoclose
3614 /// regions to avoid repeated comparisons.
3615 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3616 &'a self,
3617 selections: impl IntoIterator<Item = Selection<D>>,
3618 buffer: &'a MultiBufferSnapshot,
3619 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3620 let mut i = 0;
3621 let mut regions = self.autoclose_regions.as_slice();
3622 selections.into_iter().map(move |selection| {
3623 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3624
3625 let mut enclosing = None;
3626 while let Some(pair_state) = regions.get(i) {
3627 if pair_state.range.end.to_offset(buffer) < range.start {
3628 regions = ®ions[i + 1..];
3629 i = 0;
3630 } else if pair_state.range.start.to_offset(buffer) > range.end {
3631 break;
3632 } else {
3633 if pair_state.selection_id == selection.id {
3634 enclosing = Some(pair_state);
3635 }
3636 i += 1;
3637 }
3638 }
3639
3640 (selection, enclosing)
3641 })
3642 }
3643
3644 /// Remove any autoclose regions that no longer contain their selection.
3645 fn invalidate_autoclose_regions(
3646 &mut self,
3647 mut selections: &[Selection<Anchor>],
3648 buffer: &MultiBufferSnapshot,
3649 ) {
3650 self.autoclose_regions.retain(|state| {
3651 let mut i = 0;
3652 while let Some(selection) = selections.get(i) {
3653 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3654 selections = &selections[1..];
3655 continue;
3656 }
3657 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3658 break;
3659 }
3660 if selection.id == state.selection_id {
3661 return true;
3662 } else {
3663 i += 1;
3664 }
3665 }
3666 false
3667 });
3668 }
3669
3670 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3671 let offset = position.to_offset(buffer);
3672 let (word_range, kind) = buffer.surrounding_word(offset, true);
3673 if offset > word_range.start && kind == Some(CharKind::Word) {
3674 Some(
3675 buffer
3676 .text_for_range(word_range.start..offset)
3677 .collect::<String>(),
3678 )
3679 } else {
3680 None
3681 }
3682 }
3683
3684 pub fn toggle_inlay_hints(
3685 &mut self,
3686 _: &ToggleInlayHints,
3687 _: &mut Window,
3688 cx: &mut Context<Self>,
3689 ) {
3690 self.refresh_inlay_hints(
3691 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3692 cx,
3693 );
3694 }
3695
3696 pub fn inlay_hints_enabled(&self) -> bool {
3697 self.inlay_hint_cache.enabled
3698 }
3699
3700 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3701 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3702 return;
3703 }
3704
3705 let reason_description = reason.description();
3706 let ignore_debounce = matches!(
3707 reason,
3708 InlayHintRefreshReason::SettingsChange(_)
3709 | InlayHintRefreshReason::Toggle(_)
3710 | InlayHintRefreshReason::ExcerptsRemoved(_)
3711 );
3712 let (invalidate_cache, required_languages) = match reason {
3713 InlayHintRefreshReason::Toggle(enabled) => {
3714 self.inlay_hint_cache.enabled = enabled;
3715 if enabled {
3716 (InvalidationStrategy::RefreshRequested, None)
3717 } else {
3718 self.inlay_hint_cache.clear();
3719 self.splice_inlays(
3720 &self
3721 .visible_inlay_hints(cx)
3722 .iter()
3723 .map(|inlay| inlay.id)
3724 .collect::<Vec<InlayId>>(),
3725 Vec::new(),
3726 cx,
3727 );
3728 return;
3729 }
3730 }
3731 InlayHintRefreshReason::SettingsChange(new_settings) => {
3732 match self.inlay_hint_cache.update_settings(
3733 &self.buffer,
3734 new_settings,
3735 self.visible_inlay_hints(cx),
3736 cx,
3737 ) {
3738 ControlFlow::Break(Some(InlaySplice {
3739 to_remove,
3740 to_insert,
3741 })) => {
3742 self.splice_inlays(&to_remove, to_insert, cx);
3743 return;
3744 }
3745 ControlFlow::Break(None) => return,
3746 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3747 }
3748 }
3749 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3750 if let Some(InlaySplice {
3751 to_remove,
3752 to_insert,
3753 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3754 {
3755 self.splice_inlays(&to_remove, to_insert, cx);
3756 }
3757 return;
3758 }
3759 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3760 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3761 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3762 }
3763 InlayHintRefreshReason::RefreshRequested => {
3764 (InvalidationStrategy::RefreshRequested, None)
3765 }
3766 };
3767
3768 if let Some(InlaySplice {
3769 to_remove,
3770 to_insert,
3771 }) = self.inlay_hint_cache.spawn_hint_refresh(
3772 reason_description,
3773 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3774 invalidate_cache,
3775 ignore_debounce,
3776 cx,
3777 ) {
3778 self.splice_inlays(&to_remove, to_insert, cx);
3779 }
3780 }
3781
3782 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3783 self.display_map
3784 .read(cx)
3785 .current_inlays()
3786 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3787 .cloned()
3788 .collect()
3789 }
3790
3791 pub fn excerpts_for_inlay_hints_query(
3792 &self,
3793 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3794 cx: &mut Context<Editor>,
3795 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3796 let Some(project) = self.project.as_ref() else {
3797 return HashMap::default();
3798 };
3799 let project = project.read(cx);
3800 let multi_buffer = self.buffer().read(cx);
3801 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3802 let multi_buffer_visible_start = self
3803 .scroll_manager
3804 .anchor()
3805 .anchor
3806 .to_point(&multi_buffer_snapshot);
3807 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3808 multi_buffer_visible_start
3809 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3810 Bias::Left,
3811 );
3812 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3813 multi_buffer_snapshot
3814 .range_to_buffer_ranges(multi_buffer_visible_range)
3815 .into_iter()
3816 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3817 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3818 let buffer_file = project::File::from_dyn(buffer.file())?;
3819 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3820 let worktree_entry = buffer_worktree
3821 .read(cx)
3822 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3823 if worktree_entry.is_ignored {
3824 return None;
3825 }
3826
3827 let language = buffer.language()?;
3828 if let Some(restrict_to_languages) = restrict_to_languages {
3829 if !restrict_to_languages.contains(language) {
3830 return None;
3831 }
3832 }
3833 Some((
3834 excerpt_id,
3835 (
3836 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3837 buffer.version().clone(),
3838 excerpt_visible_range,
3839 ),
3840 ))
3841 })
3842 .collect()
3843 }
3844
3845 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3846 TextLayoutDetails {
3847 text_system: window.text_system().clone(),
3848 editor_style: self.style.clone().unwrap(),
3849 rem_size: window.rem_size(),
3850 scroll_anchor: self.scroll_manager.anchor(),
3851 visible_rows: self.visible_line_count(),
3852 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3853 }
3854 }
3855
3856 pub fn splice_inlays(
3857 &self,
3858 to_remove: &[InlayId],
3859 to_insert: Vec<Inlay>,
3860 cx: &mut Context<Self>,
3861 ) {
3862 self.display_map.update(cx, |display_map, cx| {
3863 display_map.splice_inlays(to_remove, to_insert, cx)
3864 });
3865 cx.notify();
3866 }
3867
3868 fn trigger_on_type_formatting(
3869 &self,
3870 input: String,
3871 window: &mut Window,
3872 cx: &mut Context<Self>,
3873 ) -> Option<Task<Result<()>>> {
3874 if input.len() != 1 {
3875 return None;
3876 }
3877
3878 let project = self.project.as_ref()?;
3879 let position = self.selections.newest_anchor().head();
3880 let (buffer, buffer_position) = self
3881 .buffer
3882 .read(cx)
3883 .text_anchor_for_position(position, cx)?;
3884
3885 let settings = language_settings::language_settings(
3886 buffer
3887 .read(cx)
3888 .language_at(buffer_position)
3889 .map(|l| l.name()),
3890 buffer.read(cx).file(),
3891 cx,
3892 );
3893 if !settings.use_on_type_format {
3894 return None;
3895 }
3896
3897 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3898 // hence we do LSP request & edit on host side only — add formats to host's history.
3899 let push_to_lsp_host_history = true;
3900 // If this is not the host, append its history with new edits.
3901 let push_to_client_history = project.read(cx).is_via_collab();
3902
3903 let on_type_formatting = project.update(cx, |project, cx| {
3904 project.on_type_format(
3905 buffer.clone(),
3906 buffer_position,
3907 input,
3908 push_to_lsp_host_history,
3909 cx,
3910 )
3911 });
3912 Some(cx.spawn_in(window, |editor, mut cx| async move {
3913 if let Some(transaction) = on_type_formatting.await? {
3914 if push_to_client_history {
3915 buffer
3916 .update(&mut cx, |buffer, _| {
3917 buffer.push_transaction(transaction, Instant::now());
3918 })
3919 .ok();
3920 }
3921 editor.update(&mut cx, |editor, cx| {
3922 editor.refresh_document_highlights(cx);
3923 })?;
3924 }
3925 Ok(())
3926 }))
3927 }
3928
3929 pub fn show_completions(
3930 &mut self,
3931 options: &ShowCompletions,
3932 window: &mut Window,
3933 cx: &mut Context<Self>,
3934 ) {
3935 if self.pending_rename.is_some() {
3936 return;
3937 }
3938
3939 let Some(provider) = self.completion_provider.as_ref() else {
3940 return;
3941 };
3942
3943 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3944 return;
3945 }
3946
3947 let position = self.selections.newest_anchor().head();
3948 if position.diff_base_anchor.is_some() {
3949 return;
3950 }
3951 let (buffer, buffer_position) =
3952 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3953 output
3954 } else {
3955 return;
3956 };
3957 let show_completion_documentation = buffer
3958 .read(cx)
3959 .snapshot()
3960 .settings_at(buffer_position, cx)
3961 .show_completion_documentation;
3962
3963 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3964
3965 let trigger_kind = match &options.trigger {
3966 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3967 CompletionTriggerKind::TRIGGER_CHARACTER
3968 }
3969 _ => CompletionTriggerKind::INVOKED,
3970 };
3971 let completion_context = CompletionContext {
3972 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3973 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3974 Some(String::from(trigger))
3975 } else {
3976 None
3977 }
3978 }),
3979 trigger_kind,
3980 };
3981 let completions =
3982 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3983 let sort_completions = provider.sort_completions();
3984
3985 let id = post_inc(&mut self.next_completion_id);
3986 let task = cx.spawn_in(window, |editor, mut cx| {
3987 async move {
3988 editor.update(&mut cx, |this, _| {
3989 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3990 })?;
3991 let completions = completions.await.log_err();
3992 let menu = if let Some(completions) = completions {
3993 let mut menu = CompletionsMenu::new(
3994 id,
3995 sort_completions,
3996 show_completion_documentation,
3997 position,
3998 buffer.clone(),
3999 completions.into(),
4000 );
4001
4002 menu.filter(query.as_deref(), cx.background_executor().clone())
4003 .await;
4004
4005 menu.visible().then_some(menu)
4006 } else {
4007 None
4008 };
4009
4010 editor.update_in(&mut cx, |editor, window, cx| {
4011 match editor.context_menu.borrow().as_ref() {
4012 None => {}
4013 Some(CodeContextMenu::Completions(prev_menu)) => {
4014 if prev_menu.id > id {
4015 return;
4016 }
4017 }
4018 _ => return,
4019 }
4020
4021 if editor.focus_handle.is_focused(window) && menu.is_some() {
4022 let mut menu = menu.unwrap();
4023 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4024
4025 *editor.context_menu.borrow_mut() =
4026 Some(CodeContextMenu::Completions(menu));
4027
4028 if editor.show_edit_predictions_in_menu() {
4029 editor.update_visible_inline_completion(window, cx);
4030 } else {
4031 editor.discard_inline_completion(false, cx);
4032 }
4033
4034 cx.notify();
4035 } else if editor.completion_tasks.len() <= 1 {
4036 // If there are no more completion tasks and the last menu was
4037 // empty, we should hide it.
4038 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4039 // If it was already hidden and we don't show inline
4040 // completions in the menu, we should also show the
4041 // inline-completion when available.
4042 if was_hidden && editor.show_edit_predictions_in_menu() {
4043 editor.update_visible_inline_completion(window, cx);
4044 }
4045 }
4046 })?;
4047
4048 Ok::<_, anyhow::Error>(())
4049 }
4050 .log_err()
4051 });
4052
4053 self.completion_tasks.push((id, task));
4054 }
4055
4056 pub fn confirm_completion(
4057 &mut self,
4058 action: &ConfirmCompletion,
4059 window: &mut Window,
4060 cx: &mut Context<Self>,
4061 ) -> Option<Task<Result<()>>> {
4062 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4063 }
4064
4065 pub fn compose_completion(
4066 &mut self,
4067 action: &ComposeCompletion,
4068 window: &mut Window,
4069 cx: &mut Context<Self>,
4070 ) -> Option<Task<Result<()>>> {
4071 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4072 }
4073
4074 fn do_completion(
4075 &mut self,
4076 item_ix: Option<usize>,
4077 intent: CompletionIntent,
4078 window: &mut Window,
4079 cx: &mut Context<Editor>,
4080 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4081 use language::ToOffset as _;
4082
4083 let completions_menu =
4084 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4085 menu
4086 } else {
4087 return None;
4088 };
4089
4090 let entries = completions_menu.entries.borrow();
4091 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4092 if self.show_edit_predictions_in_menu() {
4093 self.discard_inline_completion(true, cx);
4094 }
4095 let candidate_id = mat.candidate_id;
4096 drop(entries);
4097
4098 let buffer_handle = completions_menu.buffer;
4099 let completion = completions_menu
4100 .completions
4101 .borrow()
4102 .get(candidate_id)?
4103 .clone();
4104 cx.stop_propagation();
4105
4106 let snippet;
4107 let text;
4108
4109 if completion.is_snippet() {
4110 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4111 text = snippet.as_ref().unwrap().text.clone();
4112 } else {
4113 snippet = None;
4114 text = completion.new_text.clone();
4115 };
4116 let selections = self.selections.all::<usize>(cx);
4117 let buffer = buffer_handle.read(cx);
4118 let old_range = completion.old_range.to_offset(buffer);
4119 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4120
4121 let newest_selection = self.selections.newest_anchor();
4122 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4123 return None;
4124 }
4125
4126 let lookbehind = newest_selection
4127 .start
4128 .text_anchor
4129 .to_offset(buffer)
4130 .saturating_sub(old_range.start);
4131 let lookahead = old_range
4132 .end
4133 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4134 let mut common_prefix_len = old_text
4135 .bytes()
4136 .zip(text.bytes())
4137 .take_while(|(a, b)| a == b)
4138 .count();
4139
4140 let snapshot = self.buffer.read(cx).snapshot(cx);
4141 let mut range_to_replace: Option<Range<isize>> = None;
4142 let mut ranges = Vec::new();
4143 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4144 for selection in &selections {
4145 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4146 let start = selection.start.saturating_sub(lookbehind);
4147 let end = selection.end + lookahead;
4148 if selection.id == newest_selection.id {
4149 range_to_replace = Some(
4150 ((start + common_prefix_len) as isize - selection.start as isize)
4151 ..(end as isize - selection.start as isize),
4152 );
4153 }
4154 ranges.push(start + common_prefix_len..end);
4155 } else {
4156 common_prefix_len = 0;
4157 ranges.clear();
4158 ranges.extend(selections.iter().map(|s| {
4159 if s.id == newest_selection.id {
4160 range_to_replace = Some(
4161 old_range.start.to_offset_utf16(&snapshot).0 as isize
4162 - selection.start as isize
4163 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4164 - selection.start as isize,
4165 );
4166 old_range.clone()
4167 } else {
4168 s.start..s.end
4169 }
4170 }));
4171 break;
4172 }
4173 if !self.linked_edit_ranges.is_empty() {
4174 let start_anchor = snapshot.anchor_before(selection.head());
4175 let end_anchor = snapshot.anchor_after(selection.tail());
4176 if let Some(ranges) = self
4177 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4178 {
4179 for (buffer, edits) in ranges {
4180 linked_edits.entry(buffer.clone()).or_default().extend(
4181 edits
4182 .into_iter()
4183 .map(|range| (range, text[common_prefix_len..].to_owned())),
4184 );
4185 }
4186 }
4187 }
4188 }
4189 let text = &text[common_prefix_len..];
4190
4191 cx.emit(EditorEvent::InputHandled {
4192 utf16_range_to_replace: range_to_replace,
4193 text: text.into(),
4194 });
4195
4196 self.transact(window, cx, |this, window, cx| {
4197 if let Some(mut snippet) = snippet {
4198 snippet.text = text.to_string();
4199 for tabstop in snippet
4200 .tabstops
4201 .iter_mut()
4202 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4203 {
4204 tabstop.start -= common_prefix_len as isize;
4205 tabstop.end -= common_prefix_len as isize;
4206 }
4207
4208 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4209 } else {
4210 this.buffer.update(cx, |buffer, cx| {
4211 buffer.edit(
4212 ranges.iter().map(|range| (range.clone(), text)),
4213 this.autoindent_mode.clone(),
4214 cx,
4215 );
4216 });
4217 }
4218 for (buffer, edits) in linked_edits {
4219 buffer.update(cx, |buffer, cx| {
4220 let snapshot = buffer.snapshot();
4221 let edits = edits
4222 .into_iter()
4223 .map(|(range, text)| {
4224 use text::ToPoint as TP;
4225 let end_point = TP::to_point(&range.end, &snapshot);
4226 let start_point = TP::to_point(&range.start, &snapshot);
4227 (start_point..end_point, text)
4228 })
4229 .sorted_by_key(|(range, _)| range.start)
4230 .collect::<Vec<_>>();
4231 buffer.edit(edits, None, cx);
4232 })
4233 }
4234
4235 this.refresh_inline_completion(true, false, window, cx);
4236 });
4237
4238 let show_new_completions_on_confirm = completion
4239 .confirm
4240 .as_ref()
4241 .map_or(false, |confirm| confirm(intent, window, cx));
4242 if show_new_completions_on_confirm {
4243 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4244 }
4245
4246 let provider = self.completion_provider.as_ref()?;
4247 drop(completion);
4248 let apply_edits = provider.apply_additional_edits_for_completion(
4249 buffer_handle,
4250 completions_menu.completions.clone(),
4251 candidate_id,
4252 true,
4253 cx,
4254 );
4255
4256 let editor_settings = EditorSettings::get_global(cx);
4257 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4258 // After the code completion is finished, users often want to know what signatures are needed.
4259 // so we should automatically call signature_help
4260 self.show_signature_help(&ShowSignatureHelp, window, cx);
4261 }
4262
4263 Some(cx.foreground_executor().spawn(async move {
4264 apply_edits.await?;
4265 Ok(())
4266 }))
4267 }
4268
4269 pub fn toggle_code_actions(
4270 &mut self,
4271 action: &ToggleCodeActions,
4272 window: &mut Window,
4273 cx: &mut Context<Self>,
4274 ) {
4275 let mut context_menu = self.context_menu.borrow_mut();
4276 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4277 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4278 // Toggle if we're selecting the same one
4279 *context_menu = None;
4280 cx.notify();
4281 return;
4282 } else {
4283 // Otherwise, clear it and start a new one
4284 *context_menu = None;
4285 cx.notify();
4286 }
4287 }
4288 drop(context_menu);
4289 let snapshot = self.snapshot(window, cx);
4290 let deployed_from_indicator = action.deployed_from_indicator;
4291 let mut task = self.code_actions_task.take();
4292 let action = action.clone();
4293 cx.spawn_in(window, |editor, mut cx| async move {
4294 while let Some(prev_task) = task {
4295 prev_task.await.log_err();
4296 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4297 }
4298
4299 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4300 if editor.focus_handle.is_focused(window) {
4301 let multibuffer_point = action
4302 .deployed_from_indicator
4303 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4304 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4305 let (buffer, buffer_row) = snapshot
4306 .buffer_snapshot
4307 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4308 .and_then(|(buffer_snapshot, range)| {
4309 editor
4310 .buffer
4311 .read(cx)
4312 .buffer(buffer_snapshot.remote_id())
4313 .map(|buffer| (buffer, range.start.row))
4314 })?;
4315 let (_, code_actions) = editor
4316 .available_code_actions
4317 .clone()
4318 .and_then(|(location, code_actions)| {
4319 let snapshot = location.buffer.read(cx).snapshot();
4320 let point_range = location.range.to_point(&snapshot);
4321 let point_range = point_range.start.row..=point_range.end.row;
4322 if point_range.contains(&buffer_row) {
4323 Some((location, code_actions))
4324 } else {
4325 None
4326 }
4327 })
4328 .unzip();
4329 let buffer_id = buffer.read(cx).remote_id();
4330 let tasks = editor
4331 .tasks
4332 .get(&(buffer_id, buffer_row))
4333 .map(|t| Arc::new(t.to_owned()));
4334 if tasks.is_none() && code_actions.is_none() {
4335 return None;
4336 }
4337
4338 editor.completion_tasks.clear();
4339 editor.discard_inline_completion(false, cx);
4340 let task_context =
4341 tasks
4342 .as_ref()
4343 .zip(editor.project.clone())
4344 .map(|(tasks, project)| {
4345 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4346 });
4347
4348 Some(cx.spawn_in(window, |editor, mut cx| async move {
4349 let task_context = match task_context {
4350 Some(task_context) => task_context.await,
4351 None => None,
4352 };
4353 let resolved_tasks =
4354 tasks.zip(task_context).map(|(tasks, task_context)| {
4355 Rc::new(ResolvedTasks {
4356 templates: tasks.resolve(&task_context).collect(),
4357 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4358 multibuffer_point.row,
4359 tasks.column,
4360 )),
4361 })
4362 });
4363 let spawn_straight_away = resolved_tasks
4364 .as_ref()
4365 .map_or(false, |tasks| tasks.templates.len() == 1)
4366 && code_actions
4367 .as_ref()
4368 .map_or(true, |actions| actions.is_empty());
4369 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4370 *editor.context_menu.borrow_mut() =
4371 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4372 buffer,
4373 actions: CodeActionContents {
4374 tasks: resolved_tasks,
4375 actions: code_actions,
4376 },
4377 selected_item: Default::default(),
4378 scroll_handle: UniformListScrollHandle::default(),
4379 deployed_from_indicator,
4380 }));
4381 if spawn_straight_away {
4382 if let Some(task) = editor.confirm_code_action(
4383 &ConfirmCodeAction { item_ix: Some(0) },
4384 window,
4385 cx,
4386 ) {
4387 cx.notify();
4388 return task;
4389 }
4390 }
4391 cx.notify();
4392 Task::ready(Ok(()))
4393 }) {
4394 task.await
4395 } else {
4396 Ok(())
4397 }
4398 }))
4399 } else {
4400 Some(Task::ready(Ok(())))
4401 }
4402 })?;
4403 if let Some(task) = spawned_test_task {
4404 task.await?;
4405 }
4406
4407 Ok::<_, anyhow::Error>(())
4408 })
4409 .detach_and_log_err(cx);
4410 }
4411
4412 pub fn confirm_code_action(
4413 &mut self,
4414 action: &ConfirmCodeAction,
4415 window: &mut Window,
4416 cx: &mut Context<Self>,
4417 ) -> Option<Task<Result<()>>> {
4418 let actions_menu =
4419 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4420 menu
4421 } else {
4422 return None;
4423 };
4424 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4425 let action = actions_menu.actions.get(action_ix)?;
4426 let title = action.label();
4427 let buffer = actions_menu.buffer;
4428 let workspace = self.workspace()?;
4429
4430 match action {
4431 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4432 workspace.update(cx, |workspace, cx| {
4433 workspace::tasks::schedule_resolved_task(
4434 workspace,
4435 task_source_kind,
4436 resolved_task,
4437 false,
4438 cx,
4439 );
4440
4441 Some(Task::ready(Ok(())))
4442 })
4443 }
4444 CodeActionsItem::CodeAction {
4445 excerpt_id,
4446 action,
4447 provider,
4448 } => {
4449 let apply_code_action =
4450 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4451 let workspace = workspace.downgrade();
4452 Some(cx.spawn_in(window, |editor, cx| async move {
4453 let project_transaction = apply_code_action.await?;
4454 Self::open_project_transaction(
4455 &editor,
4456 workspace,
4457 project_transaction,
4458 title,
4459 cx,
4460 )
4461 .await
4462 }))
4463 }
4464 }
4465 }
4466
4467 pub async fn open_project_transaction(
4468 this: &WeakEntity<Editor>,
4469 workspace: WeakEntity<Workspace>,
4470 transaction: ProjectTransaction,
4471 title: String,
4472 mut cx: AsyncWindowContext,
4473 ) -> Result<()> {
4474 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4475 cx.update(|_, cx| {
4476 entries.sort_unstable_by_key(|(buffer, _)| {
4477 buffer.read(cx).file().map(|f| f.path().clone())
4478 });
4479 })?;
4480
4481 // If the project transaction's edits are all contained within this editor, then
4482 // avoid opening a new editor to display them.
4483
4484 if let Some((buffer, transaction)) = entries.first() {
4485 if entries.len() == 1 {
4486 let excerpt = this.update(&mut cx, |editor, cx| {
4487 editor
4488 .buffer()
4489 .read(cx)
4490 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4491 })?;
4492 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4493 if excerpted_buffer == *buffer {
4494 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4495 let excerpt_range = excerpt_range.to_offset(buffer);
4496 buffer
4497 .edited_ranges_for_transaction::<usize>(transaction)
4498 .all(|range| {
4499 excerpt_range.start <= range.start
4500 && excerpt_range.end >= range.end
4501 })
4502 })?;
4503
4504 if all_edits_within_excerpt {
4505 return Ok(());
4506 }
4507 }
4508 }
4509 }
4510 } else {
4511 return Ok(());
4512 }
4513
4514 let mut ranges_to_highlight = Vec::new();
4515 let excerpt_buffer = cx.new(|cx| {
4516 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4517 for (buffer_handle, transaction) in &entries {
4518 let buffer = buffer_handle.read(cx);
4519 ranges_to_highlight.extend(
4520 multibuffer.push_excerpts_with_context_lines(
4521 buffer_handle.clone(),
4522 buffer
4523 .edited_ranges_for_transaction::<usize>(transaction)
4524 .collect(),
4525 DEFAULT_MULTIBUFFER_CONTEXT,
4526 cx,
4527 ),
4528 );
4529 }
4530 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4531 multibuffer
4532 })?;
4533
4534 workspace.update_in(&mut cx, |workspace, window, cx| {
4535 let project = workspace.project().clone();
4536 let editor = cx
4537 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4538 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4539 editor.update(cx, |editor, cx| {
4540 editor.highlight_background::<Self>(
4541 &ranges_to_highlight,
4542 |theme| theme.editor_highlighted_line_background,
4543 cx,
4544 );
4545 });
4546 })?;
4547
4548 Ok(())
4549 }
4550
4551 pub fn clear_code_action_providers(&mut self) {
4552 self.code_action_providers.clear();
4553 self.available_code_actions.take();
4554 }
4555
4556 pub fn add_code_action_provider(
4557 &mut self,
4558 provider: Rc<dyn CodeActionProvider>,
4559 window: &mut Window,
4560 cx: &mut Context<Self>,
4561 ) {
4562 if self
4563 .code_action_providers
4564 .iter()
4565 .any(|existing_provider| existing_provider.id() == provider.id())
4566 {
4567 return;
4568 }
4569
4570 self.code_action_providers.push(provider);
4571 self.refresh_code_actions(window, cx);
4572 }
4573
4574 pub fn remove_code_action_provider(
4575 &mut self,
4576 id: Arc<str>,
4577 window: &mut Window,
4578 cx: &mut Context<Self>,
4579 ) {
4580 self.code_action_providers
4581 .retain(|provider| provider.id() != id);
4582 self.refresh_code_actions(window, cx);
4583 }
4584
4585 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4586 let buffer = self.buffer.read(cx);
4587 let newest_selection = self.selections.newest_anchor().clone();
4588 if newest_selection.head().diff_base_anchor.is_some() {
4589 return None;
4590 }
4591 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4592 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4593 if start_buffer != end_buffer {
4594 return None;
4595 }
4596
4597 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4598 cx.background_executor()
4599 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4600 .await;
4601
4602 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4603 let providers = this.code_action_providers.clone();
4604 let tasks = this
4605 .code_action_providers
4606 .iter()
4607 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4608 .collect::<Vec<_>>();
4609 (providers, tasks)
4610 })?;
4611
4612 let mut actions = Vec::new();
4613 for (provider, provider_actions) in
4614 providers.into_iter().zip(future::join_all(tasks).await)
4615 {
4616 if let Some(provider_actions) = provider_actions.log_err() {
4617 actions.extend(provider_actions.into_iter().map(|action| {
4618 AvailableCodeAction {
4619 excerpt_id: newest_selection.start.excerpt_id,
4620 action,
4621 provider: provider.clone(),
4622 }
4623 }));
4624 }
4625 }
4626
4627 this.update(&mut cx, |this, cx| {
4628 this.available_code_actions = if actions.is_empty() {
4629 None
4630 } else {
4631 Some((
4632 Location {
4633 buffer: start_buffer,
4634 range: start..end,
4635 },
4636 actions.into(),
4637 ))
4638 };
4639 cx.notify();
4640 })
4641 }));
4642 None
4643 }
4644
4645 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4646 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4647 self.show_git_blame_inline = false;
4648
4649 self.show_git_blame_inline_delay_task =
4650 Some(cx.spawn_in(window, |this, mut cx| async move {
4651 cx.background_executor().timer(delay).await;
4652
4653 this.update(&mut cx, |this, cx| {
4654 this.show_git_blame_inline = true;
4655 cx.notify();
4656 })
4657 .log_err();
4658 }));
4659 }
4660 }
4661
4662 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4663 if self.pending_rename.is_some() {
4664 return None;
4665 }
4666
4667 let provider = self.semantics_provider.clone()?;
4668 let buffer = self.buffer.read(cx);
4669 let newest_selection = self.selections.newest_anchor().clone();
4670 let cursor_position = newest_selection.head();
4671 let (cursor_buffer, cursor_buffer_position) =
4672 buffer.text_anchor_for_position(cursor_position, cx)?;
4673 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4674 if cursor_buffer != tail_buffer {
4675 return None;
4676 }
4677 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4678 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4679 cx.background_executor()
4680 .timer(Duration::from_millis(debounce))
4681 .await;
4682
4683 let highlights = if let Some(highlights) = cx
4684 .update(|cx| {
4685 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4686 })
4687 .ok()
4688 .flatten()
4689 {
4690 highlights.await.log_err()
4691 } else {
4692 None
4693 };
4694
4695 if let Some(highlights) = highlights {
4696 this.update(&mut cx, |this, cx| {
4697 if this.pending_rename.is_some() {
4698 return;
4699 }
4700
4701 let buffer_id = cursor_position.buffer_id;
4702 let buffer = this.buffer.read(cx);
4703 if !buffer
4704 .text_anchor_for_position(cursor_position, cx)
4705 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4706 {
4707 return;
4708 }
4709
4710 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4711 let mut write_ranges = Vec::new();
4712 let mut read_ranges = Vec::new();
4713 for highlight in highlights {
4714 for (excerpt_id, excerpt_range) in
4715 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4716 {
4717 let start = highlight
4718 .range
4719 .start
4720 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4721 let end = highlight
4722 .range
4723 .end
4724 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4725 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4726 continue;
4727 }
4728
4729 let range = Anchor {
4730 buffer_id,
4731 excerpt_id,
4732 text_anchor: start,
4733 diff_base_anchor: None,
4734 }..Anchor {
4735 buffer_id,
4736 excerpt_id,
4737 text_anchor: end,
4738 diff_base_anchor: None,
4739 };
4740 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4741 write_ranges.push(range);
4742 } else {
4743 read_ranges.push(range);
4744 }
4745 }
4746 }
4747
4748 this.highlight_background::<DocumentHighlightRead>(
4749 &read_ranges,
4750 |theme| theme.editor_document_highlight_read_background,
4751 cx,
4752 );
4753 this.highlight_background::<DocumentHighlightWrite>(
4754 &write_ranges,
4755 |theme| theme.editor_document_highlight_write_background,
4756 cx,
4757 );
4758 cx.notify();
4759 })
4760 .log_err();
4761 }
4762 }));
4763 None
4764 }
4765
4766 pub fn refresh_selected_text_highlights(
4767 &mut self,
4768 window: &mut Window,
4769 cx: &mut Context<Editor>,
4770 ) {
4771 self.selection_highlight_task.take();
4772 if !EditorSettings::get_global(cx).selection_highlight {
4773 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4774 return;
4775 }
4776 if self.selections.count() != 1 || self.selections.line_mode {
4777 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4778 return;
4779 }
4780 let selection = self.selections.newest::<Point>(cx);
4781 if selection.is_empty() || selection.start.row != selection.end.row {
4782 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4783 return;
4784 }
4785 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4786 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4787 cx.background_executor()
4788 .timer(Duration::from_millis(debounce))
4789 .await;
4790 let Some(matches_task) = editor
4791 .read_with(&mut cx, |editor, cx| {
4792 let buffer = editor.buffer().read(cx).snapshot(cx);
4793 cx.background_executor().spawn(async move {
4794 let mut ranges = Vec::new();
4795 let buffer_ranges =
4796 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
4797 let query = buffer.text_for_range(selection.range()).collect::<String>();
4798 for range in buffer_ranges {
4799 for (search_buffer, search_range, excerpt_id) in
4800 buffer.range_to_buffer_ranges(range)
4801 {
4802 ranges.extend(
4803 project::search::SearchQuery::text(
4804 query.clone(),
4805 false,
4806 false,
4807 false,
4808 Default::default(),
4809 Default::default(),
4810 None,
4811 )
4812 .unwrap()
4813 .search(search_buffer, Some(search_range.clone()))
4814 .await
4815 .into_iter()
4816 .map(|match_range| {
4817 let start = search_buffer
4818 .anchor_after(search_range.start + match_range.start);
4819 let end = search_buffer
4820 .anchor_before(search_range.start + match_range.end);
4821 Anchor::range_in_buffer(
4822 excerpt_id,
4823 search_buffer.remote_id(),
4824 start..end,
4825 )
4826 }),
4827 );
4828 }
4829 }
4830 ranges
4831 })
4832 })
4833 .log_err()
4834 else {
4835 return;
4836 };
4837 let matches = matches_task.await;
4838 editor
4839 .update_in(&mut cx, |editor, _, cx| {
4840 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4841 if !matches.is_empty() {
4842 editor.highlight_background::<SelectedTextHighlight>(
4843 &matches,
4844 |theme| theme.editor_document_highlight_bracket_background,
4845 cx,
4846 )
4847 }
4848 })
4849 .log_err();
4850 }));
4851 }
4852
4853 pub fn refresh_inline_completion(
4854 &mut self,
4855 debounce: bool,
4856 user_requested: bool,
4857 window: &mut Window,
4858 cx: &mut Context<Self>,
4859 ) -> Option<()> {
4860 let provider = self.edit_prediction_provider()?;
4861 let cursor = self.selections.newest_anchor().head();
4862 let (buffer, cursor_buffer_position) =
4863 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4864
4865 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4866 self.discard_inline_completion(false, cx);
4867 return None;
4868 }
4869
4870 if !user_requested
4871 && (!self.should_show_edit_predictions()
4872 || !self.is_focused(window)
4873 || buffer.read(cx).is_empty())
4874 {
4875 self.discard_inline_completion(false, cx);
4876 return None;
4877 }
4878
4879 self.update_visible_inline_completion(window, cx);
4880 provider.refresh(
4881 self.project.clone(),
4882 buffer,
4883 cursor_buffer_position,
4884 debounce,
4885 cx,
4886 );
4887 Some(())
4888 }
4889
4890 fn show_edit_predictions_in_menu(&self) -> bool {
4891 match self.edit_prediction_settings {
4892 EditPredictionSettings::Disabled => false,
4893 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4894 }
4895 }
4896
4897 pub fn edit_predictions_enabled(&self) -> bool {
4898 match self.edit_prediction_settings {
4899 EditPredictionSettings::Disabled => false,
4900 EditPredictionSettings::Enabled { .. } => true,
4901 }
4902 }
4903
4904 fn edit_prediction_requires_modifier(&self) -> bool {
4905 match self.edit_prediction_settings {
4906 EditPredictionSettings::Disabled => false,
4907 EditPredictionSettings::Enabled {
4908 preview_requires_modifier,
4909 ..
4910 } => preview_requires_modifier,
4911 }
4912 }
4913
4914 fn edit_prediction_settings_at_position(
4915 &self,
4916 buffer: &Entity<Buffer>,
4917 buffer_position: language::Anchor,
4918 cx: &App,
4919 ) -> EditPredictionSettings {
4920 if self.mode != EditorMode::Full
4921 || !self.show_inline_completions_override.unwrap_or(true)
4922 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4923 {
4924 return EditPredictionSettings::Disabled;
4925 }
4926
4927 let buffer = buffer.read(cx);
4928
4929 let file = buffer.file();
4930
4931 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4932 return EditPredictionSettings::Disabled;
4933 };
4934
4935 let by_provider = matches!(
4936 self.menu_inline_completions_policy,
4937 MenuInlineCompletionsPolicy::ByProvider
4938 );
4939
4940 let show_in_menu = by_provider
4941 && self
4942 .edit_prediction_provider
4943 .as_ref()
4944 .map_or(false, |provider| {
4945 provider.provider.show_completions_in_menu()
4946 });
4947
4948 let preview_requires_modifier =
4949 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4950
4951 EditPredictionSettings::Enabled {
4952 show_in_menu,
4953 preview_requires_modifier,
4954 }
4955 }
4956
4957 fn should_show_edit_predictions(&self) -> bool {
4958 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4959 }
4960
4961 pub fn edit_prediction_preview_is_active(&self) -> bool {
4962 matches!(
4963 self.edit_prediction_preview,
4964 EditPredictionPreview::Active { .. }
4965 )
4966 }
4967
4968 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4969 let cursor = self.selections.newest_anchor().head();
4970 if let Some((buffer, cursor_position)) =
4971 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4972 {
4973 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4974 } else {
4975 false
4976 }
4977 }
4978
4979 fn inline_completions_enabled_in_buffer(
4980 &self,
4981 buffer: &Entity<Buffer>,
4982 buffer_position: language::Anchor,
4983 cx: &App,
4984 ) -> bool {
4985 maybe!({
4986 let provider = self.edit_prediction_provider()?;
4987 if !provider.is_enabled(&buffer, buffer_position, cx) {
4988 return Some(false);
4989 }
4990 let buffer = buffer.read(cx);
4991 let Some(file) = buffer.file() else {
4992 return Some(true);
4993 };
4994 let settings = all_language_settings(Some(file), cx);
4995 Some(settings.inline_completions_enabled_for_path(file.path()))
4996 })
4997 .unwrap_or(false)
4998 }
4999
5000 fn cycle_inline_completion(
5001 &mut self,
5002 direction: Direction,
5003 window: &mut Window,
5004 cx: &mut Context<Self>,
5005 ) -> Option<()> {
5006 let provider = self.edit_prediction_provider()?;
5007 let cursor = self.selections.newest_anchor().head();
5008 let (buffer, cursor_buffer_position) =
5009 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5010 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5011 return None;
5012 }
5013
5014 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5015 self.update_visible_inline_completion(window, cx);
5016
5017 Some(())
5018 }
5019
5020 pub fn show_inline_completion(
5021 &mut self,
5022 _: &ShowEditPrediction,
5023 window: &mut Window,
5024 cx: &mut Context<Self>,
5025 ) {
5026 if !self.has_active_inline_completion() {
5027 self.refresh_inline_completion(false, true, window, cx);
5028 return;
5029 }
5030
5031 self.update_visible_inline_completion(window, cx);
5032 }
5033
5034 pub fn display_cursor_names(
5035 &mut self,
5036 _: &DisplayCursorNames,
5037 window: &mut Window,
5038 cx: &mut Context<Self>,
5039 ) {
5040 self.show_cursor_names(window, cx);
5041 }
5042
5043 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5044 self.show_cursor_names = true;
5045 cx.notify();
5046 cx.spawn_in(window, |this, mut cx| async move {
5047 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5048 this.update(&mut cx, |this, cx| {
5049 this.show_cursor_names = false;
5050 cx.notify()
5051 })
5052 .ok()
5053 })
5054 .detach();
5055 }
5056
5057 pub fn next_edit_prediction(
5058 &mut self,
5059 _: &NextEditPrediction,
5060 window: &mut Window,
5061 cx: &mut Context<Self>,
5062 ) {
5063 if self.has_active_inline_completion() {
5064 self.cycle_inline_completion(Direction::Next, window, cx);
5065 } else {
5066 let is_copilot_disabled = self
5067 .refresh_inline_completion(false, true, window, cx)
5068 .is_none();
5069 if is_copilot_disabled {
5070 cx.propagate();
5071 }
5072 }
5073 }
5074
5075 pub fn previous_edit_prediction(
5076 &mut self,
5077 _: &PreviousEditPrediction,
5078 window: &mut Window,
5079 cx: &mut Context<Self>,
5080 ) {
5081 if self.has_active_inline_completion() {
5082 self.cycle_inline_completion(Direction::Prev, window, cx);
5083 } else {
5084 let is_copilot_disabled = self
5085 .refresh_inline_completion(false, true, window, cx)
5086 .is_none();
5087 if is_copilot_disabled {
5088 cx.propagate();
5089 }
5090 }
5091 }
5092
5093 pub fn accept_edit_prediction(
5094 &mut self,
5095 _: &AcceptEditPrediction,
5096 window: &mut Window,
5097 cx: &mut Context<Self>,
5098 ) {
5099 if self.show_edit_predictions_in_menu() {
5100 self.hide_context_menu(window, cx);
5101 }
5102
5103 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5104 return;
5105 };
5106
5107 self.report_inline_completion_event(
5108 active_inline_completion.completion_id.clone(),
5109 true,
5110 cx,
5111 );
5112
5113 match &active_inline_completion.completion {
5114 InlineCompletion::Move { target, .. } => {
5115 let target = *target;
5116
5117 if let Some(position_map) = &self.last_position_map {
5118 if position_map
5119 .visible_row_range
5120 .contains(&target.to_display_point(&position_map.snapshot).row())
5121 || !self.edit_prediction_requires_modifier()
5122 {
5123 // Note that this is also done in vim's handler of the Tab action.
5124 self.change_selections(
5125 Some(Autoscroll::newest()),
5126 window,
5127 cx,
5128 |selections| {
5129 selections.select_anchor_ranges([target..target]);
5130 },
5131 );
5132 self.clear_row_highlights::<EditPredictionPreview>();
5133
5134 self.edit_prediction_preview = EditPredictionPreview::Active {
5135 previous_scroll_position: None,
5136 };
5137 } else {
5138 self.edit_prediction_preview = EditPredictionPreview::Active {
5139 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5140 };
5141 self.highlight_rows::<EditPredictionPreview>(
5142 target..target,
5143 cx.theme().colors().editor_highlighted_line_background,
5144 true,
5145 cx,
5146 );
5147 self.request_autoscroll(Autoscroll::fit(), cx);
5148 }
5149 }
5150 }
5151 InlineCompletion::Edit { edits, .. } => {
5152 if let Some(provider) = self.edit_prediction_provider() {
5153 provider.accept(cx);
5154 }
5155
5156 let snapshot = self.buffer.read(cx).snapshot(cx);
5157 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5158
5159 self.buffer.update(cx, |buffer, cx| {
5160 buffer.edit(edits.iter().cloned(), None, cx)
5161 });
5162
5163 self.change_selections(None, window, cx, |s| {
5164 s.select_anchor_ranges([last_edit_end..last_edit_end])
5165 });
5166
5167 self.update_visible_inline_completion(window, cx);
5168 if self.active_inline_completion.is_none() {
5169 self.refresh_inline_completion(true, true, window, cx);
5170 }
5171
5172 cx.notify();
5173 }
5174 }
5175
5176 self.edit_prediction_requires_modifier_in_leading_space = false;
5177 }
5178
5179 pub fn accept_partial_inline_completion(
5180 &mut self,
5181 _: &AcceptPartialEditPrediction,
5182 window: &mut Window,
5183 cx: &mut Context<Self>,
5184 ) {
5185 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5186 return;
5187 };
5188 if self.selections.count() != 1 {
5189 return;
5190 }
5191
5192 self.report_inline_completion_event(
5193 active_inline_completion.completion_id.clone(),
5194 true,
5195 cx,
5196 );
5197
5198 match &active_inline_completion.completion {
5199 InlineCompletion::Move { target, .. } => {
5200 let target = *target;
5201 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5202 selections.select_anchor_ranges([target..target]);
5203 });
5204 }
5205 InlineCompletion::Edit { edits, .. } => {
5206 // Find an insertion that starts at the cursor position.
5207 let snapshot = self.buffer.read(cx).snapshot(cx);
5208 let cursor_offset = self.selections.newest::<usize>(cx).head();
5209 let insertion = edits.iter().find_map(|(range, text)| {
5210 let range = range.to_offset(&snapshot);
5211 if range.is_empty() && range.start == cursor_offset {
5212 Some(text)
5213 } else {
5214 None
5215 }
5216 });
5217
5218 if let Some(text) = insertion {
5219 let mut partial_completion = text
5220 .chars()
5221 .by_ref()
5222 .take_while(|c| c.is_alphabetic())
5223 .collect::<String>();
5224 if partial_completion.is_empty() {
5225 partial_completion = text
5226 .chars()
5227 .by_ref()
5228 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5229 .collect::<String>();
5230 }
5231
5232 cx.emit(EditorEvent::InputHandled {
5233 utf16_range_to_replace: None,
5234 text: partial_completion.clone().into(),
5235 });
5236
5237 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5238
5239 self.refresh_inline_completion(true, true, window, cx);
5240 cx.notify();
5241 } else {
5242 self.accept_edit_prediction(&Default::default(), window, cx);
5243 }
5244 }
5245 }
5246 }
5247
5248 fn discard_inline_completion(
5249 &mut self,
5250 should_report_inline_completion_event: bool,
5251 cx: &mut Context<Self>,
5252 ) -> bool {
5253 if should_report_inline_completion_event {
5254 let completion_id = self
5255 .active_inline_completion
5256 .as_ref()
5257 .and_then(|active_completion| active_completion.completion_id.clone());
5258
5259 self.report_inline_completion_event(completion_id, false, cx);
5260 }
5261
5262 if let Some(provider) = self.edit_prediction_provider() {
5263 provider.discard(cx);
5264 }
5265
5266 self.take_active_inline_completion(cx)
5267 }
5268
5269 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5270 let Some(provider) = self.edit_prediction_provider() else {
5271 return;
5272 };
5273
5274 let Some((_, buffer, _)) = self
5275 .buffer
5276 .read(cx)
5277 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5278 else {
5279 return;
5280 };
5281
5282 let extension = buffer
5283 .read(cx)
5284 .file()
5285 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5286
5287 let event_type = match accepted {
5288 true => "Edit Prediction Accepted",
5289 false => "Edit Prediction Discarded",
5290 };
5291 telemetry::event!(
5292 event_type,
5293 provider = provider.name(),
5294 prediction_id = id,
5295 suggestion_accepted = accepted,
5296 file_extension = extension,
5297 );
5298 }
5299
5300 pub fn has_active_inline_completion(&self) -> bool {
5301 self.active_inline_completion.is_some()
5302 }
5303
5304 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5305 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5306 return false;
5307 };
5308
5309 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5310 self.clear_highlights::<InlineCompletionHighlight>(cx);
5311 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5312 true
5313 }
5314
5315 /// Returns true when we're displaying the edit prediction popover below the cursor
5316 /// like we are not previewing and the LSP autocomplete menu is visible
5317 /// or we are in `when_holding_modifier` mode.
5318 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5319 if self.edit_prediction_preview_is_active()
5320 || !self.show_edit_predictions_in_menu()
5321 || !self.edit_predictions_enabled()
5322 {
5323 return false;
5324 }
5325
5326 if self.has_visible_completions_menu() {
5327 return true;
5328 }
5329
5330 has_completion && self.edit_prediction_requires_modifier()
5331 }
5332
5333 fn handle_modifiers_changed(
5334 &mut self,
5335 modifiers: Modifiers,
5336 position_map: &PositionMap,
5337 window: &mut Window,
5338 cx: &mut Context<Self>,
5339 ) {
5340 if self.show_edit_predictions_in_menu() {
5341 self.update_edit_prediction_preview(&modifiers, window, cx);
5342 }
5343
5344 let mouse_position = window.mouse_position();
5345 if !position_map.text_hitbox.is_hovered(window) {
5346 return;
5347 }
5348
5349 self.update_hovered_link(
5350 position_map.point_for_position(mouse_position),
5351 &position_map.snapshot,
5352 modifiers,
5353 window,
5354 cx,
5355 )
5356 }
5357
5358 fn update_edit_prediction_preview(
5359 &mut self,
5360 modifiers: &Modifiers,
5361 window: &mut Window,
5362 cx: &mut Context<Self>,
5363 ) {
5364 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5365 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5366 return;
5367 };
5368
5369 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5370 if matches!(
5371 self.edit_prediction_preview,
5372 EditPredictionPreview::Inactive
5373 ) {
5374 self.edit_prediction_preview = EditPredictionPreview::Active {
5375 previous_scroll_position: None,
5376 };
5377
5378 self.update_visible_inline_completion(window, cx);
5379 cx.notify();
5380 }
5381 } else if let EditPredictionPreview::Active {
5382 previous_scroll_position,
5383 } = self.edit_prediction_preview
5384 {
5385 if let (Some(previous_scroll_position), Some(position_map)) =
5386 (previous_scroll_position, self.last_position_map.as_ref())
5387 {
5388 self.set_scroll_position(
5389 previous_scroll_position
5390 .scroll_position(&position_map.snapshot.display_snapshot),
5391 window,
5392 cx,
5393 );
5394 }
5395
5396 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5397 self.clear_row_highlights::<EditPredictionPreview>();
5398 self.update_visible_inline_completion(window, cx);
5399 cx.notify();
5400 }
5401 }
5402
5403 fn update_visible_inline_completion(
5404 &mut self,
5405 _window: &mut Window,
5406 cx: &mut Context<Self>,
5407 ) -> Option<()> {
5408 let selection = self.selections.newest_anchor();
5409 let cursor = selection.head();
5410 let multibuffer = self.buffer.read(cx).snapshot(cx);
5411 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5412 let excerpt_id = cursor.excerpt_id;
5413
5414 let show_in_menu = self.show_edit_predictions_in_menu();
5415 let completions_menu_has_precedence = !show_in_menu
5416 && (self.context_menu.borrow().is_some()
5417 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5418
5419 if completions_menu_has_precedence
5420 || !offset_selection.is_empty()
5421 || self
5422 .active_inline_completion
5423 .as_ref()
5424 .map_or(false, |completion| {
5425 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5426 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5427 !invalidation_range.contains(&offset_selection.head())
5428 })
5429 {
5430 self.discard_inline_completion(false, cx);
5431 return None;
5432 }
5433
5434 self.take_active_inline_completion(cx);
5435 let Some(provider) = self.edit_prediction_provider() else {
5436 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5437 return None;
5438 };
5439
5440 let (buffer, cursor_buffer_position) =
5441 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5442
5443 self.edit_prediction_settings =
5444 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5445
5446 self.edit_prediction_cursor_on_leading_whitespace =
5447 multibuffer.is_line_whitespace_upto(cursor);
5448
5449 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5450 let edits = inline_completion
5451 .edits
5452 .into_iter()
5453 .flat_map(|(range, new_text)| {
5454 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5455 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5456 Some((start..end, new_text))
5457 })
5458 .collect::<Vec<_>>();
5459 if edits.is_empty() {
5460 return None;
5461 }
5462
5463 let first_edit_start = edits.first().unwrap().0.start;
5464 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5465 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5466
5467 let last_edit_end = edits.last().unwrap().0.end;
5468 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5469 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5470
5471 let cursor_row = cursor.to_point(&multibuffer).row;
5472
5473 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5474
5475 let mut inlay_ids = Vec::new();
5476 let invalidation_row_range;
5477 let move_invalidation_row_range = if cursor_row < edit_start_row {
5478 Some(cursor_row..edit_end_row)
5479 } else if cursor_row > edit_end_row {
5480 Some(edit_start_row..cursor_row)
5481 } else {
5482 None
5483 };
5484 let is_move =
5485 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5486 let completion = if is_move {
5487 invalidation_row_range =
5488 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5489 let target = first_edit_start;
5490 InlineCompletion::Move { target, snapshot }
5491 } else {
5492 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5493 && !self.inline_completions_hidden_for_vim_mode;
5494
5495 if show_completions_in_buffer {
5496 if edits
5497 .iter()
5498 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5499 {
5500 let mut inlays = Vec::new();
5501 for (range, new_text) in &edits {
5502 let inlay = Inlay::inline_completion(
5503 post_inc(&mut self.next_inlay_id),
5504 range.start,
5505 new_text.as_str(),
5506 );
5507 inlay_ids.push(inlay.id);
5508 inlays.push(inlay);
5509 }
5510
5511 self.splice_inlays(&[], inlays, cx);
5512 } else {
5513 let background_color = cx.theme().status().deleted_background;
5514 self.highlight_text::<InlineCompletionHighlight>(
5515 edits.iter().map(|(range, _)| range.clone()).collect(),
5516 HighlightStyle {
5517 background_color: Some(background_color),
5518 ..Default::default()
5519 },
5520 cx,
5521 );
5522 }
5523 }
5524
5525 invalidation_row_range = edit_start_row..edit_end_row;
5526
5527 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5528 if provider.show_tab_accept_marker() {
5529 EditDisplayMode::TabAccept
5530 } else {
5531 EditDisplayMode::Inline
5532 }
5533 } else {
5534 EditDisplayMode::DiffPopover
5535 };
5536
5537 InlineCompletion::Edit {
5538 edits,
5539 edit_preview: inline_completion.edit_preview,
5540 display_mode,
5541 snapshot,
5542 }
5543 };
5544
5545 let invalidation_range = multibuffer
5546 .anchor_before(Point::new(invalidation_row_range.start, 0))
5547 ..multibuffer.anchor_after(Point::new(
5548 invalidation_row_range.end,
5549 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5550 ));
5551
5552 self.stale_inline_completion_in_menu = None;
5553 self.active_inline_completion = Some(InlineCompletionState {
5554 inlay_ids,
5555 completion,
5556 completion_id: inline_completion.id,
5557 invalidation_range,
5558 });
5559
5560 cx.notify();
5561
5562 Some(())
5563 }
5564
5565 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5566 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5567 }
5568
5569 fn render_code_actions_indicator(
5570 &self,
5571 _style: &EditorStyle,
5572 row: DisplayRow,
5573 is_active: bool,
5574 cx: &mut Context<Self>,
5575 ) -> Option<IconButton> {
5576 if self.available_code_actions.is_some() {
5577 Some(
5578 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5579 .shape(ui::IconButtonShape::Square)
5580 .icon_size(IconSize::XSmall)
5581 .icon_color(Color::Muted)
5582 .toggle_state(is_active)
5583 .tooltip({
5584 let focus_handle = self.focus_handle.clone();
5585 move |window, cx| {
5586 Tooltip::for_action_in(
5587 "Toggle Code Actions",
5588 &ToggleCodeActions {
5589 deployed_from_indicator: None,
5590 },
5591 &focus_handle,
5592 window,
5593 cx,
5594 )
5595 }
5596 })
5597 .on_click(cx.listener(move |editor, _e, window, cx| {
5598 window.focus(&editor.focus_handle(cx));
5599 editor.toggle_code_actions(
5600 &ToggleCodeActions {
5601 deployed_from_indicator: Some(row),
5602 },
5603 window,
5604 cx,
5605 );
5606 })),
5607 )
5608 } else {
5609 None
5610 }
5611 }
5612
5613 fn clear_tasks(&mut self) {
5614 self.tasks.clear()
5615 }
5616
5617 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5618 if self.tasks.insert(key, value).is_some() {
5619 // This case should hopefully be rare, but just in case...
5620 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5621 }
5622 }
5623
5624 fn build_tasks_context(
5625 project: &Entity<Project>,
5626 buffer: &Entity<Buffer>,
5627 buffer_row: u32,
5628 tasks: &Arc<RunnableTasks>,
5629 cx: &mut Context<Self>,
5630 ) -> Task<Option<task::TaskContext>> {
5631 let position = Point::new(buffer_row, tasks.column);
5632 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5633 let location = Location {
5634 buffer: buffer.clone(),
5635 range: range_start..range_start,
5636 };
5637 // Fill in the environmental variables from the tree-sitter captures
5638 let mut captured_task_variables = TaskVariables::default();
5639 for (capture_name, value) in tasks.extra_variables.clone() {
5640 captured_task_variables.insert(
5641 task::VariableName::Custom(capture_name.into()),
5642 value.clone(),
5643 );
5644 }
5645 project.update(cx, |project, cx| {
5646 project.task_store().update(cx, |task_store, cx| {
5647 task_store.task_context_for_location(captured_task_variables, location, cx)
5648 })
5649 })
5650 }
5651
5652 pub fn spawn_nearest_task(
5653 &mut self,
5654 action: &SpawnNearestTask,
5655 window: &mut Window,
5656 cx: &mut Context<Self>,
5657 ) {
5658 let Some((workspace, _)) = self.workspace.clone() else {
5659 return;
5660 };
5661 let Some(project) = self.project.clone() else {
5662 return;
5663 };
5664
5665 // Try to find a closest, enclosing node using tree-sitter that has a
5666 // task
5667 let Some((buffer, buffer_row, tasks)) = self
5668 .find_enclosing_node_task(cx)
5669 // Or find the task that's closest in row-distance.
5670 .or_else(|| self.find_closest_task(cx))
5671 else {
5672 return;
5673 };
5674
5675 let reveal_strategy = action.reveal;
5676 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5677 cx.spawn_in(window, |_, mut cx| async move {
5678 let context = task_context.await?;
5679 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5680
5681 let resolved = resolved_task.resolved.as_mut()?;
5682 resolved.reveal = reveal_strategy;
5683
5684 workspace
5685 .update(&mut cx, |workspace, cx| {
5686 workspace::tasks::schedule_resolved_task(
5687 workspace,
5688 task_source_kind,
5689 resolved_task,
5690 false,
5691 cx,
5692 );
5693 })
5694 .ok()
5695 })
5696 .detach();
5697 }
5698
5699 fn find_closest_task(
5700 &mut self,
5701 cx: &mut Context<Self>,
5702 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5703 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5704
5705 let ((buffer_id, row), tasks) = self
5706 .tasks
5707 .iter()
5708 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5709
5710 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5711 let tasks = Arc::new(tasks.to_owned());
5712 Some((buffer, *row, tasks))
5713 }
5714
5715 fn find_enclosing_node_task(
5716 &mut self,
5717 cx: &mut Context<Self>,
5718 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5719 let snapshot = self.buffer.read(cx).snapshot(cx);
5720 let offset = self.selections.newest::<usize>(cx).head();
5721 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5722 let buffer_id = excerpt.buffer().remote_id();
5723
5724 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5725 let mut cursor = layer.node().walk();
5726
5727 while cursor.goto_first_child_for_byte(offset).is_some() {
5728 if cursor.node().end_byte() == offset {
5729 cursor.goto_next_sibling();
5730 }
5731 }
5732
5733 // Ascend to the smallest ancestor that contains the range and has a task.
5734 loop {
5735 let node = cursor.node();
5736 let node_range = node.byte_range();
5737 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5738
5739 // Check if this node contains our offset
5740 if node_range.start <= offset && node_range.end >= offset {
5741 // If it contains offset, check for task
5742 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5743 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5744 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5745 }
5746 }
5747
5748 if !cursor.goto_parent() {
5749 break;
5750 }
5751 }
5752 None
5753 }
5754
5755 fn render_run_indicator(
5756 &self,
5757 _style: &EditorStyle,
5758 is_active: bool,
5759 row: DisplayRow,
5760 cx: &mut Context<Self>,
5761 ) -> IconButton {
5762 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5763 .shape(ui::IconButtonShape::Square)
5764 .icon_size(IconSize::XSmall)
5765 .icon_color(Color::Muted)
5766 .toggle_state(is_active)
5767 .on_click(cx.listener(move |editor, _e, window, cx| {
5768 window.focus(&editor.focus_handle(cx));
5769 editor.toggle_code_actions(
5770 &ToggleCodeActions {
5771 deployed_from_indicator: Some(row),
5772 },
5773 window,
5774 cx,
5775 );
5776 }))
5777 }
5778
5779 pub fn context_menu_visible(&self) -> bool {
5780 !self.edit_prediction_preview_is_active()
5781 && self
5782 .context_menu
5783 .borrow()
5784 .as_ref()
5785 .map_or(false, |menu| menu.visible())
5786 }
5787
5788 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5789 self.context_menu
5790 .borrow()
5791 .as_ref()
5792 .map(|menu| menu.origin())
5793 }
5794
5795 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5796 px(30.)
5797 }
5798
5799 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5800 if self.read_only(cx) {
5801 cx.theme().players().read_only()
5802 } else {
5803 self.style.as_ref().unwrap().local_player
5804 }
5805 }
5806
5807 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5808 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5809 let accept_keystroke = accept_binding.keystroke()?;
5810
5811 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5812
5813 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5814 Color::Accent
5815 } else {
5816 Color::Muted
5817 };
5818
5819 h_flex()
5820 .px_0p5()
5821 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5822 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5823 .text_size(TextSize::XSmall.rems(cx))
5824 .child(h_flex().children(ui::render_modifiers(
5825 &accept_keystroke.modifiers,
5826 PlatformStyle::platform(),
5827 Some(modifiers_color),
5828 Some(IconSize::XSmall.rems().into()),
5829 true,
5830 )))
5831 .when(is_platform_style_mac, |parent| {
5832 parent.child(accept_keystroke.key.clone())
5833 })
5834 .when(!is_platform_style_mac, |parent| {
5835 parent.child(
5836 Key::new(
5837 util::capitalize(&accept_keystroke.key),
5838 Some(Color::Default),
5839 )
5840 .size(Some(IconSize::XSmall.rems().into())),
5841 )
5842 })
5843 .into()
5844 }
5845
5846 fn render_edit_prediction_line_popover(
5847 &self,
5848 label: impl Into<SharedString>,
5849 icon: Option<IconName>,
5850 window: &mut Window,
5851 cx: &App,
5852 ) -> Option<Div> {
5853 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5854
5855 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5856
5857 let result = h_flex()
5858 .gap_1()
5859 .border_1()
5860 .rounded_lg()
5861 .shadow_sm()
5862 .bg(bg_color)
5863 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5864 .py_0p5()
5865 .pl_1()
5866 .pr(padding_right)
5867 .children(self.render_edit_prediction_accept_keybind(window, cx))
5868 .child(Label::new(label).size(LabelSize::Small))
5869 .when_some(icon, |element, icon| {
5870 element.child(
5871 div()
5872 .mt(px(1.5))
5873 .child(Icon::new(icon).size(IconSize::Small)),
5874 )
5875 });
5876
5877 Some(result)
5878 }
5879
5880 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5881 let accent_color = cx.theme().colors().text_accent;
5882 let editor_bg_color = cx.theme().colors().editor_background;
5883 editor_bg_color.blend(accent_color.opacity(0.1))
5884 }
5885
5886 #[allow(clippy::too_many_arguments)]
5887 fn render_edit_prediction_cursor_popover(
5888 &self,
5889 min_width: Pixels,
5890 max_width: Pixels,
5891 cursor_point: Point,
5892 style: &EditorStyle,
5893 accept_keystroke: Option<&gpui::Keystroke>,
5894 _window: &Window,
5895 cx: &mut Context<Editor>,
5896 ) -> Option<AnyElement> {
5897 let provider = self.edit_prediction_provider.as_ref()?;
5898
5899 if provider.provider.needs_terms_acceptance(cx) {
5900 return Some(
5901 h_flex()
5902 .min_w(min_width)
5903 .flex_1()
5904 .px_2()
5905 .py_1()
5906 .gap_3()
5907 .elevation_2(cx)
5908 .hover(|style| style.bg(cx.theme().colors().element_hover))
5909 .id("accept-terms")
5910 .cursor_pointer()
5911 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5912 .on_click(cx.listener(|this, _event, window, cx| {
5913 cx.stop_propagation();
5914 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5915 window.dispatch_action(
5916 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5917 cx,
5918 );
5919 }))
5920 .child(
5921 h_flex()
5922 .flex_1()
5923 .gap_2()
5924 .child(Icon::new(IconName::ZedPredict))
5925 .child(Label::new("Accept Terms of Service"))
5926 .child(div().w_full())
5927 .child(
5928 Icon::new(IconName::ArrowUpRight)
5929 .color(Color::Muted)
5930 .size(IconSize::Small),
5931 )
5932 .into_any_element(),
5933 )
5934 .into_any(),
5935 );
5936 }
5937
5938 let is_refreshing = provider.provider.is_refreshing(cx);
5939
5940 fn pending_completion_container() -> Div {
5941 h_flex()
5942 .h_full()
5943 .flex_1()
5944 .gap_2()
5945 .child(Icon::new(IconName::ZedPredict))
5946 }
5947
5948 let completion = match &self.active_inline_completion {
5949 Some(completion) => match &completion.completion {
5950 InlineCompletion::Move {
5951 target, snapshot, ..
5952 } if !self.has_visible_completions_menu() => {
5953 use text::ToPoint as _;
5954
5955 return Some(
5956 h_flex()
5957 .px_2()
5958 .py_1()
5959 .elevation_2(cx)
5960 .border_color(cx.theme().colors().border)
5961 .rounded_tl(px(0.))
5962 .gap_2()
5963 .child(
5964 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5965 Icon::new(IconName::ZedPredictDown)
5966 } else {
5967 Icon::new(IconName::ZedPredictUp)
5968 },
5969 )
5970 .child(Label::new("Hold").size(LabelSize::Small))
5971 .child(h_flex().children(ui::render_modifiers(
5972 &accept_keystroke?.modifiers,
5973 PlatformStyle::platform(),
5974 Some(Color::Default),
5975 Some(IconSize::Small.rems().into()),
5976 false,
5977 )))
5978 .into_any(),
5979 );
5980 }
5981 _ => self.render_edit_prediction_cursor_popover_preview(
5982 completion,
5983 cursor_point,
5984 style,
5985 cx,
5986 )?,
5987 },
5988
5989 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5990 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5991 stale_completion,
5992 cursor_point,
5993 style,
5994 cx,
5995 )?,
5996
5997 None => {
5998 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5999 }
6000 },
6001
6002 None => pending_completion_container().child(Label::new("No Prediction")),
6003 };
6004
6005 let completion = if is_refreshing {
6006 completion
6007 .with_animation(
6008 "loading-completion",
6009 Animation::new(Duration::from_secs(2))
6010 .repeat()
6011 .with_easing(pulsating_between(0.4, 0.8)),
6012 |label, delta| label.opacity(delta),
6013 )
6014 .into_any_element()
6015 } else {
6016 completion.into_any_element()
6017 };
6018
6019 let has_completion = self.active_inline_completion.is_some();
6020
6021 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6022 Some(
6023 h_flex()
6024 .min_w(min_width)
6025 .max_w(max_width)
6026 .flex_1()
6027 .elevation_2(cx)
6028 .border_color(cx.theme().colors().border)
6029 .child(
6030 div()
6031 .flex_1()
6032 .py_1()
6033 .px_2()
6034 .overflow_hidden()
6035 .child(completion),
6036 )
6037 .when_some(accept_keystroke, |el, accept_keystroke| {
6038 if !accept_keystroke.modifiers.modified() {
6039 return el;
6040 }
6041
6042 el.child(
6043 h_flex()
6044 .h_full()
6045 .border_l_1()
6046 .rounded_r_lg()
6047 .border_color(cx.theme().colors().border)
6048 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6049 .gap_1()
6050 .py_1()
6051 .px_2()
6052 .child(
6053 h_flex()
6054 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6055 .when(is_platform_style_mac, |parent| parent.gap_1())
6056 .child(h_flex().children(ui::render_modifiers(
6057 &accept_keystroke.modifiers,
6058 PlatformStyle::platform(),
6059 Some(if !has_completion {
6060 Color::Muted
6061 } else {
6062 Color::Default
6063 }),
6064 None,
6065 false,
6066 ))),
6067 )
6068 .child(Label::new("Preview").into_any_element())
6069 .opacity(if has_completion { 1.0 } else { 0.4 }),
6070 )
6071 })
6072 .into_any(),
6073 )
6074 }
6075
6076 fn render_edit_prediction_cursor_popover_preview(
6077 &self,
6078 completion: &InlineCompletionState,
6079 cursor_point: Point,
6080 style: &EditorStyle,
6081 cx: &mut Context<Editor>,
6082 ) -> Option<Div> {
6083 use text::ToPoint as _;
6084
6085 fn render_relative_row_jump(
6086 prefix: impl Into<String>,
6087 current_row: u32,
6088 target_row: u32,
6089 ) -> Div {
6090 let (row_diff, arrow) = if target_row < current_row {
6091 (current_row - target_row, IconName::ArrowUp)
6092 } else {
6093 (target_row - current_row, IconName::ArrowDown)
6094 };
6095
6096 h_flex()
6097 .child(
6098 Label::new(format!("{}{}", prefix.into(), row_diff))
6099 .color(Color::Muted)
6100 .size(LabelSize::Small),
6101 )
6102 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6103 }
6104
6105 match &completion.completion {
6106 InlineCompletion::Move {
6107 target, snapshot, ..
6108 } => Some(
6109 h_flex()
6110 .px_2()
6111 .gap_2()
6112 .flex_1()
6113 .child(
6114 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6115 Icon::new(IconName::ZedPredictDown)
6116 } else {
6117 Icon::new(IconName::ZedPredictUp)
6118 },
6119 )
6120 .child(Label::new("Jump to Edit")),
6121 ),
6122
6123 InlineCompletion::Edit {
6124 edits,
6125 edit_preview,
6126 snapshot,
6127 display_mode: _,
6128 } => {
6129 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6130
6131 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6132 &snapshot,
6133 &edits,
6134 edit_preview.as_ref()?,
6135 true,
6136 cx,
6137 )
6138 .first_line_preview();
6139
6140 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6141 .with_highlights(&style.text, highlighted_edits.highlights);
6142
6143 let preview = h_flex()
6144 .gap_1()
6145 .min_w_16()
6146 .child(styled_text)
6147 .when(has_more_lines, |parent| parent.child("…"));
6148
6149 let left = if first_edit_row != cursor_point.row {
6150 render_relative_row_jump("", cursor_point.row, first_edit_row)
6151 .into_any_element()
6152 } else {
6153 Icon::new(IconName::ZedPredict).into_any_element()
6154 };
6155
6156 Some(
6157 h_flex()
6158 .h_full()
6159 .flex_1()
6160 .gap_2()
6161 .pr_1()
6162 .overflow_x_hidden()
6163 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6164 .child(left)
6165 .child(preview),
6166 )
6167 }
6168 }
6169 }
6170
6171 fn render_context_menu(
6172 &self,
6173 style: &EditorStyle,
6174 max_height_in_lines: u32,
6175 y_flipped: bool,
6176 window: &mut Window,
6177 cx: &mut Context<Editor>,
6178 ) -> Option<AnyElement> {
6179 let menu = self.context_menu.borrow();
6180 let menu = menu.as_ref()?;
6181 if !menu.visible() {
6182 return None;
6183 };
6184 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6185 }
6186
6187 fn render_context_menu_aside(
6188 &self,
6189 style: &EditorStyle,
6190 max_size: Size<Pixels>,
6191 cx: &mut Context<Editor>,
6192 ) -> Option<AnyElement> {
6193 self.context_menu.borrow().as_ref().and_then(|menu| {
6194 if menu.visible() {
6195 menu.render_aside(
6196 style,
6197 max_size,
6198 self.workspace.as_ref().map(|(w, _)| w.clone()),
6199 cx,
6200 )
6201 } else {
6202 None
6203 }
6204 })
6205 }
6206
6207 fn hide_context_menu(
6208 &mut self,
6209 window: &mut Window,
6210 cx: &mut Context<Self>,
6211 ) -> Option<CodeContextMenu> {
6212 cx.notify();
6213 self.completion_tasks.clear();
6214 let context_menu = self.context_menu.borrow_mut().take();
6215 self.stale_inline_completion_in_menu.take();
6216 self.update_visible_inline_completion(window, cx);
6217 context_menu
6218 }
6219
6220 fn show_snippet_choices(
6221 &mut self,
6222 choices: &Vec<String>,
6223 selection: Range<Anchor>,
6224 cx: &mut Context<Self>,
6225 ) {
6226 if selection.start.buffer_id.is_none() {
6227 return;
6228 }
6229 let buffer_id = selection.start.buffer_id.unwrap();
6230 let buffer = self.buffer().read(cx).buffer(buffer_id);
6231 let id = post_inc(&mut self.next_completion_id);
6232
6233 if let Some(buffer) = buffer {
6234 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6235 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6236 ));
6237 }
6238 }
6239
6240 pub fn insert_snippet(
6241 &mut self,
6242 insertion_ranges: &[Range<usize>],
6243 snippet: Snippet,
6244 window: &mut Window,
6245 cx: &mut Context<Self>,
6246 ) -> Result<()> {
6247 struct Tabstop<T> {
6248 is_end_tabstop: bool,
6249 ranges: Vec<Range<T>>,
6250 choices: Option<Vec<String>>,
6251 }
6252
6253 let tabstops = self.buffer.update(cx, |buffer, cx| {
6254 let snippet_text: Arc<str> = snippet.text.clone().into();
6255 buffer.edit(
6256 insertion_ranges
6257 .iter()
6258 .cloned()
6259 .map(|range| (range, snippet_text.clone())),
6260 Some(AutoindentMode::EachLine),
6261 cx,
6262 );
6263
6264 let snapshot = &*buffer.read(cx);
6265 let snippet = &snippet;
6266 snippet
6267 .tabstops
6268 .iter()
6269 .map(|tabstop| {
6270 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6271 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6272 });
6273 let mut tabstop_ranges = tabstop
6274 .ranges
6275 .iter()
6276 .flat_map(|tabstop_range| {
6277 let mut delta = 0_isize;
6278 insertion_ranges.iter().map(move |insertion_range| {
6279 let insertion_start = insertion_range.start as isize + delta;
6280 delta +=
6281 snippet.text.len() as isize - insertion_range.len() as isize;
6282
6283 let start = ((insertion_start + tabstop_range.start) as usize)
6284 .min(snapshot.len());
6285 let end = ((insertion_start + tabstop_range.end) as usize)
6286 .min(snapshot.len());
6287 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6288 })
6289 })
6290 .collect::<Vec<_>>();
6291 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6292
6293 Tabstop {
6294 is_end_tabstop,
6295 ranges: tabstop_ranges,
6296 choices: tabstop.choices.clone(),
6297 }
6298 })
6299 .collect::<Vec<_>>()
6300 });
6301 if let Some(tabstop) = tabstops.first() {
6302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6303 s.select_ranges(tabstop.ranges.iter().cloned());
6304 });
6305
6306 if let Some(choices) = &tabstop.choices {
6307 if let Some(selection) = tabstop.ranges.first() {
6308 self.show_snippet_choices(choices, selection.clone(), cx)
6309 }
6310 }
6311
6312 // If we're already at the last tabstop and it's at the end of the snippet,
6313 // we're done, we don't need to keep the state around.
6314 if !tabstop.is_end_tabstop {
6315 let choices = tabstops
6316 .iter()
6317 .map(|tabstop| tabstop.choices.clone())
6318 .collect();
6319
6320 let ranges = tabstops
6321 .into_iter()
6322 .map(|tabstop| tabstop.ranges)
6323 .collect::<Vec<_>>();
6324
6325 self.snippet_stack.push(SnippetState {
6326 active_index: 0,
6327 ranges,
6328 choices,
6329 });
6330 }
6331
6332 // Check whether the just-entered snippet ends with an auto-closable bracket.
6333 if self.autoclose_regions.is_empty() {
6334 let snapshot = self.buffer.read(cx).snapshot(cx);
6335 for selection in &mut self.selections.all::<Point>(cx) {
6336 let selection_head = selection.head();
6337 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6338 continue;
6339 };
6340
6341 let mut bracket_pair = None;
6342 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6343 let prev_chars = snapshot
6344 .reversed_chars_at(selection_head)
6345 .collect::<String>();
6346 for (pair, enabled) in scope.brackets() {
6347 if enabled
6348 && pair.close
6349 && prev_chars.starts_with(pair.start.as_str())
6350 && next_chars.starts_with(pair.end.as_str())
6351 {
6352 bracket_pair = Some(pair.clone());
6353 break;
6354 }
6355 }
6356 if let Some(pair) = bracket_pair {
6357 let start = snapshot.anchor_after(selection_head);
6358 let end = snapshot.anchor_after(selection_head);
6359 self.autoclose_regions.push(AutocloseRegion {
6360 selection_id: selection.id,
6361 range: start..end,
6362 pair,
6363 });
6364 }
6365 }
6366 }
6367 }
6368 Ok(())
6369 }
6370
6371 pub fn move_to_next_snippet_tabstop(
6372 &mut self,
6373 window: &mut Window,
6374 cx: &mut Context<Self>,
6375 ) -> bool {
6376 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6377 }
6378
6379 pub fn move_to_prev_snippet_tabstop(
6380 &mut self,
6381 window: &mut Window,
6382 cx: &mut Context<Self>,
6383 ) -> bool {
6384 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6385 }
6386
6387 pub fn move_to_snippet_tabstop(
6388 &mut self,
6389 bias: Bias,
6390 window: &mut Window,
6391 cx: &mut Context<Self>,
6392 ) -> bool {
6393 if let Some(mut snippet) = self.snippet_stack.pop() {
6394 match bias {
6395 Bias::Left => {
6396 if snippet.active_index > 0 {
6397 snippet.active_index -= 1;
6398 } else {
6399 self.snippet_stack.push(snippet);
6400 return false;
6401 }
6402 }
6403 Bias::Right => {
6404 if snippet.active_index + 1 < snippet.ranges.len() {
6405 snippet.active_index += 1;
6406 } else {
6407 self.snippet_stack.push(snippet);
6408 return false;
6409 }
6410 }
6411 }
6412 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6414 s.select_anchor_ranges(current_ranges.iter().cloned())
6415 });
6416
6417 if let Some(choices) = &snippet.choices[snippet.active_index] {
6418 if let Some(selection) = current_ranges.first() {
6419 self.show_snippet_choices(&choices, selection.clone(), cx);
6420 }
6421 }
6422
6423 // If snippet state is not at the last tabstop, push it back on the stack
6424 if snippet.active_index + 1 < snippet.ranges.len() {
6425 self.snippet_stack.push(snippet);
6426 }
6427 return true;
6428 }
6429 }
6430
6431 false
6432 }
6433
6434 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6435 self.transact(window, cx, |this, window, cx| {
6436 this.select_all(&SelectAll, window, cx);
6437 this.insert("", window, cx);
6438 });
6439 }
6440
6441 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6442 self.transact(window, cx, |this, window, cx| {
6443 this.select_autoclose_pair(window, cx);
6444 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6445 if !this.linked_edit_ranges.is_empty() {
6446 let selections = this.selections.all::<MultiBufferPoint>(cx);
6447 let snapshot = this.buffer.read(cx).snapshot(cx);
6448
6449 for selection in selections.iter() {
6450 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6451 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6452 if selection_start.buffer_id != selection_end.buffer_id {
6453 continue;
6454 }
6455 if let Some(ranges) =
6456 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6457 {
6458 for (buffer, entries) in ranges {
6459 linked_ranges.entry(buffer).or_default().extend(entries);
6460 }
6461 }
6462 }
6463 }
6464
6465 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6466 if !this.selections.line_mode {
6467 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6468 for selection in &mut selections {
6469 if selection.is_empty() {
6470 let old_head = selection.head();
6471 let mut new_head =
6472 movement::left(&display_map, old_head.to_display_point(&display_map))
6473 .to_point(&display_map);
6474 if let Some((buffer, line_buffer_range)) = display_map
6475 .buffer_snapshot
6476 .buffer_line_for_row(MultiBufferRow(old_head.row))
6477 {
6478 let indent_size =
6479 buffer.indent_size_for_line(line_buffer_range.start.row);
6480 let indent_len = match indent_size.kind {
6481 IndentKind::Space => {
6482 buffer.settings_at(line_buffer_range.start, cx).tab_size
6483 }
6484 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6485 };
6486 if old_head.column <= indent_size.len && old_head.column > 0 {
6487 let indent_len = indent_len.get();
6488 new_head = cmp::min(
6489 new_head,
6490 MultiBufferPoint::new(
6491 old_head.row,
6492 ((old_head.column - 1) / indent_len) * indent_len,
6493 ),
6494 );
6495 }
6496 }
6497
6498 selection.set_head(new_head, SelectionGoal::None);
6499 }
6500 }
6501 }
6502
6503 this.signature_help_state.set_backspace_pressed(true);
6504 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6505 s.select(selections)
6506 });
6507 this.insert("", window, cx);
6508 let empty_str: Arc<str> = Arc::from("");
6509 for (buffer, edits) in linked_ranges {
6510 let snapshot = buffer.read(cx).snapshot();
6511 use text::ToPoint as TP;
6512
6513 let edits = edits
6514 .into_iter()
6515 .map(|range| {
6516 let end_point = TP::to_point(&range.end, &snapshot);
6517 let mut start_point = TP::to_point(&range.start, &snapshot);
6518
6519 if end_point == start_point {
6520 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6521 .saturating_sub(1);
6522 start_point =
6523 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6524 };
6525
6526 (start_point..end_point, empty_str.clone())
6527 })
6528 .sorted_by_key(|(range, _)| range.start)
6529 .collect::<Vec<_>>();
6530 buffer.update(cx, |this, cx| {
6531 this.edit(edits, None, cx);
6532 })
6533 }
6534 this.refresh_inline_completion(true, false, window, cx);
6535 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6536 });
6537 }
6538
6539 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6540 self.transact(window, cx, |this, window, cx| {
6541 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6542 let line_mode = s.line_mode;
6543 s.move_with(|map, selection| {
6544 if selection.is_empty() && !line_mode {
6545 let cursor = movement::right(map, selection.head());
6546 selection.end = cursor;
6547 selection.reversed = true;
6548 selection.goal = SelectionGoal::None;
6549 }
6550 })
6551 });
6552 this.insert("", window, cx);
6553 this.refresh_inline_completion(true, false, window, cx);
6554 });
6555 }
6556
6557 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6558 if self.move_to_prev_snippet_tabstop(window, cx) {
6559 return;
6560 }
6561
6562 self.outdent(&Outdent, window, cx);
6563 }
6564
6565 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6566 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6567 return;
6568 }
6569
6570 let mut selections = self.selections.all_adjusted(cx);
6571 let buffer = self.buffer.read(cx);
6572 let snapshot = buffer.snapshot(cx);
6573 let rows_iter = selections.iter().map(|s| s.head().row);
6574 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6575
6576 let mut edits = Vec::new();
6577 let mut prev_edited_row = 0;
6578 let mut row_delta = 0;
6579 for selection in &mut selections {
6580 if selection.start.row != prev_edited_row {
6581 row_delta = 0;
6582 }
6583 prev_edited_row = selection.end.row;
6584
6585 // If the selection is non-empty, then increase the indentation of the selected lines.
6586 if !selection.is_empty() {
6587 row_delta =
6588 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6589 continue;
6590 }
6591
6592 // If the selection is empty and the cursor is in the leading whitespace before the
6593 // suggested indentation, then auto-indent the line.
6594 let cursor = selection.head();
6595 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6596 if let Some(suggested_indent) =
6597 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6598 {
6599 if cursor.column < suggested_indent.len
6600 && cursor.column <= current_indent.len
6601 && current_indent.len <= suggested_indent.len
6602 {
6603 selection.start = Point::new(cursor.row, suggested_indent.len);
6604 selection.end = selection.start;
6605 if row_delta == 0 {
6606 edits.extend(Buffer::edit_for_indent_size_adjustment(
6607 cursor.row,
6608 current_indent,
6609 suggested_indent,
6610 ));
6611 row_delta = suggested_indent.len - current_indent.len;
6612 }
6613 continue;
6614 }
6615 }
6616
6617 // Otherwise, insert a hard or soft tab.
6618 let settings = buffer.settings_at(cursor, cx);
6619 let tab_size = if settings.hard_tabs {
6620 IndentSize::tab()
6621 } else {
6622 let tab_size = settings.tab_size.get();
6623 let char_column = snapshot
6624 .text_for_range(Point::new(cursor.row, 0)..cursor)
6625 .flat_map(str::chars)
6626 .count()
6627 + row_delta as usize;
6628 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6629 IndentSize::spaces(chars_to_next_tab_stop)
6630 };
6631 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6632 selection.end = selection.start;
6633 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6634 row_delta += tab_size.len;
6635 }
6636
6637 self.transact(window, cx, |this, window, cx| {
6638 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6639 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6640 s.select(selections)
6641 });
6642 this.refresh_inline_completion(true, false, window, cx);
6643 });
6644 }
6645
6646 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6647 if self.read_only(cx) {
6648 return;
6649 }
6650 let mut selections = self.selections.all::<Point>(cx);
6651 let mut prev_edited_row = 0;
6652 let mut row_delta = 0;
6653 let mut edits = Vec::new();
6654 let buffer = self.buffer.read(cx);
6655 let snapshot = buffer.snapshot(cx);
6656 for selection in &mut selections {
6657 if selection.start.row != prev_edited_row {
6658 row_delta = 0;
6659 }
6660 prev_edited_row = selection.end.row;
6661
6662 row_delta =
6663 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6664 }
6665
6666 self.transact(window, cx, |this, window, cx| {
6667 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6668 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6669 s.select(selections)
6670 });
6671 });
6672 }
6673
6674 fn indent_selection(
6675 buffer: &MultiBuffer,
6676 snapshot: &MultiBufferSnapshot,
6677 selection: &mut Selection<Point>,
6678 edits: &mut Vec<(Range<Point>, String)>,
6679 delta_for_start_row: u32,
6680 cx: &App,
6681 ) -> u32 {
6682 let settings = buffer.settings_at(selection.start, cx);
6683 let tab_size = settings.tab_size.get();
6684 let indent_kind = if settings.hard_tabs {
6685 IndentKind::Tab
6686 } else {
6687 IndentKind::Space
6688 };
6689 let mut start_row = selection.start.row;
6690 let mut end_row = selection.end.row + 1;
6691
6692 // If a selection ends at the beginning of a line, don't indent
6693 // that last line.
6694 if selection.end.column == 0 && selection.end.row > selection.start.row {
6695 end_row -= 1;
6696 }
6697
6698 // Avoid re-indenting a row that has already been indented by a
6699 // previous selection, but still update this selection's column
6700 // to reflect that indentation.
6701 if delta_for_start_row > 0 {
6702 start_row += 1;
6703 selection.start.column += delta_for_start_row;
6704 if selection.end.row == selection.start.row {
6705 selection.end.column += delta_for_start_row;
6706 }
6707 }
6708
6709 let mut delta_for_end_row = 0;
6710 let has_multiple_rows = start_row + 1 != end_row;
6711 for row in start_row..end_row {
6712 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6713 let indent_delta = match (current_indent.kind, indent_kind) {
6714 (IndentKind::Space, IndentKind::Space) => {
6715 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6716 IndentSize::spaces(columns_to_next_tab_stop)
6717 }
6718 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6719 (_, IndentKind::Tab) => IndentSize::tab(),
6720 };
6721
6722 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6723 0
6724 } else {
6725 selection.start.column
6726 };
6727 let row_start = Point::new(row, start);
6728 edits.push((
6729 row_start..row_start,
6730 indent_delta.chars().collect::<String>(),
6731 ));
6732
6733 // Update this selection's endpoints to reflect the indentation.
6734 if row == selection.start.row {
6735 selection.start.column += indent_delta.len;
6736 }
6737 if row == selection.end.row {
6738 selection.end.column += indent_delta.len;
6739 delta_for_end_row = indent_delta.len;
6740 }
6741 }
6742
6743 if selection.start.row == selection.end.row {
6744 delta_for_start_row + delta_for_end_row
6745 } else {
6746 delta_for_end_row
6747 }
6748 }
6749
6750 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6751 if self.read_only(cx) {
6752 return;
6753 }
6754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6755 let selections = self.selections.all::<Point>(cx);
6756 let mut deletion_ranges = Vec::new();
6757 let mut last_outdent = None;
6758 {
6759 let buffer = self.buffer.read(cx);
6760 let snapshot = buffer.snapshot(cx);
6761 for selection in &selections {
6762 let settings = buffer.settings_at(selection.start, cx);
6763 let tab_size = settings.tab_size.get();
6764 let mut rows = selection.spanned_rows(false, &display_map);
6765
6766 // Avoid re-outdenting a row that has already been outdented by a
6767 // previous selection.
6768 if let Some(last_row) = last_outdent {
6769 if last_row == rows.start {
6770 rows.start = rows.start.next_row();
6771 }
6772 }
6773 let has_multiple_rows = rows.len() > 1;
6774 for row in rows.iter_rows() {
6775 let indent_size = snapshot.indent_size_for_line(row);
6776 if indent_size.len > 0 {
6777 let deletion_len = match indent_size.kind {
6778 IndentKind::Space => {
6779 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6780 if columns_to_prev_tab_stop == 0 {
6781 tab_size
6782 } else {
6783 columns_to_prev_tab_stop
6784 }
6785 }
6786 IndentKind::Tab => 1,
6787 };
6788 let start = if has_multiple_rows
6789 || deletion_len > selection.start.column
6790 || indent_size.len < selection.start.column
6791 {
6792 0
6793 } else {
6794 selection.start.column - deletion_len
6795 };
6796 deletion_ranges.push(
6797 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6798 );
6799 last_outdent = Some(row);
6800 }
6801 }
6802 }
6803 }
6804
6805 self.transact(window, cx, |this, window, cx| {
6806 this.buffer.update(cx, |buffer, cx| {
6807 let empty_str: Arc<str> = Arc::default();
6808 buffer.edit(
6809 deletion_ranges
6810 .into_iter()
6811 .map(|range| (range, empty_str.clone())),
6812 None,
6813 cx,
6814 );
6815 });
6816 let selections = this.selections.all::<usize>(cx);
6817 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6818 s.select(selections)
6819 });
6820 });
6821 }
6822
6823 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6824 if self.read_only(cx) {
6825 return;
6826 }
6827 let selections = self
6828 .selections
6829 .all::<usize>(cx)
6830 .into_iter()
6831 .map(|s| s.range());
6832
6833 self.transact(window, cx, |this, window, cx| {
6834 this.buffer.update(cx, |buffer, cx| {
6835 buffer.autoindent_ranges(selections, cx);
6836 });
6837 let selections = this.selections.all::<usize>(cx);
6838 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6839 s.select(selections)
6840 });
6841 });
6842 }
6843
6844 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6846 let selections = self.selections.all::<Point>(cx);
6847
6848 let mut new_cursors = Vec::new();
6849 let mut edit_ranges = Vec::new();
6850 let mut selections = selections.iter().peekable();
6851 while let Some(selection) = selections.next() {
6852 let mut rows = selection.spanned_rows(false, &display_map);
6853 let goal_display_column = selection.head().to_display_point(&display_map).column();
6854
6855 // Accumulate contiguous regions of rows that we want to delete.
6856 while let Some(next_selection) = selections.peek() {
6857 let next_rows = next_selection.spanned_rows(false, &display_map);
6858 if next_rows.start <= rows.end {
6859 rows.end = next_rows.end;
6860 selections.next().unwrap();
6861 } else {
6862 break;
6863 }
6864 }
6865
6866 let buffer = &display_map.buffer_snapshot;
6867 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6868 let edit_end;
6869 let cursor_buffer_row;
6870 if buffer.max_point().row >= rows.end.0 {
6871 // If there's a line after the range, delete the \n from the end of the row range
6872 // and position the cursor on the next line.
6873 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6874 cursor_buffer_row = rows.end;
6875 } else {
6876 // If there isn't a line after the range, delete the \n from the line before the
6877 // start of the row range and position the cursor there.
6878 edit_start = edit_start.saturating_sub(1);
6879 edit_end = buffer.len();
6880 cursor_buffer_row = rows.start.previous_row();
6881 }
6882
6883 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6884 *cursor.column_mut() =
6885 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6886
6887 new_cursors.push((
6888 selection.id,
6889 buffer.anchor_after(cursor.to_point(&display_map)),
6890 ));
6891 edit_ranges.push(edit_start..edit_end);
6892 }
6893
6894 self.transact(window, cx, |this, window, cx| {
6895 let buffer = this.buffer.update(cx, |buffer, cx| {
6896 let empty_str: Arc<str> = Arc::default();
6897 buffer.edit(
6898 edit_ranges
6899 .into_iter()
6900 .map(|range| (range, empty_str.clone())),
6901 None,
6902 cx,
6903 );
6904 buffer.snapshot(cx)
6905 });
6906 let new_selections = new_cursors
6907 .into_iter()
6908 .map(|(id, cursor)| {
6909 let cursor = cursor.to_point(&buffer);
6910 Selection {
6911 id,
6912 start: cursor,
6913 end: cursor,
6914 reversed: false,
6915 goal: SelectionGoal::None,
6916 }
6917 })
6918 .collect();
6919
6920 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6921 s.select(new_selections);
6922 });
6923 });
6924 }
6925
6926 pub fn join_lines_impl(
6927 &mut self,
6928 insert_whitespace: bool,
6929 window: &mut Window,
6930 cx: &mut Context<Self>,
6931 ) {
6932 if self.read_only(cx) {
6933 return;
6934 }
6935 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6936 for selection in self.selections.all::<Point>(cx) {
6937 let start = MultiBufferRow(selection.start.row);
6938 // Treat single line selections as if they include the next line. Otherwise this action
6939 // would do nothing for single line selections individual cursors.
6940 let end = if selection.start.row == selection.end.row {
6941 MultiBufferRow(selection.start.row + 1)
6942 } else {
6943 MultiBufferRow(selection.end.row)
6944 };
6945
6946 if let Some(last_row_range) = row_ranges.last_mut() {
6947 if start <= last_row_range.end {
6948 last_row_range.end = end;
6949 continue;
6950 }
6951 }
6952 row_ranges.push(start..end);
6953 }
6954
6955 let snapshot = self.buffer.read(cx).snapshot(cx);
6956 let mut cursor_positions = Vec::new();
6957 for row_range in &row_ranges {
6958 let anchor = snapshot.anchor_before(Point::new(
6959 row_range.end.previous_row().0,
6960 snapshot.line_len(row_range.end.previous_row()),
6961 ));
6962 cursor_positions.push(anchor..anchor);
6963 }
6964
6965 self.transact(window, cx, |this, window, cx| {
6966 for row_range in row_ranges.into_iter().rev() {
6967 for row in row_range.iter_rows().rev() {
6968 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6969 let next_line_row = row.next_row();
6970 let indent = snapshot.indent_size_for_line(next_line_row);
6971 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6972
6973 let replace =
6974 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6975 " "
6976 } else {
6977 ""
6978 };
6979
6980 this.buffer.update(cx, |buffer, cx| {
6981 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6982 });
6983 }
6984 }
6985
6986 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6987 s.select_anchor_ranges(cursor_positions)
6988 });
6989 });
6990 }
6991
6992 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6993 self.join_lines_impl(true, window, cx);
6994 }
6995
6996 pub fn sort_lines_case_sensitive(
6997 &mut self,
6998 _: &SortLinesCaseSensitive,
6999 window: &mut Window,
7000 cx: &mut Context<Self>,
7001 ) {
7002 self.manipulate_lines(window, cx, |lines| lines.sort())
7003 }
7004
7005 pub fn sort_lines_case_insensitive(
7006 &mut self,
7007 _: &SortLinesCaseInsensitive,
7008 window: &mut Window,
7009 cx: &mut Context<Self>,
7010 ) {
7011 self.manipulate_lines(window, cx, |lines| {
7012 lines.sort_by_key(|line| line.to_lowercase())
7013 })
7014 }
7015
7016 pub fn unique_lines_case_insensitive(
7017 &mut self,
7018 _: &UniqueLinesCaseInsensitive,
7019 window: &mut Window,
7020 cx: &mut Context<Self>,
7021 ) {
7022 self.manipulate_lines(window, cx, |lines| {
7023 let mut seen = HashSet::default();
7024 lines.retain(|line| seen.insert(line.to_lowercase()));
7025 })
7026 }
7027
7028 pub fn unique_lines_case_sensitive(
7029 &mut self,
7030 _: &UniqueLinesCaseSensitive,
7031 window: &mut Window,
7032 cx: &mut Context<Self>,
7033 ) {
7034 self.manipulate_lines(window, cx, |lines| {
7035 let mut seen = HashSet::default();
7036 lines.retain(|line| seen.insert(*line));
7037 })
7038 }
7039
7040 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7041 let mut revert_changes = HashMap::default();
7042 let snapshot = self.snapshot(window, cx);
7043 for hunk in snapshot
7044 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7045 {
7046 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7047 }
7048 if !revert_changes.is_empty() {
7049 self.transact(window, cx, |editor, window, cx| {
7050 editor.revert(revert_changes, window, cx);
7051 });
7052 }
7053 }
7054
7055 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7056 let Some(project) = self.project.clone() else {
7057 return;
7058 };
7059 self.reload(project, window, cx)
7060 .detach_and_notify_err(window, cx);
7061 }
7062
7063 pub fn revert_selected_hunks(
7064 &mut self,
7065 _: &RevertSelectedHunks,
7066 window: &mut Window,
7067 cx: &mut Context<Self>,
7068 ) {
7069 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7070 self.discard_hunks_in_ranges(selections, window, cx);
7071 }
7072
7073 fn discard_hunks_in_ranges(
7074 &mut self,
7075 ranges: impl Iterator<Item = Range<Point>>,
7076 window: &mut Window,
7077 cx: &mut Context<Editor>,
7078 ) {
7079 let mut revert_changes = HashMap::default();
7080 let snapshot = self.snapshot(window, cx);
7081 for hunk in &snapshot.hunks_for_ranges(ranges) {
7082 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7083 }
7084 if !revert_changes.is_empty() {
7085 self.transact(window, cx, |editor, window, cx| {
7086 editor.revert(revert_changes, window, cx);
7087 });
7088 }
7089 }
7090
7091 pub fn open_active_item_in_terminal(
7092 &mut self,
7093 _: &OpenInTerminal,
7094 window: &mut Window,
7095 cx: &mut Context<Self>,
7096 ) {
7097 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7098 let project_path = buffer.read(cx).project_path(cx)?;
7099 let project = self.project.as_ref()?.read(cx);
7100 let entry = project.entry_for_path(&project_path, cx)?;
7101 let parent = match &entry.canonical_path {
7102 Some(canonical_path) => canonical_path.to_path_buf(),
7103 None => project.absolute_path(&project_path, cx)?,
7104 }
7105 .parent()?
7106 .to_path_buf();
7107 Some(parent)
7108 }) {
7109 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7110 }
7111 }
7112
7113 pub fn prepare_revert_change(
7114 &self,
7115 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7116 hunk: &MultiBufferDiffHunk,
7117 cx: &mut App,
7118 ) -> Option<()> {
7119 let buffer = self.buffer.read(cx);
7120 let diff = buffer.diff_for(hunk.buffer_id)?;
7121 let buffer = buffer.buffer(hunk.buffer_id)?;
7122 let buffer = buffer.read(cx);
7123 let original_text = diff
7124 .read(cx)
7125 .base_text()
7126 .as_ref()?
7127 .as_rope()
7128 .slice(hunk.diff_base_byte_range.clone());
7129 let buffer_snapshot = buffer.snapshot();
7130 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7131 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7132 probe
7133 .0
7134 .start
7135 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7136 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7137 }) {
7138 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7139 Some(())
7140 } else {
7141 None
7142 }
7143 }
7144
7145 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7146 self.manipulate_lines(window, cx, |lines| lines.reverse())
7147 }
7148
7149 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7150 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7151 }
7152
7153 fn manipulate_lines<Fn>(
7154 &mut self,
7155 window: &mut Window,
7156 cx: &mut Context<Self>,
7157 mut callback: Fn,
7158 ) where
7159 Fn: FnMut(&mut Vec<&str>),
7160 {
7161 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7162 let buffer = self.buffer.read(cx).snapshot(cx);
7163
7164 let mut edits = Vec::new();
7165
7166 let selections = self.selections.all::<Point>(cx);
7167 let mut selections = selections.iter().peekable();
7168 let mut contiguous_row_selections = Vec::new();
7169 let mut new_selections = Vec::new();
7170 let mut added_lines = 0;
7171 let mut removed_lines = 0;
7172
7173 while let Some(selection) = selections.next() {
7174 let (start_row, end_row) = consume_contiguous_rows(
7175 &mut contiguous_row_selections,
7176 selection,
7177 &display_map,
7178 &mut selections,
7179 );
7180
7181 let start_point = Point::new(start_row.0, 0);
7182 let end_point = Point::new(
7183 end_row.previous_row().0,
7184 buffer.line_len(end_row.previous_row()),
7185 );
7186 let text = buffer
7187 .text_for_range(start_point..end_point)
7188 .collect::<String>();
7189
7190 let mut lines = text.split('\n').collect_vec();
7191
7192 let lines_before = lines.len();
7193 callback(&mut lines);
7194 let lines_after = lines.len();
7195
7196 edits.push((start_point..end_point, lines.join("\n")));
7197
7198 // Selections must change based on added and removed line count
7199 let start_row =
7200 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7201 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7202 new_selections.push(Selection {
7203 id: selection.id,
7204 start: start_row,
7205 end: end_row,
7206 goal: SelectionGoal::None,
7207 reversed: selection.reversed,
7208 });
7209
7210 if lines_after > lines_before {
7211 added_lines += lines_after - lines_before;
7212 } else if lines_before > lines_after {
7213 removed_lines += lines_before - lines_after;
7214 }
7215 }
7216
7217 self.transact(window, cx, |this, window, cx| {
7218 let buffer = this.buffer.update(cx, |buffer, cx| {
7219 buffer.edit(edits, None, cx);
7220 buffer.snapshot(cx)
7221 });
7222
7223 // Recalculate offsets on newly edited buffer
7224 let new_selections = new_selections
7225 .iter()
7226 .map(|s| {
7227 let start_point = Point::new(s.start.0, 0);
7228 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7229 Selection {
7230 id: s.id,
7231 start: buffer.point_to_offset(start_point),
7232 end: buffer.point_to_offset(end_point),
7233 goal: s.goal,
7234 reversed: s.reversed,
7235 }
7236 })
7237 .collect();
7238
7239 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7240 s.select(new_selections);
7241 });
7242
7243 this.request_autoscroll(Autoscroll::fit(), cx);
7244 });
7245 }
7246
7247 pub fn convert_to_upper_case(
7248 &mut self,
7249 _: &ConvertToUpperCase,
7250 window: &mut Window,
7251 cx: &mut Context<Self>,
7252 ) {
7253 self.manipulate_text(window, cx, |text| text.to_uppercase())
7254 }
7255
7256 pub fn convert_to_lower_case(
7257 &mut self,
7258 _: &ConvertToLowerCase,
7259 window: &mut Window,
7260 cx: &mut Context<Self>,
7261 ) {
7262 self.manipulate_text(window, cx, |text| text.to_lowercase())
7263 }
7264
7265 pub fn convert_to_title_case(
7266 &mut self,
7267 _: &ConvertToTitleCase,
7268 window: &mut Window,
7269 cx: &mut Context<Self>,
7270 ) {
7271 self.manipulate_text(window, cx, |text| {
7272 text.split('\n')
7273 .map(|line| line.to_case(Case::Title))
7274 .join("\n")
7275 })
7276 }
7277
7278 pub fn convert_to_snake_case(
7279 &mut self,
7280 _: &ConvertToSnakeCase,
7281 window: &mut Window,
7282 cx: &mut Context<Self>,
7283 ) {
7284 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7285 }
7286
7287 pub fn convert_to_kebab_case(
7288 &mut self,
7289 _: &ConvertToKebabCase,
7290 window: &mut Window,
7291 cx: &mut Context<Self>,
7292 ) {
7293 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7294 }
7295
7296 pub fn convert_to_upper_camel_case(
7297 &mut self,
7298 _: &ConvertToUpperCamelCase,
7299 window: &mut Window,
7300 cx: &mut Context<Self>,
7301 ) {
7302 self.manipulate_text(window, cx, |text| {
7303 text.split('\n')
7304 .map(|line| line.to_case(Case::UpperCamel))
7305 .join("\n")
7306 })
7307 }
7308
7309 pub fn convert_to_lower_camel_case(
7310 &mut self,
7311 _: &ConvertToLowerCamelCase,
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) {
7315 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7316 }
7317
7318 pub fn convert_to_opposite_case(
7319 &mut self,
7320 _: &ConvertToOppositeCase,
7321 window: &mut Window,
7322 cx: &mut Context<Self>,
7323 ) {
7324 self.manipulate_text(window, cx, |text| {
7325 text.chars()
7326 .fold(String::with_capacity(text.len()), |mut t, c| {
7327 if c.is_uppercase() {
7328 t.extend(c.to_lowercase());
7329 } else {
7330 t.extend(c.to_uppercase());
7331 }
7332 t
7333 })
7334 })
7335 }
7336
7337 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7338 where
7339 Fn: FnMut(&str) -> String,
7340 {
7341 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7342 let buffer = self.buffer.read(cx).snapshot(cx);
7343
7344 let mut new_selections = Vec::new();
7345 let mut edits = Vec::new();
7346 let mut selection_adjustment = 0i32;
7347
7348 for selection in self.selections.all::<usize>(cx) {
7349 let selection_is_empty = selection.is_empty();
7350
7351 let (start, end) = if selection_is_empty {
7352 let word_range = movement::surrounding_word(
7353 &display_map,
7354 selection.start.to_display_point(&display_map),
7355 );
7356 let start = word_range.start.to_offset(&display_map, Bias::Left);
7357 let end = word_range.end.to_offset(&display_map, Bias::Left);
7358 (start, end)
7359 } else {
7360 (selection.start, selection.end)
7361 };
7362
7363 let text = buffer.text_for_range(start..end).collect::<String>();
7364 let old_length = text.len() as i32;
7365 let text = callback(&text);
7366
7367 new_selections.push(Selection {
7368 start: (start as i32 - selection_adjustment) as usize,
7369 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7370 goal: SelectionGoal::None,
7371 ..selection
7372 });
7373
7374 selection_adjustment += old_length - text.len() as i32;
7375
7376 edits.push((start..end, text));
7377 }
7378
7379 self.transact(window, cx, |this, window, cx| {
7380 this.buffer.update(cx, |buffer, cx| {
7381 buffer.edit(edits, None, cx);
7382 });
7383
7384 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7385 s.select(new_selections);
7386 });
7387
7388 this.request_autoscroll(Autoscroll::fit(), cx);
7389 });
7390 }
7391
7392 pub fn duplicate(
7393 &mut self,
7394 upwards: bool,
7395 whole_lines: bool,
7396 window: &mut Window,
7397 cx: &mut Context<Self>,
7398 ) {
7399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7400 let buffer = &display_map.buffer_snapshot;
7401 let selections = self.selections.all::<Point>(cx);
7402
7403 let mut edits = Vec::new();
7404 let mut selections_iter = selections.iter().peekable();
7405 while let Some(selection) = selections_iter.next() {
7406 let mut rows = selection.spanned_rows(false, &display_map);
7407 // duplicate line-wise
7408 if whole_lines || selection.start == selection.end {
7409 // Avoid duplicating the same lines twice.
7410 while let Some(next_selection) = selections_iter.peek() {
7411 let next_rows = next_selection.spanned_rows(false, &display_map);
7412 if next_rows.start < rows.end {
7413 rows.end = next_rows.end;
7414 selections_iter.next().unwrap();
7415 } else {
7416 break;
7417 }
7418 }
7419
7420 // Copy the text from the selected row region and splice it either at the start
7421 // or end of the region.
7422 let start = Point::new(rows.start.0, 0);
7423 let end = Point::new(
7424 rows.end.previous_row().0,
7425 buffer.line_len(rows.end.previous_row()),
7426 );
7427 let text = buffer
7428 .text_for_range(start..end)
7429 .chain(Some("\n"))
7430 .collect::<String>();
7431 let insert_location = if upwards {
7432 Point::new(rows.end.0, 0)
7433 } else {
7434 start
7435 };
7436 edits.push((insert_location..insert_location, text));
7437 } else {
7438 // duplicate character-wise
7439 let start = selection.start;
7440 let end = selection.end;
7441 let text = buffer.text_for_range(start..end).collect::<String>();
7442 edits.push((selection.end..selection.end, text));
7443 }
7444 }
7445
7446 self.transact(window, cx, |this, _, cx| {
7447 this.buffer.update(cx, |buffer, cx| {
7448 buffer.edit(edits, None, cx);
7449 });
7450
7451 this.request_autoscroll(Autoscroll::fit(), cx);
7452 });
7453 }
7454
7455 pub fn duplicate_line_up(
7456 &mut self,
7457 _: &DuplicateLineUp,
7458 window: &mut Window,
7459 cx: &mut Context<Self>,
7460 ) {
7461 self.duplicate(true, true, window, cx);
7462 }
7463
7464 pub fn duplicate_line_down(
7465 &mut self,
7466 _: &DuplicateLineDown,
7467 window: &mut Window,
7468 cx: &mut Context<Self>,
7469 ) {
7470 self.duplicate(false, true, window, cx);
7471 }
7472
7473 pub fn duplicate_selection(
7474 &mut self,
7475 _: &DuplicateSelection,
7476 window: &mut Window,
7477 cx: &mut Context<Self>,
7478 ) {
7479 self.duplicate(false, false, window, cx);
7480 }
7481
7482 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7484 let buffer = self.buffer.read(cx).snapshot(cx);
7485
7486 let mut edits = Vec::new();
7487 let mut unfold_ranges = Vec::new();
7488 let mut refold_creases = Vec::new();
7489
7490 let selections = self.selections.all::<Point>(cx);
7491 let mut selections = selections.iter().peekable();
7492 let mut contiguous_row_selections = Vec::new();
7493 let mut new_selections = Vec::new();
7494
7495 while let Some(selection) = selections.next() {
7496 // Find all the selections that span a contiguous row range
7497 let (start_row, end_row) = consume_contiguous_rows(
7498 &mut contiguous_row_selections,
7499 selection,
7500 &display_map,
7501 &mut selections,
7502 );
7503
7504 // Move the text spanned by the row range to be before the line preceding the row range
7505 if start_row.0 > 0 {
7506 let range_to_move = Point::new(
7507 start_row.previous_row().0,
7508 buffer.line_len(start_row.previous_row()),
7509 )
7510 ..Point::new(
7511 end_row.previous_row().0,
7512 buffer.line_len(end_row.previous_row()),
7513 );
7514 let insertion_point = display_map
7515 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7516 .0;
7517
7518 // Don't move lines across excerpts
7519 if buffer
7520 .excerpt_containing(insertion_point..range_to_move.end)
7521 .is_some()
7522 {
7523 let text = buffer
7524 .text_for_range(range_to_move.clone())
7525 .flat_map(|s| s.chars())
7526 .skip(1)
7527 .chain(['\n'])
7528 .collect::<String>();
7529
7530 edits.push((
7531 buffer.anchor_after(range_to_move.start)
7532 ..buffer.anchor_before(range_to_move.end),
7533 String::new(),
7534 ));
7535 let insertion_anchor = buffer.anchor_after(insertion_point);
7536 edits.push((insertion_anchor..insertion_anchor, text));
7537
7538 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7539
7540 // Move selections up
7541 new_selections.extend(contiguous_row_selections.drain(..).map(
7542 |mut selection| {
7543 selection.start.row -= row_delta;
7544 selection.end.row -= row_delta;
7545 selection
7546 },
7547 ));
7548
7549 // Move folds up
7550 unfold_ranges.push(range_to_move.clone());
7551 for fold in display_map.folds_in_range(
7552 buffer.anchor_before(range_to_move.start)
7553 ..buffer.anchor_after(range_to_move.end),
7554 ) {
7555 let mut start = fold.range.start.to_point(&buffer);
7556 let mut end = fold.range.end.to_point(&buffer);
7557 start.row -= row_delta;
7558 end.row -= row_delta;
7559 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7560 }
7561 }
7562 }
7563
7564 // If we didn't move line(s), preserve the existing selections
7565 new_selections.append(&mut contiguous_row_selections);
7566 }
7567
7568 self.transact(window, cx, |this, window, cx| {
7569 this.unfold_ranges(&unfold_ranges, true, true, cx);
7570 this.buffer.update(cx, |buffer, cx| {
7571 for (range, text) in edits {
7572 buffer.edit([(range, text)], None, cx);
7573 }
7574 });
7575 this.fold_creases(refold_creases, true, window, cx);
7576 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7577 s.select(new_selections);
7578 })
7579 });
7580 }
7581
7582 pub fn move_line_down(
7583 &mut self,
7584 _: &MoveLineDown,
7585 window: &mut Window,
7586 cx: &mut Context<Self>,
7587 ) {
7588 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7589 let buffer = self.buffer.read(cx).snapshot(cx);
7590
7591 let mut edits = Vec::new();
7592 let mut unfold_ranges = Vec::new();
7593 let mut refold_creases = Vec::new();
7594
7595 let selections = self.selections.all::<Point>(cx);
7596 let mut selections = selections.iter().peekable();
7597 let mut contiguous_row_selections = Vec::new();
7598 let mut new_selections = Vec::new();
7599
7600 while let Some(selection) = selections.next() {
7601 // Find all the selections that span a contiguous row range
7602 let (start_row, end_row) = consume_contiguous_rows(
7603 &mut contiguous_row_selections,
7604 selection,
7605 &display_map,
7606 &mut selections,
7607 );
7608
7609 // Move the text spanned by the row range to be after the last line of the row range
7610 if end_row.0 <= buffer.max_point().row {
7611 let range_to_move =
7612 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7613 let insertion_point = display_map
7614 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7615 .0;
7616
7617 // Don't move lines across excerpt boundaries
7618 if buffer
7619 .excerpt_containing(range_to_move.start..insertion_point)
7620 .is_some()
7621 {
7622 let mut text = String::from("\n");
7623 text.extend(buffer.text_for_range(range_to_move.clone()));
7624 text.pop(); // Drop trailing newline
7625 edits.push((
7626 buffer.anchor_after(range_to_move.start)
7627 ..buffer.anchor_before(range_to_move.end),
7628 String::new(),
7629 ));
7630 let insertion_anchor = buffer.anchor_after(insertion_point);
7631 edits.push((insertion_anchor..insertion_anchor, text));
7632
7633 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7634
7635 // Move selections down
7636 new_selections.extend(contiguous_row_selections.drain(..).map(
7637 |mut selection| {
7638 selection.start.row += row_delta;
7639 selection.end.row += row_delta;
7640 selection
7641 },
7642 ));
7643
7644 // Move folds down
7645 unfold_ranges.push(range_to_move.clone());
7646 for fold in display_map.folds_in_range(
7647 buffer.anchor_before(range_to_move.start)
7648 ..buffer.anchor_after(range_to_move.end),
7649 ) {
7650 let mut start = fold.range.start.to_point(&buffer);
7651 let mut end = fold.range.end.to_point(&buffer);
7652 start.row += row_delta;
7653 end.row += row_delta;
7654 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7655 }
7656 }
7657 }
7658
7659 // If we didn't move line(s), preserve the existing selections
7660 new_selections.append(&mut contiguous_row_selections);
7661 }
7662
7663 self.transact(window, cx, |this, window, cx| {
7664 this.unfold_ranges(&unfold_ranges, true, true, cx);
7665 this.buffer.update(cx, |buffer, cx| {
7666 for (range, text) in edits {
7667 buffer.edit([(range, text)], None, cx);
7668 }
7669 });
7670 this.fold_creases(refold_creases, true, window, cx);
7671 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7672 s.select(new_selections)
7673 });
7674 });
7675 }
7676
7677 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7678 let text_layout_details = &self.text_layout_details(window);
7679 self.transact(window, cx, |this, window, cx| {
7680 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7681 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7682 let line_mode = s.line_mode;
7683 s.move_with(|display_map, selection| {
7684 if !selection.is_empty() || line_mode {
7685 return;
7686 }
7687
7688 let mut head = selection.head();
7689 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7690 if head.column() == display_map.line_len(head.row()) {
7691 transpose_offset = display_map
7692 .buffer_snapshot
7693 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7694 }
7695
7696 if transpose_offset == 0 {
7697 return;
7698 }
7699
7700 *head.column_mut() += 1;
7701 head = display_map.clip_point(head, Bias::Right);
7702 let goal = SelectionGoal::HorizontalPosition(
7703 display_map
7704 .x_for_display_point(head, text_layout_details)
7705 .into(),
7706 );
7707 selection.collapse_to(head, goal);
7708
7709 let transpose_start = display_map
7710 .buffer_snapshot
7711 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7712 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7713 let transpose_end = display_map
7714 .buffer_snapshot
7715 .clip_offset(transpose_offset + 1, Bias::Right);
7716 if let Some(ch) =
7717 display_map.buffer_snapshot.chars_at(transpose_start).next()
7718 {
7719 edits.push((transpose_start..transpose_offset, String::new()));
7720 edits.push((transpose_end..transpose_end, ch.to_string()));
7721 }
7722 }
7723 });
7724 edits
7725 });
7726 this.buffer
7727 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7728 let selections = this.selections.all::<usize>(cx);
7729 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7730 s.select(selections);
7731 });
7732 });
7733 }
7734
7735 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7736 self.rewrap_impl(IsVimMode::No, cx)
7737 }
7738
7739 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7740 let buffer = self.buffer.read(cx).snapshot(cx);
7741 let selections = self.selections.all::<Point>(cx);
7742 let mut selections = selections.iter().peekable();
7743
7744 let mut edits = Vec::new();
7745 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7746
7747 while let Some(selection) = selections.next() {
7748 let mut start_row = selection.start.row;
7749 let mut end_row = selection.end.row;
7750
7751 // Skip selections that overlap with a range that has already been rewrapped.
7752 let selection_range = start_row..end_row;
7753 if rewrapped_row_ranges
7754 .iter()
7755 .any(|range| range.overlaps(&selection_range))
7756 {
7757 continue;
7758 }
7759
7760 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7761
7762 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7763 match language_scope.language_name().as_ref() {
7764 "Markdown" | "Plain Text" => {
7765 should_rewrap = true;
7766 }
7767 _ => {}
7768 }
7769 }
7770
7771 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7772
7773 // Since not all lines in the selection may be at the same indent
7774 // level, choose the indent size that is the most common between all
7775 // of the lines.
7776 //
7777 // If there is a tie, we use the deepest indent.
7778 let (indent_size, indent_end) = {
7779 let mut indent_size_occurrences = HashMap::default();
7780 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7781
7782 for row in start_row..=end_row {
7783 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7784 rows_by_indent_size.entry(indent).or_default().push(row);
7785 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7786 }
7787
7788 let indent_size = indent_size_occurrences
7789 .into_iter()
7790 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7791 .map(|(indent, _)| indent)
7792 .unwrap_or_default();
7793 let row = rows_by_indent_size[&indent_size][0];
7794 let indent_end = Point::new(row, indent_size.len);
7795
7796 (indent_size, indent_end)
7797 };
7798
7799 let mut line_prefix = indent_size.chars().collect::<String>();
7800
7801 if let Some(comment_prefix) =
7802 buffer
7803 .language_scope_at(selection.head())
7804 .and_then(|language| {
7805 language
7806 .line_comment_prefixes()
7807 .iter()
7808 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7809 .cloned()
7810 })
7811 {
7812 line_prefix.push_str(&comment_prefix);
7813 should_rewrap = true;
7814 }
7815
7816 if !should_rewrap {
7817 continue;
7818 }
7819
7820 if selection.is_empty() {
7821 'expand_upwards: while start_row > 0 {
7822 let prev_row = start_row - 1;
7823 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7824 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7825 {
7826 start_row = prev_row;
7827 } else {
7828 break 'expand_upwards;
7829 }
7830 }
7831
7832 'expand_downwards: while end_row < buffer.max_point().row {
7833 let next_row = end_row + 1;
7834 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7835 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7836 {
7837 end_row = next_row;
7838 } else {
7839 break 'expand_downwards;
7840 }
7841 }
7842 }
7843
7844 let start = Point::new(start_row, 0);
7845 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7846 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7847 let Some(lines_without_prefixes) = selection_text
7848 .lines()
7849 .map(|line| {
7850 line.strip_prefix(&line_prefix)
7851 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7852 .ok_or_else(|| {
7853 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7854 })
7855 })
7856 .collect::<Result<Vec<_>, _>>()
7857 .log_err()
7858 else {
7859 continue;
7860 };
7861
7862 let wrap_column = buffer
7863 .settings_at(Point::new(start_row, 0), cx)
7864 .preferred_line_length as usize;
7865 let wrapped_text = wrap_with_prefix(
7866 line_prefix,
7867 lines_without_prefixes.join(" "),
7868 wrap_column,
7869 tab_size,
7870 );
7871
7872 // TODO: should always use char-based diff while still supporting cursor behavior that
7873 // matches vim.
7874 let diff = match is_vim_mode {
7875 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7876 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7877 };
7878 let mut offset = start.to_offset(&buffer);
7879 let mut moved_since_edit = true;
7880
7881 for change in diff.iter_all_changes() {
7882 let value = change.value();
7883 match change.tag() {
7884 ChangeTag::Equal => {
7885 offset += value.len();
7886 moved_since_edit = true;
7887 }
7888 ChangeTag::Delete => {
7889 let start = buffer.anchor_after(offset);
7890 let end = buffer.anchor_before(offset + value.len());
7891
7892 if moved_since_edit {
7893 edits.push((start..end, String::new()));
7894 } else {
7895 edits.last_mut().unwrap().0.end = end;
7896 }
7897
7898 offset += value.len();
7899 moved_since_edit = false;
7900 }
7901 ChangeTag::Insert => {
7902 if moved_since_edit {
7903 let anchor = buffer.anchor_after(offset);
7904 edits.push((anchor..anchor, value.to_string()));
7905 } else {
7906 edits.last_mut().unwrap().1.push_str(value);
7907 }
7908
7909 moved_since_edit = false;
7910 }
7911 }
7912 }
7913
7914 rewrapped_row_ranges.push(start_row..=end_row);
7915 }
7916
7917 self.buffer
7918 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7919 }
7920
7921 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7922 let mut text = String::new();
7923 let buffer = self.buffer.read(cx).snapshot(cx);
7924 let mut selections = self.selections.all::<Point>(cx);
7925 let mut clipboard_selections = Vec::with_capacity(selections.len());
7926 {
7927 let max_point = buffer.max_point();
7928 let mut is_first = true;
7929 for selection in &mut selections {
7930 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7931 if is_entire_line {
7932 selection.start = Point::new(selection.start.row, 0);
7933 if !selection.is_empty() && selection.end.column == 0 {
7934 selection.end = cmp::min(max_point, selection.end);
7935 } else {
7936 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7937 }
7938 selection.goal = SelectionGoal::None;
7939 }
7940 if is_first {
7941 is_first = false;
7942 } else {
7943 text += "\n";
7944 }
7945 let mut len = 0;
7946 for chunk in buffer.text_for_range(selection.start..selection.end) {
7947 text.push_str(chunk);
7948 len += chunk.len();
7949 }
7950 clipboard_selections.push(ClipboardSelection {
7951 len,
7952 is_entire_line,
7953 first_line_indent: buffer
7954 .indent_size_for_line(MultiBufferRow(selection.start.row))
7955 .len,
7956 });
7957 }
7958 }
7959
7960 self.transact(window, cx, |this, window, cx| {
7961 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7962 s.select(selections);
7963 });
7964 this.insert("", window, cx);
7965 });
7966 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7967 }
7968
7969 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7970 let item = self.cut_common(window, cx);
7971 cx.write_to_clipboard(item);
7972 }
7973
7974 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7975 self.change_selections(None, window, cx, |s| {
7976 s.move_with(|snapshot, sel| {
7977 if sel.is_empty() {
7978 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7979 }
7980 });
7981 });
7982 let item = self.cut_common(window, cx);
7983 cx.set_global(KillRing(item))
7984 }
7985
7986 pub fn kill_ring_yank(
7987 &mut self,
7988 _: &KillRingYank,
7989 window: &mut Window,
7990 cx: &mut Context<Self>,
7991 ) {
7992 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7993 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7994 (kill_ring.text().to_string(), kill_ring.metadata_json())
7995 } else {
7996 return;
7997 }
7998 } else {
7999 return;
8000 };
8001 self.do_paste(&text, metadata, false, window, cx);
8002 }
8003
8004 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8005 let selections = self.selections.all::<Point>(cx);
8006 let buffer = self.buffer.read(cx).read(cx);
8007 let mut text = String::new();
8008
8009 let mut clipboard_selections = Vec::with_capacity(selections.len());
8010 {
8011 let max_point = buffer.max_point();
8012 let mut is_first = true;
8013 for selection in selections.iter() {
8014 let mut start = selection.start;
8015 let mut end = selection.end;
8016 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8017 if is_entire_line {
8018 start = Point::new(start.row, 0);
8019 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8020 }
8021 if is_first {
8022 is_first = false;
8023 } else {
8024 text += "\n";
8025 }
8026 let mut len = 0;
8027 for chunk in buffer.text_for_range(start..end) {
8028 text.push_str(chunk);
8029 len += chunk.len();
8030 }
8031 clipboard_selections.push(ClipboardSelection {
8032 len,
8033 is_entire_line,
8034 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8035 });
8036 }
8037 }
8038
8039 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8040 text,
8041 clipboard_selections,
8042 ));
8043 }
8044
8045 pub fn do_paste(
8046 &mut self,
8047 text: &String,
8048 clipboard_selections: Option<Vec<ClipboardSelection>>,
8049 handle_entire_lines: bool,
8050 window: &mut Window,
8051 cx: &mut Context<Self>,
8052 ) {
8053 if self.read_only(cx) {
8054 return;
8055 }
8056
8057 let clipboard_text = Cow::Borrowed(text);
8058
8059 self.transact(window, cx, |this, window, cx| {
8060 if let Some(mut clipboard_selections) = clipboard_selections {
8061 let old_selections = this.selections.all::<usize>(cx);
8062 let all_selections_were_entire_line =
8063 clipboard_selections.iter().all(|s| s.is_entire_line);
8064 let first_selection_indent_column =
8065 clipboard_selections.first().map(|s| s.first_line_indent);
8066 if clipboard_selections.len() != old_selections.len() {
8067 clipboard_selections.drain(..);
8068 }
8069 let cursor_offset = this.selections.last::<usize>(cx).head();
8070 let mut auto_indent_on_paste = true;
8071
8072 this.buffer.update(cx, |buffer, cx| {
8073 let snapshot = buffer.read(cx);
8074 auto_indent_on_paste =
8075 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8076
8077 let mut start_offset = 0;
8078 let mut edits = Vec::new();
8079 let mut original_indent_columns = Vec::new();
8080 for (ix, selection) in old_selections.iter().enumerate() {
8081 let to_insert;
8082 let entire_line;
8083 let original_indent_column;
8084 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8085 let end_offset = start_offset + clipboard_selection.len;
8086 to_insert = &clipboard_text[start_offset..end_offset];
8087 entire_line = clipboard_selection.is_entire_line;
8088 start_offset = end_offset + 1;
8089 original_indent_column = Some(clipboard_selection.first_line_indent);
8090 } else {
8091 to_insert = clipboard_text.as_str();
8092 entire_line = all_selections_were_entire_line;
8093 original_indent_column = first_selection_indent_column
8094 }
8095
8096 // If the corresponding selection was empty when this slice of the
8097 // clipboard text was written, then the entire line containing the
8098 // selection was copied. If this selection is also currently empty,
8099 // then paste the line before the current line of the buffer.
8100 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8101 let column = selection.start.to_point(&snapshot).column as usize;
8102 let line_start = selection.start - column;
8103 line_start..line_start
8104 } else {
8105 selection.range()
8106 };
8107
8108 edits.push((range, to_insert));
8109 original_indent_columns.extend(original_indent_column);
8110 }
8111 drop(snapshot);
8112
8113 buffer.edit(
8114 edits,
8115 if auto_indent_on_paste {
8116 Some(AutoindentMode::Block {
8117 original_indent_columns,
8118 })
8119 } else {
8120 None
8121 },
8122 cx,
8123 );
8124 });
8125
8126 let selections = this.selections.all::<usize>(cx);
8127 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8128 s.select(selections)
8129 });
8130 } else {
8131 this.insert(&clipboard_text, window, cx);
8132 }
8133 });
8134 }
8135
8136 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8137 if let Some(item) = cx.read_from_clipboard() {
8138 let entries = item.entries();
8139
8140 match entries.first() {
8141 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8142 // of all the pasted entries.
8143 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8144 .do_paste(
8145 clipboard_string.text(),
8146 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8147 true,
8148 window,
8149 cx,
8150 ),
8151 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8152 }
8153 }
8154 }
8155
8156 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8157 if self.read_only(cx) {
8158 return;
8159 }
8160
8161 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8162 if let Some((selections, _)) =
8163 self.selection_history.transaction(transaction_id).cloned()
8164 {
8165 self.change_selections(None, window, cx, |s| {
8166 s.select_anchors(selections.to_vec());
8167 });
8168 }
8169 self.request_autoscroll(Autoscroll::fit(), cx);
8170 self.unmark_text(window, cx);
8171 self.refresh_inline_completion(true, false, window, cx);
8172 cx.emit(EditorEvent::Edited { transaction_id });
8173 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8174 }
8175 }
8176
8177 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8178 if self.read_only(cx) {
8179 return;
8180 }
8181
8182 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8183 if let Some((_, Some(selections))) =
8184 self.selection_history.transaction(transaction_id).cloned()
8185 {
8186 self.change_selections(None, window, cx, |s| {
8187 s.select_anchors(selections.to_vec());
8188 });
8189 }
8190 self.request_autoscroll(Autoscroll::fit(), cx);
8191 self.unmark_text(window, cx);
8192 self.refresh_inline_completion(true, false, window, cx);
8193 cx.emit(EditorEvent::Edited { transaction_id });
8194 }
8195 }
8196
8197 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8198 self.buffer
8199 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8200 }
8201
8202 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8203 self.buffer
8204 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8205 }
8206
8207 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8208 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8209 let line_mode = s.line_mode;
8210 s.move_with(|map, selection| {
8211 let cursor = if selection.is_empty() && !line_mode {
8212 movement::left(map, selection.start)
8213 } else {
8214 selection.start
8215 };
8216 selection.collapse_to(cursor, SelectionGoal::None);
8217 });
8218 })
8219 }
8220
8221 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8222 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8223 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8224 })
8225 }
8226
8227 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8228 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8229 let line_mode = s.line_mode;
8230 s.move_with(|map, selection| {
8231 let cursor = if selection.is_empty() && !line_mode {
8232 movement::right(map, selection.end)
8233 } else {
8234 selection.end
8235 };
8236 selection.collapse_to(cursor, SelectionGoal::None)
8237 });
8238 })
8239 }
8240
8241 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8242 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8243 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8244 })
8245 }
8246
8247 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8248 if self.take_rename(true, window, cx).is_some() {
8249 return;
8250 }
8251
8252 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8253 cx.propagate();
8254 return;
8255 }
8256
8257 let text_layout_details = &self.text_layout_details(window);
8258 let selection_count = self.selections.count();
8259 let first_selection = self.selections.first_anchor();
8260
8261 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8262 let line_mode = s.line_mode;
8263 s.move_with(|map, selection| {
8264 if !selection.is_empty() && !line_mode {
8265 selection.goal = SelectionGoal::None;
8266 }
8267 let (cursor, goal) = movement::up(
8268 map,
8269 selection.start,
8270 selection.goal,
8271 false,
8272 text_layout_details,
8273 );
8274 selection.collapse_to(cursor, goal);
8275 });
8276 });
8277
8278 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8279 {
8280 cx.propagate();
8281 }
8282 }
8283
8284 pub fn move_up_by_lines(
8285 &mut self,
8286 action: &MoveUpByLines,
8287 window: &mut Window,
8288 cx: &mut Context<Self>,
8289 ) {
8290 if self.take_rename(true, window, cx).is_some() {
8291 return;
8292 }
8293
8294 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8295 cx.propagate();
8296 return;
8297 }
8298
8299 let text_layout_details = &self.text_layout_details(window);
8300
8301 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8302 let line_mode = s.line_mode;
8303 s.move_with(|map, selection| {
8304 if !selection.is_empty() && !line_mode {
8305 selection.goal = SelectionGoal::None;
8306 }
8307 let (cursor, goal) = movement::up_by_rows(
8308 map,
8309 selection.start,
8310 action.lines,
8311 selection.goal,
8312 false,
8313 text_layout_details,
8314 );
8315 selection.collapse_to(cursor, goal);
8316 });
8317 })
8318 }
8319
8320 pub fn move_down_by_lines(
8321 &mut self,
8322 action: &MoveDownByLines,
8323 window: &mut Window,
8324 cx: &mut Context<Self>,
8325 ) {
8326 if self.take_rename(true, window, cx).is_some() {
8327 return;
8328 }
8329
8330 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8331 cx.propagate();
8332 return;
8333 }
8334
8335 let text_layout_details = &self.text_layout_details(window);
8336
8337 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8338 let line_mode = s.line_mode;
8339 s.move_with(|map, selection| {
8340 if !selection.is_empty() && !line_mode {
8341 selection.goal = SelectionGoal::None;
8342 }
8343 let (cursor, goal) = movement::down_by_rows(
8344 map,
8345 selection.start,
8346 action.lines,
8347 selection.goal,
8348 false,
8349 text_layout_details,
8350 );
8351 selection.collapse_to(cursor, goal);
8352 });
8353 })
8354 }
8355
8356 pub fn select_down_by_lines(
8357 &mut self,
8358 action: &SelectDownByLines,
8359 window: &mut Window,
8360 cx: &mut Context<Self>,
8361 ) {
8362 let text_layout_details = &self.text_layout_details(window);
8363 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8364 s.move_heads_with(|map, head, goal| {
8365 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8366 })
8367 })
8368 }
8369
8370 pub fn select_up_by_lines(
8371 &mut self,
8372 action: &SelectUpByLines,
8373 window: &mut Window,
8374 cx: &mut Context<Self>,
8375 ) {
8376 let text_layout_details = &self.text_layout_details(window);
8377 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8378 s.move_heads_with(|map, head, goal| {
8379 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8380 })
8381 })
8382 }
8383
8384 pub fn select_page_up(
8385 &mut self,
8386 _: &SelectPageUp,
8387 window: &mut Window,
8388 cx: &mut Context<Self>,
8389 ) {
8390 let Some(row_count) = self.visible_row_count() else {
8391 return;
8392 };
8393
8394 let text_layout_details = &self.text_layout_details(window);
8395
8396 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8397 s.move_heads_with(|map, head, goal| {
8398 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8399 })
8400 })
8401 }
8402
8403 pub fn move_page_up(
8404 &mut self,
8405 action: &MovePageUp,
8406 window: &mut Window,
8407 cx: &mut Context<Self>,
8408 ) {
8409 if self.take_rename(true, window, cx).is_some() {
8410 return;
8411 }
8412
8413 if self
8414 .context_menu
8415 .borrow_mut()
8416 .as_mut()
8417 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8418 .unwrap_or(false)
8419 {
8420 return;
8421 }
8422
8423 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8424 cx.propagate();
8425 return;
8426 }
8427
8428 let Some(row_count) = self.visible_row_count() else {
8429 return;
8430 };
8431
8432 let autoscroll = if action.center_cursor {
8433 Autoscroll::center()
8434 } else {
8435 Autoscroll::fit()
8436 };
8437
8438 let text_layout_details = &self.text_layout_details(window);
8439
8440 self.change_selections(Some(autoscroll), window, cx, |s| {
8441 let line_mode = s.line_mode;
8442 s.move_with(|map, selection| {
8443 if !selection.is_empty() && !line_mode {
8444 selection.goal = SelectionGoal::None;
8445 }
8446 let (cursor, goal) = movement::up_by_rows(
8447 map,
8448 selection.end,
8449 row_count,
8450 selection.goal,
8451 false,
8452 text_layout_details,
8453 );
8454 selection.collapse_to(cursor, goal);
8455 });
8456 });
8457 }
8458
8459 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8460 let text_layout_details = &self.text_layout_details(window);
8461 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8462 s.move_heads_with(|map, head, goal| {
8463 movement::up(map, head, goal, false, text_layout_details)
8464 })
8465 })
8466 }
8467
8468 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8469 self.take_rename(true, window, cx);
8470
8471 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8472 cx.propagate();
8473 return;
8474 }
8475
8476 let text_layout_details = &self.text_layout_details(window);
8477 let selection_count = self.selections.count();
8478 let first_selection = self.selections.first_anchor();
8479
8480 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8481 let line_mode = s.line_mode;
8482 s.move_with(|map, selection| {
8483 if !selection.is_empty() && !line_mode {
8484 selection.goal = SelectionGoal::None;
8485 }
8486 let (cursor, goal) = movement::down(
8487 map,
8488 selection.end,
8489 selection.goal,
8490 false,
8491 text_layout_details,
8492 );
8493 selection.collapse_to(cursor, goal);
8494 });
8495 });
8496
8497 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8498 {
8499 cx.propagate();
8500 }
8501 }
8502
8503 pub fn select_page_down(
8504 &mut self,
8505 _: &SelectPageDown,
8506 window: &mut Window,
8507 cx: &mut Context<Self>,
8508 ) {
8509 let Some(row_count) = self.visible_row_count() else {
8510 return;
8511 };
8512
8513 let text_layout_details = &self.text_layout_details(window);
8514
8515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8516 s.move_heads_with(|map, head, goal| {
8517 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8518 })
8519 })
8520 }
8521
8522 pub fn move_page_down(
8523 &mut self,
8524 action: &MovePageDown,
8525 window: &mut Window,
8526 cx: &mut Context<Self>,
8527 ) {
8528 if self.take_rename(true, window, cx).is_some() {
8529 return;
8530 }
8531
8532 if self
8533 .context_menu
8534 .borrow_mut()
8535 .as_mut()
8536 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8537 .unwrap_or(false)
8538 {
8539 return;
8540 }
8541
8542 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8543 cx.propagate();
8544 return;
8545 }
8546
8547 let Some(row_count) = self.visible_row_count() else {
8548 return;
8549 };
8550
8551 let autoscroll = if action.center_cursor {
8552 Autoscroll::center()
8553 } else {
8554 Autoscroll::fit()
8555 };
8556
8557 let text_layout_details = &self.text_layout_details(window);
8558 self.change_selections(Some(autoscroll), window, cx, |s| {
8559 let line_mode = s.line_mode;
8560 s.move_with(|map, selection| {
8561 if !selection.is_empty() && !line_mode {
8562 selection.goal = SelectionGoal::None;
8563 }
8564 let (cursor, goal) = movement::down_by_rows(
8565 map,
8566 selection.end,
8567 row_count,
8568 selection.goal,
8569 false,
8570 text_layout_details,
8571 );
8572 selection.collapse_to(cursor, goal);
8573 });
8574 });
8575 }
8576
8577 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8578 let text_layout_details = &self.text_layout_details(window);
8579 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8580 s.move_heads_with(|map, head, goal| {
8581 movement::down(map, head, goal, false, text_layout_details)
8582 })
8583 });
8584 }
8585
8586 pub fn context_menu_first(
8587 &mut self,
8588 _: &ContextMenuFirst,
8589 _window: &mut Window,
8590 cx: &mut Context<Self>,
8591 ) {
8592 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8593 context_menu.select_first(self.completion_provider.as_deref(), cx);
8594 }
8595 }
8596
8597 pub fn context_menu_prev(
8598 &mut self,
8599 _: &ContextMenuPrev,
8600 _window: &mut Window,
8601 cx: &mut Context<Self>,
8602 ) {
8603 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8604 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8605 }
8606 }
8607
8608 pub fn context_menu_next(
8609 &mut self,
8610 _: &ContextMenuNext,
8611 _window: &mut Window,
8612 cx: &mut Context<Self>,
8613 ) {
8614 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8615 context_menu.select_next(self.completion_provider.as_deref(), cx);
8616 }
8617 }
8618
8619 pub fn context_menu_last(
8620 &mut self,
8621 _: &ContextMenuLast,
8622 _window: &mut Window,
8623 cx: &mut Context<Self>,
8624 ) {
8625 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8626 context_menu.select_last(self.completion_provider.as_deref(), cx);
8627 }
8628 }
8629
8630 pub fn move_to_previous_word_start(
8631 &mut self,
8632 _: &MoveToPreviousWordStart,
8633 window: &mut Window,
8634 cx: &mut Context<Self>,
8635 ) {
8636 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8637 s.move_cursors_with(|map, head, _| {
8638 (
8639 movement::previous_word_start(map, head),
8640 SelectionGoal::None,
8641 )
8642 });
8643 })
8644 }
8645
8646 pub fn move_to_previous_subword_start(
8647 &mut self,
8648 _: &MoveToPreviousSubwordStart,
8649 window: &mut Window,
8650 cx: &mut Context<Self>,
8651 ) {
8652 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8653 s.move_cursors_with(|map, head, _| {
8654 (
8655 movement::previous_subword_start(map, head),
8656 SelectionGoal::None,
8657 )
8658 });
8659 })
8660 }
8661
8662 pub fn select_to_previous_word_start(
8663 &mut self,
8664 _: &SelectToPreviousWordStart,
8665 window: &mut Window,
8666 cx: &mut Context<Self>,
8667 ) {
8668 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8669 s.move_heads_with(|map, head, _| {
8670 (
8671 movement::previous_word_start(map, head),
8672 SelectionGoal::None,
8673 )
8674 });
8675 })
8676 }
8677
8678 pub fn select_to_previous_subword_start(
8679 &mut self,
8680 _: &SelectToPreviousSubwordStart,
8681 window: &mut Window,
8682 cx: &mut Context<Self>,
8683 ) {
8684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8685 s.move_heads_with(|map, head, _| {
8686 (
8687 movement::previous_subword_start(map, head),
8688 SelectionGoal::None,
8689 )
8690 });
8691 })
8692 }
8693
8694 pub fn delete_to_previous_word_start(
8695 &mut self,
8696 action: &DeleteToPreviousWordStart,
8697 window: &mut Window,
8698 cx: &mut Context<Self>,
8699 ) {
8700 self.transact(window, cx, |this, window, cx| {
8701 this.select_autoclose_pair(window, cx);
8702 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8703 let line_mode = s.line_mode;
8704 s.move_with(|map, selection| {
8705 if selection.is_empty() && !line_mode {
8706 let cursor = if action.ignore_newlines {
8707 movement::previous_word_start(map, selection.head())
8708 } else {
8709 movement::previous_word_start_or_newline(map, selection.head())
8710 };
8711 selection.set_head(cursor, SelectionGoal::None);
8712 }
8713 });
8714 });
8715 this.insert("", window, cx);
8716 });
8717 }
8718
8719 pub fn delete_to_previous_subword_start(
8720 &mut self,
8721 _: &DeleteToPreviousSubwordStart,
8722 window: &mut Window,
8723 cx: &mut Context<Self>,
8724 ) {
8725 self.transact(window, cx, |this, window, cx| {
8726 this.select_autoclose_pair(window, cx);
8727 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8728 let line_mode = s.line_mode;
8729 s.move_with(|map, selection| {
8730 if selection.is_empty() && !line_mode {
8731 let cursor = movement::previous_subword_start(map, selection.head());
8732 selection.set_head(cursor, SelectionGoal::None);
8733 }
8734 });
8735 });
8736 this.insert("", window, cx);
8737 });
8738 }
8739
8740 pub fn move_to_next_word_end(
8741 &mut self,
8742 _: &MoveToNextWordEnd,
8743 window: &mut Window,
8744 cx: &mut Context<Self>,
8745 ) {
8746 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8747 s.move_cursors_with(|map, head, _| {
8748 (movement::next_word_end(map, head), SelectionGoal::None)
8749 });
8750 })
8751 }
8752
8753 pub fn move_to_next_subword_end(
8754 &mut self,
8755 _: &MoveToNextSubwordEnd,
8756 window: &mut Window,
8757 cx: &mut Context<Self>,
8758 ) {
8759 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8760 s.move_cursors_with(|map, head, _| {
8761 (movement::next_subword_end(map, head), SelectionGoal::None)
8762 });
8763 })
8764 }
8765
8766 pub fn select_to_next_word_end(
8767 &mut self,
8768 _: &SelectToNextWordEnd,
8769 window: &mut Window,
8770 cx: &mut Context<Self>,
8771 ) {
8772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.move_heads_with(|map, head, _| {
8774 (movement::next_word_end(map, head), SelectionGoal::None)
8775 });
8776 })
8777 }
8778
8779 pub fn select_to_next_subword_end(
8780 &mut self,
8781 _: &SelectToNextSubwordEnd,
8782 window: &mut Window,
8783 cx: &mut Context<Self>,
8784 ) {
8785 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8786 s.move_heads_with(|map, head, _| {
8787 (movement::next_subword_end(map, head), SelectionGoal::None)
8788 });
8789 })
8790 }
8791
8792 pub fn delete_to_next_word_end(
8793 &mut self,
8794 action: &DeleteToNextWordEnd,
8795 window: &mut Window,
8796 cx: &mut Context<Self>,
8797 ) {
8798 self.transact(window, cx, |this, window, cx| {
8799 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8800 let line_mode = s.line_mode;
8801 s.move_with(|map, selection| {
8802 if selection.is_empty() && !line_mode {
8803 let cursor = if action.ignore_newlines {
8804 movement::next_word_end(map, selection.head())
8805 } else {
8806 movement::next_word_end_or_newline(map, selection.head())
8807 };
8808 selection.set_head(cursor, SelectionGoal::None);
8809 }
8810 });
8811 });
8812 this.insert("", window, cx);
8813 });
8814 }
8815
8816 pub fn delete_to_next_subword_end(
8817 &mut self,
8818 _: &DeleteToNextSubwordEnd,
8819 window: &mut Window,
8820 cx: &mut Context<Self>,
8821 ) {
8822 self.transact(window, cx, |this, window, cx| {
8823 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8824 s.move_with(|map, selection| {
8825 if selection.is_empty() {
8826 let cursor = movement::next_subword_end(map, selection.head());
8827 selection.set_head(cursor, SelectionGoal::None);
8828 }
8829 });
8830 });
8831 this.insert("", window, cx);
8832 });
8833 }
8834
8835 pub fn move_to_beginning_of_line(
8836 &mut self,
8837 action: &MoveToBeginningOfLine,
8838 window: &mut Window,
8839 cx: &mut Context<Self>,
8840 ) {
8841 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8842 s.move_cursors_with(|map, head, _| {
8843 (
8844 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8845 SelectionGoal::None,
8846 )
8847 });
8848 })
8849 }
8850
8851 pub fn select_to_beginning_of_line(
8852 &mut self,
8853 action: &SelectToBeginningOfLine,
8854 window: &mut Window,
8855 cx: &mut Context<Self>,
8856 ) {
8857 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8858 s.move_heads_with(|map, head, _| {
8859 (
8860 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8861 SelectionGoal::None,
8862 )
8863 });
8864 });
8865 }
8866
8867 pub fn delete_to_beginning_of_line(
8868 &mut self,
8869 _: &DeleteToBeginningOfLine,
8870 window: &mut Window,
8871 cx: &mut Context<Self>,
8872 ) {
8873 self.transact(window, cx, |this, window, cx| {
8874 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8875 s.move_with(|_, selection| {
8876 selection.reversed = true;
8877 });
8878 });
8879
8880 this.select_to_beginning_of_line(
8881 &SelectToBeginningOfLine {
8882 stop_at_soft_wraps: false,
8883 },
8884 window,
8885 cx,
8886 );
8887 this.backspace(&Backspace, window, cx);
8888 });
8889 }
8890
8891 pub fn move_to_end_of_line(
8892 &mut self,
8893 action: &MoveToEndOfLine,
8894 window: &mut Window,
8895 cx: &mut Context<Self>,
8896 ) {
8897 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8898 s.move_cursors_with(|map, head, _| {
8899 (
8900 movement::line_end(map, head, action.stop_at_soft_wraps),
8901 SelectionGoal::None,
8902 )
8903 });
8904 })
8905 }
8906
8907 pub fn select_to_end_of_line(
8908 &mut self,
8909 action: &SelectToEndOfLine,
8910 window: &mut Window,
8911 cx: &mut Context<Self>,
8912 ) {
8913 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8914 s.move_heads_with(|map, head, _| {
8915 (
8916 movement::line_end(map, head, action.stop_at_soft_wraps),
8917 SelectionGoal::None,
8918 )
8919 });
8920 })
8921 }
8922
8923 pub fn delete_to_end_of_line(
8924 &mut self,
8925 _: &DeleteToEndOfLine,
8926 window: &mut Window,
8927 cx: &mut Context<Self>,
8928 ) {
8929 self.transact(window, cx, |this, window, cx| {
8930 this.select_to_end_of_line(
8931 &SelectToEndOfLine {
8932 stop_at_soft_wraps: false,
8933 },
8934 window,
8935 cx,
8936 );
8937 this.delete(&Delete, window, cx);
8938 });
8939 }
8940
8941 pub fn cut_to_end_of_line(
8942 &mut self,
8943 _: &CutToEndOfLine,
8944 window: &mut Window,
8945 cx: &mut Context<Self>,
8946 ) {
8947 self.transact(window, cx, |this, window, cx| {
8948 this.select_to_end_of_line(
8949 &SelectToEndOfLine {
8950 stop_at_soft_wraps: false,
8951 },
8952 window,
8953 cx,
8954 );
8955 this.cut(&Cut, window, cx);
8956 });
8957 }
8958
8959 pub fn move_to_start_of_paragraph(
8960 &mut self,
8961 _: &MoveToStartOfParagraph,
8962 window: &mut Window,
8963 cx: &mut Context<Self>,
8964 ) {
8965 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8966 cx.propagate();
8967 return;
8968 }
8969
8970 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8971 s.move_with(|map, selection| {
8972 selection.collapse_to(
8973 movement::start_of_paragraph(map, selection.head(), 1),
8974 SelectionGoal::None,
8975 )
8976 });
8977 })
8978 }
8979
8980 pub fn move_to_end_of_paragraph(
8981 &mut self,
8982 _: &MoveToEndOfParagraph,
8983 window: &mut Window,
8984 cx: &mut Context<Self>,
8985 ) {
8986 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8987 cx.propagate();
8988 return;
8989 }
8990
8991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8992 s.move_with(|map, selection| {
8993 selection.collapse_to(
8994 movement::end_of_paragraph(map, selection.head(), 1),
8995 SelectionGoal::None,
8996 )
8997 });
8998 })
8999 }
9000
9001 pub fn select_to_start_of_paragraph(
9002 &mut self,
9003 _: &SelectToStartOfParagraph,
9004 window: &mut Window,
9005 cx: &mut Context<Self>,
9006 ) {
9007 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9008 cx.propagate();
9009 return;
9010 }
9011
9012 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9013 s.move_heads_with(|map, head, _| {
9014 (
9015 movement::start_of_paragraph(map, head, 1),
9016 SelectionGoal::None,
9017 )
9018 });
9019 })
9020 }
9021
9022 pub fn select_to_end_of_paragraph(
9023 &mut self,
9024 _: &SelectToEndOfParagraph,
9025 window: &mut Window,
9026 cx: &mut Context<Self>,
9027 ) {
9028 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9029 cx.propagate();
9030 return;
9031 }
9032
9033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9034 s.move_heads_with(|map, head, _| {
9035 (
9036 movement::end_of_paragraph(map, head, 1),
9037 SelectionGoal::None,
9038 )
9039 });
9040 })
9041 }
9042
9043 pub fn move_to_beginning(
9044 &mut self,
9045 _: &MoveToBeginning,
9046 window: &mut Window,
9047 cx: &mut Context<Self>,
9048 ) {
9049 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9050 cx.propagate();
9051 return;
9052 }
9053
9054 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9055 s.select_ranges(vec![0..0]);
9056 });
9057 }
9058
9059 pub fn select_to_beginning(
9060 &mut self,
9061 _: &SelectToBeginning,
9062 window: &mut Window,
9063 cx: &mut Context<Self>,
9064 ) {
9065 let mut selection = self.selections.last::<Point>(cx);
9066 selection.set_head(Point::zero(), SelectionGoal::None);
9067
9068 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9069 s.select(vec![selection]);
9070 });
9071 }
9072
9073 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9074 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9075 cx.propagate();
9076 return;
9077 }
9078
9079 let cursor = self.buffer.read(cx).read(cx).len();
9080 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9081 s.select_ranges(vec![cursor..cursor])
9082 });
9083 }
9084
9085 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9086 self.nav_history = nav_history;
9087 }
9088
9089 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9090 self.nav_history.as_ref()
9091 }
9092
9093 fn push_to_nav_history(
9094 &mut self,
9095 cursor_anchor: Anchor,
9096 new_position: Option<Point>,
9097 cx: &mut Context<Self>,
9098 ) {
9099 if let Some(nav_history) = self.nav_history.as_mut() {
9100 let buffer = self.buffer.read(cx).read(cx);
9101 let cursor_position = cursor_anchor.to_point(&buffer);
9102 let scroll_state = self.scroll_manager.anchor();
9103 let scroll_top_row = scroll_state.top_row(&buffer);
9104 drop(buffer);
9105
9106 if let Some(new_position) = new_position {
9107 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9108 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9109 return;
9110 }
9111 }
9112
9113 nav_history.push(
9114 Some(NavigationData {
9115 cursor_anchor,
9116 cursor_position,
9117 scroll_anchor: scroll_state,
9118 scroll_top_row,
9119 }),
9120 cx,
9121 );
9122 }
9123 }
9124
9125 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9126 let buffer = self.buffer.read(cx).snapshot(cx);
9127 let mut selection = self.selections.first::<usize>(cx);
9128 selection.set_head(buffer.len(), SelectionGoal::None);
9129 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9130 s.select(vec![selection]);
9131 });
9132 }
9133
9134 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9135 let end = self.buffer.read(cx).read(cx).len();
9136 self.change_selections(None, window, cx, |s| {
9137 s.select_ranges(vec![0..end]);
9138 });
9139 }
9140
9141 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9142 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9143 let mut selections = self.selections.all::<Point>(cx);
9144 let max_point = display_map.buffer_snapshot.max_point();
9145 for selection in &mut selections {
9146 let rows = selection.spanned_rows(true, &display_map);
9147 selection.start = Point::new(rows.start.0, 0);
9148 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9149 selection.reversed = false;
9150 }
9151 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9152 s.select(selections);
9153 });
9154 }
9155
9156 pub fn split_selection_into_lines(
9157 &mut self,
9158 _: &SplitSelectionIntoLines,
9159 window: &mut Window,
9160 cx: &mut Context<Self>,
9161 ) {
9162 let selections = self
9163 .selections
9164 .all::<Point>(cx)
9165 .into_iter()
9166 .map(|selection| selection.start..selection.end)
9167 .collect::<Vec<_>>();
9168 self.unfold_ranges(&selections, true, true, cx);
9169
9170 let mut new_selection_ranges = Vec::new();
9171 {
9172 let buffer = self.buffer.read(cx).read(cx);
9173 for selection in selections {
9174 for row in selection.start.row..selection.end.row {
9175 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9176 new_selection_ranges.push(cursor..cursor);
9177 }
9178
9179 let is_multiline_selection = selection.start.row != selection.end.row;
9180 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9181 // so this action feels more ergonomic when paired with other selection operations
9182 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9183 if !should_skip_last {
9184 new_selection_ranges.push(selection.end..selection.end);
9185 }
9186 }
9187 }
9188 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9189 s.select_ranges(new_selection_ranges);
9190 });
9191 }
9192
9193 pub fn add_selection_above(
9194 &mut self,
9195 _: &AddSelectionAbove,
9196 window: &mut Window,
9197 cx: &mut Context<Self>,
9198 ) {
9199 self.add_selection(true, window, cx);
9200 }
9201
9202 pub fn add_selection_below(
9203 &mut self,
9204 _: &AddSelectionBelow,
9205 window: &mut Window,
9206 cx: &mut Context<Self>,
9207 ) {
9208 self.add_selection(false, window, cx);
9209 }
9210
9211 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9212 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9213 let mut selections = self.selections.all::<Point>(cx);
9214 let text_layout_details = self.text_layout_details(window);
9215 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9216 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9217 let range = oldest_selection.display_range(&display_map).sorted();
9218
9219 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9220 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9221 let positions = start_x.min(end_x)..start_x.max(end_x);
9222
9223 selections.clear();
9224 let mut stack = Vec::new();
9225 for row in range.start.row().0..=range.end.row().0 {
9226 if let Some(selection) = self.selections.build_columnar_selection(
9227 &display_map,
9228 DisplayRow(row),
9229 &positions,
9230 oldest_selection.reversed,
9231 &text_layout_details,
9232 ) {
9233 stack.push(selection.id);
9234 selections.push(selection);
9235 }
9236 }
9237
9238 if above {
9239 stack.reverse();
9240 }
9241
9242 AddSelectionsState { above, stack }
9243 });
9244
9245 let last_added_selection = *state.stack.last().unwrap();
9246 let mut new_selections = Vec::new();
9247 if above == state.above {
9248 let end_row = if above {
9249 DisplayRow(0)
9250 } else {
9251 display_map.max_point().row()
9252 };
9253
9254 'outer: for selection in selections {
9255 if selection.id == last_added_selection {
9256 let range = selection.display_range(&display_map).sorted();
9257 debug_assert_eq!(range.start.row(), range.end.row());
9258 let mut row = range.start.row();
9259 let positions =
9260 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9261 px(start)..px(end)
9262 } else {
9263 let start_x =
9264 display_map.x_for_display_point(range.start, &text_layout_details);
9265 let end_x =
9266 display_map.x_for_display_point(range.end, &text_layout_details);
9267 start_x.min(end_x)..start_x.max(end_x)
9268 };
9269
9270 while row != end_row {
9271 if above {
9272 row.0 -= 1;
9273 } else {
9274 row.0 += 1;
9275 }
9276
9277 if let Some(new_selection) = self.selections.build_columnar_selection(
9278 &display_map,
9279 row,
9280 &positions,
9281 selection.reversed,
9282 &text_layout_details,
9283 ) {
9284 state.stack.push(new_selection.id);
9285 if above {
9286 new_selections.push(new_selection);
9287 new_selections.push(selection);
9288 } else {
9289 new_selections.push(selection);
9290 new_selections.push(new_selection);
9291 }
9292
9293 continue 'outer;
9294 }
9295 }
9296 }
9297
9298 new_selections.push(selection);
9299 }
9300 } else {
9301 new_selections = selections;
9302 new_selections.retain(|s| s.id != last_added_selection);
9303 state.stack.pop();
9304 }
9305
9306 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9307 s.select(new_selections);
9308 });
9309 if state.stack.len() > 1 {
9310 self.add_selections_state = Some(state);
9311 }
9312 }
9313
9314 pub fn select_next_match_internal(
9315 &mut self,
9316 display_map: &DisplaySnapshot,
9317 replace_newest: bool,
9318 autoscroll: Option<Autoscroll>,
9319 window: &mut Window,
9320 cx: &mut Context<Self>,
9321 ) -> Result<()> {
9322 fn select_next_match_ranges(
9323 this: &mut Editor,
9324 range: Range<usize>,
9325 replace_newest: bool,
9326 auto_scroll: Option<Autoscroll>,
9327 window: &mut Window,
9328 cx: &mut Context<Editor>,
9329 ) {
9330 this.unfold_ranges(&[range.clone()], false, true, cx);
9331 this.change_selections(auto_scroll, window, cx, |s| {
9332 if replace_newest {
9333 s.delete(s.newest_anchor().id);
9334 }
9335 s.insert_range(range.clone());
9336 });
9337 }
9338
9339 let buffer = &display_map.buffer_snapshot;
9340 let mut selections = self.selections.all::<usize>(cx);
9341 if let Some(mut select_next_state) = self.select_next_state.take() {
9342 let query = &select_next_state.query;
9343 if !select_next_state.done {
9344 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9345 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9346 let mut next_selected_range = None;
9347
9348 let bytes_after_last_selection =
9349 buffer.bytes_in_range(last_selection.end..buffer.len());
9350 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9351 let query_matches = query
9352 .stream_find_iter(bytes_after_last_selection)
9353 .map(|result| (last_selection.end, result))
9354 .chain(
9355 query
9356 .stream_find_iter(bytes_before_first_selection)
9357 .map(|result| (0, result)),
9358 );
9359
9360 for (start_offset, query_match) in query_matches {
9361 let query_match = query_match.unwrap(); // can only fail due to I/O
9362 let offset_range =
9363 start_offset + query_match.start()..start_offset + query_match.end();
9364 let display_range = offset_range.start.to_display_point(display_map)
9365 ..offset_range.end.to_display_point(display_map);
9366
9367 if !select_next_state.wordwise
9368 || (!movement::is_inside_word(display_map, display_range.start)
9369 && !movement::is_inside_word(display_map, display_range.end))
9370 {
9371 // TODO: This is n^2, because we might check all the selections
9372 if !selections
9373 .iter()
9374 .any(|selection| selection.range().overlaps(&offset_range))
9375 {
9376 next_selected_range = Some(offset_range);
9377 break;
9378 }
9379 }
9380 }
9381
9382 if let Some(next_selected_range) = next_selected_range {
9383 select_next_match_ranges(
9384 self,
9385 next_selected_range,
9386 replace_newest,
9387 autoscroll,
9388 window,
9389 cx,
9390 );
9391 } else {
9392 select_next_state.done = true;
9393 }
9394 }
9395
9396 self.select_next_state = Some(select_next_state);
9397 } else {
9398 let mut only_carets = true;
9399 let mut same_text_selected = true;
9400 let mut selected_text = None;
9401
9402 let mut selections_iter = selections.iter().peekable();
9403 while let Some(selection) = selections_iter.next() {
9404 if selection.start != selection.end {
9405 only_carets = false;
9406 }
9407
9408 if same_text_selected {
9409 if selected_text.is_none() {
9410 selected_text =
9411 Some(buffer.text_for_range(selection.range()).collect::<String>());
9412 }
9413
9414 if let Some(next_selection) = selections_iter.peek() {
9415 if next_selection.range().len() == selection.range().len() {
9416 let next_selected_text = buffer
9417 .text_for_range(next_selection.range())
9418 .collect::<String>();
9419 if Some(next_selected_text) != selected_text {
9420 same_text_selected = false;
9421 selected_text = None;
9422 }
9423 } else {
9424 same_text_selected = false;
9425 selected_text = None;
9426 }
9427 }
9428 }
9429 }
9430
9431 if only_carets {
9432 for selection in &mut selections {
9433 let word_range = movement::surrounding_word(
9434 display_map,
9435 selection.start.to_display_point(display_map),
9436 );
9437 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9438 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9439 selection.goal = SelectionGoal::None;
9440 selection.reversed = false;
9441 select_next_match_ranges(
9442 self,
9443 selection.start..selection.end,
9444 replace_newest,
9445 autoscroll,
9446 window,
9447 cx,
9448 );
9449 }
9450
9451 if selections.len() == 1 {
9452 let selection = selections
9453 .last()
9454 .expect("ensured that there's only one selection");
9455 let query = buffer
9456 .text_for_range(selection.start..selection.end)
9457 .collect::<String>();
9458 let is_empty = query.is_empty();
9459 let select_state = SelectNextState {
9460 query: AhoCorasick::new(&[query])?,
9461 wordwise: true,
9462 done: is_empty,
9463 };
9464 self.select_next_state = Some(select_state);
9465 } else {
9466 self.select_next_state = None;
9467 }
9468 } else if let Some(selected_text) = selected_text {
9469 self.select_next_state = Some(SelectNextState {
9470 query: AhoCorasick::new(&[selected_text])?,
9471 wordwise: false,
9472 done: false,
9473 });
9474 self.select_next_match_internal(
9475 display_map,
9476 replace_newest,
9477 autoscroll,
9478 window,
9479 cx,
9480 )?;
9481 }
9482 }
9483 Ok(())
9484 }
9485
9486 pub fn select_all_matches(
9487 &mut self,
9488 _action: &SelectAllMatches,
9489 window: &mut Window,
9490 cx: &mut Context<Self>,
9491 ) -> Result<()> {
9492 self.push_to_selection_history();
9493 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9494
9495 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9496 let Some(select_next_state) = self.select_next_state.as_mut() else {
9497 return Ok(());
9498 };
9499 if select_next_state.done {
9500 return Ok(());
9501 }
9502
9503 let mut new_selections = self.selections.all::<usize>(cx);
9504
9505 let buffer = &display_map.buffer_snapshot;
9506 let query_matches = select_next_state
9507 .query
9508 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9509
9510 for query_match in query_matches {
9511 let query_match = query_match.unwrap(); // can only fail due to I/O
9512 let offset_range = query_match.start()..query_match.end();
9513 let display_range = offset_range.start.to_display_point(&display_map)
9514 ..offset_range.end.to_display_point(&display_map);
9515
9516 if !select_next_state.wordwise
9517 || (!movement::is_inside_word(&display_map, display_range.start)
9518 && !movement::is_inside_word(&display_map, display_range.end))
9519 {
9520 self.selections.change_with(cx, |selections| {
9521 new_selections.push(Selection {
9522 id: selections.new_selection_id(),
9523 start: offset_range.start,
9524 end: offset_range.end,
9525 reversed: false,
9526 goal: SelectionGoal::None,
9527 });
9528 });
9529 }
9530 }
9531
9532 new_selections.sort_by_key(|selection| selection.start);
9533 let mut ix = 0;
9534 while ix + 1 < new_selections.len() {
9535 let current_selection = &new_selections[ix];
9536 let next_selection = &new_selections[ix + 1];
9537 if current_selection.range().overlaps(&next_selection.range()) {
9538 if current_selection.id < next_selection.id {
9539 new_selections.remove(ix + 1);
9540 } else {
9541 new_selections.remove(ix);
9542 }
9543 } else {
9544 ix += 1;
9545 }
9546 }
9547
9548 let reversed = self.selections.oldest::<usize>(cx).reversed;
9549
9550 for selection in new_selections.iter_mut() {
9551 selection.reversed = reversed;
9552 }
9553
9554 select_next_state.done = true;
9555 self.unfold_ranges(
9556 &new_selections
9557 .iter()
9558 .map(|selection| selection.range())
9559 .collect::<Vec<_>>(),
9560 false,
9561 false,
9562 cx,
9563 );
9564 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9565 selections.select(new_selections)
9566 });
9567
9568 Ok(())
9569 }
9570
9571 pub fn select_next(
9572 &mut self,
9573 action: &SelectNext,
9574 window: &mut Window,
9575 cx: &mut Context<Self>,
9576 ) -> Result<()> {
9577 self.push_to_selection_history();
9578 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9579 self.select_next_match_internal(
9580 &display_map,
9581 action.replace_newest,
9582 Some(Autoscroll::newest()),
9583 window,
9584 cx,
9585 )?;
9586 Ok(())
9587 }
9588
9589 pub fn select_previous(
9590 &mut self,
9591 action: &SelectPrevious,
9592 window: &mut Window,
9593 cx: &mut Context<Self>,
9594 ) -> Result<()> {
9595 self.push_to_selection_history();
9596 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9597 let buffer = &display_map.buffer_snapshot;
9598 let mut selections = self.selections.all::<usize>(cx);
9599 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9600 let query = &select_prev_state.query;
9601 if !select_prev_state.done {
9602 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9603 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9604 let mut next_selected_range = None;
9605 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9606 let bytes_before_last_selection =
9607 buffer.reversed_bytes_in_range(0..last_selection.start);
9608 let bytes_after_first_selection =
9609 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9610 let query_matches = query
9611 .stream_find_iter(bytes_before_last_selection)
9612 .map(|result| (last_selection.start, result))
9613 .chain(
9614 query
9615 .stream_find_iter(bytes_after_first_selection)
9616 .map(|result| (buffer.len(), result)),
9617 );
9618 for (end_offset, query_match) in query_matches {
9619 let query_match = query_match.unwrap(); // can only fail due to I/O
9620 let offset_range =
9621 end_offset - query_match.end()..end_offset - query_match.start();
9622 let display_range = offset_range.start.to_display_point(&display_map)
9623 ..offset_range.end.to_display_point(&display_map);
9624
9625 if !select_prev_state.wordwise
9626 || (!movement::is_inside_word(&display_map, display_range.start)
9627 && !movement::is_inside_word(&display_map, display_range.end))
9628 {
9629 next_selected_range = Some(offset_range);
9630 break;
9631 }
9632 }
9633
9634 if let Some(next_selected_range) = next_selected_range {
9635 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9636 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9637 if action.replace_newest {
9638 s.delete(s.newest_anchor().id);
9639 }
9640 s.insert_range(next_selected_range);
9641 });
9642 } else {
9643 select_prev_state.done = true;
9644 }
9645 }
9646
9647 self.select_prev_state = Some(select_prev_state);
9648 } else {
9649 let mut only_carets = true;
9650 let mut same_text_selected = true;
9651 let mut selected_text = None;
9652
9653 let mut selections_iter = selections.iter().peekable();
9654 while let Some(selection) = selections_iter.next() {
9655 if selection.start != selection.end {
9656 only_carets = false;
9657 }
9658
9659 if same_text_selected {
9660 if selected_text.is_none() {
9661 selected_text =
9662 Some(buffer.text_for_range(selection.range()).collect::<String>());
9663 }
9664
9665 if let Some(next_selection) = selections_iter.peek() {
9666 if next_selection.range().len() == selection.range().len() {
9667 let next_selected_text = buffer
9668 .text_for_range(next_selection.range())
9669 .collect::<String>();
9670 if Some(next_selected_text) != selected_text {
9671 same_text_selected = false;
9672 selected_text = None;
9673 }
9674 } else {
9675 same_text_selected = false;
9676 selected_text = None;
9677 }
9678 }
9679 }
9680 }
9681
9682 if only_carets {
9683 for selection in &mut selections {
9684 let word_range = movement::surrounding_word(
9685 &display_map,
9686 selection.start.to_display_point(&display_map),
9687 );
9688 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9689 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9690 selection.goal = SelectionGoal::None;
9691 selection.reversed = false;
9692 }
9693 if selections.len() == 1 {
9694 let selection = selections
9695 .last()
9696 .expect("ensured that there's only one selection");
9697 let query = buffer
9698 .text_for_range(selection.start..selection.end)
9699 .collect::<String>();
9700 let is_empty = query.is_empty();
9701 let select_state = SelectNextState {
9702 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9703 wordwise: true,
9704 done: is_empty,
9705 };
9706 self.select_prev_state = Some(select_state);
9707 } else {
9708 self.select_prev_state = None;
9709 }
9710
9711 self.unfold_ranges(
9712 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9713 false,
9714 true,
9715 cx,
9716 );
9717 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9718 s.select(selections);
9719 });
9720 } else if let Some(selected_text) = selected_text {
9721 self.select_prev_state = Some(SelectNextState {
9722 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9723 wordwise: false,
9724 done: false,
9725 });
9726 self.select_previous(action, window, cx)?;
9727 }
9728 }
9729 Ok(())
9730 }
9731
9732 pub fn toggle_comments(
9733 &mut self,
9734 action: &ToggleComments,
9735 window: &mut Window,
9736 cx: &mut Context<Self>,
9737 ) {
9738 if self.read_only(cx) {
9739 return;
9740 }
9741 let text_layout_details = &self.text_layout_details(window);
9742 self.transact(window, cx, |this, window, cx| {
9743 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9744 let mut edits = Vec::new();
9745 let mut selection_edit_ranges = Vec::new();
9746 let mut last_toggled_row = None;
9747 let snapshot = this.buffer.read(cx).read(cx);
9748 let empty_str: Arc<str> = Arc::default();
9749 let mut suffixes_inserted = Vec::new();
9750 let ignore_indent = action.ignore_indent;
9751
9752 fn comment_prefix_range(
9753 snapshot: &MultiBufferSnapshot,
9754 row: MultiBufferRow,
9755 comment_prefix: &str,
9756 comment_prefix_whitespace: &str,
9757 ignore_indent: bool,
9758 ) -> Range<Point> {
9759 let indent_size = if ignore_indent {
9760 0
9761 } else {
9762 snapshot.indent_size_for_line(row).len
9763 };
9764
9765 let start = Point::new(row.0, indent_size);
9766
9767 let mut line_bytes = snapshot
9768 .bytes_in_range(start..snapshot.max_point())
9769 .flatten()
9770 .copied();
9771
9772 // If this line currently begins with the line comment prefix, then record
9773 // the range containing the prefix.
9774 if line_bytes
9775 .by_ref()
9776 .take(comment_prefix.len())
9777 .eq(comment_prefix.bytes())
9778 {
9779 // Include any whitespace that matches the comment prefix.
9780 let matching_whitespace_len = line_bytes
9781 .zip(comment_prefix_whitespace.bytes())
9782 .take_while(|(a, b)| a == b)
9783 .count() as u32;
9784 let end = Point::new(
9785 start.row,
9786 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9787 );
9788 start..end
9789 } else {
9790 start..start
9791 }
9792 }
9793
9794 fn comment_suffix_range(
9795 snapshot: &MultiBufferSnapshot,
9796 row: MultiBufferRow,
9797 comment_suffix: &str,
9798 comment_suffix_has_leading_space: bool,
9799 ) -> Range<Point> {
9800 let end = Point::new(row.0, snapshot.line_len(row));
9801 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9802
9803 let mut line_end_bytes = snapshot
9804 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9805 .flatten()
9806 .copied();
9807
9808 let leading_space_len = if suffix_start_column > 0
9809 && line_end_bytes.next() == Some(b' ')
9810 && comment_suffix_has_leading_space
9811 {
9812 1
9813 } else {
9814 0
9815 };
9816
9817 // If this line currently begins with the line comment prefix, then record
9818 // the range containing the prefix.
9819 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9820 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9821 start..end
9822 } else {
9823 end..end
9824 }
9825 }
9826
9827 // TODO: Handle selections that cross excerpts
9828 for selection in &mut selections {
9829 let start_column = snapshot
9830 .indent_size_for_line(MultiBufferRow(selection.start.row))
9831 .len;
9832 let language = if let Some(language) =
9833 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9834 {
9835 language
9836 } else {
9837 continue;
9838 };
9839
9840 selection_edit_ranges.clear();
9841
9842 // If multiple selections contain a given row, avoid processing that
9843 // row more than once.
9844 let mut start_row = MultiBufferRow(selection.start.row);
9845 if last_toggled_row == Some(start_row) {
9846 start_row = start_row.next_row();
9847 }
9848 let end_row =
9849 if selection.end.row > selection.start.row && selection.end.column == 0 {
9850 MultiBufferRow(selection.end.row - 1)
9851 } else {
9852 MultiBufferRow(selection.end.row)
9853 };
9854 last_toggled_row = Some(end_row);
9855
9856 if start_row > end_row {
9857 continue;
9858 }
9859
9860 // If the language has line comments, toggle those.
9861 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9862
9863 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9864 if ignore_indent {
9865 full_comment_prefixes = full_comment_prefixes
9866 .into_iter()
9867 .map(|s| Arc::from(s.trim_end()))
9868 .collect();
9869 }
9870
9871 if !full_comment_prefixes.is_empty() {
9872 let first_prefix = full_comment_prefixes
9873 .first()
9874 .expect("prefixes is non-empty");
9875 let prefix_trimmed_lengths = full_comment_prefixes
9876 .iter()
9877 .map(|p| p.trim_end_matches(' ').len())
9878 .collect::<SmallVec<[usize; 4]>>();
9879
9880 let mut all_selection_lines_are_comments = true;
9881
9882 for row in start_row.0..=end_row.0 {
9883 let row = MultiBufferRow(row);
9884 if start_row < end_row && snapshot.is_line_blank(row) {
9885 continue;
9886 }
9887
9888 let prefix_range = full_comment_prefixes
9889 .iter()
9890 .zip(prefix_trimmed_lengths.iter().copied())
9891 .map(|(prefix, trimmed_prefix_len)| {
9892 comment_prefix_range(
9893 snapshot.deref(),
9894 row,
9895 &prefix[..trimmed_prefix_len],
9896 &prefix[trimmed_prefix_len..],
9897 ignore_indent,
9898 )
9899 })
9900 .max_by_key(|range| range.end.column - range.start.column)
9901 .expect("prefixes is non-empty");
9902
9903 if prefix_range.is_empty() {
9904 all_selection_lines_are_comments = false;
9905 }
9906
9907 selection_edit_ranges.push(prefix_range);
9908 }
9909
9910 if all_selection_lines_are_comments {
9911 edits.extend(
9912 selection_edit_ranges
9913 .iter()
9914 .cloned()
9915 .map(|range| (range, empty_str.clone())),
9916 );
9917 } else {
9918 let min_column = selection_edit_ranges
9919 .iter()
9920 .map(|range| range.start.column)
9921 .min()
9922 .unwrap_or(0);
9923 edits.extend(selection_edit_ranges.iter().map(|range| {
9924 let position = Point::new(range.start.row, min_column);
9925 (position..position, first_prefix.clone())
9926 }));
9927 }
9928 } else if let Some((full_comment_prefix, comment_suffix)) =
9929 language.block_comment_delimiters()
9930 {
9931 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9932 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9933 let prefix_range = comment_prefix_range(
9934 snapshot.deref(),
9935 start_row,
9936 comment_prefix,
9937 comment_prefix_whitespace,
9938 ignore_indent,
9939 );
9940 let suffix_range = comment_suffix_range(
9941 snapshot.deref(),
9942 end_row,
9943 comment_suffix.trim_start_matches(' '),
9944 comment_suffix.starts_with(' '),
9945 );
9946
9947 if prefix_range.is_empty() || suffix_range.is_empty() {
9948 edits.push((
9949 prefix_range.start..prefix_range.start,
9950 full_comment_prefix.clone(),
9951 ));
9952 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9953 suffixes_inserted.push((end_row, comment_suffix.len()));
9954 } else {
9955 edits.push((prefix_range, empty_str.clone()));
9956 edits.push((suffix_range, empty_str.clone()));
9957 }
9958 } else {
9959 continue;
9960 }
9961 }
9962
9963 drop(snapshot);
9964 this.buffer.update(cx, |buffer, cx| {
9965 buffer.edit(edits, None, cx);
9966 });
9967
9968 // Adjust selections so that they end before any comment suffixes that
9969 // were inserted.
9970 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9971 let mut selections = this.selections.all::<Point>(cx);
9972 let snapshot = this.buffer.read(cx).read(cx);
9973 for selection in &mut selections {
9974 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9975 match row.cmp(&MultiBufferRow(selection.end.row)) {
9976 Ordering::Less => {
9977 suffixes_inserted.next();
9978 continue;
9979 }
9980 Ordering::Greater => break,
9981 Ordering::Equal => {
9982 if selection.end.column == snapshot.line_len(row) {
9983 if selection.is_empty() {
9984 selection.start.column -= suffix_len as u32;
9985 }
9986 selection.end.column -= suffix_len as u32;
9987 }
9988 break;
9989 }
9990 }
9991 }
9992 }
9993
9994 drop(snapshot);
9995 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9996 s.select(selections)
9997 });
9998
9999 let selections = this.selections.all::<Point>(cx);
10000 let selections_on_single_row = selections.windows(2).all(|selections| {
10001 selections[0].start.row == selections[1].start.row
10002 && selections[0].end.row == selections[1].end.row
10003 && selections[0].start.row == selections[0].end.row
10004 });
10005 let selections_selecting = selections
10006 .iter()
10007 .any(|selection| selection.start != selection.end);
10008 let advance_downwards = action.advance_downwards
10009 && selections_on_single_row
10010 && !selections_selecting
10011 && !matches!(this.mode, EditorMode::SingleLine { .. });
10012
10013 if advance_downwards {
10014 let snapshot = this.buffer.read(cx).snapshot(cx);
10015
10016 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10017 s.move_cursors_with(|display_snapshot, display_point, _| {
10018 let mut point = display_point.to_point(display_snapshot);
10019 point.row += 1;
10020 point = snapshot.clip_point(point, Bias::Left);
10021 let display_point = point.to_display_point(display_snapshot);
10022 let goal = SelectionGoal::HorizontalPosition(
10023 display_snapshot
10024 .x_for_display_point(display_point, text_layout_details)
10025 .into(),
10026 );
10027 (display_point, goal)
10028 })
10029 });
10030 }
10031 });
10032 }
10033
10034 pub fn select_enclosing_symbol(
10035 &mut self,
10036 _: &SelectEnclosingSymbol,
10037 window: &mut Window,
10038 cx: &mut Context<Self>,
10039 ) {
10040 let buffer = self.buffer.read(cx).snapshot(cx);
10041 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10042
10043 fn update_selection(
10044 selection: &Selection<usize>,
10045 buffer_snap: &MultiBufferSnapshot,
10046 ) -> Option<Selection<usize>> {
10047 let cursor = selection.head();
10048 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10049 for symbol in symbols.iter().rev() {
10050 let start = symbol.range.start.to_offset(buffer_snap);
10051 let end = symbol.range.end.to_offset(buffer_snap);
10052 let new_range = start..end;
10053 if start < selection.start || end > selection.end {
10054 return Some(Selection {
10055 id: selection.id,
10056 start: new_range.start,
10057 end: new_range.end,
10058 goal: SelectionGoal::None,
10059 reversed: selection.reversed,
10060 });
10061 }
10062 }
10063 None
10064 }
10065
10066 let mut selected_larger_symbol = false;
10067 let new_selections = old_selections
10068 .iter()
10069 .map(|selection| match update_selection(selection, &buffer) {
10070 Some(new_selection) => {
10071 if new_selection.range() != selection.range() {
10072 selected_larger_symbol = true;
10073 }
10074 new_selection
10075 }
10076 None => selection.clone(),
10077 })
10078 .collect::<Vec<_>>();
10079
10080 if selected_larger_symbol {
10081 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10082 s.select(new_selections);
10083 });
10084 }
10085 }
10086
10087 pub fn select_larger_syntax_node(
10088 &mut self,
10089 _: &SelectLargerSyntaxNode,
10090 window: &mut Window,
10091 cx: &mut Context<Self>,
10092 ) {
10093 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10094 let buffer = self.buffer.read(cx).snapshot(cx);
10095 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10096
10097 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10098 let mut selected_larger_node = false;
10099 let new_selections = old_selections
10100 .iter()
10101 .map(|selection| {
10102 let old_range = selection.start..selection.end;
10103 let mut new_range = old_range.clone();
10104 let mut new_node = None;
10105 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10106 {
10107 new_node = Some(node);
10108 new_range = containing_range;
10109 if !display_map.intersects_fold(new_range.start)
10110 && !display_map.intersects_fold(new_range.end)
10111 {
10112 break;
10113 }
10114 }
10115
10116 if let Some(node) = new_node {
10117 // Log the ancestor, to support using this action as a way to explore TreeSitter
10118 // nodes. Parent and grandparent are also logged because this operation will not
10119 // visit nodes that have the same range as their parent.
10120 log::info!("Node: {node:?}");
10121 let parent = node.parent();
10122 log::info!("Parent: {parent:?}");
10123 let grandparent = parent.and_then(|x| x.parent());
10124 log::info!("Grandparent: {grandparent:?}");
10125 }
10126
10127 selected_larger_node |= new_range != old_range;
10128 Selection {
10129 id: selection.id,
10130 start: new_range.start,
10131 end: new_range.end,
10132 goal: SelectionGoal::None,
10133 reversed: selection.reversed,
10134 }
10135 })
10136 .collect::<Vec<_>>();
10137
10138 if selected_larger_node {
10139 stack.push(old_selections);
10140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10141 s.select(new_selections);
10142 });
10143 }
10144 self.select_larger_syntax_node_stack = stack;
10145 }
10146
10147 pub fn select_smaller_syntax_node(
10148 &mut self,
10149 _: &SelectSmallerSyntaxNode,
10150 window: &mut Window,
10151 cx: &mut Context<Self>,
10152 ) {
10153 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10154 if let Some(selections) = stack.pop() {
10155 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10156 s.select(selections.to_vec());
10157 });
10158 }
10159 self.select_larger_syntax_node_stack = stack;
10160 }
10161
10162 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10163 if !EditorSettings::get_global(cx).gutter.runnables {
10164 self.clear_tasks();
10165 return Task::ready(());
10166 }
10167 let project = self.project.as_ref().map(Entity::downgrade);
10168 cx.spawn_in(window, |this, mut cx| async move {
10169 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10170 let Some(project) = project.and_then(|p| p.upgrade()) else {
10171 return;
10172 };
10173 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10174 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10175 }) else {
10176 return;
10177 };
10178
10179 let hide_runnables = project
10180 .update(&mut cx, |project, cx| {
10181 // Do not display any test indicators in non-dev server remote projects.
10182 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10183 })
10184 .unwrap_or(true);
10185 if hide_runnables {
10186 return;
10187 }
10188 let new_rows =
10189 cx.background_executor()
10190 .spawn({
10191 let snapshot = display_snapshot.clone();
10192 async move {
10193 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10194 }
10195 })
10196 .await;
10197
10198 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10199 this.update(&mut cx, |this, _| {
10200 this.clear_tasks();
10201 for (key, value) in rows {
10202 this.insert_tasks(key, value);
10203 }
10204 })
10205 .ok();
10206 })
10207 }
10208 fn fetch_runnable_ranges(
10209 snapshot: &DisplaySnapshot,
10210 range: Range<Anchor>,
10211 ) -> Vec<language::RunnableRange> {
10212 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10213 }
10214
10215 fn runnable_rows(
10216 project: Entity<Project>,
10217 snapshot: DisplaySnapshot,
10218 runnable_ranges: Vec<RunnableRange>,
10219 mut cx: AsyncWindowContext,
10220 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10221 runnable_ranges
10222 .into_iter()
10223 .filter_map(|mut runnable| {
10224 let tasks = cx
10225 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10226 .ok()?;
10227 if tasks.is_empty() {
10228 return None;
10229 }
10230
10231 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10232
10233 let row = snapshot
10234 .buffer_snapshot
10235 .buffer_line_for_row(MultiBufferRow(point.row))?
10236 .1
10237 .start
10238 .row;
10239
10240 let context_range =
10241 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10242 Some((
10243 (runnable.buffer_id, row),
10244 RunnableTasks {
10245 templates: tasks,
10246 offset: MultiBufferOffset(runnable.run_range.start),
10247 context_range,
10248 column: point.column,
10249 extra_variables: runnable.extra_captures,
10250 },
10251 ))
10252 })
10253 .collect()
10254 }
10255
10256 fn templates_with_tags(
10257 project: &Entity<Project>,
10258 runnable: &mut Runnable,
10259 cx: &mut App,
10260 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10261 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10262 let (worktree_id, file) = project
10263 .buffer_for_id(runnable.buffer, cx)
10264 .and_then(|buffer| buffer.read(cx).file())
10265 .map(|file| (file.worktree_id(cx), file.clone()))
10266 .unzip();
10267
10268 (
10269 project.task_store().read(cx).task_inventory().cloned(),
10270 worktree_id,
10271 file,
10272 )
10273 });
10274
10275 let tags = mem::take(&mut runnable.tags);
10276 let mut tags: Vec<_> = tags
10277 .into_iter()
10278 .flat_map(|tag| {
10279 let tag = tag.0.clone();
10280 inventory
10281 .as_ref()
10282 .into_iter()
10283 .flat_map(|inventory| {
10284 inventory.read(cx).list_tasks(
10285 file.clone(),
10286 Some(runnable.language.clone()),
10287 worktree_id,
10288 cx,
10289 )
10290 })
10291 .filter(move |(_, template)| {
10292 template.tags.iter().any(|source_tag| source_tag == &tag)
10293 })
10294 })
10295 .sorted_by_key(|(kind, _)| kind.to_owned())
10296 .collect();
10297 if let Some((leading_tag_source, _)) = tags.first() {
10298 // Strongest source wins; if we have worktree tag binding, prefer that to
10299 // global and language bindings;
10300 // if we have a global binding, prefer that to language binding.
10301 let first_mismatch = tags
10302 .iter()
10303 .position(|(tag_source, _)| tag_source != leading_tag_source);
10304 if let Some(index) = first_mismatch {
10305 tags.truncate(index);
10306 }
10307 }
10308
10309 tags
10310 }
10311
10312 pub fn move_to_enclosing_bracket(
10313 &mut self,
10314 _: &MoveToEnclosingBracket,
10315 window: &mut Window,
10316 cx: &mut Context<Self>,
10317 ) {
10318 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10319 s.move_offsets_with(|snapshot, selection| {
10320 let Some(enclosing_bracket_ranges) =
10321 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10322 else {
10323 return;
10324 };
10325
10326 let mut best_length = usize::MAX;
10327 let mut best_inside = false;
10328 let mut best_in_bracket_range = false;
10329 let mut best_destination = None;
10330 for (open, close) in enclosing_bracket_ranges {
10331 let close = close.to_inclusive();
10332 let length = close.end() - open.start;
10333 let inside = selection.start >= open.end && selection.end <= *close.start();
10334 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10335 || close.contains(&selection.head());
10336
10337 // If best is next to a bracket and current isn't, skip
10338 if !in_bracket_range && best_in_bracket_range {
10339 continue;
10340 }
10341
10342 // Prefer smaller lengths unless best is inside and current isn't
10343 if length > best_length && (best_inside || !inside) {
10344 continue;
10345 }
10346
10347 best_length = length;
10348 best_inside = inside;
10349 best_in_bracket_range = in_bracket_range;
10350 best_destination = Some(
10351 if close.contains(&selection.start) && close.contains(&selection.end) {
10352 if inside {
10353 open.end
10354 } else {
10355 open.start
10356 }
10357 } else if inside {
10358 *close.start()
10359 } else {
10360 *close.end()
10361 },
10362 );
10363 }
10364
10365 if let Some(destination) = best_destination {
10366 selection.collapse_to(destination, SelectionGoal::None);
10367 }
10368 })
10369 });
10370 }
10371
10372 pub fn undo_selection(
10373 &mut self,
10374 _: &UndoSelection,
10375 window: &mut Window,
10376 cx: &mut Context<Self>,
10377 ) {
10378 self.end_selection(window, cx);
10379 self.selection_history.mode = SelectionHistoryMode::Undoing;
10380 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10381 self.change_selections(None, window, cx, |s| {
10382 s.select_anchors(entry.selections.to_vec())
10383 });
10384 self.select_next_state = entry.select_next_state;
10385 self.select_prev_state = entry.select_prev_state;
10386 self.add_selections_state = entry.add_selections_state;
10387 self.request_autoscroll(Autoscroll::newest(), cx);
10388 }
10389 self.selection_history.mode = SelectionHistoryMode::Normal;
10390 }
10391
10392 pub fn redo_selection(
10393 &mut self,
10394 _: &RedoSelection,
10395 window: &mut Window,
10396 cx: &mut Context<Self>,
10397 ) {
10398 self.end_selection(window, cx);
10399 self.selection_history.mode = SelectionHistoryMode::Redoing;
10400 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10401 self.change_selections(None, window, cx, |s| {
10402 s.select_anchors(entry.selections.to_vec())
10403 });
10404 self.select_next_state = entry.select_next_state;
10405 self.select_prev_state = entry.select_prev_state;
10406 self.add_selections_state = entry.add_selections_state;
10407 self.request_autoscroll(Autoscroll::newest(), cx);
10408 }
10409 self.selection_history.mode = SelectionHistoryMode::Normal;
10410 }
10411
10412 pub fn expand_excerpts(
10413 &mut self,
10414 action: &ExpandExcerpts,
10415 _: &mut Window,
10416 cx: &mut Context<Self>,
10417 ) {
10418 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10419 }
10420
10421 pub fn expand_excerpts_down(
10422 &mut self,
10423 action: &ExpandExcerptsDown,
10424 _: &mut Window,
10425 cx: &mut Context<Self>,
10426 ) {
10427 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10428 }
10429
10430 pub fn expand_excerpts_up(
10431 &mut self,
10432 action: &ExpandExcerptsUp,
10433 _: &mut Window,
10434 cx: &mut Context<Self>,
10435 ) {
10436 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10437 }
10438
10439 pub fn expand_excerpts_for_direction(
10440 &mut self,
10441 lines: u32,
10442 direction: ExpandExcerptDirection,
10443
10444 cx: &mut Context<Self>,
10445 ) {
10446 let selections = self.selections.disjoint_anchors();
10447
10448 let lines = if lines == 0 {
10449 EditorSettings::get_global(cx).expand_excerpt_lines
10450 } else {
10451 lines
10452 };
10453
10454 self.buffer.update(cx, |buffer, cx| {
10455 let snapshot = buffer.snapshot(cx);
10456 let mut excerpt_ids = selections
10457 .iter()
10458 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10459 .collect::<Vec<_>>();
10460 excerpt_ids.sort();
10461 excerpt_ids.dedup();
10462 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10463 })
10464 }
10465
10466 pub fn expand_excerpt(
10467 &mut self,
10468 excerpt: ExcerptId,
10469 direction: ExpandExcerptDirection,
10470 cx: &mut Context<Self>,
10471 ) {
10472 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10473 self.buffer.update(cx, |buffer, cx| {
10474 buffer.expand_excerpts([excerpt], lines, direction, cx)
10475 })
10476 }
10477
10478 pub fn go_to_singleton_buffer_point(
10479 &mut self,
10480 point: Point,
10481 window: &mut Window,
10482 cx: &mut Context<Self>,
10483 ) {
10484 self.go_to_singleton_buffer_range(point..point, window, cx);
10485 }
10486
10487 pub fn go_to_singleton_buffer_range(
10488 &mut self,
10489 range: Range<Point>,
10490 window: &mut Window,
10491 cx: &mut Context<Self>,
10492 ) {
10493 let multibuffer = self.buffer().read(cx);
10494 let Some(buffer) = multibuffer.as_singleton() else {
10495 return;
10496 };
10497 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10498 return;
10499 };
10500 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10501 return;
10502 };
10503 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10504 s.select_anchor_ranges([start..end])
10505 });
10506 }
10507
10508 fn go_to_diagnostic(
10509 &mut self,
10510 _: &GoToDiagnostic,
10511 window: &mut Window,
10512 cx: &mut Context<Self>,
10513 ) {
10514 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10515 }
10516
10517 fn go_to_prev_diagnostic(
10518 &mut self,
10519 _: &GoToPrevDiagnostic,
10520 window: &mut Window,
10521 cx: &mut Context<Self>,
10522 ) {
10523 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10524 }
10525
10526 pub fn go_to_diagnostic_impl(
10527 &mut self,
10528 direction: Direction,
10529 window: &mut Window,
10530 cx: &mut Context<Self>,
10531 ) {
10532 let buffer = self.buffer.read(cx).snapshot(cx);
10533 let selection = self.selections.newest::<usize>(cx);
10534
10535 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10536 if direction == Direction::Next {
10537 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10538 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10539 return;
10540 };
10541 self.activate_diagnostics(
10542 buffer_id,
10543 popover.local_diagnostic.diagnostic.group_id,
10544 window,
10545 cx,
10546 );
10547 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10548 let primary_range_start = active_diagnostics.primary_range.start;
10549 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10550 let mut new_selection = s.newest_anchor().clone();
10551 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10552 s.select_anchors(vec![new_selection.clone()]);
10553 });
10554 self.refresh_inline_completion(false, true, window, cx);
10555 }
10556 return;
10557 }
10558 }
10559
10560 let active_group_id = self
10561 .active_diagnostics
10562 .as_ref()
10563 .map(|active_group| active_group.group_id);
10564 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10565 active_diagnostics
10566 .primary_range
10567 .to_offset(&buffer)
10568 .to_inclusive()
10569 });
10570 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10571 if active_primary_range.contains(&selection.head()) {
10572 *active_primary_range.start()
10573 } else {
10574 selection.head()
10575 }
10576 } else {
10577 selection.head()
10578 };
10579
10580 let snapshot = self.snapshot(window, cx);
10581 let primary_diagnostics_before = buffer
10582 .diagnostics_in_range::<usize>(0..search_start)
10583 .filter(|entry| entry.diagnostic.is_primary)
10584 .filter(|entry| entry.range.start != entry.range.end)
10585 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10586 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10587 .collect::<Vec<_>>();
10588 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10589 primary_diagnostics_before
10590 .iter()
10591 .position(|entry| entry.diagnostic.group_id == active_group_id)
10592 });
10593
10594 let primary_diagnostics_after = buffer
10595 .diagnostics_in_range::<usize>(search_start..buffer.len())
10596 .filter(|entry| entry.diagnostic.is_primary)
10597 .filter(|entry| entry.range.start != entry.range.end)
10598 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10599 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10600 .collect::<Vec<_>>();
10601 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10602 primary_diagnostics_after
10603 .iter()
10604 .enumerate()
10605 .rev()
10606 .find_map(|(i, entry)| {
10607 if entry.diagnostic.group_id == active_group_id {
10608 Some(i)
10609 } else {
10610 None
10611 }
10612 })
10613 });
10614
10615 let next_primary_diagnostic = match direction {
10616 Direction::Prev => primary_diagnostics_before
10617 .iter()
10618 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10619 .rev()
10620 .next(),
10621 Direction::Next => primary_diagnostics_after
10622 .iter()
10623 .skip(
10624 last_same_group_diagnostic_after
10625 .map(|index| index + 1)
10626 .unwrap_or(0),
10627 )
10628 .next(),
10629 };
10630
10631 // Cycle around to the start of the buffer, potentially moving back to the start of
10632 // the currently active diagnostic.
10633 let cycle_around = || match direction {
10634 Direction::Prev => primary_diagnostics_after
10635 .iter()
10636 .rev()
10637 .chain(primary_diagnostics_before.iter().rev())
10638 .next(),
10639 Direction::Next => primary_diagnostics_before
10640 .iter()
10641 .chain(primary_diagnostics_after.iter())
10642 .next(),
10643 };
10644
10645 if let Some((primary_range, group_id)) = next_primary_diagnostic
10646 .or_else(cycle_around)
10647 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10648 {
10649 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10650 return;
10651 };
10652 self.activate_diagnostics(buffer_id, group_id, window, cx);
10653 if self.active_diagnostics.is_some() {
10654 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10655 s.select(vec![Selection {
10656 id: selection.id,
10657 start: primary_range.start,
10658 end: primary_range.start,
10659 reversed: false,
10660 goal: SelectionGoal::None,
10661 }]);
10662 });
10663 self.refresh_inline_completion(false, true, window, cx);
10664 }
10665 }
10666 }
10667
10668 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10669 let snapshot = self.snapshot(window, cx);
10670 let selection = self.selections.newest::<Point>(cx);
10671 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10672 }
10673
10674 fn go_to_hunk_after_position(
10675 &mut self,
10676 snapshot: &EditorSnapshot,
10677 position: Point,
10678 window: &mut Window,
10679 cx: &mut Context<Editor>,
10680 ) -> Option<MultiBufferDiffHunk> {
10681 let mut hunk = snapshot
10682 .buffer_snapshot
10683 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10684 .find(|hunk| hunk.row_range.start.0 > position.row);
10685 if hunk.is_none() {
10686 hunk = snapshot
10687 .buffer_snapshot
10688 .diff_hunks_in_range(Point::zero()..position)
10689 .find(|hunk| hunk.row_range.end.0 < position.row)
10690 }
10691 if let Some(hunk) = &hunk {
10692 let destination = Point::new(hunk.row_range.start.0, 0);
10693 self.unfold_ranges(&[destination..destination], false, false, cx);
10694 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10695 s.select_ranges(vec![destination..destination]);
10696 });
10697 }
10698
10699 hunk
10700 }
10701
10702 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10703 let snapshot = self.snapshot(window, cx);
10704 let selection = self.selections.newest::<Point>(cx);
10705 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10706 }
10707
10708 fn go_to_hunk_before_position(
10709 &mut self,
10710 snapshot: &EditorSnapshot,
10711 position: Point,
10712 window: &mut Window,
10713 cx: &mut Context<Editor>,
10714 ) -> Option<MultiBufferDiffHunk> {
10715 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10716 if hunk.is_none() {
10717 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10718 }
10719 if let Some(hunk) = &hunk {
10720 let destination = Point::new(hunk.row_range.start.0, 0);
10721 self.unfold_ranges(&[destination..destination], false, false, cx);
10722 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10723 s.select_ranges(vec![destination..destination]);
10724 });
10725 }
10726
10727 hunk
10728 }
10729
10730 pub fn go_to_definition(
10731 &mut self,
10732 _: &GoToDefinition,
10733 window: &mut Window,
10734 cx: &mut Context<Self>,
10735 ) -> Task<Result<Navigated>> {
10736 let definition =
10737 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10738 cx.spawn_in(window, |editor, mut cx| async move {
10739 if definition.await? == Navigated::Yes {
10740 return Ok(Navigated::Yes);
10741 }
10742 match editor.update_in(&mut cx, |editor, window, cx| {
10743 editor.find_all_references(&FindAllReferences, window, cx)
10744 })? {
10745 Some(references) => references.await,
10746 None => Ok(Navigated::No),
10747 }
10748 })
10749 }
10750
10751 pub fn go_to_declaration(
10752 &mut self,
10753 _: &GoToDeclaration,
10754 window: &mut Window,
10755 cx: &mut Context<Self>,
10756 ) -> Task<Result<Navigated>> {
10757 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10758 }
10759
10760 pub fn go_to_declaration_split(
10761 &mut self,
10762 _: &GoToDeclaration,
10763 window: &mut Window,
10764 cx: &mut Context<Self>,
10765 ) -> Task<Result<Navigated>> {
10766 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10767 }
10768
10769 pub fn go_to_implementation(
10770 &mut self,
10771 _: &GoToImplementation,
10772 window: &mut Window,
10773 cx: &mut Context<Self>,
10774 ) -> Task<Result<Navigated>> {
10775 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10776 }
10777
10778 pub fn go_to_implementation_split(
10779 &mut self,
10780 _: &GoToImplementationSplit,
10781 window: &mut Window,
10782 cx: &mut Context<Self>,
10783 ) -> Task<Result<Navigated>> {
10784 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10785 }
10786
10787 pub fn go_to_type_definition(
10788 &mut self,
10789 _: &GoToTypeDefinition,
10790 window: &mut Window,
10791 cx: &mut Context<Self>,
10792 ) -> Task<Result<Navigated>> {
10793 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10794 }
10795
10796 pub fn go_to_definition_split(
10797 &mut self,
10798 _: &GoToDefinitionSplit,
10799 window: &mut Window,
10800 cx: &mut Context<Self>,
10801 ) -> Task<Result<Navigated>> {
10802 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10803 }
10804
10805 pub fn go_to_type_definition_split(
10806 &mut self,
10807 _: &GoToTypeDefinitionSplit,
10808 window: &mut Window,
10809 cx: &mut Context<Self>,
10810 ) -> Task<Result<Navigated>> {
10811 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10812 }
10813
10814 fn go_to_definition_of_kind(
10815 &mut self,
10816 kind: GotoDefinitionKind,
10817 split: bool,
10818 window: &mut Window,
10819 cx: &mut Context<Self>,
10820 ) -> Task<Result<Navigated>> {
10821 let Some(provider) = self.semantics_provider.clone() else {
10822 return Task::ready(Ok(Navigated::No));
10823 };
10824 let head = self.selections.newest::<usize>(cx).head();
10825 let buffer = self.buffer.read(cx);
10826 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10827 text_anchor
10828 } else {
10829 return Task::ready(Ok(Navigated::No));
10830 };
10831
10832 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10833 return Task::ready(Ok(Navigated::No));
10834 };
10835
10836 cx.spawn_in(window, |editor, mut cx| async move {
10837 let definitions = definitions.await?;
10838 let navigated = editor
10839 .update_in(&mut cx, |editor, window, cx| {
10840 editor.navigate_to_hover_links(
10841 Some(kind),
10842 definitions
10843 .into_iter()
10844 .filter(|location| {
10845 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10846 })
10847 .map(HoverLink::Text)
10848 .collect::<Vec<_>>(),
10849 split,
10850 window,
10851 cx,
10852 )
10853 })?
10854 .await?;
10855 anyhow::Ok(navigated)
10856 })
10857 }
10858
10859 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10860 let selection = self.selections.newest_anchor();
10861 let head = selection.head();
10862 let tail = selection.tail();
10863
10864 let Some((buffer, start_position)) =
10865 self.buffer.read(cx).text_anchor_for_position(head, cx)
10866 else {
10867 return;
10868 };
10869
10870 let end_position = if head != tail {
10871 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10872 return;
10873 };
10874 Some(pos)
10875 } else {
10876 None
10877 };
10878
10879 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10880 let url = if let Some(end_pos) = end_position {
10881 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10882 } else {
10883 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10884 };
10885
10886 if let Some(url) = url {
10887 editor.update(&mut cx, |_, cx| {
10888 cx.open_url(&url);
10889 })
10890 } else {
10891 Ok(())
10892 }
10893 });
10894
10895 url_finder.detach();
10896 }
10897
10898 pub fn open_selected_filename(
10899 &mut self,
10900 _: &OpenSelectedFilename,
10901 window: &mut Window,
10902 cx: &mut Context<Self>,
10903 ) {
10904 let Some(workspace) = self.workspace() else {
10905 return;
10906 };
10907
10908 let position = self.selections.newest_anchor().head();
10909
10910 let Some((buffer, buffer_position)) =
10911 self.buffer.read(cx).text_anchor_for_position(position, cx)
10912 else {
10913 return;
10914 };
10915
10916 let project = self.project.clone();
10917
10918 cx.spawn_in(window, |_, mut cx| async move {
10919 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10920
10921 if let Some((_, path)) = result {
10922 workspace
10923 .update_in(&mut cx, |workspace, window, cx| {
10924 workspace.open_resolved_path(path, window, cx)
10925 })?
10926 .await?;
10927 }
10928 anyhow::Ok(())
10929 })
10930 .detach();
10931 }
10932
10933 pub(crate) fn navigate_to_hover_links(
10934 &mut self,
10935 kind: Option<GotoDefinitionKind>,
10936 mut definitions: Vec<HoverLink>,
10937 split: bool,
10938 window: &mut Window,
10939 cx: &mut Context<Editor>,
10940 ) -> Task<Result<Navigated>> {
10941 // If there is one definition, just open it directly
10942 if definitions.len() == 1 {
10943 let definition = definitions.pop().unwrap();
10944
10945 enum TargetTaskResult {
10946 Location(Option<Location>),
10947 AlreadyNavigated,
10948 }
10949
10950 let target_task = match definition {
10951 HoverLink::Text(link) => {
10952 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10953 }
10954 HoverLink::InlayHint(lsp_location, server_id) => {
10955 let computation =
10956 self.compute_target_location(lsp_location, server_id, window, cx);
10957 cx.background_executor().spawn(async move {
10958 let location = computation.await?;
10959 Ok(TargetTaskResult::Location(location))
10960 })
10961 }
10962 HoverLink::Url(url) => {
10963 cx.open_url(&url);
10964 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10965 }
10966 HoverLink::File(path) => {
10967 if let Some(workspace) = self.workspace() {
10968 cx.spawn_in(window, |_, mut cx| async move {
10969 workspace
10970 .update_in(&mut cx, |workspace, window, cx| {
10971 workspace.open_resolved_path(path, window, cx)
10972 })?
10973 .await
10974 .map(|_| TargetTaskResult::AlreadyNavigated)
10975 })
10976 } else {
10977 Task::ready(Ok(TargetTaskResult::Location(None)))
10978 }
10979 }
10980 };
10981 cx.spawn_in(window, |editor, mut cx| async move {
10982 let target = match target_task.await.context("target resolution task")? {
10983 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10984 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10985 TargetTaskResult::Location(Some(target)) => target,
10986 };
10987
10988 editor.update_in(&mut cx, |editor, window, cx| {
10989 let Some(workspace) = editor.workspace() else {
10990 return Navigated::No;
10991 };
10992 let pane = workspace.read(cx).active_pane().clone();
10993
10994 let range = target.range.to_point(target.buffer.read(cx));
10995 let range = editor.range_for_match(&range);
10996 let range = collapse_multiline_range(range);
10997
10998 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10999 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11000 } else {
11001 window.defer(cx, move |window, cx| {
11002 let target_editor: Entity<Self> =
11003 workspace.update(cx, |workspace, cx| {
11004 let pane = if split {
11005 workspace.adjacent_pane(window, cx)
11006 } else {
11007 workspace.active_pane().clone()
11008 };
11009
11010 workspace.open_project_item(
11011 pane,
11012 target.buffer.clone(),
11013 true,
11014 true,
11015 window,
11016 cx,
11017 )
11018 });
11019 target_editor.update(cx, |target_editor, cx| {
11020 // When selecting a definition in a different buffer, disable the nav history
11021 // to avoid creating a history entry at the previous cursor location.
11022 pane.update(cx, |pane, _| pane.disable_history());
11023 target_editor.go_to_singleton_buffer_range(range, window, cx);
11024 pane.update(cx, |pane, _| pane.enable_history());
11025 });
11026 });
11027 }
11028 Navigated::Yes
11029 })
11030 })
11031 } else if !definitions.is_empty() {
11032 cx.spawn_in(window, |editor, mut cx| async move {
11033 let (title, location_tasks, workspace) = editor
11034 .update_in(&mut cx, |editor, window, cx| {
11035 let tab_kind = match kind {
11036 Some(GotoDefinitionKind::Implementation) => "Implementations",
11037 _ => "Definitions",
11038 };
11039 let title = definitions
11040 .iter()
11041 .find_map(|definition| match definition {
11042 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11043 let buffer = origin.buffer.read(cx);
11044 format!(
11045 "{} for {}",
11046 tab_kind,
11047 buffer
11048 .text_for_range(origin.range.clone())
11049 .collect::<String>()
11050 )
11051 }),
11052 HoverLink::InlayHint(_, _) => None,
11053 HoverLink::Url(_) => None,
11054 HoverLink::File(_) => None,
11055 })
11056 .unwrap_or(tab_kind.to_string());
11057 let location_tasks = definitions
11058 .into_iter()
11059 .map(|definition| match definition {
11060 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11061 HoverLink::InlayHint(lsp_location, server_id) => editor
11062 .compute_target_location(lsp_location, server_id, window, cx),
11063 HoverLink::Url(_) => Task::ready(Ok(None)),
11064 HoverLink::File(_) => Task::ready(Ok(None)),
11065 })
11066 .collect::<Vec<_>>();
11067 (title, location_tasks, editor.workspace().clone())
11068 })
11069 .context("location tasks preparation")?;
11070
11071 let locations = future::join_all(location_tasks)
11072 .await
11073 .into_iter()
11074 .filter_map(|location| location.transpose())
11075 .collect::<Result<_>>()
11076 .context("location tasks")?;
11077
11078 let Some(workspace) = workspace else {
11079 return Ok(Navigated::No);
11080 };
11081 let opened = workspace
11082 .update_in(&mut cx, |workspace, window, cx| {
11083 Self::open_locations_in_multibuffer(
11084 workspace,
11085 locations,
11086 title,
11087 split,
11088 MultibufferSelectionMode::First,
11089 window,
11090 cx,
11091 )
11092 })
11093 .ok();
11094
11095 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11096 })
11097 } else {
11098 Task::ready(Ok(Navigated::No))
11099 }
11100 }
11101
11102 fn compute_target_location(
11103 &self,
11104 lsp_location: lsp::Location,
11105 server_id: LanguageServerId,
11106 window: &mut Window,
11107 cx: &mut Context<Self>,
11108 ) -> Task<anyhow::Result<Option<Location>>> {
11109 let Some(project) = self.project.clone() else {
11110 return Task::ready(Ok(None));
11111 };
11112
11113 cx.spawn_in(window, move |editor, mut cx| async move {
11114 let location_task = editor.update(&mut cx, |_, cx| {
11115 project.update(cx, |project, cx| {
11116 let language_server_name = project
11117 .language_server_statuses(cx)
11118 .find(|(id, _)| server_id == *id)
11119 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11120 language_server_name.map(|language_server_name| {
11121 project.open_local_buffer_via_lsp(
11122 lsp_location.uri.clone(),
11123 server_id,
11124 language_server_name,
11125 cx,
11126 )
11127 })
11128 })
11129 })?;
11130 let location = match location_task {
11131 Some(task) => Some({
11132 let target_buffer_handle = task.await.context("open local buffer")?;
11133 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11134 let target_start = target_buffer
11135 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11136 let target_end = target_buffer
11137 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11138 target_buffer.anchor_after(target_start)
11139 ..target_buffer.anchor_before(target_end)
11140 })?;
11141 Location {
11142 buffer: target_buffer_handle,
11143 range,
11144 }
11145 }),
11146 None => None,
11147 };
11148 Ok(location)
11149 })
11150 }
11151
11152 pub fn find_all_references(
11153 &mut self,
11154 _: &FindAllReferences,
11155 window: &mut Window,
11156 cx: &mut Context<Self>,
11157 ) -> Option<Task<Result<Navigated>>> {
11158 let selection = self.selections.newest::<usize>(cx);
11159 let multi_buffer = self.buffer.read(cx);
11160 let head = selection.head();
11161
11162 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11163 let head_anchor = multi_buffer_snapshot.anchor_at(
11164 head,
11165 if head < selection.tail() {
11166 Bias::Right
11167 } else {
11168 Bias::Left
11169 },
11170 );
11171
11172 match self
11173 .find_all_references_task_sources
11174 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11175 {
11176 Ok(_) => {
11177 log::info!(
11178 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11179 );
11180 return None;
11181 }
11182 Err(i) => {
11183 self.find_all_references_task_sources.insert(i, head_anchor);
11184 }
11185 }
11186
11187 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11188 let workspace = self.workspace()?;
11189 let project = workspace.read(cx).project().clone();
11190 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11191 Some(cx.spawn_in(window, |editor, mut cx| async move {
11192 let _cleanup = defer({
11193 let mut cx = cx.clone();
11194 move || {
11195 let _ = editor.update(&mut cx, |editor, _| {
11196 if let Ok(i) =
11197 editor
11198 .find_all_references_task_sources
11199 .binary_search_by(|anchor| {
11200 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11201 })
11202 {
11203 editor.find_all_references_task_sources.remove(i);
11204 }
11205 });
11206 }
11207 });
11208
11209 let locations = references.await?;
11210 if locations.is_empty() {
11211 return anyhow::Ok(Navigated::No);
11212 }
11213
11214 workspace.update_in(&mut cx, |workspace, window, cx| {
11215 let title = locations
11216 .first()
11217 .as_ref()
11218 .map(|location| {
11219 let buffer = location.buffer.read(cx);
11220 format!(
11221 "References to `{}`",
11222 buffer
11223 .text_for_range(location.range.clone())
11224 .collect::<String>()
11225 )
11226 })
11227 .unwrap();
11228 Self::open_locations_in_multibuffer(
11229 workspace,
11230 locations,
11231 title,
11232 false,
11233 MultibufferSelectionMode::First,
11234 window,
11235 cx,
11236 );
11237 Navigated::Yes
11238 })
11239 }))
11240 }
11241
11242 /// Opens a multibuffer with the given project locations in it
11243 pub fn open_locations_in_multibuffer(
11244 workspace: &mut Workspace,
11245 mut locations: Vec<Location>,
11246 title: String,
11247 split: bool,
11248 multibuffer_selection_mode: MultibufferSelectionMode,
11249 window: &mut Window,
11250 cx: &mut Context<Workspace>,
11251 ) {
11252 // If there are multiple definitions, open them in a multibuffer
11253 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11254 let mut locations = locations.into_iter().peekable();
11255 let mut ranges = Vec::new();
11256 let capability = workspace.project().read(cx).capability();
11257
11258 let excerpt_buffer = cx.new(|cx| {
11259 let mut multibuffer = MultiBuffer::new(capability);
11260 while let Some(location) = locations.next() {
11261 let buffer = location.buffer.read(cx);
11262 let mut ranges_for_buffer = Vec::new();
11263 let range = location.range.to_offset(buffer);
11264 ranges_for_buffer.push(range.clone());
11265
11266 while let Some(next_location) = locations.peek() {
11267 if next_location.buffer == location.buffer {
11268 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11269 locations.next();
11270 } else {
11271 break;
11272 }
11273 }
11274
11275 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11276 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11277 location.buffer.clone(),
11278 ranges_for_buffer,
11279 DEFAULT_MULTIBUFFER_CONTEXT,
11280 cx,
11281 ))
11282 }
11283
11284 multibuffer.with_title(title)
11285 });
11286
11287 let editor = cx.new(|cx| {
11288 Editor::for_multibuffer(
11289 excerpt_buffer,
11290 Some(workspace.project().clone()),
11291 true,
11292 window,
11293 cx,
11294 )
11295 });
11296 editor.update(cx, |editor, cx| {
11297 match multibuffer_selection_mode {
11298 MultibufferSelectionMode::First => {
11299 if let Some(first_range) = ranges.first() {
11300 editor.change_selections(None, window, cx, |selections| {
11301 selections.clear_disjoint();
11302 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11303 });
11304 }
11305 editor.highlight_background::<Self>(
11306 &ranges,
11307 |theme| theme.editor_highlighted_line_background,
11308 cx,
11309 );
11310 }
11311 MultibufferSelectionMode::All => {
11312 editor.change_selections(None, window, cx, |selections| {
11313 selections.clear_disjoint();
11314 selections.select_anchor_ranges(ranges);
11315 });
11316 }
11317 }
11318 editor.register_buffers_with_language_servers(cx);
11319 });
11320
11321 let item = Box::new(editor);
11322 let item_id = item.item_id();
11323
11324 if split {
11325 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11326 } else {
11327 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11328 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11329 pane.close_current_preview_item(window, cx)
11330 } else {
11331 None
11332 }
11333 });
11334 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11335 }
11336 workspace.active_pane().update(cx, |pane, cx| {
11337 pane.set_preview_item_id(Some(item_id), cx);
11338 });
11339 }
11340
11341 pub fn rename(
11342 &mut self,
11343 _: &Rename,
11344 window: &mut Window,
11345 cx: &mut Context<Self>,
11346 ) -> Option<Task<Result<()>>> {
11347 use language::ToOffset as _;
11348
11349 let provider = self.semantics_provider.clone()?;
11350 let selection = self.selections.newest_anchor().clone();
11351 let (cursor_buffer, cursor_buffer_position) = self
11352 .buffer
11353 .read(cx)
11354 .text_anchor_for_position(selection.head(), cx)?;
11355 let (tail_buffer, cursor_buffer_position_end) = self
11356 .buffer
11357 .read(cx)
11358 .text_anchor_for_position(selection.tail(), cx)?;
11359 if tail_buffer != cursor_buffer {
11360 return None;
11361 }
11362
11363 let snapshot = cursor_buffer.read(cx).snapshot();
11364 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11365 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11366 let prepare_rename = provider
11367 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11368 .unwrap_or_else(|| Task::ready(Ok(None)));
11369 drop(snapshot);
11370
11371 Some(cx.spawn_in(window, |this, mut cx| async move {
11372 let rename_range = if let Some(range) = prepare_rename.await? {
11373 Some(range)
11374 } else {
11375 this.update(&mut cx, |this, cx| {
11376 let buffer = this.buffer.read(cx).snapshot(cx);
11377 let mut buffer_highlights = this
11378 .document_highlights_for_position(selection.head(), &buffer)
11379 .filter(|highlight| {
11380 highlight.start.excerpt_id == selection.head().excerpt_id
11381 && highlight.end.excerpt_id == selection.head().excerpt_id
11382 });
11383 buffer_highlights
11384 .next()
11385 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11386 })?
11387 };
11388 if let Some(rename_range) = rename_range {
11389 this.update_in(&mut cx, |this, window, cx| {
11390 let snapshot = cursor_buffer.read(cx).snapshot();
11391 let rename_buffer_range = rename_range.to_offset(&snapshot);
11392 let cursor_offset_in_rename_range =
11393 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11394 let cursor_offset_in_rename_range_end =
11395 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11396
11397 this.take_rename(false, window, cx);
11398 let buffer = this.buffer.read(cx).read(cx);
11399 let cursor_offset = selection.head().to_offset(&buffer);
11400 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11401 let rename_end = rename_start + rename_buffer_range.len();
11402 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11403 let mut old_highlight_id = None;
11404 let old_name: Arc<str> = buffer
11405 .chunks(rename_start..rename_end, true)
11406 .map(|chunk| {
11407 if old_highlight_id.is_none() {
11408 old_highlight_id = chunk.syntax_highlight_id;
11409 }
11410 chunk.text
11411 })
11412 .collect::<String>()
11413 .into();
11414
11415 drop(buffer);
11416
11417 // Position the selection in the rename editor so that it matches the current selection.
11418 this.show_local_selections = false;
11419 let rename_editor = cx.new(|cx| {
11420 let mut editor = Editor::single_line(window, cx);
11421 editor.buffer.update(cx, |buffer, cx| {
11422 buffer.edit([(0..0, old_name.clone())], None, cx)
11423 });
11424 let rename_selection_range = match cursor_offset_in_rename_range
11425 .cmp(&cursor_offset_in_rename_range_end)
11426 {
11427 Ordering::Equal => {
11428 editor.select_all(&SelectAll, window, cx);
11429 return editor;
11430 }
11431 Ordering::Less => {
11432 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11433 }
11434 Ordering::Greater => {
11435 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11436 }
11437 };
11438 if rename_selection_range.end > old_name.len() {
11439 editor.select_all(&SelectAll, window, cx);
11440 } else {
11441 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11442 s.select_ranges([rename_selection_range]);
11443 });
11444 }
11445 editor
11446 });
11447 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11448 if e == &EditorEvent::Focused {
11449 cx.emit(EditorEvent::FocusedIn)
11450 }
11451 })
11452 .detach();
11453
11454 let write_highlights =
11455 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11456 let read_highlights =
11457 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11458 let ranges = write_highlights
11459 .iter()
11460 .flat_map(|(_, ranges)| ranges.iter())
11461 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11462 .cloned()
11463 .collect();
11464
11465 this.highlight_text::<Rename>(
11466 ranges,
11467 HighlightStyle {
11468 fade_out: Some(0.6),
11469 ..Default::default()
11470 },
11471 cx,
11472 );
11473 let rename_focus_handle = rename_editor.focus_handle(cx);
11474 window.focus(&rename_focus_handle);
11475 let block_id = this.insert_blocks(
11476 [BlockProperties {
11477 style: BlockStyle::Flex,
11478 placement: BlockPlacement::Below(range.start),
11479 height: 1,
11480 render: Arc::new({
11481 let rename_editor = rename_editor.clone();
11482 move |cx: &mut BlockContext| {
11483 let mut text_style = cx.editor_style.text.clone();
11484 if let Some(highlight_style) = old_highlight_id
11485 .and_then(|h| h.style(&cx.editor_style.syntax))
11486 {
11487 text_style = text_style.highlight(highlight_style);
11488 }
11489 div()
11490 .block_mouse_down()
11491 .pl(cx.anchor_x)
11492 .child(EditorElement::new(
11493 &rename_editor,
11494 EditorStyle {
11495 background: cx.theme().system().transparent,
11496 local_player: cx.editor_style.local_player,
11497 text: text_style,
11498 scrollbar_width: cx.editor_style.scrollbar_width,
11499 syntax: cx.editor_style.syntax.clone(),
11500 status: cx.editor_style.status.clone(),
11501 inlay_hints_style: HighlightStyle {
11502 font_weight: Some(FontWeight::BOLD),
11503 ..make_inlay_hints_style(cx.app)
11504 },
11505 inline_completion_styles: make_suggestion_styles(
11506 cx.app,
11507 ),
11508 ..EditorStyle::default()
11509 },
11510 ))
11511 .into_any_element()
11512 }
11513 }),
11514 priority: 0,
11515 }],
11516 Some(Autoscroll::fit()),
11517 cx,
11518 )[0];
11519 this.pending_rename = Some(RenameState {
11520 range,
11521 old_name,
11522 editor: rename_editor,
11523 block_id,
11524 });
11525 })?;
11526 }
11527
11528 Ok(())
11529 }))
11530 }
11531
11532 pub fn confirm_rename(
11533 &mut self,
11534 _: &ConfirmRename,
11535 window: &mut Window,
11536 cx: &mut Context<Self>,
11537 ) -> Option<Task<Result<()>>> {
11538 let rename = self.take_rename(false, window, cx)?;
11539 let workspace = self.workspace()?.downgrade();
11540 let (buffer, start) = self
11541 .buffer
11542 .read(cx)
11543 .text_anchor_for_position(rename.range.start, cx)?;
11544 let (end_buffer, _) = self
11545 .buffer
11546 .read(cx)
11547 .text_anchor_for_position(rename.range.end, cx)?;
11548 if buffer != end_buffer {
11549 return None;
11550 }
11551
11552 let old_name = rename.old_name;
11553 let new_name = rename.editor.read(cx).text(cx);
11554
11555 let rename = self.semantics_provider.as_ref()?.perform_rename(
11556 &buffer,
11557 start,
11558 new_name.clone(),
11559 cx,
11560 )?;
11561
11562 Some(cx.spawn_in(window, |editor, mut cx| async move {
11563 let project_transaction = rename.await?;
11564 Self::open_project_transaction(
11565 &editor,
11566 workspace,
11567 project_transaction,
11568 format!("Rename: {} → {}", old_name, new_name),
11569 cx.clone(),
11570 )
11571 .await?;
11572
11573 editor.update(&mut cx, |editor, cx| {
11574 editor.refresh_document_highlights(cx);
11575 })?;
11576 Ok(())
11577 }))
11578 }
11579
11580 fn take_rename(
11581 &mut self,
11582 moving_cursor: bool,
11583 window: &mut Window,
11584 cx: &mut Context<Self>,
11585 ) -> Option<RenameState> {
11586 let rename = self.pending_rename.take()?;
11587 if rename.editor.focus_handle(cx).is_focused(window) {
11588 window.focus(&self.focus_handle);
11589 }
11590
11591 self.remove_blocks(
11592 [rename.block_id].into_iter().collect(),
11593 Some(Autoscroll::fit()),
11594 cx,
11595 );
11596 self.clear_highlights::<Rename>(cx);
11597 self.show_local_selections = true;
11598
11599 if moving_cursor {
11600 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11601 editor.selections.newest::<usize>(cx).head()
11602 });
11603
11604 // Update the selection to match the position of the selection inside
11605 // the rename editor.
11606 let snapshot = self.buffer.read(cx).read(cx);
11607 let rename_range = rename.range.to_offset(&snapshot);
11608 let cursor_in_editor = snapshot
11609 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11610 .min(rename_range.end);
11611 drop(snapshot);
11612
11613 self.change_selections(None, window, cx, |s| {
11614 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11615 });
11616 } else {
11617 self.refresh_document_highlights(cx);
11618 }
11619
11620 Some(rename)
11621 }
11622
11623 pub fn pending_rename(&self) -> Option<&RenameState> {
11624 self.pending_rename.as_ref()
11625 }
11626
11627 fn format(
11628 &mut self,
11629 _: &Format,
11630 window: &mut Window,
11631 cx: &mut Context<Self>,
11632 ) -> Option<Task<Result<()>>> {
11633 let project = match &self.project {
11634 Some(project) => project.clone(),
11635 None => return None,
11636 };
11637
11638 Some(self.perform_format(
11639 project,
11640 FormatTrigger::Manual,
11641 FormatTarget::Buffers,
11642 window,
11643 cx,
11644 ))
11645 }
11646
11647 fn format_selections(
11648 &mut self,
11649 _: &FormatSelections,
11650 window: &mut Window,
11651 cx: &mut Context<Self>,
11652 ) -> Option<Task<Result<()>>> {
11653 let project = match &self.project {
11654 Some(project) => project.clone(),
11655 None => return None,
11656 };
11657
11658 let ranges = self
11659 .selections
11660 .all_adjusted(cx)
11661 .into_iter()
11662 .map(|selection| selection.range())
11663 .collect_vec();
11664
11665 Some(self.perform_format(
11666 project,
11667 FormatTrigger::Manual,
11668 FormatTarget::Ranges(ranges),
11669 window,
11670 cx,
11671 ))
11672 }
11673
11674 fn perform_format(
11675 &mut self,
11676 project: Entity<Project>,
11677 trigger: FormatTrigger,
11678 target: FormatTarget,
11679 window: &mut Window,
11680 cx: &mut Context<Self>,
11681 ) -> Task<Result<()>> {
11682 let buffer = self.buffer.clone();
11683 let (buffers, target) = match target {
11684 FormatTarget::Buffers => {
11685 let mut buffers = buffer.read(cx).all_buffers();
11686 if trigger == FormatTrigger::Save {
11687 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11688 }
11689 (buffers, LspFormatTarget::Buffers)
11690 }
11691 FormatTarget::Ranges(selection_ranges) => {
11692 let multi_buffer = buffer.read(cx);
11693 let snapshot = multi_buffer.read(cx);
11694 let mut buffers = HashSet::default();
11695 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11696 BTreeMap::new();
11697 for selection_range in selection_ranges {
11698 for (buffer, buffer_range, _) in
11699 snapshot.range_to_buffer_ranges(selection_range)
11700 {
11701 let buffer_id = buffer.remote_id();
11702 let start = buffer.anchor_before(buffer_range.start);
11703 let end = buffer.anchor_after(buffer_range.end);
11704 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11705 buffer_id_to_ranges
11706 .entry(buffer_id)
11707 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11708 .or_insert_with(|| vec![start..end]);
11709 }
11710 }
11711 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11712 }
11713 };
11714
11715 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11716 let format = project.update(cx, |project, cx| {
11717 project.format(buffers, target, true, trigger, cx)
11718 });
11719
11720 cx.spawn_in(window, |_, mut cx| async move {
11721 let transaction = futures::select_biased! {
11722 () = timeout => {
11723 log::warn!("timed out waiting for formatting");
11724 None
11725 }
11726 transaction = format.log_err().fuse() => transaction,
11727 };
11728
11729 buffer
11730 .update(&mut cx, |buffer, cx| {
11731 if let Some(transaction) = transaction {
11732 if !buffer.is_singleton() {
11733 buffer.push_transaction(&transaction.0, cx);
11734 }
11735 }
11736
11737 cx.notify();
11738 })
11739 .ok();
11740
11741 Ok(())
11742 })
11743 }
11744
11745 fn restart_language_server(
11746 &mut self,
11747 _: &RestartLanguageServer,
11748 _: &mut Window,
11749 cx: &mut Context<Self>,
11750 ) {
11751 if let Some(project) = self.project.clone() {
11752 self.buffer.update(cx, |multi_buffer, cx| {
11753 project.update(cx, |project, cx| {
11754 project.restart_language_servers_for_buffers(
11755 multi_buffer.all_buffers().into_iter().collect(),
11756 cx,
11757 );
11758 });
11759 })
11760 }
11761 }
11762
11763 fn cancel_language_server_work(
11764 workspace: &mut Workspace,
11765 _: &actions::CancelLanguageServerWork,
11766 _: &mut Window,
11767 cx: &mut Context<Workspace>,
11768 ) {
11769 let project = workspace.project();
11770 let buffers = workspace
11771 .active_item(cx)
11772 .and_then(|item| item.act_as::<Editor>(cx))
11773 .map_or(HashSet::default(), |editor| {
11774 editor.read(cx).buffer.read(cx).all_buffers()
11775 });
11776 project.update(cx, |project, cx| {
11777 project.cancel_language_server_work_for_buffers(buffers, cx);
11778 });
11779 }
11780
11781 fn show_character_palette(
11782 &mut self,
11783 _: &ShowCharacterPalette,
11784 window: &mut Window,
11785 _: &mut Context<Self>,
11786 ) {
11787 window.show_character_palette();
11788 }
11789
11790 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11791 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11792 let buffer = self.buffer.read(cx).snapshot(cx);
11793 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11794 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11795 let is_valid = buffer
11796 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11797 .any(|entry| {
11798 entry.diagnostic.is_primary
11799 && !entry.range.is_empty()
11800 && entry.range.start == primary_range_start
11801 && entry.diagnostic.message == active_diagnostics.primary_message
11802 });
11803
11804 if is_valid != active_diagnostics.is_valid {
11805 active_diagnostics.is_valid = is_valid;
11806 let mut new_styles = HashMap::default();
11807 for (block_id, diagnostic) in &active_diagnostics.blocks {
11808 new_styles.insert(
11809 *block_id,
11810 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11811 );
11812 }
11813 self.display_map.update(cx, |display_map, _cx| {
11814 display_map.replace_blocks(new_styles)
11815 });
11816 }
11817 }
11818 }
11819
11820 fn activate_diagnostics(
11821 &mut self,
11822 buffer_id: BufferId,
11823 group_id: usize,
11824 window: &mut Window,
11825 cx: &mut Context<Self>,
11826 ) {
11827 self.dismiss_diagnostics(cx);
11828 let snapshot = self.snapshot(window, cx);
11829 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11830 let buffer = self.buffer.read(cx).snapshot(cx);
11831
11832 let mut primary_range = None;
11833 let mut primary_message = None;
11834 let diagnostic_group = buffer
11835 .diagnostic_group(buffer_id, group_id)
11836 .filter_map(|entry| {
11837 let start = entry.range.start;
11838 let end = entry.range.end;
11839 if snapshot.is_line_folded(MultiBufferRow(start.row))
11840 && (start.row == end.row
11841 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11842 {
11843 return None;
11844 }
11845 if entry.diagnostic.is_primary {
11846 primary_range = Some(entry.range.clone());
11847 primary_message = Some(entry.diagnostic.message.clone());
11848 }
11849 Some(entry)
11850 })
11851 .collect::<Vec<_>>();
11852 let primary_range = primary_range?;
11853 let primary_message = primary_message?;
11854
11855 let blocks = display_map
11856 .insert_blocks(
11857 diagnostic_group.iter().map(|entry| {
11858 let diagnostic = entry.diagnostic.clone();
11859 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11860 BlockProperties {
11861 style: BlockStyle::Fixed,
11862 placement: BlockPlacement::Below(
11863 buffer.anchor_after(entry.range.start),
11864 ),
11865 height: message_height,
11866 render: diagnostic_block_renderer(diagnostic, None, true, true),
11867 priority: 0,
11868 }
11869 }),
11870 cx,
11871 )
11872 .into_iter()
11873 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11874 .collect();
11875
11876 Some(ActiveDiagnosticGroup {
11877 primary_range: buffer.anchor_before(primary_range.start)
11878 ..buffer.anchor_after(primary_range.end),
11879 primary_message,
11880 group_id,
11881 blocks,
11882 is_valid: true,
11883 })
11884 });
11885 }
11886
11887 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11888 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11889 self.display_map.update(cx, |display_map, cx| {
11890 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11891 });
11892 cx.notify();
11893 }
11894 }
11895
11896 pub fn set_selections_from_remote(
11897 &mut self,
11898 selections: Vec<Selection<Anchor>>,
11899 pending_selection: Option<Selection<Anchor>>,
11900 window: &mut Window,
11901 cx: &mut Context<Self>,
11902 ) {
11903 let old_cursor_position = self.selections.newest_anchor().head();
11904 self.selections.change_with(cx, |s| {
11905 s.select_anchors(selections);
11906 if let Some(pending_selection) = pending_selection {
11907 s.set_pending(pending_selection, SelectMode::Character);
11908 } else {
11909 s.clear_pending();
11910 }
11911 });
11912 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11913 }
11914
11915 fn push_to_selection_history(&mut self) {
11916 self.selection_history.push(SelectionHistoryEntry {
11917 selections: self.selections.disjoint_anchors(),
11918 select_next_state: self.select_next_state.clone(),
11919 select_prev_state: self.select_prev_state.clone(),
11920 add_selections_state: self.add_selections_state.clone(),
11921 });
11922 }
11923
11924 pub fn transact(
11925 &mut self,
11926 window: &mut Window,
11927 cx: &mut Context<Self>,
11928 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11929 ) -> Option<TransactionId> {
11930 self.start_transaction_at(Instant::now(), window, cx);
11931 update(self, window, cx);
11932 self.end_transaction_at(Instant::now(), cx)
11933 }
11934
11935 pub fn start_transaction_at(
11936 &mut self,
11937 now: Instant,
11938 window: &mut Window,
11939 cx: &mut Context<Self>,
11940 ) {
11941 self.end_selection(window, cx);
11942 if let Some(tx_id) = self
11943 .buffer
11944 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11945 {
11946 self.selection_history
11947 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11948 cx.emit(EditorEvent::TransactionBegun {
11949 transaction_id: tx_id,
11950 })
11951 }
11952 }
11953
11954 pub fn end_transaction_at(
11955 &mut self,
11956 now: Instant,
11957 cx: &mut Context<Self>,
11958 ) -> Option<TransactionId> {
11959 if let Some(transaction_id) = self
11960 .buffer
11961 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11962 {
11963 if let Some((_, end_selections)) =
11964 self.selection_history.transaction_mut(transaction_id)
11965 {
11966 *end_selections = Some(self.selections.disjoint_anchors());
11967 } else {
11968 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11969 }
11970
11971 cx.emit(EditorEvent::Edited { transaction_id });
11972 Some(transaction_id)
11973 } else {
11974 None
11975 }
11976 }
11977
11978 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11979 if self.selection_mark_mode {
11980 self.change_selections(None, window, cx, |s| {
11981 s.move_with(|_, sel| {
11982 sel.collapse_to(sel.head(), SelectionGoal::None);
11983 });
11984 })
11985 }
11986 self.selection_mark_mode = true;
11987 cx.notify();
11988 }
11989
11990 pub fn swap_selection_ends(
11991 &mut self,
11992 _: &actions::SwapSelectionEnds,
11993 window: &mut Window,
11994 cx: &mut Context<Self>,
11995 ) {
11996 self.change_selections(None, window, cx, |s| {
11997 s.move_with(|_, sel| {
11998 if sel.start != sel.end {
11999 sel.reversed = !sel.reversed
12000 }
12001 });
12002 });
12003 self.request_autoscroll(Autoscroll::newest(), cx);
12004 cx.notify();
12005 }
12006
12007 pub fn toggle_fold(
12008 &mut self,
12009 _: &actions::ToggleFold,
12010 window: &mut Window,
12011 cx: &mut Context<Self>,
12012 ) {
12013 if self.is_singleton(cx) {
12014 let selection = self.selections.newest::<Point>(cx);
12015
12016 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12017 let range = if selection.is_empty() {
12018 let point = selection.head().to_display_point(&display_map);
12019 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12020 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12021 .to_point(&display_map);
12022 start..end
12023 } else {
12024 selection.range()
12025 };
12026 if display_map.folds_in_range(range).next().is_some() {
12027 self.unfold_lines(&Default::default(), window, cx)
12028 } else {
12029 self.fold(&Default::default(), window, cx)
12030 }
12031 } else {
12032 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12033 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12034 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12035 .map(|(snapshot, _, _)| snapshot.remote_id())
12036 .collect();
12037
12038 for buffer_id in buffer_ids {
12039 if self.is_buffer_folded(buffer_id, cx) {
12040 self.unfold_buffer(buffer_id, cx);
12041 } else {
12042 self.fold_buffer(buffer_id, cx);
12043 }
12044 }
12045 }
12046 }
12047
12048 pub fn toggle_fold_recursive(
12049 &mut self,
12050 _: &actions::ToggleFoldRecursive,
12051 window: &mut Window,
12052 cx: &mut Context<Self>,
12053 ) {
12054 let selection = self.selections.newest::<Point>(cx);
12055
12056 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12057 let range = if selection.is_empty() {
12058 let point = selection.head().to_display_point(&display_map);
12059 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12060 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12061 .to_point(&display_map);
12062 start..end
12063 } else {
12064 selection.range()
12065 };
12066 if display_map.folds_in_range(range).next().is_some() {
12067 self.unfold_recursive(&Default::default(), window, cx)
12068 } else {
12069 self.fold_recursive(&Default::default(), window, cx)
12070 }
12071 }
12072
12073 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12074 if self.is_singleton(cx) {
12075 let mut to_fold = Vec::new();
12076 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12077 let selections = self.selections.all_adjusted(cx);
12078
12079 for selection in selections {
12080 let range = selection.range().sorted();
12081 let buffer_start_row = range.start.row;
12082
12083 if range.start.row != range.end.row {
12084 let mut found = false;
12085 let mut row = range.start.row;
12086 while row <= range.end.row {
12087 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12088 {
12089 found = true;
12090 row = crease.range().end.row + 1;
12091 to_fold.push(crease);
12092 } else {
12093 row += 1
12094 }
12095 }
12096 if found {
12097 continue;
12098 }
12099 }
12100
12101 for row in (0..=range.start.row).rev() {
12102 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12103 if crease.range().end.row >= buffer_start_row {
12104 to_fold.push(crease);
12105 if row <= range.start.row {
12106 break;
12107 }
12108 }
12109 }
12110 }
12111 }
12112
12113 self.fold_creases(to_fold, true, window, cx);
12114 } else {
12115 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12116
12117 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12118 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12119 .map(|(snapshot, _, _)| snapshot.remote_id())
12120 .collect();
12121 for buffer_id in buffer_ids {
12122 self.fold_buffer(buffer_id, cx);
12123 }
12124 }
12125 }
12126
12127 fn fold_at_level(
12128 &mut self,
12129 fold_at: &FoldAtLevel,
12130 window: &mut Window,
12131 cx: &mut Context<Self>,
12132 ) {
12133 if !self.buffer.read(cx).is_singleton() {
12134 return;
12135 }
12136
12137 let fold_at_level = fold_at.0;
12138 let snapshot = self.buffer.read(cx).snapshot(cx);
12139 let mut to_fold = Vec::new();
12140 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12141
12142 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12143 while start_row < end_row {
12144 match self
12145 .snapshot(window, cx)
12146 .crease_for_buffer_row(MultiBufferRow(start_row))
12147 {
12148 Some(crease) => {
12149 let nested_start_row = crease.range().start.row + 1;
12150 let nested_end_row = crease.range().end.row;
12151
12152 if current_level < fold_at_level {
12153 stack.push((nested_start_row, nested_end_row, current_level + 1));
12154 } else if current_level == fold_at_level {
12155 to_fold.push(crease);
12156 }
12157
12158 start_row = nested_end_row + 1;
12159 }
12160 None => start_row += 1,
12161 }
12162 }
12163 }
12164
12165 self.fold_creases(to_fold, true, window, cx);
12166 }
12167
12168 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12169 if self.buffer.read(cx).is_singleton() {
12170 let mut fold_ranges = Vec::new();
12171 let snapshot = self.buffer.read(cx).snapshot(cx);
12172
12173 for row in 0..snapshot.max_row().0 {
12174 if let Some(foldable_range) = self
12175 .snapshot(window, cx)
12176 .crease_for_buffer_row(MultiBufferRow(row))
12177 {
12178 fold_ranges.push(foldable_range);
12179 }
12180 }
12181
12182 self.fold_creases(fold_ranges, true, window, cx);
12183 } else {
12184 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12185 editor
12186 .update_in(&mut cx, |editor, _, cx| {
12187 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12188 editor.fold_buffer(buffer_id, cx);
12189 }
12190 })
12191 .ok();
12192 });
12193 }
12194 }
12195
12196 pub fn fold_function_bodies(
12197 &mut self,
12198 _: &actions::FoldFunctionBodies,
12199 window: &mut Window,
12200 cx: &mut Context<Self>,
12201 ) {
12202 let snapshot = self.buffer.read(cx).snapshot(cx);
12203
12204 let ranges = snapshot
12205 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12206 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12207 .collect::<Vec<_>>();
12208
12209 let creases = ranges
12210 .into_iter()
12211 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12212 .collect();
12213
12214 self.fold_creases(creases, true, window, cx);
12215 }
12216
12217 pub fn fold_recursive(
12218 &mut self,
12219 _: &actions::FoldRecursive,
12220 window: &mut Window,
12221 cx: &mut Context<Self>,
12222 ) {
12223 let mut to_fold = Vec::new();
12224 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12225 let selections = self.selections.all_adjusted(cx);
12226
12227 for selection in selections {
12228 let range = selection.range().sorted();
12229 let buffer_start_row = range.start.row;
12230
12231 if range.start.row != range.end.row {
12232 let mut found = false;
12233 for row in range.start.row..=range.end.row {
12234 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12235 found = true;
12236 to_fold.push(crease);
12237 }
12238 }
12239 if found {
12240 continue;
12241 }
12242 }
12243
12244 for row in (0..=range.start.row).rev() {
12245 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12246 if crease.range().end.row >= buffer_start_row {
12247 to_fold.push(crease);
12248 } else {
12249 break;
12250 }
12251 }
12252 }
12253 }
12254
12255 self.fold_creases(to_fold, true, window, cx);
12256 }
12257
12258 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12259 let buffer_row = fold_at.buffer_row;
12260 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12261
12262 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12263 let autoscroll = self
12264 .selections
12265 .all::<Point>(cx)
12266 .iter()
12267 .any(|selection| crease.range().overlaps(&selection.range()));
12268
12269 self.fold_creases(vec![crease], autoscroll, window, cx);
12270 }
12271 }
12272
12273 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12274 if self.is_singleton(cx) {
12275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12276 let buffer = &display_map.buffer_snapshot;
12277 let selections = self.selections.all::<Point>(cx);
12278 let ranges = selections
12279 .iter()
12280 .map(|s| {
12281 let range = s.display_range(&display_map).sorted();
12282 let mut start = range.start.to_point(&display_map);
12283 let mut end = range.end.to_point(&display_map);
12284 start.column = 0;
12285 end.column = buffer.line_len(MultiBufferRow(end.row));
12286 start..end
12287 })
12288 .collect::<Vec<_>>();
12289
12290 self.unfold_ranges(&ranges, true, true, cx);
12291 } else {
12292 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12293 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12294 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12295 .map(|(snapshot, _, _)| snapshot.remote_id())
12296 .collect();
12297 for buffer_id in buffer_ids {
12298 self.unfold_buffer(buffer_id, cx);
12299 }
12300 }
12301 }
12302
12303 pub fn unfold_recursive(
12304 &mut self,
12305 _: &UnfoldRecursive,
12306 _window: &mut Window,
12307 cx: &mut Context<Self>,
12308 ) {
12309 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12310 let selections = self.selections.all::<Point>(cx);
12311 let ranges = selections
12312 .iter()
12313 .map(|s| {
12314 let mut range = s.display_range(&display_map).sorted();
12315 *range.start.column_mut() = 0;
12316 *range.end.column_mut() = display_map.line_len(range.end.row());
12317 let start = range.start.to_point(&display_map);
12318 let end = range.end.to_point(&display_map);
12319 start..end
12320 })
12321 .collect::<Vec<_>>();
12322
12323 self.unfold_ranges(&ranges, true, true, cx);
12324 }
12325
12326 pub fn unfold_at(
12327 &mut self,
12328 unfold_at: &UnfoldAt,
12329 _window: &mut Window,
12330 cx: &mut Context<Self>,
12331 ) {
12332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12333
12334 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12335 ..Point::new(
12336 unfold_at.buffer_row.0,
12337 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12338 );
12339
12340 let autoscroll = self
12341 .selections
12342 .all::<Point>(cx)
12343 .iter()
12344 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12345
12346 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12347 }
12348
12349 pub fn unfold_all(
12350 &mut self,
12351 _: &actions::UnfoldAll,
12352 _window: &mut Window,
12353 cx: &mut Context<Self>,
12354 ) {
12355 if self.buffer.read(cx).is_singleton() {
12356 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12357 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12358 } else {
12359 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12360 editor
12361 .update(&mut cx, |editor, cx| {
12362 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12363 editor.unfold_buffer(buffer_id, cx);
12364 }
12365 })
12366 .ok();
12367 });
12368 }
12369 }
12370
12371 pub fn fold_selected_ranges(
12372 &mut self,
12373 _: &FoldSelectedRanges,
12374 window: &mut Window,
12375 cx: &mut Context<Self>,
12376 ) {
12377 let selections = self.selections.all::<Point>(cx);
12378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12379 let line_mode = self.selections.line_mode;
12380 let ranges = selections
12381 .into_iter()
12382 .map(|s| {
12383 if line_mode {
12384 let start = Point::new(s.start.row, 0);
12385 let end = Point::new(
12386 s.end.row,
12387 display_map
12388 .buffer_snapshot
12389 .line_len(MultiBufferRow(s.end.row)),
12390 );
12391 Crease::simple(start..end, display_map.fold_placeholder.clone())
12392 } else {
12393 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12394 }
12395 })
12396 .collect::<Vec<_>>();
12397 self.fold_creases(ranges, true, window, cx);
12398 }
12399
12400 pub fn fold_ranges<T: ToOffset + Clone>(
12401 &mut self,
12402 ranges: Vec<Range<T>>,
12403 auto_scroll: bool,
12404 window: &mut Window,
12405 cx: &mut Context<Self>,
12406 ) {
12407 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12408 let ranges = ranges
12409 .into_iter()
12410 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12411 .collect::<Vec<_>>();
12412 self.fold_creases(ranges, auto_scroll, window, cx);
12413 }
12414
12415 pub fn fold_creases<T: ToOffset + Clone>(
12416 &mut self,
12417 creases: Vec<Crease<T>>,
12418 auto_scroll: bool,
12419 window: &mut Window,
12420 cx: &mut Context<Self>,
12421 ) {
12422 if creases.is_empty() {
12423 return;
12424 }
12425
12426 let mut buffers_affected = HashSet::default();
12427 let multi_buffer = self.buffer().read(cx);
12428 for crease in &creases {
12429 if let Some((_, buffer, _)) =
12430 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12431 {
12432 buffers_affected.insert(buffer.read(cx).remote_id());
12433 };
12434 }
12435
12436 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12437
12438 if auto_scroll {
12439 self.request_autoscroll(Autoscroll::fit(), cx);
12440 }
12441
12442 cx.notify();
12443
12444 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12445 // Clear diagnostics block when folding a range that contains it.
12446 let snapshot = self.snapshot(window, cx);
12447 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12448 drop(snapshot);
12449 self.active_diagnostics = Some(active_diagnostics);
12450 self.dismiss_diagnostics(cx);
12451 } else {
12452 self.active_diagnostics = Some(active_diagnostics);
12453 }
12454 }
12455
12456 self.scrollbar_marker_state.dirty = true;
12457 }
12458
12459 /// Removes any folds whose ranges intersect any of the given ranges.
12460 pub fn unfold_ranges<T: ToOffset + Clone>(
12461 &mut self,
12462 ranges: &[Range<T>],
12463 inclusive: bool,
12464 auto_scroll: bool,
12465 cx: &mut Context<Self>,
12466 ) {
12467 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12468 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12469 });
12470 }
12471
12472 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12473 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12474 return;
12475 }
12476 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12477 self.display_map
12478 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12479 cx.emit(EditorEvent::BufferFoldToggled {
12480 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12481 folded: true,
12482 });
12483 cx.notify();
12484 }
12485
12486 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12487 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12488 return;
12489 }
12490 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12491 self.display_map.update(cx, |display_map, cx| {
12492 display_map.unfold_buffer(buffer_id, cx);
12493 });
12494 cx.emit(EditorEvent::BufferFoldToggled {
12495 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12496 folded: false,
12497 });
12498 cx.notify();
12499 }
12500
12501 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12502 self.display_map.read(cx).is_buffer_folded(buffer)
12503 }
12504
12505 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12506 self.display_map.read(cx).folded_buffers()
12507 }
12508
12509 /// Removes any folds with the given ranges.
12510 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12511 &mut self,
12512 ranges: &[Range<T>],
12513 type_id: TypeId,
12514 auto_scroll: bool,
12515 cx: &mut Context<Self>,
12516 ) {
12517 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12518 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12519 });
12520 }
12521
12522 fn remove_folds_with<T: ToOffset + Clone>(
12523 &mut self,
12524 ranges: &[Range<T>],
12525 auto_scroll: bool,
12526 cx: &mut Context<Self>,
12527 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12528 ) {
12529 if ranges.is_empty() {
12530 return;
12531 }
12532
12533 let mut buffers_affected = HashSet::default();
12534 let multi_buffer = self.buffer().read(cx);
12535 for range in ranges {
12536 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12537 buffers_affected.insert(buffer.read(cx).remote_id());
12538 };
12539 }
12540
12541 self.display_map.update(cx, update);
12542
12543 if auto_scroll {
12544 self.request_autoscroll(Autoscroll::fit(), cx);
12545 }
12546
12547 cx.notify();
12548 self.scrollbar_marker_state.dirty = true;
12549 self.active_indent_guides_state.dirty = true;
12550 }
12551
12552 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12553 self.display_map.read(cx).fold_placeholder.clone()
12554 }
12555
12556 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12557 self.buffer.update(cx, |buffer, cx| {
12558 buffer.set_all_diff_hunks_expanded(cx);
12559 });
12560 }
12561
12562 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12563 self.distinguish_unstaged_diff_hunks = true;
12564 }
12565
12566 pub fn expand_all_diff_hunks(
12567 &mut self,
12568 _: &ExpandAllHunkDiffs,
12569 _window: &mut Window,
12570 cx: &mut Context<Self>,
12571 ) {
12572 self.buffer.update(cx, |buffer, cx| {
12573 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12574 });
12575 }
12576
12577 pub fn toggle_selected_diff_hunks(
12578 &mut self,
12579 _: &ToggleSelectedDiffHunks,
12580 _window: &mut Window,
12581 cx: &mut Context<Self>,
12582 ) {
12583 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12584 self.toggle_diff_hunks_in_ranges(ranges, cx);
12585 }
12586
12587 fn diff_hunks_in_ranges<'a>(
12588 &'a self,
12589 ranges: &'a [Range<Anchor>],
12590 buffer: &'a MultiBufferSnapshot,
12591 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12592 ranges.iter().flat_map(move |range| {
12593 let end_excerpt_id = range.end.excerpt_id;
12594 let range = range.to_point(buffer);
12595 let mut peek_end = range.end;
12596 if range.end.row < buffer.max_row().0 {
12597 peek_end = Point::new(range.end.row + 1, 0);
12598 }
12599 buffer
12600 .diff_hunks_in_range(range.start..peek_end)
12601 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12602 })
12603 }
12604
12605 pub fn has_stageable_diff_hunks_in_ranges(
12606 &self,
12607 ranges: &[Range<Anchor>],
12608 snapshot: &MultiBufferSnapshot,
12609 ) -> bool {
12610 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12611 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12612 }
12613
12614 pub fn toggle_staged_selected_diff_hunks(
12615 &mut self,
12616 _: &ToggleStagedSelectedDiffHunks,
12617 _window: &mut Window,
12618 cx: &mut Context<Self>,
12619 ) {
12620 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12621 self.stage_or_unstage_diff_hunks(&ranges, cx);
12622 }
12623
12624 pub fn stage_or_unstage_diff_hunks(
12625 &mut self,
12626 ranges: &[Range<Anchor>],
12627 cx: &mut Context<Self>,
12628 ) {
12629 let Some(project) = &self.project else {
12630 return;
12631 };
12632 let snapshot = self.buffer.read(cx).snapshot(cx);
12633 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12634
12635 let chunk_by = self
12636 .diff_hunks_in_ranges(&ranges, &snapshot)
12637 .chunk_by(|hunk| hunk.buffer_id);
12638 for (buffer_id, hunks) in &chunk_by {
12639 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12640 log::debug!("no buffer for id");
12641 continue;
12642 };
12643 let buffer = buffer.read(cx).snapshot();
12644 let Some((repo, path)) = project
12645 .read(cx)
12646 .repository_and_path_for_buffer_id(buffer_id, cx)
12647 else {
12648 log::debug!("no git repo for buffer id");
12649 continue;
12650 };
12651 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12652 log::debug!("no diff for buffer id");
12653 continue;
12654 };
12655 let Some(secondary_diff) = diff.secondary_diff() else {
12656 log::debug!("no secondary diff for buffer id");
12657 continue;
12658 };
12659
12660 let edits = diff.secondary_edits_for_stage_or_unstage(
12661 stage,
12662 hunks.map(|hunk| {
12663 (
12664 hunk.diff_base_byte_range.clone(),
12665 hunk.secondary_diff_base_byte_range.clone(),
12666 hunk.buffer_range.clone(),
12667 )
12668 }),
12669 &buffer,
12670 );
12671
12672 let index_base = secondary_diff.base_text().map_or_else(
12673 || Rope::from(""),
12674 |snapshot| snapshot.text.as_rope().clone(),
12675 );
12676 let index_buffer = cx.new(|cx| {
12677 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12678 });
12679 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12680 index_buffer.edit(edits, None, cx);
12681 index_buffer.snapshot().as_rope().to_string()
12682 });
12683 let new_index_text = if new_index_text.is_empty()
12684 && (diff.is_single_insertion
12685 || buffer
12686 .file()
12687 .map_or(false, |file| file.disk_state() == DiskState::New))
12688 {
12689 log::debug!("removing from index");
12690 None
12691 } else {
12692 Some(new_index_text)
12693 };
12694
12695 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12696 }
12697 }
12698
12699 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12700 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12701 self.buffer
12702 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12703 }
12704
12705 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12706 self.buffer.update(cx, |buffer, cx| {
12707 let ranges = vec![Anchor::min()..Anchor::max()];
12708 if !buffer.all_diff_hunks_expanded()
12709 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12710 {
12711 buffer.collapse_diff_hunks(ranges, cx);
12712 true
12713 } else {
12714 false
12715 }
12716 })
12717 }
12718
12719 fn toggle_diff_hunks_in_ranges(
12720 &mut self,
12721 ranges: Vec<Range<Anchor>>,
12722 cx: &mut Context<'_, Editor>,
12723 ) {
12724 self.buffer.update(cx, |buffer, cx| {
12725 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12726 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12727 })
12728 }
12729
12730 fn toggle_diff_hunks_in_ranges_narrow(
12731 &mut self,
12732 ranges: Vec<Range<Anchor>>,
12733 cx: &mut Context<'_, Editor>,
12734 ) {
12735 self.buffer.update(cx, |buffer, cx| {
12736 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12737 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12738 })
12739 }
12740
12741 pub(crate) fn apply_all_diff_hunks(
12742 &mut self,
12743 _: &ApplyAllDiffHunks,
12744 window: &mut Window,
12745 cx: &mut Context<Self>,
12746 ) {
12747 let buffers = self.buffer.read(cx).all_buffers();
12748 for branch_buffer in buffers {
12749 branch_buffer.update(cx, |branch_buffer, cx| {
12750 branch_buffer.merge_into_base(Vec::new(), cx);
12751 });
12752 }
12753
12754 if let Some(project) = self.project.clone() {
12755 self.save(true, project, window, cx).detach_and_log_err(cx);
12756 }
12757 }
12758
12759 pub(crate) fn apply_selected_diff_hunks(
12760 &mut self,
12761 _: &ApplyDiffHunk,
12762 window: &mut Window,
12763 cx: &mut Context<Self>,
12764 ) {
12765 let snapshot = self.snapshot(window, cx);
12766 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12767 let mut ranges_by_buffer = HashMap::default();
12768 self.transact(window, cx, |editor, _window, cx| {
12769 for hunk in hunks {
12770 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12771 ranges_by_buffer
12772 .entry(buffer.clone())
12773 .or_insert_with(Vec::new)
12774 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12775 }
12776 }
12777
12778 for (buffer, ranges) in ranges_by_buffer {
12779 buffer.update(cx, |buffer, cx| {
12780 buffer.merge_into_base(ranges, cx);
12781 });
12782 }
12783 });
12784
12785 if let Some(project) = self.project.clone() {
12786 self.save(true, project, window, cx).detach_and_log_err(cx);
12787 }
12788 }
12789
12790 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12791 if hovered != self.gutter_hovered {
12792 self.gutter_hovered = hovered;
12793 cx.notify();
12794 }
12795 }
12796
12797 pub fn insert_blocks(
12798 &mut self,
12799 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12800 autoscroll: Option<Autoscroll>,
12801 cx: &mut Context<Self>,
12802 ) -> Vec<CustomBlockId> {
12803 let blocks = self
12804 .display_map
12805 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12806 if let Some(autoscroll) = autoscroll {
12807 self.request_autoscroll(autoscroll, cx);
12808 }
12809 cx.notify();
12810 blocks
12811 }
12812
12813 pub fn resize_blocks(
12814 &mut self,
12815 heights: HashMap<CustomBlockId, u32>,
12816 autoscroll: Option<Autoscroll>,
12817 cx: &mut Context<Self>,
12818 ) {
12819 self.display_map
12820 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12821 if let Some(autoscroll) = autoscroll {
12822 self.request_autoscroll(autoscroll, cx);
12823 }
12824 cx.notify();
12825 }
12826
12827 pub fn replace_blocks(
12828 &mut self,
12829 renderers: HashMap<CustomBlockId, RenderBlock>,
12830 autoscroll: Option<Autoscroll>,
12831 cx: &mut Context<Self>,
12832 ) {
12833 self.display_map
12834 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12835 if let Some(autoscroll) = autoscroll {
12836 self.request_autoscroll(autoscroll, cx);
12837 }
12838 cx.notify();
12839 }
12840
12841 pub fn remove_blocks(
12842 &mut self,
12843 block_ids: HashSet<CustomBlockId>,
12844 autoscroll: Option<Autoscroll>,
12845 cx: &mut Context<Self>,
12846 ) {
12847 self.display_map.update(cx, |display_map, cx| {
12848 display_map.remove_blocks(block_ids, cx)
12849 });
12850 if let Some(autoscroll) = autoscroll {
12851 self.request_autoscroll(autoscroll, cx);
12852 }
12853 cx.notify();
12854 }
12855
12856 pub fn row_for_block(
12857 &self,
12858 block_id: CustomBlockId,
12859 cx: &mut Context<Self>,
12860 ) -> Option<DisplayRow> {
12861 self.display_map
12862 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12863 }
12864
12865 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12866 self.focused_block = Some(focused_block);
12867 }
12868
12869 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12870 self.focused_block.take()
12871 }
12872
12873 pub fn insert_creases(
12874 &mut self,
12875 creases: impl IntoIterator<Item = Crease<Anchor>>,
12876 cx: &mut Context<Self>,
12877 ) -> Vec<CreaseId> {
12878 self.display_map
12879 .update(cx, |map, cx| map.insert_creases(creases, cx))
12880 }
12881
12882 pub fn remove_creases(
12883 &mut self,
12884 ids: impl IntoIterator<Item = CreaseId>,
12885 cx: &mut Context<Self>,
12886 ) {
12887 self.display_map
12888 .update(cx, |map, cx| map.remove_creases(ids, cx));
12889 }
12890
12891 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12892 self.display_map
12893 .update(cx, |map, cx| map.snapshot(cx))
12894 .longest_row()
12895 }
12896
12897 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12898 self.display_map
12899 .update(cx, |map, cx| map.snapshot(cx))
12900 .max_point()
12901 }
12902
12903 pub fn text(&self, cx: &App) -> String {
12904 self.buffer.read(cx).read(cx).text()
12905 }
12906
12907 pub fn is_empty(&self, cx: &App) -> bool {
12908 self.buffer.read(cx).read(cx).is_empty()
12909 }
12910
12911 pub fn text_option(&self, cx: &App) -> Option<String> {
12912 let text = self.text(cx);
12913 let text = text.trim();
12914
12915 if text.is_empty() {
12916 return None;
12917 }
12918
12919 Some(text.to_string())
12920 }
12921
12922 pub fn set_text(
12923 &mut self,
12924 text: impl Into<Arc<str>>,
12925 window: &mut Window,
12926 cx: &mut Context<Self>,
12927 ) {
12928 self.transact(window, cx, |this, _, cx| {
12929 this.buffer
12930 .read(cx)
12931 .as_singleton()
12932 .expect("you can only call set_text on editors for singleton buffers")
12933 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12934 });
12935 }
12936
12937 pub fn display_text(&self, cx: &mut App) -> String {
12938 self.display_map
12939 .update(cx, |map, cx| map.snapshot(cx))
12940 .text()
12941 }
12942
12943 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12944 let mut wrap_guides = smallvec::smallvec![];
12945
12946 if self.show_wrap_guides == Some(false) {
12947 return wrap_guides;
12948 }
12949
12950 let settings = self.buffer.read(cx).settings_at(0, cx);
12951 if settings.show_wrap_guides {
12952 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12953 wrap_guides.push((soft_wrap as usize, true));
12954 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12955 wrap_guides.push((soft_wrap as usize, true));
12956 }
12957 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12958 }
12959
12960 wrap_guides
12961 }
12962
12963 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12964 let settings = self.buffer.read(cx).settings_at(0, cx);
12965 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12966 match mode {
12967 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12968 SoftWrap::None
12969 }
12970 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12971 language_settings::SoftWrap::PreferredLineLength => {
12972 SoftWrap::Column(settings.preferred_line_length)
12973 }
12974 language_settings::SoftWrap::Bounded => {
12975 SoftWrap::Bounded(settings.preferred_line_length)
12976 }
12977 }
12978 }
12979
12980 pub fn set_soft_wrap_mode(
12981 &mut self,
12982 mode: language_settings::SoftWrap,
12983
12984 cx: &mut Context<Self>,
12985 ) {
12986 self.soft_wrap_mode_override = Some(mode);
12987 cx.notify();
12988 }
12989
12990 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12991 self.text_style_refinement = Some(style);
12992 }
12993
12994 /// called by the Element so we know what style we were most recently rendered with.
12995 pub(crate) fn set_style(
12996 &mut self,
12997 style: EditorStyle,
12998 window: &mut Window,
12999 cx: &mut Context<Self>,
13000 ) {
13001 let rem_size = window.rem_size();
13002 self.display_map.update(cx, |map, cx| {
13003 map.set_font(
13004 style.text.font(),
13005 style.text.font_size.to_pixels(rem_size),
13006 cx,
13007 )
13008 });
13009 self.style = Some(style);
13010 }
13011
13012 pub fn style(&self) -> Option<&EditorStyle> {
13013 self.style.as_ref()
13014 }
13015
13016 // Called by the element. This method is not designed to be called outside of the editor
13017 // element's layout code because it does not notify when rewrapping is computed synchronously.
13018 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13019 self.display_map
13020 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13021 }
13022
13023 pub fn set_soft_wrap(&mut self) {
13024 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13025 }
13026
13027 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13028 if self.soft_wrap_mode_override.is_some() {
13029 self.soft_wrap_mode_override.take();
13030 } else {
13031 let soft_wrap = match self.soft_wrap_mode(cx) {
13032 SoftWrap::GitDiff => return,
13033 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13034 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13035 language_settings::SoftWrap::None
13036 }
13037 };
13038 self.soft_wrap_mode_override = Some(soft_wrap);
13039 }
13040 cx.notify();
13041 }
13042
13043 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13044 let Some(workspace) = self.workspace() else {
13045 return;
13046 };
13047 let fs = workspace.read(cx).app_state().fs.clone();
13048 let current_show = TabBarSettings::get_global(cx).show;
13049 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13050 setting.show = Some(!current_show);
13051 });
13052 }
13053
13054 pub fn toggle_indent_guides(
13055 &mut self,
13056 _: &ToggleIndentGuides,
13057 _: &mut Window,
13058 cx: &mut Context<Self>,
13059 ) {
13060 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13061 self.buffer
13062 .read(cx)
13063 .settings_at(0, cx)
13064 .indent_guides
13065 .enabled
13066 });
13067 self.show_indent_guides = Some(!currently_enabled);
13068 cx.notify();
13069 }
13070
13071 fn should_show_indent_guides(&self) -> Option<bool> {
13072 self.show_indent_guides
13073 }
13074
13075 pub fn toggle_line_numbers(
13076 &mut self,
13077 _: &ToggleLineNumbers,
13078 _: &mut Window,
13079 cx: &mut Context<Self>,
13080 ) {
13081 let mut editor_settings = EditorSettings::get_global(cx).clone();
13082 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13083 EditorSettings::override_global(editor_settings, cx);
13084 }
13085
13086 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13087 self.use_relative_line_numbers
13088 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13089 }
13090
13091 pub fn toggle_relative_line_numbers(
13092 &mut self,
13093 _: &ToggleRelativeLineNumbers,
13094 _: &mut Window,
13095 cx: &mut Context<Self>,
13096 ) {
13097 let is_relative = self.should_use_relative_line_numbers(cx);
13098 self.set_relative_line_number(Some(!is_relative), cx)
13099 }
13100
13101 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13102 self.use_relative_line_numbers = is_relative;
13103 cx.notify();
13104 }
13105
13106 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13107 self.show_gutter = show_gutter;
13108 cx.notify();
13109 }
13110
13111 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13112 self.show_scrollbars = show_scrollbars;
13113 cx.notify();
13114 }
13115
13116 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13117 self.show_line_numbers = Some(show_line_numbers);
13118 cx.notify();
13119 }
13120
13121 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13122 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13123 cx.notify();
13124 }
13125
13126 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13127 self.show_code_actions = Some(show_code_actions);
13128 cx.notify();
13129 }
13130
13131 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13132 self.show_runnables = Some(show_runnables);
13133 cx.notify();
13134 }
13135
13136 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13137 if self.display_map.read(cx).masked != masked {
13138 self.display_map.update(cx, |map, _| map.masked = masked);
13139 }
13140 cx.notify()
13141 }
13142
13143 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13144 self.show_wrap_guides = Some(show_wrap_guides);
13145 cx.notify();
13146 }
13147
13148 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13149 self.show_indent_guides = Some(show_indent_guides);
13150 cx.notify();
13151 }
13152
13153 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13154 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13155 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13156 if let Some(dir) = file.abs_path(cx).parent() {
13157 return Some(dir.to_owned());
13158 }
13159 }
13160
13161 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13162 return Some(project_path.path.to_path_buf());
13163 }
13164 }
13165
13166 None
13167 }
13168
13169 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13170 self.active_excerpt(cx)?
13171 .1
13172 .read(cx)
13173 .file()
13174 .and_then(|f| f.as_local())
13175 }
13176
13177 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13178 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13179 let buffer = buffer.read(cx);
13180 if let Some(project_path) = buffer.project_path(cx) {
13181 let project = self.project.as_ref()?.read(cx);
13182 project.absolute_path(&project_path, cx)
13183 } else {
13184 buffer
13185 .file()
13186 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13187 }
13188 })
13189 }
13190
13191 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13192 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13193 let project_path = buffer.read(cx).project_path(cx)?;
13194 let project = self.project.as_ref()?.read(cx);
13195 let entry = project.entry_for_path(&project_path, cx)?;
13196 let path = entry.path.to_path_buf();
13197 Some(path)
13198 })
13199 }
13200
13201 pub fn reveal_in_finder(
13202 &mut self,
13203 _: &RevealInFileManager,
13204 _window: &mut Window,
13205 cx: &mut Context<Self>,
13206 ) {
13207 if let Some(target) = self.target_file(cx) {
13208 cx.reveal_path(&target.abs_path(cx));
13209 }
13210 }
13211
13212 pub fn copy_path(
13213 &mut self,
13214 _: &zed_actions::workspace::CopyPath,
13215 _window: &mut Window,
13216 cx: &mut Context<Self>,
13217 ) {
13218 if let Some(path) = self.target_file_abs_path(cx) {
13219 if let Some(path) = path.to_str() {
13220 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13221 }
13222 }
13223 }
13224
13225 pub fn copy_relative_path(
13226 &mut self,
13227 _: &zed_actions::workspace::CopyRelativePath,
13228 _window: &mut Window,
13229 cx: &mut Context<Self>,
13230 ) {
13231 if let Some(path) = self.target_file_path(cx) {
13232 if let Some(path) = path.to_str() {
13233 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13234 }
13235 }
13236 }
13237
13238 pub fn copy_file_name_without_extension(
13239 &mut self,
13240 _: &CopyFileNameWithoutExtension,
13241 _: &mut Window,
13242 cx: &mut Context<Self>,
13243 ) {
13244 if let Some(file) = self.target_file(cx) {
13245 if let Some(file_stem) = file.path().file_stem() {
13246 if let Some(name) = file_stem.to_str() {
13247 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13248 }
13249 }
13250 }
13251 }
13252
13253 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13254 if let Some(file) = self.target_file(cx) {
13255 if let Some(file_name) = file.path().file_name() {
13256 if let Some(name) = file_name.to_str() {
13257 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13258 }
13259 }
13260 }
13261 }
13262
13263 pub fn toggle_git_blame(
13264 &mut self,
13265 _: &ToggleGitBlame,
13266 window: &mut Window,
13267 cx: &mut Context<Self>,
13268 ) {
13269 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13270
13271 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13272 self.start_git_blame(true, window, cx);
13273 }
13274
13275 cx.notify();
13276 }
13277
13278 pub fn toggle_git_blame_inline(
13279 &mut self,
13280 _: &ToggleGitBlameInline,
13281 window: &mut Window,
13282 cx: &mut Context<Self>,
13283 ) {
13284 self.toggle_git_blame_inline_internal(true, window, cx);
13285 cx.notify();
13286 }
13287
13288 pub fn git_blame_inline_enabled(&self) -> bool {
13289 self.git_blame_inline_enabled
13290 }
13291
13292 pub fn toggle_selection_menu(
13293 &mut self,
13294 _: &ToggleSelectionMenu,
13295 _: &mut Window,
13296 cx: &mut Context<Self>,
13297 ) {
13298 self.show_selection_menu = self
13299 .show_selection_menu
13300 .map(|show_selections_menu| !show_selections_menu)
13301 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13302
13303 cx.notify();
13304 }
13305
13306 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13307 self.show_selection_menu
13308 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13309 }
13310
13311 fn start_git_blame(
13312 &mut self,
13313 user_triggered: bool,
13314 window: &mut Window,
13315 cx: &mut Context<Self>,
13316 ) {
13317 if let Some(project) = self.project.as_ref() {
13318 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13319 return;
13320 };
13321
13322 if buffer.read(cx).file().is_none() {
13323 return;
13324 }
13325
13326 let focused = self.focus_handle(cx).contains_focused(window, cx);
13327
13328 let project = project.clone();
13329 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13330 self.blame_subscription =
13331 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13332 self.blame = Some(blame);
13333 }
13334 }
13335
13336 fn toggle_git_blame_inline_internal(
13337 &mut self,
13338 user_triggered: bool,
13339 window: &mut Window,
13340 cx: &mut Context<Self>,
13341 ) {
13342 if self.git_blame_inline_enabled {
13343 self.git_blame_inline_enabled = false;
13344 self.show_git_blame_inline = false;
13345 self.show_git_blame_inline_delay_task.take();
13346 } else {
13347 self.git_blame_inline_enabled = true;
13348 self.start_git_blame_inline(user_triggered, window, cx);
13349 }
13350
13351 cx.notify();
13352 }
13353
13354 fn start_git_blame_inline(
13355 &mut self,
13356 user_triggered: bool,
13357 window: &mut Window,
13358 cx: &mut Context<Self>,
13359 ) {
13360 self.start_git_blame(user_triggered, window, cx);
13361
13362 if ProjectSettings::get_global(cx)
13363 .git
13364 .inline_blame_delay()
13365 .is_some()
13366 {
13367 self.start_inline_blame_timer(window, cx);
13368 } else {
13369 self.show_git_blame_inline = true
13370 }
13371 }
13372
13373 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13374 self.blame.as_ref()
13375 }
13376
13377 pub fn show_git_blame_gutter(&self) -> bool {
13378 self.show_git_blame_gutter
13379 }
13380
13381 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13382 self.show_git_blame_gutter && self.has_blame_entries(cx)
13383 }
13384
13385 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13386 self.show_git_blame_inline
13387 && self.focus_handle.is_focused(window)
13388 && !self.newest_selection_head_on_empty_line(cx)
13389 && self.has_blame_entries(cx)
13390 }
13391
13392 fn has_blame_entries(&self, cx: &App) -> bool {
13393 self.blame()
13394 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13395 }
13396
13397 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13398 let cursor_anchor = self.selections.newest_anchor().head();
13399
13400 let snapshot = self.buffer.read(cx).snapshot(cx);
13401 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13402
13403 snapshot.line_len(buffer_row) == 0
13404 }
13405
13406 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13407 let buffer_and_selection = maybe!({
13408 let selection = self.selections.newest::<Point>(cx);
13409 let selection_range = selection.range();
13410
13411 let multi_buffer = self.buffer().read(cx);
13412 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13413 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13414
13415 let (buffer, range, _) = if selection.reversed {
13416 buffer_ranges.first()
13417 } else {
13418 buffer_ranges.last()
13419 }?;
13420
13421 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13422 ..text::ToPoint::to_point(&range.end, &buffer).row;
13423 Some((
13424 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13425 selection,
13426 ))
13427 });
13428
13429 let Some((buffer, selection)) = buffer_and_selection else {
13430 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13431 };
13432
13433 let Some(project) = self.project.as_ref() else {
13434 return Task::ready(Err(anyhow!("editor does not have project")));
13435 };
13436
13437 project.update(cx, |project, cx| {
13438 project.get_permalink_to_line(&buffer, selection, cx)
13439 })
13440 }
13441
13442 pub fn copy_permalink_to_line(
13443 &mut self,
13444 _: &CopyPermalinkToLine,
13445 window: &mut Window,
13446 cx: &mut Context<Self>,
13447 ) {
13448 let permalink_task = self.get_permalink_to_line(cx);
13449 let workspace = self.workspace();
13450
13451 cx.spawn_in(window, |_, mut cx| async move {
13452 match permalink_task.await {
13453 Ok(permalink) => {
13454 cx.update(|_, cx| {
13455 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13456 })
13457 .ok();
13458 }
13459 Err(err) => {
13460 let message = format!("Failed to copy permalink: {err}");
13461
13462 Err::<(), anyhow::Error>(err).log_err();
13463
13464 if let Some(workspace) = workspace {
13465 workspace
13466 .update_in(&mut cx, |workspace, _, cx| {
13467 struct CopyPermalinkToLine;
13468
13469 workspace.show_toast(
13470 Toast::new(
13471 NotificationId::unique::<CopyPermalinkToLine>(),
13472 message,
13473 ),
13474 cx,
13475 )
13476 })
13477 .ok();
13478 }
13479 }
13480 }
13481 })
13482 .detach();
13483 }
13484
13485 pub fn copy_file_location(
13486 &mut self,
13487 _: &CopyFileLocation,
13488 _: &mut Window,
13489 cx: &mut Context<Self>,
13490 ) {
13491 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13492 if let Some(file) = self.target_file(cx) {
13493 if let Some(path) = file.path().to_str() {
13494 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13495 }
13496 }
13497 }
13498
13499 pub fn open_permalink_to_line(
13500 &mut self,
13501 _: &OpenPermalinkToLine,
13502 window: &mut Window,
13503 cx: &mut Context<Self>,
13504 ) {
13505 let permalink_task = self.get_permalink_to_line(cx);
13506 let workspace = self.workspace();
13507
13508 cx.spawn_in(window, |_, mut cx| async move {
13509 match permalink_task.await {
13510 Ok(permalink) => {
13511 cx.update(|_, cx| {
13512 cx.open_url(permalink.as_ref());
13513 })
13514 .ok();
13515 }
13516 Err(err) => {
13517 let message = format!("Failed to open permalink: {err}");
13518
13519 Err::<(), anyhow::Error>(err).log_err();
13520
13521 if let Some(workspace) = workspace {
13522 workspace
13523 .update(&mut cx, |workspace, cx| {
13524 struct OpenPermalinkToLine;
13525
13526 workspace.show_toast(
13527 Toast::new(
13528 NotificationId::unique::<OpenPermalinkToLine>(),
13529 message,
13530 ),
13531 cx,
13532 )
13533 })
13534 .ok();
13535 }
13536 }
13537 }
13538 })
13539 .detach();
13540 }
13541
13542 pub fn insert_uuid_v4(
13543 &mut self,
13544 _: &InsertUuidV4,
13545 window: &mut Window,
13546 cx: &mut Context<Self>,
13547 ) {
13548 self.insert_uuid(UuidVersion::V4, window, cx);
13549 }
13550
13551 pub fn insert_uuid_v7(
13552 &mut self,
13553 _: &InsertUuidV7,
13554 window: &mut Window,
13555 cx: &mut Context<Self>,
13556 ) {
13557 self.insert_uuid(UuidVersion::V7, window, cx);
13558 }
13559
13560 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13561 self.transact(window, cx, |this, window, cx| {
13562 let edits = this
13563 .selections
13564 .all::<Point>(cx)
13565 .into_iter()
13566 .map(|selection| {
13567 let uuid = match version {
13568 UuidVersion::V4 => uuid::Uuid::new_v4(),
13569 UuidVersion::V7 => uuid::Uuid::now_v7(),
13570 };
13571
13572 (selection.range(), uuid.to_string())
13573 });
13574 this.edit(edits, cx);
13575 this.refresh_inline_completion(true, false, window, cx);
13576 });
13577 }
13578
13579 pub fn open_selections_in_multibuffer(
13580 &mut self,
13581 _: &OpenSelectionsInMultibuffer,
13582 window: &mut Window,
13583 cx: &mut Context<Self>,
13584 ) {
13585 let multibuffer = self.buffer.read(cx);
13586
13587 let Some(buffer) = multibuffer.as_singleton() else {
13588 return;
13589 };
13590
13591 let Some(workspace) = self.workspace() else {
13592 return;
13593 };
13594
13595 let locations = self
13596 .selections
13597 .disjoint_anchors()
13598 .iter()
13599 .map(|range| Location {
13600 buffer: buffer.clone(),
13601 range: range.start.text_anchor..range.end.text_anchor,
13602 })
13603 .collect::<Vec<_>>();
13604
13605 let title = multibuffer.title(cx).to_string();
13606
13607 cx.spawn_in(window, |_, mut cx| async move {
13608 workspace.update_in(&mut cx, |workspace, window, cx| {
13609 Self::open_locations_in_multibuffer(
13610 workspace,
13611 locations,
13612 format!("Selections for '{title}'"),
13613 false,
13614 MultibufferSelectionMode::All,
13615 window,
13616 cx,
13617 );
13618 })
13619 })
13620 .detach();
13621 }
13622
13623 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13624 /// last highlight added will be used.
13625 ///
13626 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13627 pub fn highlight_rows<T: 'static>(
13628 &mut self,
13629 range: Range<Anchor>,
13630 color: Hsla,
13631 should_autoscroll: bool,
13632 cx: &mut Context<Self>,
13633 ) {
13634 let snapshot = self.buffer().read(cx).snapshot(cx);
13635 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13636 let ix = row_highlights.binary_search_by(|highlight| {
13637 Ordering::Equal
13638 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13639 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13640 });
13641
13642 if let Err(mut ix) = ix {
13643 let index = post_inc(&mut self.highlight_order);
13644
13645 // If this range intersects with the preceding highlight, then merge it with
13646 // the preceding highlight. Otherwise insert a new highlight.
13647 let mut merged = false;
13648 if ix > 0 {
13649 let prev_highlight = &mut row_highlights[ix - 1];
13650 if prev_highlight
13651 .range
13652 .end
13653 .cmp(&range.start, &snapshot)
13654 .is_ge()
13655 {
13656 ix -= 1;
13657 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13658 prev_highlight.range.end = range.end;
13659 }
13660 merged = true;
13661 prev_highlight.index = index;
13662 prev_highlight.color = color;
13663 prev_highlight.should_autoscroll = should_autoscroll;
13664 }
13665 }
13666
13667 if !merged {
13668 row_highlights.insert(
13669 ix,
13670 RowHighlight {
13671 range: range.clone(),
13672 index,
13673 color,
13674 should_autoscroll,
13675 },
13676 );
13677 }
13678
13679 // If any of the following highlights intersect with this one, merge them.
13680 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13681 let highlight = &row_highlights[ix];
13682 if next_highlight
13683 .range
13684 .start
13685 .cmp(&highlight.range.end, &snapshot)
13686 .is_le()
13687 {
13688 if next_highlight
13689 .range
13690 .end
13691 .cmp(&highlight.range.end, &snapshot)
13692 .is_gt()
13693 {
13694 row_highlights[ix].range.end = next_highlight.range.end;
13695 }
13696 row_highlights.remove(ix + 1);
13697 } else {
13698 break;
13699 }
13700 }
13701 }
13702 }
13703
13704 /// Remove any highlighted row ranges of the given type that intersect the
13705 /// given ranges.
13706 pub fn remove_highlighted_rows<T: 'static>(
13707 &mut self,
13708 ranges_to_remove: Vec<Range<Anchor>>,
13709 cx: &mut Context<Self>,
13710 ) {
13711 let snapshot = self.buffer().read(cx).snapshot(cx);
13712 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13713 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13714 row_highlights.retain(|highlight| {
13715 while let Some(range_to_remove) = ranges_to_remove.peek() {
13716 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13717 Ordering::Less | Ordering::Equal => {
13718 ranges_to_remove.next();
13719 }
13720 Ordering::Greater => {
13721 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13722 Ordering::Less | Ordering::Equal => {
13723 return false;
13724 }
13725 Ordering::Greater => break,
13726 }
13727 }
13728 }
13729 }
13730
13731 true
13732 })
13733 }
13734
13735 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13736 pub fn clear_row_highlights<T: 'static>(&mut self) {
13737 self.highlighted_rows.remove(&TypeId::of::<T>());
13738 }
13739
13740 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13741 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13742 self.highlighted_rows
13743 .get(&TypeId::of::<T>())
13744 .map_or(&[] as &[_], |vec| vec.as_slice())
13745 .iter()
13746 .map(|highlight| (highlight.range.clone(), highlight.color))
13747 }
13748
13749 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13750 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13751 /// Allows to ignore certain kinds of highlights.
13752 pub fn highlighted_display_rows(
13753 &self,
13754 window: &mut Window,
13755 cx: &mut App,
13756 ) -> BTreeMap<DisplayRow, Hsla> {
13757 let snapshot = self.snapshot(window, cx);
13758 let mut used_highlight_orders = HashMap::default();
13759 self.highlighted_rows
13760 .iter()
13761 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13762 .fold(
13763 BTreeMap::<DisplayRow, Hsla>::new(),
13764 |mut unique_rows, highlight| {
13765 let start = highlight.range.start.to_display_point(&snapshot);
13766 let end = highlight.range.end.to_display_point(&snapshot);
13767 let start_row = start.row().0;
13768 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13769 && end.column() == 0
13770 {
13771 end.row().0.saturating_sub(1)
13772 } else {
13773 end.row().0
13774 };
13775 for row in start_row..=end_row {
13776 let used_index =
13777 used_highlight_orders.entry(row).or_insert(highlight.index);
13778 if highlight.index >= *used_index {
13779 *used_index = highlight.index;
13780 unique_rows.insert(DisplayRow(row), highlight.color);
13781 }
13782 }
13783 unique_rows
13784 },
13785 )
13786 }
13787
13788 pub fn highlighted_display_row_for_autoscroll(
13789 &self,
13790 snapshot: &DisplaySnapshot,
13791 ) -> Option<DisplayRow> {
13792 self.highlighted_rows
13793 .values()
13794 .flat_map(|highlighted_rows| highlighted_rows.iter())
13795 .filter_map(|highlight| {
13796 if highlight.should_autoscroll {
13797 Some(highlight.range.start.to_display_point(snapshot).row())
13798 } else {
13799 None
13800 }
13801 })
13802 .min()
13803 }
13804
13805 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13806 self.highlight_background::<SearchWithinRange>(
13807 ranges,
13808 |colors| colors.editor_document_highlight_read_background,
13809 cx,
13810 )
13811 }
13812
13813 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13814 self.breadcrumb_header = Some(new_header);
13815 }
13816
13817 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13818 self.clear_background_highlights::<SearchWithinRange>(cx);
13819 }
13820
13821 pub fn highlight_background<T: 'static>(
13822 &mut self,
13823 ranges: &[Range<Anchor>],
13824 color_fetcher: fn(&ThemeColors) -> Hsla,
13825 cx: &mut Context<Self>,
13826 ) {
13827 self.background_highlights
13828 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13829 self.scrollbar_marker_state.dirty = true;
13830 cx.notify();
13831 }
13832
13833 pub fn clear_background_highlights<T: 'static>(
13834 &mut self,
13835 cx: &mut Context<Self>,
13836 ) -> Option<BackgroundHighlight> {
13837 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13838 if !text_highlights.1.is_empty() {
13839 self.scrollbar_marker_state.dirty = true;
13840 cx.notify();
13841 }
13842 Some(text_highlights)
13843 }
13844
13845 pub fn highlight_gutter<T: 'static>(
13846 &mut self,
13847 ranges: &[Range<Anchor>],
13848 color_fetcher: fn(&App) -> Hsla,
13849 cx: &mut Context<Self>,
13850 ) {
13851 self.gutter_highlights
13852 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13853 cx.notify();
13854 }
13855
13856 pub fn clear_gutter_highlights<T: 'static>(
13857 &mut self,
13858 cx: &mut Context<Self>,
13859 ) -> Option<GutterHighlight> {
13860 cx.notify();
13861 self.gutter_highlights.remove(&TypeId::of::<T>())
13862 }
13863
13864 #[cfg(feature = "test-support")]
13865 pub fn all_text_background_highlights(
13866 &self,
13867 window: &mut Window,
13868 cx: &mut Context<Self>,
13869 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13870 let snapshot = self.snapshot(window, cx);
13871 let buffer = &snapshot.buffer_snapshot;
13872 let start = buffer.anchor_before(0);
13873 let end = buffer.anchor_after(buffer.len());
13874 let theme = cx.theme().colors();
13875 self.background_highlights_in_range(start..end, &snapshot, theme)
13876 }
13877
13878 #[cfg(feature = "test-support")]
13879 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13880 let snapshot = self.buffer().read(cx).snapshot(cx);
13881
13882 let highlights = self
13883 .background_highlights
13884 .get(&TypeId::of::<items::BufferSearchHighlights>());
13885
13886 if let Some((_color, ranges)) = highlights {
13887 ranges
13888 .iter()
13889 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13890 .collect_vec()
13891 } else {
13892 vec![]
13893 }
13894 }
13895
13896 fn document_highlights_for_position<'a>(
13897 &'a self,
13898 position: Anchor,
13899 buffer: &'a MultiBufferSnapshot,
13900 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13901 let read_highlights = self
13902 .background_highlights
13903 .get(&TypeId::of::<DocumentHighlightRead>())
13904 .map(|h| &h.1);
13905 let write_highlights = self
13906 .background_highlights
13907 .get(&TypeId::of::<DocumentHighlightWrite>())
13908 .map(|h| &h.1);
13909 let left_position = position.bias_left(buffer);
13910 let right_position = position.bias_right(buffer);
13911 read_highlights
13912 .into_iter()
13913 .chain(write_highlights)
13914 .flat_map(move |ranges| {
13915 let start_ix = match ranges.binary_search_by(|probe| {
13916 let cmp = probe.end.cmp(&left_position, buffer);
13917 if cmp.is_ge() {
13918 Ordering::Greater
13919 } else {
13920 Ordering::Less
13921 }
13922 }) {
13923 Ok(i) | Err(i) => i,
13924 };
13925
13926 ranges[start_ix..]
13927 .iter()
13928 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13929 })
13930 }
13931
13932 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13933 self.background_highlights
13934 .get(&TypeId::of::<T>())
13935 .map_or(false, |(_, highlights)| !highlights.is_empty())
13936 }
13937
13938 pub fn background_highlights_in_range(
13939 &self,
13940 search_range: Range<Anchor>,
13941 display_snapshot: &DisplaySnapshot,
13942 theme: &ThemeColors,
13943 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13944 let mut results = Vec::new();
13945 for (color_fetcher, ranges) in self.background_highlights.values() {
13946 let color = color_fetcher(theme);
13947 let start_ix = match ranges.binary_search_by(|probe| {
13948 let cmp = probe
13949 .end
13950 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13951 if cmp.is_gt() {
13952 Ordering::Greater
13953 } else {
13954 Ordering::Less
13955 }
13956 }) {
13957 Ok(i) | Err(i) => i,
13958 };
13959 for range in &ranges[start_ix..] {
13960 if range
13961 .start
13962 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13963 .is_ge()
13964 {
13965 break;
13966 }
13967
13968 let start = range.start.to_display_point(display_snapshot);
13969 let end = range.end.to_display_point(display_snapshot);
13970 results.push((start..end, color))
13971 }
13972 }
13973 results
13974 }
13975
13976 pub fn background_highlight_row_ranges<T: 'static>(
13977 &self,
13978 search_range: Range<Anchor>,
13979 display_snapshot: &DisplaySnapshot,
13980 count: usize,
13981 ) -> Vec<RangeInclusive<DisplayPoint>> {
13982 let mut results = Vec::new();
13983 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13984 return vec![];
13985 };
13986
13987 let start_ix = match ranges.binary_search_by(|probe| {
13988 let cmp = probe
13989 .end
13990 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13991 if cmp.is_gt() {
13992 Ordering::Greater
13993 } else {
13994 Ordering::Less
13995 }
13996 }) {
13997 Ok(i) | Err(i) => i,
13998 };
13999 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14000 if let (Some(start_display), Some(end_display)) = (start, end) {
14001 results.push(
14002 start_display.to_display_point(display_snapshot)
14003 ..=end_display.to_display_point(display_snapshot),
14004 );
14005 }
14006 };
14007 let mut start_row: Option<Point> = None;
14008 let mut end_row: Option<Point> = None;
14009 if ranges.len() > count {
14010 return Vec::new();
14011 }
14012 for range in &ranges[start_ix..] {
14013 if range
14014 .start
14015 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14016 .is_ge()
14017 {
14018 break;
14019 }
14020 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14021 if let Some(current_row) = &end_row {
14022 if end.row == current_row.row {
14023 continue;
14024 }
14025 }
14026 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14027 if start_row.is_none() {
14028 assert_eq!(end_row, None);
14029 start_row = Some(start);
14030 end_row = Some(end);
14031 continue;
14032 }
14033 if let Some(current_end) = end_row.as_mut() {
14034 if start.row > current_end.row + 1 {
14035 push_region(start_row, end_row);
14036 start_row = Some(start);
14037 end_row = Some(end);
14038 } else {
14039 // Merge two hunks.
14040 *current_end = end;
14041 }
14042 } else {
14043 unreachable!();
14044 }
14045 }
14046 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14047 push_region(start_row, end_row);
14048 results
14049 }
14050
14051 pub fn gutter_highlights_in_range(
14052 &self,
14053 search_range: Range<Anchor>,
14054 display_snapshot: &DisplaySnapshot,
14055 cx: &App,
14056 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14057 let mut results = Vec::new();
14058 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14059 let color = color_fetcher(cx);
14060 let start_ix = match ranges.binary_search_by(|probe| {
14061 let cmp = probe
14062 .end
14063 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14064 if cmp.is_gt() {
14065 Ordering::Greater
14066 } else {
14067 Ordering::Less
14068 }
14069 }) {
14070 Ok(i) | Err(i) => i,
14071 };
14072 for range in &ranges[start_ix..] {
14073 if range
14074 .start
14075 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14076 .is_ge()
14077 {
14078 break;
14079 }
14080
14081 let start = range.start.to_display_point(display_snapshot);
14082 let end = range.end.to_display_point(display_snapshot);
14083 results.push((start..end, color))
14084 }
14085 }
14086 results
14087 }
14088
14089 /// Get the text ranges corresponding to the redaction query
14090 pub fn redacted_ranges(
14091 &self,
14092 search_range: Range<Anchor>,
14093 display_snapshot: &DisplaySnapshot,
14094 cx: &App,
14095 ) -> Vec<Range<DisplayPoint>> {
14096 display_snapshot
14097 .buffer_snapshot
14098 .redacted_ranges(search_range, |file| {
14099 if let Some(file) = file {
14100 file.is_private()
14101 && EditorSettings::get(
14102 Some(SettingsLocation {
14103 worktree_id: file.worktree_id(cx),
14104 path: file.path().as_ref(),
14105 }),
14106 cx,
14107 )
14108 .redact_private_values
14109 } else {
14110 false
14111 }
14112 })
14113 .map(|range| {
14114 range.start.to_display_point(display_snapshot)
14115 ..range.end.to_display_point(display_snapshot)
14116 })
14117 .collect()
14118 }
14119
14120 pub fn highlight_text<T: 'static>(
14121 &mut self,
14122 ranges: Vec<Range<Anchor>>,
14123 style: HighlightStyle,
14124 cx: &mut Context<Self>,
14125 ) {
14126 self.display_map.update(cx, |map, _| {
14127 map.highlight_text(TypeId::of::<T>(), ranges, style)
14128 });
14129 cx.notify();
14130 }
14131
14132 pub(crate) fn highlight_inlays<T: 'static>(
14133 &mut self,
14134 highlights: Vec<InlayHighlight>,
14135 style: HighlightStyle,
14136 cx: &mut Context<Self>,
14137 ) {
14138 self.display_map.update(cx, |map, _| {
14139 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14140 });
14141 cx.notify();
14142 }
14143
14144 pub fn text_highlights<'a, T: 'static>(
14145 &'a self,
14146 cx: &'a App,
14147 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14148 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14149 }
14150
14151 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14152 let cleared = self
14153 .display_map
14154 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14155 if cleared {
14156 cx.notify();
14157 }
14158 }
14159
14160 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14161 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14162 && self.focus_handle.is_focused(window)
14163 }
14164
14165 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14166 self.show_cursor_when_unfocused = is_enabled;
14167 cx.notify();
14168 }
14169
14170 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14171 cx.notify();
14172 }
14173
14174 fn on_buffer_event(
14175 &mut self,
14176 multibuffer: &Entity<MultiBuffer>,
14177 event: &multi_buffer::Event,
14178 window: &mut Window,
14179 cx: &mut Context<Self>,
14180 ) {
14181 match event {
14182 multi_buffer::Event::Edited {
14183 singleton_buffer_edited,
14184 edited_buffer: buffer_edited,
14185 } => {
14186 self.scrollbar_marker_state.dirty = true;
14187 self.active_indent_guides_state.dirty = true;
14188 self.refresh_active_diagnostics(cx);
14189 self.refresh_code_actions(window, cx);
14190 if self.has_active_inline_completion() {
14191 self.update_visible_inline_completion(window, cx);
14192 }
14193 if let Some(buffer) = buffer_edited {
14194 let buffer_id = buffer.read(cx).remote_id();
14195 if !self.registered_buffers.contains_key(&buffer_id) {
14196 if let Some(project) = self.project.as_ref() {
14197 project.update(cx, |project, cx| {
14198 self.registered_buffers.insert(
14199 buffer_id,
14200 project.register_buffer_with_language_servers(&buffer, cx),
14201 );
14202 })
14203 }
14204 }
14205 }
14206 cx.emit(EditorEvent::BufferEdited);
14207 cx.emit(SearchEvent::MatchesInvalidated);
14208 if *singleton_buffer_edited {
14209 if let Some(project) = &self.project {
14210 #[allow(clippy::mutable_key_type)]
14211 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14212 multibuffer
14213 .all_buffers()
14214 .into_iter()
14215 .filter_map(|buffer| {
14216 buffer.update(cx, |buffer, cx| {
14217 let language = buffer.language()?;
14218 let should_discard = project.update(cx, |project, cx| {
14219 project.is_local()
14220 && !project.has_language_servers_for(buffer, cx)
14221 });
14222 should_discard.not().then_some(language.clone())
14223 })
14224 })
14225 .collect::<HashSet<_>>()
14226 });
14227 if !languages_affected.is_empty() {
14228 self.refresh_inlay_hints(
14229 InlayHintRefreshReason::BufferEdited(languages_affected),
14230 cx,
14231 );
14232 }
14233 }
14234 }
14235
14236 let Some(project) = &self.project else { return };
14237 let (telemetry, is_via_ssh) = {
14238 let project = project.read(cx);
14239 let telemetry = project.client().telemetry().clone();
14240 let is_via_ssh = project.is_via_ssh();
14241 (telemetry, is_via_ssh)
14242 };
14243 refresh_linked_ranges(self, window, cx);
14244 telemetry.log_edit_event("editor", is_via_ssh);
14245 }
14246 multi_buffer::Event::ExcerptsAdded {
14247 buffer,
14248 predecessor,
14249 excerpts,
14250 } => {
14251 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14252 let buffer_id = buffer.read(cx).remote_id();
14253 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14254 if let Some(project) = &self.project {
14255 get_uncommitted_diff_for_buffer(
14256 project,
14257 [buffer.clone()],
14258 self.buffer.clone(),
14259 cx,
14260 )
14261 .detach();
14262 }
14263 }
14264 cx.emit(EditorEvent::ExcerptsAdded {
14265 buffer: buffer.clone(),
14266 predecessor: *predecessor,
14267 excerpts: excerpts.clone(),
14268 });
14269 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14270 }
14271 multi_buffer::Event::ExcerptsRemoved { ids } => {
14272 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14273 let buffer = self.buffer.read(cx);
14274 self.registered_buffers
14275 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14276 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14277 }
14278 multi_buffer::Event::ExcerptsEdited { ids } => {
14279 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14280 }
14281 multi_buffer::Event::ExcerptsExpanded { ids } => {
14282 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14283 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14284 }
14285 multi_buffer::Event::Reparsed(buffer_id) => {
14286 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14287
14288 cx.emit(EditorEvent::Reparsed(*buffer_id));
14289 }
14290 multi_buffer::Event::DiffHunksToggled => {
14291 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14292 }
14293 multi_buffer::Event::LanguageChanged(buffer_id) => {
14294 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14295 cx.emit(EditorEvent::Reparsed(*buffer_id));
14296 cx.notify();
14297 }
14298 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14299 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14300 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14301 cx.emit(EditorEvent::TitleChanged)
14302 }
14303 // multi_buffer::Event::DiffBaseChanged => {
14304 // self.scrollbar_marker_state.dirty = true;
14305 // cx.emit(EditorEvent::DiffBaseChanged);
14306 // cx.notify();
14307 // }
14308 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14309 multi_buffer::Event::DiagnosticsUpdated => {
14310 self.refresh_active_diagnostics(cx);
14311 self.scrollbar_marker_state.dirty = true;
14312 cx.notify();
14313 }
14314 _ => {}
14315 };
14316 }
14317
14318 fn on_display_map_changed(
14319 &mut self,
14320 _: Entity<DisplayMap>,
14321 _: &mut Window,
14322 cx: &mut Context<Self>,
14323 ) {
14324 cx.notify();
14325 }
14326
14327 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14328 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14329 self.refresh_inline_completion(true, false, window, cx);
14330 self.refresh_inlay_hints(
14331 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14332 self.selections.newest_anchor().head(),
14333 &self.buffer.read(cx).snapshot(cx),
14334 cx,
14335 )),
14336 cx,
14337 );
14338
14339 let old_cursor_shape = self.cursor_shape;
14340
14341 {
14342 let editor_settings = EditorSettings::get_global(cx);
14343 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14344 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14345 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14346 }
14347
14348 if old_cursor_shape != self.cursor_shape {
14349 cx.emit(EditorEvent::CursorShapeChanged);
14350 }
14351
14352 let project_settings = ProjectSettings::get_global(cx);
14353 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14354
14355 if self.mode == EditorMode::Full {
14356 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14357 if self.git_blame_inline_enabled != inline_blame_enabled {
14358 self.toggle_git_blame_inline_internal(false, window, cx);
14359 }
14360 }
14361
14362 cx.notify();
14363 }
14364
14365 pub fn set_searchable(&mut self, searchable: bool) {
14366 self.searchable = searchable;
14367 }
14368
14369 pub fn searchable(&self) -> bool {
14370 self.searchable
14371 }
14372
14373 fn open_proposed_changes_editor(
14374 &mut self,
14375 _: &OpenProposedChangesEditor,
14376 window: &mut Window,
14377 cx: &mut Context<Self>,
14378 ) {
14379 let Some(workspace) = self.workspace() else {
14380 cx.propagate();
14381 return;
14382 };
14383
14384 let selections = self.selections.all::<usize>(cx);
14385 let multi_buffer = self.buffer.read(cx);
14386 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14387 let mut new_selections_by_buffer = HashMap::default();
14388 for selection in selections {
14389 for (buffer, range, _) in
14390 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14391 {
14392 let mut range = range.to_point(buffer);
14393 range.start.column = 0;
14394 range.end.column = buffer.line_len(range.end.row);
14395 new_selections_by_buffer
14396 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14397 .or_insert(Vec::new())
14398 .push(range)
14399 }
14400 }
14401
14402 let proposed_changes_buffers = new_selections_by_buffer
14403 .into_iter()
14404 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14405 .collect::<Vec<_>>();
14406 let proposed_changes_editor = cx.new(|cx| {
14407 ProposedChangesEditor::new(
14408 "Proposed changes",
14409 proposed_changes_buffers,
14410 self.project.clone(),
14411 window,
14412 cx,
14413 )
14414 });
14415
14416 window.defer(cx, move |window, cx| {
14417 workspace.update(cx, |workspace, cx| {
14418 workspace.active_pane().update(cx, |pane, cx| {
14419 pane.add_item(
14420 Box::new(proposed_changes_editor),
14421 true,
14422 true,
14423 None,
14424 window,
14425 cx,
14426 );
14427 });
14428 });
14429 });
14430 }
14431
14432 pub fn open_excerpts_in_split(
14433 &mut self,
14434 _: &OpenExcerptsSplit,
14435 window: &mut Window,
14436 cx: &mut Context<Self>,
14437 ) {
14438 self.open_excerpts_common(None, true, window, cx)
14439 }
14440
14441 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14442 self.open_excerpts_common(None, false, window, cx)
14443 }
14444
14445 fn open_excerpts_common(
14446 &mut self,
14447 jump_data: Option<JumpData>,
14448 split: bool,
14449 window: &mut Window,
14450 cx: &mut Context<Self>,
14451 ) {
14452 let Some(workspace) = self.workspace() else {
14453 cx.propagate();
14454 return;
14455 };
14456
14457 if self.buffer.read(cx).is_singleton() {
14458 cx.propagate();
14459 return;
14460 }
14461
14462 let mut new_selections_by_buffer = HashMap::default();
14463 match &jump_data {
14464 Some(JumpData::MultiBufferPoint {
14465 excerpt_id,
14466 position,
14467 anchor,
14468 line_offset_from_top,
14469 }) => {
14470 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14471 if let Some(buffer) = multi_buffer_snapshot
14472 .buffer_id_for_excerpt(*excerpt_id)
14473 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14474 {
14475 let buffer_snapshot = buffer.read(cx).snapshot();
14476 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14477 language::ToPoint::to_point(anchor, &buffer_snapshot)
14478 } else {
14479 buffer_snapshot.clip_point(*position, Bias::Left)
14480 };
14481 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14482 new_selections_by_buffer.insert(
14483 buffer,
14484 (
14485 vec![jump_to_offset..jump_to_offset],
14486 Some(*line_offset_from_top),
14487 ),
14488 );
14489 }
14490 }
14491 Some(JumpData::MultiBufferRow {
14492 row,
14493 line_offset_from_top,
14494 }) => {
14495 let point = MultiBufferPoint::new(row.0, 0);
14496 if let Some((buffer, buffer_point, _)) =
14497 self.buffer.read(cx).point_to_buffer_point(point, cx)
14498 {
14499 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14500 new_selections_by_buffer
14501 .entry(buffer)
14502 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14503 .0
14504 .push(buffer_offset..buffer_offset)
14505 }
14506 }
14507 None => {
14508 let selections = self.selections.all::<usize>(cx);
14509 let multi_buffer = self.buffer.read(cx);
14510 for selection in selections {
14511 for (buffer, mut range, _) in multi_buffer
14512 .snapshot(cx)
14513 .range_to_buffer_ranges(selection.range())
14514 {
14515 // When editing branch buffers, jump to the corresponding location
14516 // in their base buffer.
14517 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14518 let buffer = buffer_handle.read(cx);
14519 if let Some(base_buffer) = buffer.base_buffer() {
14520 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14521 buffer_handle = base_buffer;
14522 }
14523
14524 if selection.reversed {
14525 mem::swap(&mut range.start, &mut range.end);
14526 }
14527 new_selections_by_buffer
14528 .entry(buffer_handle)
14529 .or_insert((Vec::new(), None))
14530 .0
14531 .push(range)
14532 }
14533 }
14534 }
14535 }
14536
14537 if new_selections_by_buffer.is_empty() {
14538 return;
14539 }
14540
14541 // We defer the pane interaction because we ourselves are a workspace item
14542 // and activating a new item causes the pane to call a method on us reentrantly,
14543 // which panics if we're on the stack.
14544 window.defer(cx, move |window, cx| {
14545 workspace.update(cx, |workspace, cx| {
14546 let pane = if split {
14547 workspace.adjacent_pane(window, cx)
14548 } else {
14549 workspace.active_pane().clone()
14550 };
14551
14552 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14553 let editor = buffer
14554 .read(cx)
14555 .file()
14556 .is_none()
14557 .then(|| {
14558 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14559 // so `workspace.open_project_item` will never find them, always opening a new editor.
14560 // Instead, we try to activate the existing editor in the pane first.
14561 let (editor, pane_item_index) =
14562 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14563 let editor = item.downcast::<Editor>()?;
14564 let singleton_buffer =
14565 editor.read(cx).buffer().read(cx).as_singleton()?;
14566 if singleton_buffer == buffer {
14567 Some((editor, i))
14568 } else {
14569 None
14570 }
14571 })?;
14572 pane.update(cx, |pane, cx| {
14573 pane.activate_item(pane_item_index, true, true, window, cx)
14574 });
14575 Some(editor)
14576 })
14577 .flatten()
14578 .unwrap_or_else(|| {
14579 workspace.open_project_item::<Self>(
14580 pane.clone(),
14581 buffer,
14582 true,
14583 true,
14584 window,
14585 cx,
14586 )
14587 });
14588
14589 editor.update(cx, |editor, cx| {
14590 let autoscroll = match scroll_offset {
14591 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14592 None => Autoscroll::newest(),
14593 };
14594 let nav_history = editor.nav_history.take();
14595 editor.change_selections(Some(autoscroll), window, cx, |s| {
14596 s.select_ranges(ranges);
14597 });
14598 editor.nav_history = nav_history;
14599 });
14600 }
14601 })
14602 });
14603 }
14604
14605 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14606 let snapshot = self.buffer.read(cx).read(cx);
14607 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14608 Some(
14609 ranges
14610 .iter()
14611 .map(move |range| {
14612 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14613 })
14614 .collect(),
14615 )
14616 }
14617
14618 fn selection_replacement_ranges(
14619 &self,
14620 range: Range<OffsetUtf16>,
14621 cx: &mut App,
14622 ) -> Vec<Range<OffsetUtf16>> {
14623 let selections = self.selections.all::<OffsetUtf16>(cx);
14624 let newest_selection = selections
14625 .iter()
14626 .max_by_key(|selection| selection.id)
14627 .unwrap();
14628 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14629 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14630 let snapshot = self.buffer.read(cx).read(cx);
14631 selections
14632 .into_iter()
14633 .map(|mut selection| {
14634 selection.start.0 =
14635 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14636 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14637 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14638 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14639 })
14640 .collect()
14641 }
14642
14643 fn report_editor_event(
14644 &self,
14645 event_type: &'static str,
14646 file_extension: Option<String>,
14647 cx: &App,
14648 ) {
14649 if cfg!(any(test, feature = "test-support")) {
14650 return;
14651 }
14652
14653 let Some(project) = &self.project else { return };
14654
14655 // If None, we are in a file without an extension
14656 let file = self
14657 .buffer
14658 .read(cx)
14659 .as_singleton()
14660 .and_then(|b| b.read(cx).file());
14661 let file_extension = file_extension.or(file
14662 .as_ref()
14663 .and_then(|file| Path::new(file.file_name(cx)).extension())
14664 .and_then(|e| e.to_str())
14665 .map(|a| a.to_string()));
14666
14667 let vim_mode = cx
14668 .global::<SettingsStore>()
14669 .raw_user_settings()
14670 .get("vim_mode")
14671 == Some(&serde_json::Value::Bool(true));
14672
14673 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14674 let copilot_enabled = edit_predictions_provider
14675 == language::language_settings::EditPredictionProvider::Copilot;
14676 let copilot_enabled_for_language = self
14677 .buffer
14678 .read(cx)
14679 .settings_at(0, cx)
14680 .show_edit_predictions;
14681
14682 let project = project.read(cx);
14683 telemetry::event!(
14684 event_type,
14685 file_extension,
14686 vim_mode,
14687 copilot_enabled,
14688 copilot_enabled_for_language,
14689 edit_predictions_provider,
14690 is_via_ssh = project.is_via_ssh(),
14691 );
14692 }
14693
14694 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14695 /// with each line being an array of {text, highlight} objects.
14696 fn copy_highlight_json(
14697 &mut self,
14698 _: &CopyHighlightJson,
14699 window: &mut Window,
14700 cx: &mut Context<Self>,
14701 ) {
14702 #[derive(Serialize)]
14703 struct Chunk<'a> {
14704 text: String,
14705 highlight: Option<&'a str>,
14706 }
14707
14708 let snapshot = self.buffer.read(cx).snapshot(cx);
14709 let range = self
14710 .selected_text_range(false, window, cx)
14711 .and_then(|selection| {
14712 if selection.range.is_empty() {
14713 None
14714 } else {
14715 Some(selection.range)
14716 }
14717 })
14718 .unwrap_or_else(|| 0..snapshot.len());
14719
14720 let chunks = snapshot.chunks(range, true);
14721 let mut lines = Vec::new();
14722 let mut line: VecDeque<Chunk> = VecDeque::new();
14723
14724 let Some(style) = self.style.as_ref() else {
14725 return;
14726 };
14727
14728 for chunk in chunks {
14729 let highlight = chunk
14730 .syntax_highlight_id
14731 .and_then(|id| id.name(&style.syntax));
14732 let mut chunk_lines = chunk.text.split('\n').peekable();
14733 while let Some(text) = chunk_lines.next() {
14734 let mut merged_with_last_token = false;
14735 if let Some(last_token) = line.back_mut() {
14736 if last_token.highlight == highlight {
14737 last_token.text.push_str(text);
14738 merged_with_last_token = true;
14739 }
14740 }
14741
14742 if !merged_with_last_token {
14743 line.push_back(Chunk {
14744 text: text.into(),
14745 highlight,
14746 });
14747 }
14748
14749 if chunk_lines.peek().is_some() {
14750 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14751 line.pop_front();
14752 }
14753 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14754 line.pop_back();
14755 }
14756
14757 lines.push(mem::take(&mut line));
14758 }
14759 }
14760 }
14761
14762 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14763 return;
14764 };
14765 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14766 }
14767
14768 pub fn open_context_menu(
14769 &mut self,
14770 _: &OpenContextMenu,
14771 window: &mut Window,
14772 cx: &mut Context<Self>,
14773 ) {
14774 self.request_autoscroll(Autoscroll::newest(), cx);
14775 let position = self.selections.newest_display(cx).start;
14776 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14777 }
14778
14779 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14780 &self.inlay_hint_cache
14781 }
14782
14783 pub fn replay_insert_event(
14784 &mut self,
14785 text: &str,
14786 relative_utf16_range: Option<Range<isize>>,
14787 window: &mut Window,
14788 cx: &mut Context<Self>,
14789 ) {
14790 if !self.input_enabled {
14791 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14792 return;
14793 }
14794 if let Some(relative_utf16_range) = relative_utf16_range {
14795 let selections = self.selections.all::<OffsetUtf16>(cx);
14796 self.change_selections(None, window, cx, |s| {
14797 let new_ranges = selections.into_iter().map(|range| {
14798 let start = OffsetUtf16(
14799 range
14800 .head()
14801 .0
14802 .saturating_add_signed(relative_utf16_range.start),
14803 );
14804 let end = OffsetUtf16(
14805 range
14806 .head()
14807 .0
14808 .saturating_add_signed(relative_utf16_range.end),
14809 );
14810 start..end
14811 });
14812 s.select_ranges(new_ranges);
14813 });
14814 }
14815
14816 self.handle_input(text, window, cx);
14817 }
14818
14819 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14820 let Some(provider) = self.semantics_provider.as_ref() else {
14821 return false;
14822 };
14823
14824 let mut supports = false;
14825 self.buffer().update(cx, |this, cx| {
14826 this.for_each_buffer(|buffer| {
14827 supports |= provider.supports_inlay_hints(buffer, cx);
14828 });
14829 });
14830
14831 supports
14832 }
14833
14834 pub fn is_focused(&self, window: &Window) -> bool {
14835 self.focus_handle.is_focused(window)
14836 }
14837
14838 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14839 cx.emit(EditorEvent::Focused);
14840
14841 if let Some(descendant) = self
14842 .last_focused_descendant
14843 .take()
14844 .and_then(|descendant| descendant.upgrade())
14845 {
14846 window.focus(&descendant);
14847 } else {
14848 if let Some(blame) = self.blame.as_ref() {
14849 blame.update(cx, GitBlame::focus)
14850 }
14851
14852 self.blink_manager.update(cx, BlinkManager::enable);
14853 self.show_cursor_names(window, cx);
14854 self.buffer.update(cx, |buffer, cx| {
14855 buffer.finalize_last_transaction(cx);
14856 if self.leader_peer_id.is_none() {
14857 buffer.set_active_selections(
14858 &self.selections.disjoint_anchors(),
14859 self.selections.line_mode,
14860 self.cursor_shape,
14861 cx,
14862 );
14863 }
14864 });
14865 }
14866 }
14867
14868 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14869 cx.emit(EditorEvent::FocusedIn)
14870 }
14871
14872 fn handle_focus_out(
14873 &mut self,
14874 event: FocusOutEvent,
14875 _window: &mut Window,
14876 _cx: &mut Context<Self>,
14877 ) {
14878 if event.blurred != self.focus_handle {
14879 self.last_focused_descendant = Some(event.blurred);
14880 }
14881 }
14882
14883 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14884 self.blink_manager.update(cx, BlinkManager::disable);
14885 self.buffer
14886 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14887
14888 if let Some(blame) = self.blame.as_ref() {
14889 blame.update(cx, GitBlame::blur)
14890 }
14891 if !self.hover_state.focused(window, cx) {
14892 hide_hover(self, cx);
14893 }
14894
14895 self.hide_context_menu(window, cx);
14896 self.discard_inline_completion(false, cx);
14897 cx.emit(EditorEvent::Blurred);
14898 cx.notify();
14899 }
14900
14901 pub fn register_action<A: Action>(
14902 &mut self,
14903 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14904 ) -> Subscription {
14905 let id = self.next_editor_action_id.post_inc();
14906 let listener = Arc::new(listener);
14907 self.editor_actions.borrow_mut().insert(
14908 id,
14909 Box::new(move |window, _| {
14910 let listener = listener.clone();
14911 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14912 let action = action.downcast_ref().unwrap();
14913 if phase == DispatchPhase::Bubble {
14914 listener(action, window, cx)
14915 }
14916 })
14917 }),
14918 );
14919
14920 let editor_actions = self.editor_actions.clone();
14921 Subscription::new(move || {
14922 editor_actions.borrow_mut().remove(&id);
14923 })
14924 }
14925
14926 pub fn file_header_size(&self) -> u32 {
14927 FILE_HEADER_HEIGHT
14928 }
14929
14930 pub fn revert(
14931 &mut self,
14932 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14933 window: &mut Window,
14934 cx: &mut Context<Self>,
14935 ) {
14936 self.buffer().update(cx, |multi_buffer, cx| {
14937 for (buffer_id, changes) in revert_changes {
14938 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14939 buffer.update(cx, |buffer, cx| {
14940 buffer.edit(
14941 changes.into_iter().map(|(range, text)| {
14942 (range, text.to_string().map(Arc::<str>::from))
14943 }),
14944 None,
14945 cx,
14946 );
14947 });
14948 }
14949 }
14950 });
14951 self.change_selections(None, window, cx, |selections| selections.refresh());
14952 }
14953
14954 pub fn to_pixel_point(
14955 &self,
14956 source: multi_buffer::Anchor,
14957 editor_snapshot: &EditorSnapshot,
14958 window: &mut Window,
14959 ) -> Option<gpui::Point<Pixels>> {
14960 let source_point = source.to_display_point(editor_snapshot);
14961 self.display_to_pixel_point(source_point, editor_snapshot, window)
14962 }
14963
14964 pub fn display_to_pixel_point(
14965 &self,
14966 source: DisplayPoint,
14967 editor_snapshot: &EditorSnapshot,
14968 window: &mut Window,
14969 ) -> Option<gpui::Point<Pixels>> {
14970 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14971 let text_layout_details = self.text_layout_details(window);
14972 let scroll_top = text_layout_details
14973 .scroll_anchor
14974 .scroll_position(editor_snapshot)
14975 .y;
14976
14977 if source.row().as_f32() < scroll_top.floor() {
14978 return None;
14979 }
14980 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14981 let source_y = line_height * (source.row().as_f32() - scroll_top);
14982 Some(gpui::Point::new(source_x, source_y))
14983 }
14984
14985 pub fn has_visible_completions_menu(&self) -> bool {
14986 !self.edit_prediction_preview_is_active()
14987 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14988 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14989 })
14990 }
14991
14992 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14993 self.addons
14994 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14995 }
14996
14997 pub fn unregister_addon<T: Addon>(&mut self) {
14998 self.addons.remove(&std::any::TypeId::of::<T>());
14999 }
15000
15001 pub fn addon<T: Addon>(&self) -> Option<&T> {
15002 let type_id = std::any::TypeId::of::<T>();
15003 self.addons
15004 .get(&type_id)
15005 .and_then(|item| item.to_any().downcast_ref::<T>())
15006 }
15007
15008 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15009 let text_layout_details = self.text_layout_details(window);
15010 let style = &text_layout_details.editor_style;
15011 let font_id = window.text_system().resolve_font(&style.text.font());
15012 let font_size = style.text.font_size.to_pixels(window.rem_size());
15013 let line_height = style.text.line_height_in_pixels(window.rem_size());
15014 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15015
15016 gpui::Size::new(em_width, line_height)
15017 }
15018
15019 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15020 self.load_diff_task.clone()
15021 }
15022
15023 fn read_selections_from_db(
15024 &mut self,
15025 item_id: u64,
15026 workspace_id: WorkspaceId,
15027 window: &mut Window,
15028 cx: &mut Context<Editor>,
15029 ) {
15030 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
15031 return;
15032 }
15033 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15034 return;
15035 };
15036 if selections.is_empty() {
15037 return;
15038 }
15039
15040 let snapshot = self.buffer.read(cx).snapshot(cx);
15041 self.change_selections(None, window, cx, |s| {
15042 s.select_ranges(selections.into_iter().map(|(start, end)| {
15043 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15044 }));
15045 });
15046 }
15047}
15048
15049fn get_uncommitted_diff_for_buffer(
15050 project: &Entity<Project>,
15051 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15052 buffer: Entity<MultiBuffer>,
15053 cx: &mut App,
15054) -> Task<()> {
15055 let mut tasks = Vec::new();
15056 project.update(cx, |project, cx| {
15057 for buffer in buffers {
15058 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15059 }
15060 });
15061 cx.spawn(|mut cx| async move {
15062 let diffs = futures::future::join_all(tasks).await;
15063 buffer
15064 .update(&mut cx, |buffer, cx| {
15065 for diff in diffs.into_iter().flatten() {
15066 buffer.add_diff(diff, cx);
15067 }
15068 })
15069 .ok();
15070 })
15071}
15072
15073fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15074 let tab_size = tab_size.get() as usize;
15075 let mut width = offset;
15076
15077 for ch in text.chars() {
15078 width += if ch == '\t' {
15079 tab_size - (width % tab_size)
15080 } else {
15081 1
15082 };
15083 }
15084
15085 width - offset
15086}
15087
15088#[cfg(test)]
15089mod tests {
15090 use super::*;
15091
15092 #[test]
15093 fn test_string_size_with_expanded_tabs() {
15094 let nz = |val| NonZeroU32::new(val).unwrap();
15095 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15096 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15097 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15098 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15099 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15100 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15101 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15102 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15103 }
15104}
15105
15106/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15107struct WordBreakingTokenizer<'a> {
15108 input: &'a str,
15109}
15110
15111impl<'a> WordBreakingTokenizer<'a> {
15112 fn new(input: &'a str) -> Self {
15113 Self { input }
15114 }
15115}
15116
15117fn is_char_ideographic(ch: char) -> bool {
15118 use unicode_script::Script::*;
15119 use unicode_script::UnicodeScript;
15120 matches!(ch.script(), Han | Tangut | Yi)
15121}
15122
15123fn is_grapheme_ideographic(text: &str) -> bool {
15124 text.chars().any(is_char_ideographic)
15125}
15126
15127fn is_grapheme_whitespace(text: &str) -> bool {
15128 text.chars().any(|x| x.is_whitespace())
15129}
15130
15131fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15132 text.chars().next().map_or(false, |ch| {
15133 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15134 })
15135}
15136
15137#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15138struct WordBreakToken<'a> {
15139 token: &'a str,
15140 grapheme_len: usize,
15141 is_whitespace: bool,
15142}
15143
15144impl<'a> Iterator for WordBreakingTokenizer<'a> {
15145 /// Yields a span, the count of graphemes in the token, and whether it was
15146 /// whitespace. Note that it also breaks at word boundaries.
15147 type Item = WordBreakToken<'a>;
15148
15149 fn next(&mut self) -> Option<Self::Item> {
15150 use unicode_segmentation::UnicodeSegmentation;
15151 if self.input.is_empty() {
15152 return None;
15153 }
15154
15155 let mut iter = self.input.graphemes(true).peekable();
15156 let mut offset = 0;
15157 let mut graphemes = 0;
15158 if let Some(first_grapheme) = iter.next() {
15159 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15160 offset += first_grapheme.len();
15161 graphemes += 1;
15162 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15163 if let Some(grapheme) = iter.peek().copied() {
15164 if should_stay_with_preceding_ideograph(grapheme) {
15165 offset += grapheme.len();
15166 graphemes += 1;
15167 }
15168 }
15169 } else {
15170 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15171 let mut next_word_bound = words.peek().copied();
15172 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15173 next_word_bound = words.next();
15174 }
15175 while let Some(grapheme) = iter.peek().copied() {
15176 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15177 break;
15178 };
15179 if is_grapheme_whitespace(grapheme) != is_whitespace {
15180 break;
15181 };
15182 offset += grapheme.len();
15183 graphemes += 1;
15184 iter.next();
15185 }
15186 }
15187 let token = &self.input[..offset];
15188 self.input = &self.input[offset..];
15189 if is_whitespace {
15190 Some(WordBreakToken {
15191 token: " ",
15192 grapheme_len: 1,
15193 is_whitespace: true,
15194 })
15195 } else {
15196 Some(WordBreakToken {
15197 token,
15198 grapheme_len: graphemes,
15199 is_whitespace: false,
15200 })
15201 }
15202 } else {
15203 None
15204 }
15205 }
15206}
15207
15208#[test]
15209fn test_word_breaking_tokenizer() {
15210 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15211 ("", &[]),
15212 (" ", &[(" ", 1, true)]),
15213 ("Ʒ", &[("Ʒ", 1, false)]),
15214 ("Ǽ", &[("Ǽ", 1, false)]),
15215 ("⋑", &[("⋑", 1, false)]),
15216 ("⋑⋑", &[("⋑⋑", 2, false)]),
15217 (
15218 "原理,进而",
15219 &[
15220 ("原", 1, false),
15221 ("理,", 2, false),
15222 ("进", 1, false),
15223 ("而", 1, false),
15224 ],
15225 ),
15226 (
15227 "hello world",
15228 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15229 ),
15230 (
15231 "hello, world",
15232 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15233 ),
15234 (
15235 " hello world",
15236 &[
15237 (" ", 1, true),
15238 ("hello", 5, false),
15239 (" ", 1, true),
15240 ("world", 5, false),
15241 ],
15242 ),
15243 (
15244 "这是什么 \n 钢笔",
15245 &[
15246 ("这", 1, false),
15247 ("是", 1, false),
15248 ("什", 1, false),
15249 ("么", 1, false),
15250 (" ", 1, true),
15251 ("钢", 1, false),
15252 ("笔", 1, false),
15253 ],
15254 ),
15255 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15256 ];
15257
15258 for (input, result) in tests {
15259 assert_eq!(
15260 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15261 result
15262 .iter()
15263 .copied()
15264 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15265 token,
15266 grapheme_len,
15267 is_whitespace,
15268 })
15269 .collect::<Vec<_>>()
15270 );
15271 }
15272}
15273
15274fn wrap_with_prefix(
15275 line_prefix: String,
15276 unwrapped_text: String,
15277 wrap_column: usize,
15278 tab_size: NonZeroU32,
15279) -> String {
15280 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15281 let mut wrapped_text = String::new();
15282 let mut current_line = line_prefix.clone();
15283
15284 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15285 let mut current_line_len = line_prefix_len;
15286 for WordBreakToken {
15287 token,
15288 grapheme_len,
15289 is_whitespace,
15290 } in tokenizer
15291 {
15292 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15293 wrapped_text.push_str(current_line.trim_end());
15294 wrapped_text.push('\n');
15295 current_line.truncate(line_prefix.len());
15296 current_line_len = line_prefix_len;
15297 if !is_whitespace {
15298 current_line.push_str(token);
15299 current_line_len += grapheme_len;
15300 }
15301 } else if !is_whitespace {
15302 current_line.push_str(token);
15303 current_line_len += grapheme_len;
15304 } else if current_line_len != line_prefix_len {
15305 current_line.push(' ');
15306 current_line_len += 1;
15307 }
15308 }
15309
15310 if !current_line.is_empty() {
15311 wrapped_text.push_str(¤t_line);
15312 }
15313 wrapped_text
15314}
15315
15316#[test]
15317fn test_wrap_with_prefix() {
15318 assert_eq!(
15319 wrap_with_prefix(
15320 "# ".to_string(),
15321 "abcdefg".to_string(),
15322 4,
15323 NonZeroU32::new(4).unwrap()
15324 ),
15325 "# abcdefg"
15326 );
15327 assert_eq!(
15328 wrap_with_prefix(
15329 "".to_string(),
15330 "\thello world".to_string(),
15331 8,
15332 NonZeroU32::new(4).unwrap()
15333 ),
15334 "hello\nworld"
15335 );
15336 assert_eq!(
15337 wrap_with_prefix(
15338 "// ".to_string(),
15339 "xx \nyy zz aa bb cc".to_string(),
15340 12,
15341 NonZeroU32::new(4).unwrap()
15342 ),
15343 "// xx yy zz\n// aa bb cc"
15344 );
15345 assert_eq!(
15346 wrap_with_prefix(
15347 String::new(),
15348 "这是什么 \n 钢笔".to_string(),
15349 3,
15350 NonZeroU32::new(4).unwrap()
15351 ),
15352 "这是什\n么 钢\n笔"
15353 );
15354}
15355
15356pub trait CollaborationHub {
15357 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15358 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15359 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15360}
15361
15362impl CollaborationHub for Entity<Project> {
15363 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15364 self.read(cx).collaborators()
15365 }
15366
15367 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15368 self.read(cx).user_store().read(cx).participant_indices()
15369 }
15370
15371 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15372 let this = self.read(cx);
15373 let user_ids = this.collaborators().values().map(|c| c.user_id);
15374 this.user_store().read_with(cx, |user_store, cx| {
15375 user_store.participant_names(user_ids, cx)
15376 })
15377 }
15378}
15379
15380pub trait SemanticsProvider {
15381 fn hover(
15382 &self,
15383 buffer: &Entity<Buffer>,
15384 position: text::Anchor,
15385 cx: &mut App,
15386 ) -> Option<Task<Vec<project::Hover>>>;
15387
15388 fn inlay_hints(
15389 &self,
15390 buffer_handle: Entity<Buffer>,
15391 range: Range<text::Anchor>,
15392 cx: &mut App,
15393 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15394
15395 fn resolve_inlay_hint(
15396 &self,
15397 hint: InlayHint,
15398 buffer_handle: Entity<Buffer>,
15399 server_id: LanguageServerId,
15400 cx: &mut App,
15401 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15402
15403 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15404
15405 fn document_highlights(
15406 &self,
15407 buffer: &Entity<Buffer>,
15408 position: text::Anchor,
15409 cx: &mut App,
15410 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15411
15412 fn definitions(
15413 &self,
15414 buffer: &Entity<Buffer>,
15415 position: text::Anchor,
15416 kind: GotoDefinitionKind,
15417 cx: &mut App,
15418 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15419
15420 fn range_for_rename(
15421 &self,
15422 buffer: &Entity<Buffer>,
15423 position: text::Anchor,
15424 cx: &mut App,
15425 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15426
15427 fn perform_rename(
15428 &self,
15429 buffer: &Entity<Buffer>,
15430 position: text::Anchor,
15431 new_name: String,
15432 cx: &mut App,
15433 ) -> Option<Task<Result<ProjectTransaction>>>;
15434}
15435
15436pub trait CompletionProvider {
15437 fn completions(
15438 &self,
15439 buffer: &Entity<Buffer>,
15440 buffer_position: text::Anchor,
15441 trigger: CompletionContext,
15442 window: &mut Window,
15443 cx: &mut Context<Editor>,
15444 ) -> Task<Result<Vec<Completion>>>;
15445
15446 fn resolve_completions(
15447 &self,
15448 buffer: Entity<Buffer>,
15449 completion_indices: Vec<usize>,
15450 completions: Rc<RefCell<Box<[Completion]>>>,
15451 cx: &mut Context<Editor>,
15452 ) -> Task<Result<bool>>;
15453
15454 fn apply_additional_edits_for_completion(
15455 &self,
15456 _buffer: Entity<Buffer>,
15457 _completions: Rc<RefCell<Box<[Completion]>>>,
15458 _completion_index: usize,
15459 _push_to_history: bool,
15460 _cx: &mut Context<Editor>,
15461 ) -> Task<Result<Option<language::Transaction>>> {
15462 Task::ready(Ok(None))
15463 }
15464
15465 fn is_completion_trigger(
15466 &self,
15467 buffer: &Entity<Buffer>,
15468 position: language::Anchor,
15469 text: &str,
15470 trigger_in_words: bool,
15471 cx: &mut Context<Editor>,
15472 ) -> bool;
15473
15474 fn sort_completions(&self) -> bool {
15475 true
15476 }
15477}
15478
15479pub trait CodeActionProvider {
15480 fn id(&self) -> Arc<str>;
15481
15482 fn code_actions(
15483 &self,
15484 buffer: &Entity<Buffer>,
15485 range: Range<text::Anchor>,
15486 window: &mut Window,
15487 cx: &mut App,
15488 ) -> Task<Result<Vec<CodeAction>>>;
15489
15490 fn apply_code_action(
15491 &self,
15492 buffer_handle: Entity<Buffer>,
15493 action: CodeAction,
15494 excerpt_id: ExcerptId,
15495 push_to_history: bool,
15496 window: &mut Window,
15497 cx: &mut App,
15498 ) -> Task<Result<ProjectTransaction>>;
15499}
15500
15501impl CodeActionProvider for Entity<Project> {
15502 fn id(&self) -> Arc<str> {
15503 "project".into()
15504 }
15505
15506 fn code_actions(
15507 &self,
15508 buffer: &Entity<Buffer>,
15509 range: Range<text::Anchor>,
15510 _window: &mut Window,
15511 cx: &mut App,
15512 ) -> Task<Result<Vec<CodeAction>>> {
15513 self.update(cx, |project, cx| {
15514 project.code_actions(buffer, range, None, cx)
15515 })
15516 }
15517
15518 fn apply_code_action(
15519 &self,
15520 buffer_handle: Entity<Buffer>,
15521 action: CodeAction,
15522 _excerpt_id: ExcerptId,
15523 push_to_history: bool,
15524 _window: &mut Window,
15525 cx: &mut App,
15526 ) -> Task<Result<ProjectTransaction>> {
15527 self.update(cx, |project, cx| {
15528 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15529 })
15530 }
15531}
15532
15533fn snippet_completions(
15534 project: &Project,
15535 buffer: &Entity<Buffer>,
15536 buffer_position: text::Anchor,
15537 cx: &mut App,
15538) -> Task<Result<Vec<Completion>>> {
15539 let language = buffer.read(cx).language_at(buffer_position);
15540 let language_name = language.as_ref().map(|language| language.lsp_id());
15541 let snippet_store = project.snippets().read(cx);
15542 let snippets = snippet_store.snippets_for(language_name, cx);
15543
15544 if snippets.is_empty() {
15545 return Task::ready(Ok(vec![]));
15546 }
15547 let snapshot = buffer.read(cx).text_snapshot();
15548 let chars: String = snapshot
15549 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15550 .collect();
15551
15552 let scope = language.map(|language| language.default_scope());
15553 let executor = cx.background_executor().clone();
15554
15555 cx.background_executor().spawn(async move {
15556 let classifier = CharClassifier::new(scope).for_completion(true);
15557 let mut last_word = chars
15558 .chars()
15559 .take_while(|c| classifier.is_word(*c))
15560 .collect::<String>();
15561 last_word = last_word.chars().rev().collect();
15562
15563 if last_word.is_empty() {
15564 return Ok(vec![]);
15565 }
15566
15567 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15568 let to_lsp = |point: &text::Anchor| {
15569 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15570 point_to_lsp(end)
15571 };
15572 let lsp_end = to_lsp(&buffer_position);
15573
15574 let candidates = snippets
15575 .iter()
15576 .enumerate()
15577 .flat_map(|(ix, snippet)| {
15578 snippet
15579 .prefix
15580 .iter()
15581 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15582 })
15583 .collect::<Vec<StringMatchCandidate>>();
15584
15585 let mut matches = fuzzy::match_strings(
15586 &candidates,
15587 &last_word,
15588 last_word.chars().any(|c| c.is_uppercase()),
15589 100,
15590 &Default::default(),
15591 executor,
15592 )
15593 .await;
15594
15595 // Remove all candidates where the query's start does not match the start of any word in the candidate
15596 if let Some(query_start) = last_word.chars().next() {
15597 matches.retain(|string_match| {
15598 split_words(&string_match.string).any(|word| {
15599 // Check that the first codepoint of the word as lowercase matches the first
15600 // codepoint of the query as lowercase
15601 word.chars()
15602 .flat_map(|codepoint| codepoint.to_lowercase())
15603 .zip(query_start.to_lowercase())
15604 .all(|(word_cp, query_cp)| word_cp == query_cp)
15605 })
15606 });
15607 }
15608
15609 let matched_strings = matches
15610 .into_iter()
15611 .map(|m| m.string)
15612 .collect::<HashSet<_>>();
15613
15614 let result: Vec<Completion> = snippets
15615 .into_iter()
15616 .filter_map(|snippet| {
15617 let matching_prefix = snippet
15618 .prefix
15619 .iter()
15620 .find(|prefix| matched_strings.contains(*prefix))?;
15621 let start = as_offset - last_word.len();
15622 let start = snapshot.anchor_before(start);
15623 let range = start..buffer_position;
15624 let lsp_start = to_lsp(&start);
15625 let lsp_range = lsp::Range {
15626 start: lsp_start,
15627 end: lsp_end,
15628 };
15629 Some(Completion {
15630 old_range: range,
15631 new_text: snippet.body.clone(),
15632 resolved: false,
15633 label: CodeLabel {
15634 text: matching_prefix.clone(),
15635 runs: vec![],
15636 filter_range: 0..matching_prefix.len(),
15637 },
15638 server_id: LanguageServerId(usize::MAX),
15639 documentation: snippet
15640 .description
15641 .clone()
15642 .map(CompletionDocumentation::SingleLine),
15643 lsp_completion: lsp::CompletionItem {
15644 label: snippet.prefix.first().unwrap().clone(),
15645 kind: Some(CompletionItemKind::SNIPPET),
15646 label_details: snippet.description.as_ref().map(|description| {
15647 lsp::CompletionItemLabelDetails {
15648 detail: Some(description.clone()),
15649 description: None,
15650 }
15651 }),
15652 insert_text_format: Some(InsertTextFormat::SNIPPET),
15653 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15654 lsp::InsertReplaceEdit {
15655 new_text: snippet.body.clone(),
15656 insert: lsp_range,
15657 replace: lsp_range,
15658 },
15659 )),
15660 filter_text: Some(snippet.body.clone()),
15661 sort_text: Some(char::MAX.to_string()),
15662 ..Default::default()
15663 },
15664 confirm: None,
15665 })
15666 })
15667 .collect();
15668
15669 Ok(result)
15670 })
15671}
15672
15673impl CompletionProvider for Entity<Project> {
15674 fn completions(
15675 &self,
15676 buffer: &Entity<Buffer>,
15677 buffer_position: text::Anchor,
15678 options: CompletionContext,
15679 _window: &mut Window,
15680 cx: &mut Context<Editor>,
15681 ) -> Task<Result<Vec<Completion>>> {
15682 self.update(cx, |project, cx| {
15683 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15684 let project_completions = project.completions(buffer, buffer_position, options, cx);
15685 cx.background_executor().spawn(async move {
15686 let mut completions = project_completions.await?;
15687 let snippets_completions = snippets.await?;
15688 completions.extend(snippets_completions);
15689 Ok(completions)
15690 })
15691 })
15692 }
15693
15694 fn resolve_completions(
15695 &self,
15696 buffer: Entity<Buffer>,
15697 completion_indices: Vec<usize>,
15698 completions: Rc<RefCell<Box<[Completion]>>>,
15699 cx: &mut Context<Editor>,
15700 ) -> Task<Result<bool>> {
15701 self.update(cx, |project, cx| {
15702 project.lsp_store().update(cx, |lsp_store, cx| {
15703 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15704 })
15705 })
15706 }
15707
15708 fn apply_additional_edits_for_completion(
15709 &self,
15710 buffer: Entity<Buffer>,
15711 completions: Rc<RefCell<Box<[Completion]>>>,
15712 completion_index: usize,
15713 push_to_history: bool,
15714 cx: &mut Context<Editor>,
15715 ) -> Task<Result<Option<language::Transaction>>> {
15716 self.update(cx, |project, cx| {
15717 project.lsp_store().update(cx, |lsp_store, cx| {
15718 lsp_store.apply_additional_edits_for_completion(
15719 buffer,
15720 completions,
15721 completion_index,
15722 push_to_history,
15723 cx,
15724 )
15725 })
15726 })
15727 }
15728
15729 fn is_completion_trigger(
15730 &self,
15731 buffer: &Entity<Buffer>,
15732 position: language::Anchor,
15733 text: &str,
15734 trigger_in_words: bool,
15735 cx: &mut Context<Editor>,
15736 ) -> bool {
15737 let mut chars = text.chars();
15738 let char = if let Some(char) = chars.next() {
15739 char
15740 } else {
15741 return false;
15742 };
15743 if chars.next().is_some() {
15744 return false;
15745 }
15746
15747 let buffer = buffer.read(cx);
15748 let snapshot = buffer.snapshot();
15749 if !snapshot.settings_at(position, cx).show_completions_on_input {
15750 return false;
15751 }
15752 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15753 if trigger_in_words && classifier.is_word(char) {
15754 return true;
15755 }
15756
15757 buffer.completion_triggers().contains(text)
15758 }
15759}
15760
15761impl SemanticsProvider for Entity<Project> {
15762 fn hover(
15763 &self,
15764 buffer: &Entity<Buffer>,
15765 position: text::Anchor,
15766 cx: &mut App,
15767 ) -> Option<Task<Vec<project::Hover>>> {
15768 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15769 }
15770
15771 fn document_highlights(
15772 &self,
15773 buffer: &Entity<Buffer>,
15774 position: text::Anchor,
15775 cx: &mut App,
15776 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15777 Some(self.update(cx, |project, cx| {
15778 project.document_highlights(buffer, position, cx)
15779 }))
15780 }
15781
15782 fn definitions(
15783 &self,
15784 buffer: &Entity<Buffer>,
15785 position: text::Anchor,
15786 kind: GotoDefinitionKind,
15787 cx: &mut App,
15788 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15789 Some(self.update(cx, |project, cx| match kind {
15790 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15791 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15792 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15793 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15794 }))
15795 }
15796
15797 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15798 // TODO: make this work for remote projects
15799 self.update(cx, |this, cx| {
15800 buffer.update(cx, |buffer, cx| {
15801 this.any_language_server_supports_inlay_hints(buffer, cx)
15802 })
15803 })
15804 }
15805
15806 fn inlay_hints(
15807 &self,
15808 buffer_handle: Entity<Buffer>,
15809 range: Range<text::Anchor>,
15810 cx: &mut App,
15811 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15812 Some(self.update(cx, |project, cx| {
15813 project.inlay_hints(buffer_handle, range, cx)
15814 }))
15815 }
15816
15817 fn resolve_inlay_hint(
15818 &self,
15819 hint: InlayHint,
15820 buffer_handle: Entity<Buffer>,
15821 server_id: LanguageServerId,
15822 cx: &mut App,
15823 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15824 Some(self.update(cx, |project, cx| {
15825 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15826 }))
15827 }
15828
15829 fn range_for_rename(
15830 &self,
15831 buffer: &Entity<Buffer>,
15832 position: text::Anchor,
15833 cx: &mut App,
15834 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15835 Some(self.update(cx, |project, cx| {
15836 let buffer = buffer.clone();
15837 let task = project.prepare_rename(buffer.clone(), position, cx);
15838 cx.spawn(|_, mut cx| async move {
15839 Ok(match task.await? {
15840 PrepareRenameResponse::Success(range) => Some(range),
15841 PrepareRenameResponse::InvalidPosition => None,
15842 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15843 // Fallback on using TreeSitter info to determine identifier range
15844 buffer.update(&mut cx, |buffer, _| {
15845 let snapshot = buffer.snapshot();
15846 let (range, kind) = snapshot.surrounding_word(position);
15847 if kind != Some(CharKind::Word) {
15848 return None;
15849 }
15850 Some(
15851 snapshot.anchor_before(range.start)
15852 ..snapshot.anchor_after(range.end),
15853 )
15854 })?
15855 }
15856 })
15857 })
15858 }))
15859 }
15860
15861 fn perform_rename(
15862 &self,
15863 buffer: &Entity<Buffer>,
15864 position: text::Anchor,
15865 new_name: String,
15866 cx: &mut App,
15867 ) -> Option<Task<Result<ProjectTransaction>>> {
15868 Some(self.update(cx, |project, cx| {
15869 project.perform_rename(buffer.clone(), position, new_name, cx)
15870 }))
15871 }
15872}
15873
15874fn inlay_hint_settings(
15875 location: Anchor,
15876 snapshot: &MultiBufferSnapshot,
15877 cx: &mut Context<Editor>,
15878) -> InlayHintSettings {
15879 let file = snapshot.file_at(location);
15880 let language = snapshot.language_at(location).map(|l| l.name());
15881 language_settings(language, file, cx).inlay_hints
15882}
15883
15884fn consume_contiguous_rows(
15885 contiguous_row_selections: &mut Vec<Selection<Point>>,
15886 selection: &Selection<Point>,
15887 display_map: &DisplaySnapshot,
15888 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15889) -> (MultiBufferRow, MultiBufferRow) {
15890 contiguous_row_selections.push(selection.clone());
15891 let start_row = MultiBufferRow(selection.start.row);
15892 let mut end_row = ending_row(selection, display_map);
15893
15894 while let Some(next_selection) = selections.peek() {
15895 if next_selection.start.row <= end_row.0 {
15896 end_row = ending_row(next_selection, display_map);
15897 contiguous_row_selections.push(selections.next().unwrap().clone());
15898 } else {
15899 break;
15900 }
15901 }
15902 (start_row, end_row)
15903}
15904
15905fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15906 if next_selection.end.column > 0 || next_selection.is_empty() {
15907 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15908 } else {
15909 MultiBufferRow(next_selection.end.row)
15910 }
15911}
15912
15913impl EditorSnapshot {
15914 pub fn remote_selections_in_range<'a>(
15915 &'a self,
15916 range: &'a Range<Anchor>,
15917 collaboration_hub: &dyn CollaborationHub,
15918 cx: &'a App,
15919 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15920 let participant_names = collaboration_hub.user_names(cx);
15921 let participant_indices = collaboration_hub.user_participant_indices(cx);
15922 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15923 let collaborators_by_replica_id = collaborators_by_peer_id
15924 .iter()
15925 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15926 .collect::<HashMap<_, _>>();
15927 self.buffer_snapshot
15928 .selections_in_range(range, false)
15929 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15930 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15931 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15932 let user_name = participant_names.get(&collaborator.user_id).cloned();
15933 Some(RemoteSelection {
15934 replica_id,
15935 selection,
15936 cursor_shape,
15937 line_mode,
15938 participant_index,
15939 peer_id: collaborator.peer_id,
15940 user_name,
15941 })
15942 })
15943 }
15944
15945 pub fn hunks_for_ranges(
15946 &self,
15947 ranges: impl Iterator<Item = Range<Point>>,
15948 ) -> Vec<MultiBufferDiffHunk> {
15949 let mut hunks = Vec::new();
15950 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15951 HashMap::default();
15952 for query_range in ranges {
15953 let query_rows =
15954 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15955 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15956 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15957 ) {
15958 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15959 // when the caret is just above or just below the deleted hunk.
15960 let allow_adjacent = hunk.status().is_removed();
15961 let related_to_selection = if allow_adjacent {
15962 hunk.row_range.overlaps(&query_rows)
15963 || hunk.row_range.start == query_rows.end
15964 || hunk.row_range.end == query_rows.start
15965 } else {
15966 hunk.row_range.overlaps(&query_rows)
15967 };
15968 if related_to_selection {
15969 if !processed_buffer_rows
15970 .entry(hunk.buffer_id)
15971 .or_default()
15972 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15973 {
15974 continue;
15975 }
15976 hunks.push(hunk);
15977 }
15978 }
15979 }
15980
15981 hunks
15982 }
15983
15984 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15985 self.display_snapshot.buffer_snapshot.language_at(position)
15986 }
15987
15988 pub fn is_focused(&self) -> bool {
15989 self.is_focused
15990 }
15991
15992 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15993 self.placeholder_text.as_ref()
15994 }
15995
15996 pub fn scroll_position(&self) -> gpui::Point<f32> {
15997 self.scroll_anchor.scroll_position(&self.display_snapshot)
15998 }
15999
16000 fn gutter_dimensions(
16001 &self,
16002 font_id: FontId,
16003 font_size: Pixels,
16004 max_line_number_width: Pixels,
16005 cx: &App,
16006 ) -> Option<GutterDimensions> {
16007 if !self.show_gutter {
16008 return None;
16009 }
16010
16011 let descent = cx.text_system().descent(font_id, font_size);
16012 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16013 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16014
16015 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16016 matches!(
16017 ProjectSettings::get_global(cx).git.git_gutter,
16018 Some(GitGutterSetting::TrackedFiles)
16019 )
16020 });
16021 let gutter_settings = EditorSettings::get_global(cx).gutter;
16022 let show_line_numbers = self
16023 .show_line_numbers
16024 .unwrap_or(gutter_settings.line_numbers);
16025 let line_gutter_width = if show_line_numbers {
16026 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16027 let min_width_for_number_on_gutter = em_advance * 4.0;
16028 max_line_number_width.max(min_width_for_number_on_gutter)
16029 } else {
16030 0.0.into()
16031 };
16032
16033 let show_code_actions = self
16034 .show_code_actions
16035 .unwrap_or(gutter_settings.code_actions);
16036
16037 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16038
16039 let git_blame_entries_width =
16040 self.git_blame_gutter_max_author_length
16041 .map(|max_author_length| {
16042 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16043
16044 /// The number of characters to dedicate to gaps and margins.
16045 const SPACING_WIDTH: usize = 4;
16046
16047 let max_char_count = max_author_length
16048 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16049 + ::git::SHORT_SHA_LENGTH
16050 + MAX_RELATIVE_TIMESTAMP.len()
16051 + SPACING_WIDTH;
16052
16053 em_advance * max_char_count
16054 });
16055
16056 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16057 left_padding += if show_code_actions || show_runnables {
16058 em_width * 3.0
16059 } else if show_git_gutter && show_line_numbers {
16060 em_width * 2.0
16061 } else if show_git_gutter || show_line_numbers {
16062 em_width
16063 } else {
16064 px(0.)
16065 };
16066
16067 let right_padding = if gutter_settings.folds && show_line_numbers {
16068 em_width * 4.0
16069 } else if gutter_settings.folds {
16070 em_width * 3.0
16071 } else if show_line_numbers {
16072 em_width
16073 } else {
16074 px(0.)
16075 };
16076
16077 Some(GutterDimensions {
16078 left_padding,
16079 right_padding,
16080 width: line_gutter_width + left_padding + right_padding,
16081 margin: -descent,
16082 git_blame_entries_width,
16083 })
16084 }
16085
16086 pub fn render_crease_toggle(
16087 &self,
16088 buffer_row: MultiBufferRow,
16089 row_contains_cursor: bool,
16090 editor: Entity<Editor>,
16091 window: &mut Window,
16092 cx: &mut App,
16093 ) -> Option<AnyElement> {
16094 let folded = self.is_line_folded(buffer_row);
16095 let mut is_foldable = false;
16096
16097 if let Some(crease) = self
16098 .crease_snapshot
16099 .query_row(buffer_row, &self.buffer_snapshot)
16100 {
16101 is_foldable = true;
16102 match crease {
16103 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16104 if let Some(render_toggle) = render_toggle {
16105 let toggle_callback =
16106 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16107 if folded {
16108 editor.update(cx, |editor, cx| {
16109 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16110 });
16111 } else {
16112 editor.update(cx, |editor, cx| {
16113 editor.unfold_at(
16114 &crate::UnfoldAt { buffer_row },
16115 window,
16116 cx,
16117 )
16118 });
16119 }
16120 });
16121 return Some((render_toggle)(
16122 buffer_row,
16123 folded,
16124 toggle_callback,
16125 window,
16126 cx,
16127 ));
16128 }
16129 }
16130 }
16131 }
16132
16133 is_foldable |= self.starts_indent(buffer_row);
16134
16135 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16136 Some(
16137 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16138 .toggle_state(folded)
16139 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16140 if folded {
16141 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16142 } else {
16143 this.fold_at(&FoldAt { buffer_row }, window, cx);
16144 }
16145 }))
16146 .into_any_element(),
16147 )
16148 } else {
16149 None
16150 }
16151 }
16152
16153 pub fn render_crease_trailer(
16154 &self,
16155 buffer_row: MultiBufferRow,
16156 window: &mut Window,
16157 cx: &mut App,
16158 ) -> Option<AnyElement> {
16159 let folded = self.is_line_folded(buffer_row);
16160 if let Crease::Inline { render_trailer, .. } = self
16161 .crease_snapshot
16162 .query_row(buffer_row, &self.buffer_snapshot)?
16163 {
16164 let render_trailer = render_trailer.as_ref()?;
16165 Some(render_trailer(buffer_row, folded, window, cx))
16166 } else {
16167 None
16168 }
16169 }
16170}
16171
16172impl Deref for EditorSnapshot {
16173 type Target = DisplaySnapshot;
16174
16175 fn deref(&self) -> &Self::Target {
16176 &self.display_snapshot
16177 }
16178}
16179
16180#[derive(Clone, Debug, PartialEq, Eq)]
16181pub enum EditorEvent {
16182 InputIgnored {
16183 text: Arc<str>,
16184 },
16185 InputHandled {
16186 utf16_range_to_replace: Option<Range<isize>>,
16187 text: Arc<str>,
16188 },
16189 ExcerptsAdded {
16190 buffer: Entity<Buffer>,
16191 predecessor: ExcerptId,
16192 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16193 },
16194 ExcerptsRemoved {
16195 ids: Vec<ExcerptId>,
16196 },
16197 BufferFoldToggled {
16198 ids: Vec<ExcerptId>,
16199 folded: bool,
16200 },
16201 ExcerptsEdited {
16202 ids: Vec<ExcerptId>,
16203 },
16204 ExcerptsExpanded {
16205 ids: Vec<ExcerptId>,
16206 },
16207 BufferEdited,
16208 Edited {
16209 transaction_id: clock::Lamport,
16210 },
16211 Reparsed(BufferId),
16212 Focused,
16213 FocusedIn,
16214 Blurred,
16215 DirtyChanged,
16216 Saved,
16217 TitleChanged,
16218 DiffBaseChanged,
16219 SelectionsChanged {
16220 local: bool,
16221 },
16222 ScrollPositionChanged {
16223 local: bool,
16224 autoscroll: bool,
16225 },
16226 Closed,
16227 TransactionUndone {
16228 transaction_id: clock::Lamport,
16229 },
16230 TransactionBegun {
16231 transaction_id: clock::Lamport,
16232 },
16233 Reloaded,
16234 CursorShapeChanged,
16235}
16236
16237impl EventEmitter<EditorEvent> for Editor {}
16238
16239impl Focusable for Editor {
16240 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16241 self.focus_handle.clone()
16242 }
16243}
16244
16245impl Render for Editor {
16246 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16247 let settings = ThemeSettings::get_global(cx);
16248
16249 let mut text_style = match self.mode {
16250 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16251 color: cx.theme().colors().editor_foreground,
16252 font_family: settings.ui_font.family.clone(),
16253 font_features: settings.ui_font.features.clone(),
16254 font_fallbacks: settings.ui_font.fallbacks.clone(),
16255 font_size: rems(0.875).into(),
16256 font_weight: settings.ui_font.weight,
16257 line_height: relative(settings.buffer_line_height.value()),
16258 ..Default::default()
16259 },
16260 EditorMode::Full => TextStyle {
16261 color: cx.theme().colors().editor_foreground,
16262 font_family: settings.buffer_font.family.clone(),
16263 font_features: settings.buffer_font.features.clone(),
16264 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16265 font_size: settings.buffer_font_size(cx).into(),
16266 font_weight: settings.buffer_font.weight,
16267 line_height: relative(settings.buffer_line_height.value()),
16268 ..Default::default()
16269 },
16270 };
16271 if let Some(text_style_refinement) = &self.text_style_refinement {
16272 text_style.refine(text_style_refinement)
16273 }
16274
16275 let background = match self.mode {
16276 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16277 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16278 EditorMode::Full => cx.theme().colors().editor_background,
16279 };
16280
16281 EditorElement::new(
16282 &cx.entity(),
16283 EditorStyle {
16284 background,
16285 local_player: cx.theme().players().local(),
16286 text: text_style,
16287 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16288 syntax: cx.theme().syntax().clone(),
16289 status: cx.theme().status().clone(),
16290 inlay_hints_style: make_inlay_hints_style(cx),
16291 inline_completion_styles: make_suggestion_styles(cx),
16292 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16293 },
16294 )
16295 }
16296}
16297
16298impl EntityInputHandler for Editor {
16299 fn text_for_range(
16300 &mut self,
16301 range_utf16: Range<usize>,
16302 adjusted_range: &mut Option<Range<usize>>,
16303 _: &mut Window,
16304 cx: &mut Context<Self>,
16305 ) -> Option<String> {
16306 let snapshot = self.buffer.read(cx).read(cx);
16307 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16308 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16309 if (start.0..end.0) != range_utf16 {
16310 adjusted_range.replace(start.0..end.0);
16311 }
16312 Some(snapshot.text_for_range(start..end).collect())
16313 }
16314
16315 fn selected_text_range(
16316 &mut self,
16317 ignore_disabled_input: bool,
16318 _: &mut Window,
16319 cx: &mut Context<Self>,
16320 ) -> Option<UTF16Selection> {
16321 // Prevent the IME menu from appearing when holding down an alphabetic key
16322 // while input is disabled.
16323 if !ignore_disabled_input && !self.input_enabled {
16324 return None;
16325 }
16326
16327 let selection = self.selections.newest::<OffsetUtf16>(cx);
16328 let range = selection.range();
16329
16330 Some(UTF16Selection {
16331 range: range.start.0..range.end.0,
16332 reversed: selection.reversed,
16333 })
16334 }
16335
16336 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16337 let snapshot = self.buffer.read(cx).read(cx);
16338 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16339 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16340 }
16341
16342 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16343 self.clear_highlights::<InputComposition>(cx);
16344 self.ime_transaction.take();
16345 }
16346
16347 fn replace_text_in_range(
16348 &mut self,
16349 range_utf16: Option<Range<usize>>,
16350 text: &str,
16351 window: &mut Window,
16352 cx: &mut Context<Self>,
16353 ) {
16354 if !self.input_enabled {
16355 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16356 return;
16357 }
16358
16359 self.transact(window, cx, |this, window, cx| {
16360 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16361 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16362 Some(this.selection_replacement_ranges(range_utf16, cx))
16363 } else {
16364 this.marked_text_ranges(cx)
16365 };
16366
16367 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16368 let newest_selection_id = this.selections.newest_anchor().id;
16369 this.selections
16370 .all::<OffsetUtf16>(cx)
16371 .iter()
16372 .zip(ranges_to_replace.iter())
16373 .find_map(|(selection, range)| {
16374 if selection.id == newest_selection_id {
16375 Some(
16376 (range.start.0 as isize - selection.head().0 as isize)
16377 ..(range.end.0 as isize - selection.head().0 as isize),
16378 )
16379 } else {
16380 None
16381 }
16382 })
16383 });
16384
16385 cx.emit(EditorEvent::InputHandled {
16386 utf16_range_to_replace: range_to_replace,
16387 text: text.into(),
16388 });
16389
16390 if let Some(new_selected_ranges) = new_selected_ranges {
16391 this.change_selections(None, window, cx, |selections| {
16392 selections.select_ranges(new_selected_ranges)
16393 });
16394 this.backspace(&Default::default(), window, cx);
16395 }
16396
16397 this.handle_input(text, window, cx);
16398 });
16399
16400 if let Some(transaction) = self.ime_transaction {
16401 self.buffer.update(cx, |buffer, cx| {
16402 buffer.group_until_transaction(transaction, cx);
16403 });
16404 }
16405
16406 self.unmark_text(window, cx);
16407 }
16408
16409 fn replace_and_mark_text_in_range(
16410 &mut self,
16411 range_utf16: Option<Range<usize>>,
16412 text: &str,
16413 new_selected_range_utf16: Option<Range<usize>>,
16414 window: &mut Window,
16415 cx: &mut Context<Self>,
16416 ) {
16417 if !self.input_enabled {
16418 return;
16419 }
16420
16421 let transaction = self.transact(window, cx, |this, window, cx| {
16422 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16423 let snapshot = this.buffer.read(cx).read(cx);
16424 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16425 for marked_range in &mut marked_ranges {
16426 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16427 marked_range.start.0 += relative_range_utf16.start;
16428 marked_range.start =
16429 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16430 marked_range.end =
16431 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16432 }
16433 }
16434 Some(marked_ranges)
16435 } else if let Some(range_utf16) = range_utf16 {
16436 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16437 Some(this.selection_replacement_ranges(range_utf16, cx))
16438 } else {
16439 None
16440 };
16441
16442 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16443 let newest_selection_id = this.selections.newest_anchor().id;
16444 this.selections
16445 .all::<OffsetUtf16>(cx)
16446 .iter()
16447 .zip(ranges_to_replace.iter())
16448 .find_map(|(selection, range)| {
16449 if selection.id == newest_selection_id {
16450 Some(
16451 (range.start.0 as isize - selection.head().0 as isize)
16452 ..(range.end.0 as isize - selection.head().0 as isize),
16453 )
16454 } else {
16455 None
16456 }
16457 })
16458 });
16459
16460 cx.emit(EditorEvent::InputHandled {
16461 utf16_range_to_replace: range_to_replace,
16462 text: text.into(),
16463 });
16464
16465 if let Some(ranges) = ranges_to_replace {
16466 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16467 }
16468
16469 let marked_ranges = {
16470 let snapshot = this.buffer.read(cx).read(cx);
16471 this.selections
16472 .disjoint_anchors()
16473 .iter()
16474 .map(|selection| {
16475 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16476 })
16477 .collect::<Vec<_>>()
16478 };
16479
16480 if text.is_empty() {
16481 this.unmark_text(window, cx);
16482 } else {
16483 this.highlight_text::<InputComposition>(
16484 marked_ranges.clone(),
16485 HighlightStyle {
16486 underline: Some(UnderlineStyle {
16487 thickness: px(1.),
16488 color: None,
16489 wavy: false,
16490 }),
16491 ..Default::default()
16492 },
16493 cx,
16494 );
16495 }
16496
16497 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16498 let use_autoclose = this.use_autoclose;
16499 let use_auto_surround = this.use_auto_surround;
16500 this.set_use_autoclose(false);
16501 this.set_use_auto_surround(false);
16502 this.handle_input(text, window, cx);
16503 this.set_use_autoclose(use_autoclose);
16504 this.set_use_auto_surround(use_auto_surround);
16505
16506 if let Some(new_selected_range) = new_selected_range_utf16 {
16507 let snapshot = this.buffer.read(cx).read(cx);
16508 let new_selected_ranges = marked_ranges
16509 .into_iter()
16510 .map(|marked_range| {
16511 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16512 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16513 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16514 snapshot.clip_offset_utf16(new_start, Bias::Left)
16515 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16516 })
16517 .collect::<Vec<_>>();
16518
16519 drop(snapshot);
16520 this.change_selections(None, window, cx, |selections| {
16521 selections.select_ranges(new_selected_ranges)
16522 });
16523 }
16524 });
16525
16526 self.ime_transaction = self.ime_transaction.or(transaction);
16527 if let Some(transaction) = self.ime_transaction {
16528 self.buffer.update(cx, |buffer, cx| {
16529 buffer.group_until_transaction(transaction, cx);
16530 });
16531 }
16532
16533 if self.text_highlights::<InputComposition>(cx).is_none() {
16534 self.ime_transaction.take();
16535 }
16536 }
16537
16538 fn bounds_for_range(
16539 &mut self,
16540 range_utf16: Range<usize>,
16541 element_bounds: gpui::Bounds<Pixels>,
16542 window: &mut Window,
16543 cx: &mut Context<Self>,
16544 ) -> Option<gpui::Bounds<Pixels>> {
16545 let text_layout_details = self.text_layout_details(window);
16546 let gpui::Size {
16547 width: em_width,
16548 height: line_height,
16549 } = self.character_size(window);
16550
16551 let snapshot = self.snapshot(window, cx);
16552 let scroll_position = snapshot.scroll_position();
16553 let scroll_left = scroll_position.x * em_width;
16554
16555 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16556 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16557 + self.gutter_dimensions.width
16558 + self.gutter_dimensions.margin;
16559 let y = line_height * (start.row().as_f32() - scroll_position.y);
16560
16561 Some(Bounds {
16562 origin: element_bounds.origin + point(x, y),
16563 size: size(em_width, line_height),
16564 })
16565 }
16566
16567 fn character_index_for_point(
16568 &mut self,
16569 point: gpui::Point<Pixels>,
16570 _window: &mut Window,
16571 _cx: &mut Context<Self>,
16572 ) -> Option<usize> {
16573 let position_map = self.last_position_map.as_ref()?;
16574 if !position_map.text_hitbox.contains(&point) {
16575 return None;
16576 }
16577 let display_point = position_map.point_for_position(point).previous_valid;
16578 let anchor = position_map
16579 .snapshot
16580 .display_point_to_anchor(display_point, Bias::Left);
16581 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16582 Some(utf16_offset.0)
16583 }
16584}
16585
16586trait SelectionExt {
16587 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16588 fn spanned_rows(
16589 &self,
16590 include_end_if_at_line_start: bool,
16591 map: &DisplaySnapshot,
16592 ) -> Range<MultiBufferRow>;
16593}
16594
16595impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16596 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16597 let start = self
16598 .start
16599 .to_point(&map.buffer_snapshot)
16600 .to_display_point(map);
16601 let end = self
16602 .end
16603 .to_point(&map.buffer_snapshot)
16604 .to_display_point(map);
16605 if self.reversed {
16606 end..start
16607 } else {
16608 start..end
16609 }
16610 }
16611
16612 fn spanned_rows(
16613 &self,
16614 include_end_if_at_line_start: bool,
16615 map: &DisplaySnapshot,
16616 ) -> Range<MultiBufferRow> {
16617 let start = self.start.to_point(&map.buffer_snapshot);
16618 let mut end = self.end.to_point(&map.buffer_snapshot);
16619 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16620 end.row -= 1;
16621 }
16622
16623 let buffer_start = map.prev_line_boundary(start).0;
16624 let buffer_end = map.next_line_boundary(end).0;
16625 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16626 }
16627}
16628
16629impl<T: InvalidationRegion> InvalidationStack<T> {
16630 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16631 where
16632 S: Clone + ToOffset,
16633 {
16634 while let Some(region) = self.last() {
16635 let all_selections_inside_invalidation_ranges =
16636 if selections.len() == region.ranges().len() {
16637 selections
16638 .iter()
16639 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16640 .all(|(selection, invalidation_range)| {
16641 let head = selection.head().to_offset(buffer);
16642 invalidation_range.start <= head && invalidation_range.end >= head
16643 })
16644 } else {
16645 false
16646 };
16647
16648 if all_selections_inside_invalidation_ranges {
16649 break;
16650 } else {
16651 self.pop();
16652 }
16653 }
16654 }
16655}
16656
16657impl<T> Default for InvalidationStack<T> {
16658 fn default() -> Self {
16659 Self(Default::default())
16660 }
16661}
16662
16663impl<T> Deref for InvalidationStack<T> {
16664 type Target = Vec<T>;
16665
16666 fn deref(&self) -> &Self::Target {
16667 &self.0
16668 }
16669}
16670
16671impl<T> DerefMut for InvalidationStack<T> {
16672 fn deref_mut(&mut self) -> &mut Self::Target {
16673 &mut self.0
16674 }
16675}
16676
16677impl InvalidationRegion for SnippetState {
16678 fn ranges(&self) -> &[Range<Anchor>] {
16679 &self.ranges[self.active_index]
16680 }
16681}
16682
16683pub fn diagnostic_block_renderer(
16684 diagnostic: Diagnostic,
16685 max_message_rows: Option<u8>,
16686 allow_closing: bool,
16687 _is_valid: bool,
16688) -> RenderBlock {
16689 let (text_without_backticks, code_ranges) =
16690 highlight_diagnostic_message(&diagnostic, max_message_rows);
16691
16692 Arc::new(move |cx: &mut BlockContext| {
16693 let group_id: SharedString = cx.block_id.to_string().into();
16694
16695 let mut text_style = cx.window.text_style().clone();
16696 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16697 let theme_settings = ThemeSettings::get_global(cx);
16698 text_style.font_family = theme_settings.buffer_font.family.clone();
16699 text_style.font_style = theme_settings.buffer_font.style;
16700 text_style.font_features = theme_settings.buffer_font.features.clone();
16701 text_style.font_weight = theme_settings.buffer_font.weight;
16702
16703 let multi_line_diagnostic = diagnostic.message.contains('\n');
16704
16705 let buttons = |diagnostic: &Diagnostic| {
16706 if multi_line_diagnostic {
16707 v_flex()
16708 } else {
16709 h_flex()
16710 }
16711 .when(allow_closing, |div| {
16712 div.children(diagnostic.is_primary.then(|| {
16713 IconButton::new("close-block", IconName::XCircle)
16714 .icon_color(Color::Muted)
16715 .size(ButtonSize::Compact)
16716 .style(ButtonStyle::Transparent)
16717 .visible_on_hover(group_id.clone())
16718 .on_click(move |_click, window, cx| {
16719 window.dispatch_action(Box::new(Cancel), cx)
16720 })
16721 .tooltip(|window, cx| {
16722 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16723 })
16724 }))
16725 })
16726 .child(
16727 IconButton::new("copy-block", IconName::Copy)
16728 .icon_color(Color::Muted)
16729 .size(ButtonSize::Compact)
16730 .style(ButtonStyle::Transparent)
16731 .visible_on_hover(group_id.clone())
16732 .on_click({
16733 let message = diagnostic.message.clone();
16734 move |_click, _, cx| {
16735 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16736 }
16737 })
16738 .tooltip(Tooltip::text("Copy diagnostic message")),
16739 )
16740 };
16741
16742 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16743 AvailableSpace::min_size(),
16744 cx.window,
16745 cx.app,
16746 );
16747
16748 h_flex()
16749 .id(cx.block_id)
16750 .group(group_id.clone())
16751 .relative()
16752 .size_full()
16753 .block_mouse_down()
16754 .pl(cx.gutter_dimensions.width)
16755 .w(cx.max_width - cx.gutter_dimensions.full_width())
16756 .child(
16757 div()
16758 .flex()
16759 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16760 .flex_shrink(),
16761 )
16762 .child(buttons(&diagnostic))
16763 .child(div().flex().flex_shrink_0().child(
16764 StyledText::new(text_without_backticks.clone()).with_highlights(
16765 &text_style,
16766 code_ranges.iter().map(|range| {
16767 (
16768 range.clone(),
16769 HighlightStyle {
16770 font_weight: Some(FontWeight::BOLD),
16771 ..Default::default()
16772 },
16773 )
16774 }),
16775 ),
16776 ))
16777 .into_any_element()
16778 })
16779}
16780
16781fn inline_completion_edit_text(
16782 current_snapshot: &BufferSnapshot,
16783 edits: &[(Range<Anchor>, String)],
16784 edit_preview: &EditPreview,
16785 include_deletions: bool,
16786 cx: &App,
16787) -> HighlightedText {
16788 let edits = edits
16789 .iter()
16790 .map(|(anchor, text)| {
16791 (
16792 anchor.start.text_anchor..anchor.end.text_anchor,
16793 text.clone(),
16794 )
16795 })
16796 .collect::<Vec<_>>();
16797
16798 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16799}
16800
16801pub fn highlight_diagnostic_message(
16802 diagnostic: &Diagnostic,
16803 mut max_message_rows: Option<u8>,
16804) -> (SharedString, Vec<Range<usize>>) {
16805 let mut text_without_backticks = String::new();
16806 let mut code_ranges = Vec::new();
16807
16808 if let Some(source) = &diagnostic.source {
16809 text_without_backticks.push_str(source);
16810 code_ranges.push(0..source.len());
16811 text_without_backticks.push_str(": ");
16812 }
16813
16814 let mut prev_offset = 0;
16815 let mut in_code_block = false;
16816 let has_row_limit = max_message_rows.is_some();
16817 let mut newline_indices = diagnostic
16818 .message
16819 .match_indices('\n')
16820 .filter(|_| has_row_limit)
16821 .map(|(ix, _)| ix)
16822 .fuse()
16823 .peekable();
16824
16825 for (quote_ix, _) in diagnostic
16826 .message
16827 .match_indices('`')
16828 .chain([(diagnostic.message.len(), "")])
16829 {
16830 let mut first_newline_ix = None;
16831 let mut last_newline_ix = None;
16832 while let Some(newline_ix) = newline_indices.peek() {
16833 if *newline_ix < quote_ix {
16834 if first_newline_ix.is_none() {
16835 first_newline_ix = Some(*newline_ix);
16836 }
16837 last_newline_ix = Some(*newline_ix);
16838
16839 if let Some(rows_left) = &mut max_message_rows {
16840 if *rows_left == 0 {
16841 break;
16842 } else {
16843 *rows_left -= 1;
16844 }
16845 }
16846 let _ = newline_indices.next();
16847 } else {
16848 break;
16849 }
16850 }
16851 let prev_len = text_without_backticks.len();
16852 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16853 text_without_backticks.push_str(new_text);
16854 if in_code_block {
16855 code_ranges.push(prev_len..text_without_backticks.len());
16856 }
16857 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16858 in_code_block = !in_code_block;
16859 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16860 text_without_backticks.push_str("...");
16861 break;
16862 }
16863 }
16864
16865 (text_without_backticks.into(), code_ranges)
16866}
16867
16868fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16869 match severity {
16870 DiagnosticSeverity::ERROR => colors.error,
16871 DiagnosticSeverity::WARNING => colors.warning,
16872 DiagnosticSeverity::INFORMATION => colors.info,
16873 DiagnosticSeverity::HINT => colors.info,
16874 _ => colors.ignored,
16875 }
16876}
16877
16878pub fn styled_runs_for_code_label<'a>(
16879 label: &'a CodeLabel,
16880 syntax_theme: &'a theme::SyntaxTheme,
16881) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16882 let fade_out = HighlightStyle {
16883 fade_out: Some(0.35),
16884 ..Default::default()
16885 };
16886
16887 let mut prev_end = label.filter_range.end;
16888 label
16889 .runs
16890 .iter()
16891 .enumerate()
16892 .flat_map(move |(ix, (range, highlight_id))| {
16893 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16894 style
16895 } else {
16896 return Default::default();
16897 };
16898 let mut muted_style = style;
16899 muted_style.highlight(fade_out);
16900
16901 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16902 if range.start >= label.filter_range.end {
16903 if range.start > prev_end {
16904 runs.push((prev_end..range.start, fade_out));
16905 }
16906 runs.push((range.clone(), muted_style));
16907 } else if range.end <= label.filter_range.end {
16908 runs.push((range.clone(), style));
16909 } else {
16910 runs.push((range.start..label.filter_range.end, style));
16911 runs.push((label.filter_range.end..range.end, muted_style));
16912 }
16913 prev_end = cmp::max(prev_end, range.end);
16914
16915 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16916 runs.push((prev_end..label.text.len(), fade_out));
16917 }
16918
16919 runs
16920 })
16921}
16922
16923pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16924 let mut prev_index = 0;
16925 let mut prev_codepoint: Option<char> = None;
16926 text.char_indices()
16927 .chain([(text.len(), '\0')])
16928 .filter_map(move |(index, codepoint)| {
16929 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16930 let is_boundary = index == text.len()
16931 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16932 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16933 if is_boundary {
16934 let chunk = &text[prev_index..index];
16935 prev_index = index;
16936 Some(chunk)
16937 } else {
16938 None
16939 }
16940 })
16941}
16942
16943pub trait RangeToAnchorExt: Sized {
16944 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16945
16946 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16947 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16948 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16949 }
16950}
16951
16952impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16953 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16954 let start_offset = self.start.to_offset(snapshot);
16955 let end_offset = self.end.to_offset(snapshot);
16956 if start_offset == end_offset {
16957 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16958 } else {
16959 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16960 }
16961 }
16962}
16963
16964pub trait RowExt {
16965 fn as_f32(&self) -> f32;
16966
16967 fn next_row(&self) -> Self;
16968
16969 fn previous_row(&self) -> Self;
16970
16971 fn minus(&self, other: Self) -> u32;
16972}
16973
16974impl RowExt for DisplayRow {
16975 fn as_f32(&self) -> f32 {
16976 self.0 as f32
16977 }
16978
16979 fn next_row(&self) -> Self {
16980 Self(self.0 + 1)
16981 }
16982
16983 fn previous_row(&self) -> Self {
16984 Self(self.0.saturating_sub(1))
16985 }
16986
16987 fn minus(&self, other: Self) -> u32 {
16988 self.0 - other.0
16989 }
16990}
16991
16992impl RowExt for MultiBufferRow {
16993 fn as_f32(&self) -> f32 {
16994 self.0 as f32
16995 }
16996
16997 fn next_row(&self) -> Self {
16998 Self(self.0 + 1)
16999 }
17000
17001 fn previous_row(&self) -> Self {
17002 Self(self.0.saturating_sub(1))
17003 }
17004
17005 fn minus(&self, other: Self) -> u32 {
17006 self.0 - other.0
17007 }
17008}
17009
17010trait RowRangeExt {
17011 type Row;
17012
17013 fn len(&self) -> usize;
17014
17015 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17016}
17017
17018impl RowRangeExt for Range<MultiBufferRow> {
17019 type Row = MultiBufferRow;
17020
17021 fn len(&self) -> usize {
17022 (self.end.0 - self.start.0) as usize
17023 }
17024
17025 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17026 (self.start.0..self.end.0).map(MultiBufferRow)
17027 }
17028}
17029
17030impl RowRangeExt for Range<DisplayRow> {
17031 type Row = DisplayRow;
17032
17033 fn len(&self) -> usize {
17034 (self.end.0 - self.start.0) as usize
17035 }
17036
17037 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17038 (self.start.0..self.end.0).map(DisplayRow)
17039 }
17040}
17041
17042/// If select range has more than one line, we
17043/// just point the cursor to range.start.
17044fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17045 if range.start.row == range.end.row {
17046 range
17047 } else {
17048 range.start..range.start
17049 }
17050}
17051pub struct KillRing(ClipboardItem);
17052impl Global for KillRing {}
17053
17054const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17055
17056fn all_edits_insertions_or_deletions(
17057 edits: &Vec<(Range<Anchor>, String)>,
17058 snapshot: &MultiBufferSnapshot,
17059) -> bool {
17060 let mut all_insertions = true;
17061 let mut all_deletions = true;
17062
17063 for (range, new_text) in edits.iter() {
17064 let range_is_empty = range.to_offset(&snapshot).is_empty();
17065 let text_is_empty = new_text.is_empty();
17066
17067 if range_is_empty != text_is_empty {
17068 if range_is_empty {
17069 all_deletions = false;
17070 } else {
17071 all_insertions = false;
17072 }
17073 } else {
17074 return false;
17075 }
17076
17077 if !all_insertions && !all_deletions {
17078 return false;
17079 }
17080 }
17081 all_insertions || all_deletions
17082}