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 jsx_tag_auto_close;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51pub(crate) use actions::*;
52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use buffer_diff::DiffHunkStatus;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63use editor_settings::GoToDefinitionFallback;
64pub use editor_settings::{
65 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use feature_flags::{Debugger, FeatureFlagAppExt};
73use futures::{
74 future::{self, join, Shared},
75 FutureExt,
76};
77use fuzzy::StringMatchCandidate;
78
79use ::git::Restore;
80use code_context_menus::{
81 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
82 CompletionsMenu, ContextMenuOrigin,
83};
84use git::blame::GitBlame;
85use gpui::{
86 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
87 AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
88 Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
89 EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
90 Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
91 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
92 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
93 WeakEntity, WeakFocusHandle, Window,
94};
95use highlight_matching_bracket::refresh_matching_bracket_highlights;
96use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
97use hover_popover::{hide_hover, HoverState};
98use indent_guides::ActiveIndentGuidesState;
99use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
100pub use inline_completion::Direction;
101use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
102pub use items::MAX_TAB_TITLE_LEN;
103use itertools::Itertools;
104use language::{
105 language_settings::{
106 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
107 WordsCompletionMode,
108 },
109 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
110 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
111 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
112 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
113};
114use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
115use linked_editing_ranges::refresh_linked_ranges;
116use mouse_context_menu::MouseContextMenu;
117use persistence::DB;
118use project::{
119 debugger::breakpoint_store::{
120 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
121 },
122 ProjectPath,
123};
124
125pub use proposed_changes_editor::{
126 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
127};
128use smallvec::smallvec;
129use std::{cell::OnceCell, iter::Peekable};
130use task::{ResolvedTask, TaskTemplate, TaskVariables};
131
132pub use lsp::CompletionContext;
133use lsp::{
134 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
135 InsertTextFormat, LanguageServerId, LanguageServerName,
136};
137
138use language::BufferSnapshot;
139use movement::TextLayoutDetails;
140pub use multi_buffer::{
141 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
142 ToOffset, ToPoint,
143};
144use multi_buffer::{
145 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
146 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
147};
148use parking_lot::Mutex;
149use project::{
150 debugger::breakpoint_store::{Breakpoint, BreakpointKind},
151 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
152 project_settings::{GitGutterSetting, ProjectSettings},
153 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
154 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
155 TaskSourceKind,
156};
157use rand::prelude::*;
158use rpc::{proto::*, ErrorExt};
159use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
160use selections_collection::{
161 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
162};
163use serde::{Deserialize, Serialize};
164use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
165use smallvec::SmallVec;
166use snippet::Snippet;
167use std::sync::Arc;
168use std::{
169 any::TypeId,
170 borrow::Cow,
171 cell::RefCell,
172 cmp::{self, Ordering, Reverse},
173 mem,
174 num::NonZeroU32,
175 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
176 path::{Path, PathBuf},
177 rc::Rc,
178 time::{Duration, Instant},
179};
180pub use sum_tree::Bias;
181use sum_tree::TreeMap;
182use text::{BufferId, OffsetUtf16, Rope};
183use theme::{
184 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
185 ThemeColors, ThemeSettings,
186};
187use ui::{
188 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
189 Tooltip,
190};
191use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
192use workspace::{
193 item::{ItemHandle, PreviewTabsSettings},
194 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
195 searchable::SearchEvent,
196 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
197 RestoreOnStartupBehavior, SplitDirection, TabBarSettings, Toast, ViewId, Workspace,
198 WorkspaceId, WorkspaceSettings, SERIALIZATION_THROTTLE_TIME,
199};
200
201use crate::hover_links::{find_url, find_url_from_range};
202use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
203
204pub const FILE_HEADER_HEIGHT: u32 = 2;
205pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
206pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
207const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
208const MAX_LINE_LEN: usize = 1024;
209const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
210const MAX_SELECTION_HISTORY_LEN: usize = 1024;
211pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
212#[doc(hidden)]
213pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
214
215pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
216pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
217pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
218
219pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
220pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
221pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
222
223const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
224 alt: true,
225 shift: true,
226 control: false,
227 platform: false,
228 function: false,
229};
230
231#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
232pub enum InlayId {
233 InlineCompletion(usize),
234 Hint(usize),
235}
236
237impl InlayId {
238 fn id(&self) -> usize {
239 match self {
240 Self::InlineCompletion(id) => *id,
241 Self::Hint(id) => *id,
242 }
243 }
244}
245
246pub enum DebugCurrentRowHighlight {}
247enum DocumentHighlightRead {}
248enum DocumentHighlightWrite {}
249enum InputComposition {}
250enum SelectedTextHighlight {}
251
252#[derive(Debug, Copy, Clone, PartialEq, Eq)]
253pub enum Navigated {
254 Yes,
255 No,
256}
257
258impl Navigated {
259 pub fn from_bool(yes: bool) -> Navigated {
260 if yes {
261 Navigated::Yes
262 } else {
263 Navigated::No
264 }
265 }
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
269enum DisplayDiffHunk {
270 Folded {
271 display_row: DisplayRow,
272 },
273 Unfolded {
274 is_created_file: bool,
275 diff_base_byte_range: Range<usize>,
276 display_row_range: Range<DisplayRow>,
277 multi_buffer_range: Range<Anchor>,
278 status: DiffHunkStatus,
279 },
280}
281
282pub fn init_settings(cx: &mut App) {
283 EditorSettings::register(cx);
284}
285
286pub fn init(cx: &mut App) {
287 init_settings(cx);
288
289 workspace::register_project_item::<Editor>(cx);
290 workspace::FollowableViewRegistry::register::<Editor>(cx);
291 workspace::register_serializable_item::<Editor>(cx);
292
293 cx.observe_new(
294 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
295 workspace.register_action(Editor::new_file);
296 workspace.register_action(Editor::new_file_vertical);
297 workspace.register_action(Editor::new_file_horizontal);
298 workspace.register_action(Editor::cancel_language_server_work);
299 },
300 )
301 .detach();
302
303 cx.on_action(move |_: &workspace::NewFile, cx| {
304 let app_state = workspace::AppState::global(cx);
305 if let Some(app_state) = app_state.upgrade() {
306 workspace::open_new(
307 Default::default(),
308 app_state,
309 cx,
310 |workspace, window, cx| {
311 Editor::new_file(workspace, &Default::default(), window, cx)
312 },
313 )
314 .detach();
315 }
316 });
317 cx.on_action(move |_: &workspace::NewWindow, cx| {
318 let app_state = workspace::AppState::global(cx);
319 if let Some(app_state) = app_state.upgrade() {
320 workspace::open_new(
321 Default::default(),
322 app_state,
323 cx,
324 |workspace, window, cx| {
325 cx.activate(true);
326 Editor::new_file(workspace, &Default::default(), window, cx)
327 },
328 )
329 .detach();
330 }
331 });
332}
333
334pub struct SearchWithinRange;
335
336trait InvalidationRegion {
337 fn ranges(&self) -> &[Range<Anchor>];
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum SelectPhase {
342 Begin {
343 position: DisplayPoint,
344 add: bool,
345 click_count: usize,
346 },
347 BeginColumnar {
348 position: DisplayPoint,
349 reset: bool,
350 goal_column: u32,
351 },
352 Extend {
353 position: DisplayPoint,
354 click_count: usize,
355 },
356 Update {
357 position: DisplayPoint,
358 goal_column: u32,
359 scroll_delta: gpui::Point<f32>,
360 },
361 End,
362}
363
364#[derive(Clone, Debug)]
365pub enum SelectMode {
366 Character,
367 Word(Range<Anchor>),
368 Line(Range<Anchor>),
369 All,
370}
371
372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
373pub enum EditorMode {
374 SingleLine { auto_width: bool },
375 AutoHeight { max_lines: usize },
376 Full,
377}
378
379#[derive(Copy, Clone, Debug)]
380pub enum SoftWrap {
381 /// Prefer not to wrap at all.
382 ///
383 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
384 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
385 GitDiff,
386 /// Prefer a single line generally, unless an overly long line is encountered.
387 None,
388 /// Soft wrap lines that exceed the editor width.
389 EditorWidth,
390 /// Soft wrap lines at the preferred line length.
391 Column(u32),
392 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
393 Bounded(u32),
394}
395
396#[derive(Clone)]
397pub struct EditorStyle {
398 pub background: Hsla,
399 pub local_player: PlayerColor,
400 pub text: TextStyle,
401 pub scrollbar_width: Pixels,
402 pub syntax: Arc<SyntaxTheme>,
403 pub status: StatusColors,
404 pub inlay_hints_style: HighlightStyle,
405 pub inline_completion_styles: InlineCompletionStyles,
406 pub unnecessary_code_fade: f32,
407}
408
409impl Default for EditorStyle {
410 fn default() -> Self {
411 Self {
412 background: Hsla::default(),
413 local_player: PlayerColor::default(),
414 text: TextStyle::default(),
415 scrollbar_width: Pixels::default(),
416 syntax: Default::default(),
417 // HACK: Status colors don't have a real default.
418 // We should look into removing the status colors from the editor
419 // style and retrieve them directly from the theme.
420 status: StatusColors::dark(),
421 inlay_hints_style: HighlightStyle::default(),
422 inline_completion_styles: InlineCompletionStyles {
423 insertion: HighlightStyle::default(),
424 whitespace: HighlightStyle::default(),
425 },
426 unnecessary_code_fade: Default::default(),
427 }
428 }
429}
430
431pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
432 let show_background = language_settings::language_settings(None, None, cx)
433 .inlay_hints
434 .show_background;
435
436 HighlightStyle {
437 color: Some(cx.theme().status().hint),
438 background_color: show_background.then(|| cx.theme().status().hint_background),
439 ..HighlightStyle::default()
440 }
441}
442
443pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
444 InlineCompletionStyles {
445 insertion: HighlightStyle {
446 color: Some(cx.theme().status().predictive),
447 ..HighlightStyle::default()
448 },
449 whitespace: HighlightStyle {
450 background_color: Some(cx.theme().status().created_background),
451 ..HighlightStyle::default()
452 },
453 }
454}
455
456type CompletionId = usize;
457
458pub(crate) enum EditDisplayMode {
459 TabAccept,
460 DiffPopover,
461 Inline,
462}
463
464enum InlineCompletion {
465 Edit {
466 edits: Vec<(Range<Anchor>, String)>,
467 edit_preview: Option<EditPreview>,
468 display_mode: EditDisplayMode,
469 snapshot: BufferSnapshot,
470 },
471 Move {
472 target: Anchor,
473 snapshot: BufferSnapshot,
474 },
475}
476
477struct InlineCompletionState {
478 inlay_ids: Vec<InlayId>,
479 completion: InlineCompletion,
480 completion_id: Option<SharedString>,
481 invalidation_range: Range<Anchor>,
482}
483
484enum EditPredictionSettings {
485 Disabled,
486 Enabled {
487 show_in_menu: bool,
488 preview_requires_modifier: bool,
489 },
490}
491
492enum InlineCompletionHighlight {}
493
494#[derive(Debug, Clone)]
495struct InlineDiagnostic {
496 message: SharedString,
497 group_id: usize,
498 is_primary: bool,
499 start: Point,
500 severity: DiagnosticSeverity,
501}
502
503pub enum MenuInlineCompletionsPolicy {
504 Never,
505 ByProvider,
506}
507
508pub enum EditPredictionPreview {
509 /// Modifier is not pressed
510 Inactive { released_too_fast: bool },
511 /// Modifier pressed
512 Active {
513 since: Instant,
514 previous_scroll_position: Option<ScrollAnchor>,
515 },
516}
517
518impl EditPredictionPreview {
519 pub fn released_too_fast(&self) -> bool {
520 match self {
521 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
522 EditPredictionPreview::Active { .. } => false,
523 }
524 }
525
526 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
527 if let EditPredictionPreview::Active {
528 previous_scroll_position,
529 ..
530 } = self
531 {
532 *previous_scroll_position = scroll_position;
533 }
534 }
535}
536
537pub struct ContextMenuOptions {
538 pub min_entries_visible: usize,
539 pub max_entries_visible: usize,
540 pub placement: Option<ContextMenuPlacement>,
541}
542
543#[derive(Debug, Clone, PartialEq, Eq)]
544pub enum ContextMenuPlacement {
545 Above,
546 Below,
547}
548
549#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
550struct EditorActionId(usize);
551
552impl EditorActionId {
553 pub fn post_inc(&mut self) -> Self {
554 let answer = self.0;
555
556 *self = Self(answer + 1);
557
558 Self(answer)
559 }
560}
561
562// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
563// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
564
565type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
566type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
567
568#[derive(Default)]
569struct ScrollbarMarkerState {
570 scrollbar_size: Size<Pixels>,
571 dirty: bool,
572 markers: Arc<[PaintQuad]>,
573 pending_refresh: Option<Task<Result<()>>>,
574}
575
576impl ScrollbarMarkerState {
577 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
578 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
579 }
580}
581
582#[derive(Clone, Debug)]
583struct RunnableTasks {
584 templates: Vec<(TaskSourceKind, TaskTemplate)>,
585 offset: multi_buffer::Anchor,
586 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
587 column: u32,
588 // Values of all named captures, including those starting with '_'
589 extra_variables: HashMap<String, String>,
590 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
591 context_range: Range<BufferOffset>,
592}
593
594impl RunnableTasks {
595 fn resolve<'a>(
596 &'a self,
597 cx: &'a task::TaskContext,
598 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
599 self.templates.iter().filter_map(|(kind, template)| {
600 template
601 .resolve_task(&kind.to_id_base(), cx)
602 .map(|task| (kind.clone(), task))
603 })
604 }
605}
606
607#[derive(Clone)]
608struct ResolvedTasks {
609 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
610 position: Anchor,
611}
612
613#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
614struct BufferOffset(usize);
615
616// Addons allow storing per-editor state in other crates (e.g. Vim)
617pub trait Addon: 'static {
618 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
619
620 fn render_buffer_header_controls(
621 &self,
622 _: &ExcerptInfo,
623 _: &Window,
624 _: &App,
625 ) -> Option<AnyElement> {
626 None
627 }
628
629 fn to_any(&self) -> &dyn std::any::Any;
630}
631
632/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
633///
634/// See the [module level documentation](self) for more information.
635pub struct Editor {
636 focus_handle: FocusHandle,
637 last_focused_descendant: Option<WeakFocusHandle>,
638 /// The text buffer being edited
639 buffer: Entity<MultiBuffer>,
640 /// Map of how text in the buffer should be displayed.
641 /// Handles soft wraps, folds, fake inlay text insertions, etc.
642 pub display_map: Entity<DisplayMap>,
643 pub selections: SelectionsCollection,
644 pub scroll_manager: ScrollManager,
645 /// When inline assist editors are linked, they all render cursors because
646 /// typing enters text into each of them, even the ones that aren't focused.
647 pub(crate) show_cursor_when_unfocused: bool,
648 columnar_selection_tail: Option<Anchor>,
649 add_selections_state: Option<AddSelectionsState>,
650 select_next_state: Option<SelectNextState>,
651 select_prev_state: Option<SelectNextState>,
652 selection_history: SelectionHistory,
653 autoclose_regions: Vec<AutocloseRegion>,
654 snippet_stack: InvalidationStack<SnippetState>,
655 select_syntax_node_history: SelectSyntaxNodeHistory,
656 ime_transaction: Option<TransactionId>,
657 active_diagnostics: Option<ActiveDiagnosticGroup>,
658 show_inline_diagnostics: bool,
659 inline_diagnostics_update: Task<()>,
660 inline_diagnostics_enabled: bool,
661 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
662 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
663 hard_wrap: Option<usize>,
664
665 // TODO: make this a access method
666 pub project: Option<Entity<Project>>,
667 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
668 completion_provider: Option<Box<dyn CompletionProvider>>,
669 collaboration_hub: Option<Box<dyn CollaborationHub>>,
670 blink_manager: Entity<BlinkManager>,
671 show_cursor_names: bool,
672 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
673 pub show_local_selections: bool,
674 mode: EditorMode,
675 show_breadcrumbs: bool,
676 show_gutter: bool,
677 show_scrollbars: bool,
678 show_line_numbers: Option<bool>,
679 use_relative_line_numbers: Option<bool>,
680 show_git_diff_gutter: Option<bool>,
681 show_code_actions: Option<bool>,
682 show_runnables: Option<bool>,
683 show_breakpoints: Option<bool>,
684 show_wrap_guides: Option<bool>,
685 show_indent_guides: Option<bool>,
686 placeholder_text: Option<Arc<str>>,
687 highlight_order: usize,
688 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
689 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
690 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
691 scrollbar_marker_state: ScrollbarMarkerState,
692 active_indent_guides_state: ActiveIndentGuidesState,
693 nav_history: Option<ItemNavHistory>,
694 context_menu: RefCell<Option<CodeContextMenu>>,
695 context_menu_options: Option<ContextMenuOptions>,
696 mouse_context_menu: Option<MouseContextMenu>,
697 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
698 signature_help_state: SignatureHelpState,
699 auto_signature_help: Option<bool>,
700 find_all_references_task_sources: Vec<Anchor>,
701 next_completion_id: CompletionId,
702 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
703 code_actions_task: Option<Task<Result<()>>>,
704 selection_highlight_task: Option<Task<()>>,
705 document_highlights_task: Option<Task<()>>,
706 linked_editing_range_task: Option<Task<Option<()>>>,
707 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
708 pending_rename: Option<RenameState>,
709 searchable: bool,
710 cursor_shape: CursorShape,
711 current_line_highlight: Option<CurrentLineHighlight>,
712 collapse_matches: bool,
713 autoindent_mode: Option<AutoindentMode>,
714 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
715 input_enabled: bool,
716 use_modal_editing: bool,
717 read_only: bool,
718 leader_peer_id: Option<PeerId>,
719 remote_id: Option<ViewId>,
720 hover_state: HoverState,
721 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
722 gutter_hovered: bool,
723 hovered_link_state: Option<HoveredLinkState>,
724 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
725 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
726 active_inline_completion: Option<InlineCompletionState>,
727 /// Used to prevent flickering as the user types while the menu is open
728 stale_inline_completion_in_menu: Option<InlineCompletionState>,
729 edit_prediction_settings: EditPredictionSettings,
730 inline_completions_hidden_for_vim_mode: bool,
731 show_inline_completions_override: Option<bool>,
732 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
733 edit_prediction_preview: EditPredictionPreview,
734 edit_prediction_indent_conflict: bool,
735 edit_prediction_requires_modifier_in_indent_conflict: bool,
736 inlay_hint_cache: InlayHintCache,
737 next_inlay_id: usize,
738 _subscriptions: Vec<Subscription>,
739 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
740 gutter_dimensions: GutterDimensions,
741 style: Option<EditorStyle>,
742 text_style_refinement: Option<TextStyleRefinement>,
743 next_editor_action_id: EditorActionId,
744 editor_actions:
745 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
746 use_autoclose: bool,
747 use_auto_surround: bool,
748 auto_replace_emoji_shortcode: bool,
749 jsx_tag_auto_close_enabled_in_any_buffer: bool,
750 show_git_blame_gutter: bool,
751 show_git_blame_inline: bool,
752 show_git_blame_inline_delay_task: Option<Task<()>>,
753 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
754 git_blame_inline_enabled: bool,
755 serialize_dirty_buffers: bool,
756 show_selection_menu: Option<bool>,
757 blame: Option<Entity<GitBlame>>,
758 blame_subscription: Option<Subscription>,
759 custom_context_menu: Option<
760 Box<
761 dyn 'static
762 + Fn(
763 &mut Self,
764 DisplayPoint,
765 &mut Window,
766 &mut Context<Self>,
767 ) -> Option<Entity<ui::ContextMenu>>,
768 >,
769 >,
770 last_bounds: Option<Bounds<Pixels>>,
771 last_position_map: Option<Rc<PositionMap>>,
772 expect_bounds_change: Option<Bounds<Pixels>>,
773 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
774 tasks_update_task: Option<Task<()>>,
775 pub breakpoint_store: Option<Entity<BreakpointStore>>,
776 /// Allow's a user to create a breakpoint by selecting this indicator
777 /// It should be None while a user is not hovering over the gutter
778 /// Otherwise it represents the point that the breakpoint will be shown
779 pub gutter_breakpoint_indicator: Option<DisplayPoint>,
780 in_project_search: bool,
781 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
782 breadcrumb_header: Option<String>,
783 focused_block: Option<FocusedBlock>,
784 next_scroll_position: NextScrollCursorCenterTopBottom,
785 addons: HashMap<TypeId, Box<dyn Addon>>,
786 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
787 load_diff_task: Option<Shared<Task<()>>>,
788 selection_mark_mode: bool,
789 toggle_fold_multiple_buffers: Task<()>,
790 _scroll_cursor_center_top_bottom_task: Task<()>,
791 serialize_selections: Task<()>,
792 serialize_folds: Task<()>,
793 mouse_cursor_hidden: bool,
794 hide_mouse_while_typing: bool,
795}
796
797#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
798enum NextScrollCursorCenterTopBottom {
799 #[default]
800 Center,
801 Top,
802 Bottom,
803}
804
805impl NextScrollCursorCenterTopBottom {
806 fn next(&self) -> Self {
807 match self {
808 Self::Center => Self::Top,
809 Self::Top => Self::Bottom,
810 Self::Bottom => Self::Center,
811 }
812 }
813}
814
815#[derive(Clone)]
816pub struct EditorSnapshot {
817 pub mode: EditorMode,
818 show_gutter: bool,
819 show_line_numbers: Option<bool>,
820 show_git_diff_gutter: Option<bool>,
821 show_code_actions: Option<bool>,
822 show_runnables: Option<bool>,
823 show_breakpoints: Option<bool>,
824 git_blame_gutter_max_author_length: Option<usize>,
825 pub display_snapshot: DisplaySnapshot,
826 pub placeholder_text: Option<Arc<str>>,
827 is_focused: bool,
828 scroll_anchor: ScrollAnchor,
829 ongoing_scroll: OngoingScroll,
830 current_line_highlight: CurrentLineHighlight,
831 gutter_hovered: bool,
832}
833
834const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
835
836#[derive(Default, Debug, Clone, Copy)]
837pub struct GutterDimensions {
838 pub left_padding: Pixels,
839 pub right_padding: Pixels,
840 pub width: Pixels,
841 pub margin: Pixels,
842 pub git_blame_entries_width: Option<Pixels>,
843}
844
845impl GutterDimensions {
846 /// The full width of the space taken up by the gutter.
847 pub fn full_width(&self) -> Pixels {
848 self.margin + self.width
849 }
850
851 /// The width of the space reserved for the fold indicators,
852 /// use alongside 'justify_end' and `gutter_width` to
853 /// right align content with the line numbers
854 pub fn fold_area_width(&self) -> Pixels {
855 self.margin + self.right_padding
856 }
857}
858
859#[derive(Debug)]
860pub struct RemoteSelection {
861 pub replica_id: ReplicaId,
862 pub selection: Selection<Anchor>,
863 pub cursor_shape: CursorShape,
864 pub peer_id: PeerId,
865 pub line_mode: bool,
866 pub participant_index: Option<ParticipantIndex>,
867 pub user_name: Option<SharedString>,
868}
869
870#[derive(Clone, Debug)]
871struct SelectionHistoryEntry {
872 selections: Arc<[Selection<Anchor>]>,
873 select_next_state: Option<SelectNextState>,
874 select_prev_state: Option<SelectNextState>,
875 add_selections_state: Option<AddSelectionsState>,
876}
877
878enum SelectionHistoryMode {
879 Normal,
880 Undoing,
881 Redoing,
882}
883
884#[derive(Clone, PartialEq, Eq, Hash)]
885struct HoveredCursor {
886 replica_id: u16,
887 selection_id: usize,
888}
889
890impl Default for SelectionHistoryMode {
891 fn default() -> Self {
892 Self::Normal
893 }
894}
895
896#[derive(Default)]
897struct SelectionHistory {
898 #[allow(clippy::type_complexity)]
899 selections_by_transaction:
900 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
901 mode: SelectionHistoryMode,
902 undo_stack: VecDeque<SelectionHistoryEntry>,
903 redo_stack: VecDeque<SelectionHistoryEntry>,
904}
905
906impl SelectionHistory {
907 fn insert_transaction(
908 &mut self,
909 transaction_id: TransactionId,
910 selections: Arc<[Selection<Anchor>]>,
911 ) {
912 self.selections_by_transaction
913 .insert(transaction_id, (selections, None));
914 }
915
916 #[allow(clippy::type_complexity)]
917 fn transaction(
918 &self,
919 transaction_id: TransactionId,
920 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
921 self.selections_by_transaction.get(&transaction_id)
922 }
923
924 #[allow(clippy::type_complexity)]
925 fn transaction_mut(
926 &mut self,
927 transaction_id: TransactionId,
928 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
929 self.selections_by_transaction.get_mut(&transaction_id)
930 }
931
932 fn push(&mut self, entry: SelectionHistoryEntry) {
933 if !entry.selections.is_empty() {
934 match self.mode {
935 SelectionHistoryMode::Normal => {
936 self.push_undo(entry);
937 self.redo_stack.clear();
938 }
939 SelectionHistoryMode::Undoing => self.push_redo(entry),
940 SelectionHistoryMode::Redoing => self.push_undo(entry),
941 }
942 }
943 }
944
945 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
946 if self
947 .undo_stack
948 .back()
949 .map_or(true, |e| e.selections != entry.selections)
950 {
951 self.undo_stack.push_back(entry);
952 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
953 self.undo_stack.pop_front();
954 }
955 }
956 }
957
958 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
959 if self
960 .redo_stack
961 .back()
962 .map_or(true, |e| e.selections != entry.selections)
963 {
964 self.redo_stack.push_back(entry);
965 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
966 self.redo_stack.pop_front();
967 }
968 }
969 }
970}
971
972struct RowHighlight {
973 index: usize,
974 range: Range<Anchor>,
975 color: Hsla,
976 should_autoscroll: bool,
977}
978
979#[derive(Clone, Debug)]
980struct AddSelectionsState {
981 above: bool,
982 stack: Vec<usize>,
983}
984
985#[derive(Clone)]
986struct SelectNextState {
987 query: AhoCorasick,
988 wordwise: bool,
989 done: bool,
990}
991
992impl std::fmt::Debug for SelectNextState {
993 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
994 f.debug_struct(std::any::type_name::<Self>())
995 .field("wordwise", &self.wordwise)
996 .field("done", &self.done)
997 .finish()
998 }
999}
1000
1001#[derive(Debug)]
1002struct AutocloseRegion {
1003 selection_id: usize,
1004 range: Range<Anchor>,
1005 pair: BracketPair,
1006}
1007
1008#[derive(Debug)]
1009struct SnippetState {
1010 ranges: Vec<Vec<Range<Anchor>>>,
1011 active_index: usize,
1012 choices: Vec<Option<Vec<String>>>,
1013}
1014
1015#[doc(hidden)]
1016pub struct RenameState {
1017 pub range: Range<Anchor>,
1018 pub old_name: Arc<str>,
1019 pub editor: Entity<Editor>,
1020 block_id: CustomBlockId,
1021}
1022
1023struct InvalidationStack<T>(Vec<T>);
1024
1025struct RegisteredInlineCompletionProvider {
1026 provider: Arc<dyn InlineCompletionProviderHandle>,
1027 _subscription: Subscription,
1028}
1029
1030#[derive(Debug, PartialEq, Eq)]
1031struct ActiveDiagnosticGroup {
1032 primary_range: Range<Anchor>,
1033 primary_message: String,
1034 group_id: usize,
1035 blocks: HashMap<CustomBlockId, Diagnostic>,
1036 is_valid: bool,
1037}
1038
1039#[derive(Serialize, Deserialize, Clone, Debug)]
1040pub struct ClipboardSelection {
1041 /// The number of bytes in this selection.
1042 pub len: usize,
1043 /// Whether this was a full-line selection.
1044 pub is_entire_line: bool,
1045 /// The indentation of the first line when this content was originally copied.
1046 pub first_line_indent: u32,
1047}
1048
1049// selections, scroll behavior, was newest selection reversed
1050type SelectSyntaxNodeHistoryState = (
1051 Box<[Selection<usize>]>,
1052 SelectSyntaxNodeScrollBehavior,
1053 bool,
1054);
1055
1056#[derive(Default)]
1057struct SelectSyntaxNodeHistory {
1058 stack: Vec<SelectSyntaxNodeHistoryState>,
1059 // disable temporarily to allow changing selections without losing the stack
1060 pub disable_clearing: bool,
1061}
1062
1063impl SelectSyntaxNodeHistory {
1064 pub fn try_clear(&mut self) {
1065 if !self.disable_clearing {
1066 self.stack.clear();
1067 }
1068 }
1069
1070 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1071 self.stack.push(selection);
1072 }
1073
1074 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1075 self.stack.pop()
1076 }
1077}
1078
1079enum SelectSyntaxNodeScrollBehavior {
1080 CursorTop,
1081 CenterSelection,
1082 CursorBottom,
1083}
1084
1085#[derive(Debug)]
1086pub(crate) struct NavigationData {
1087 cursor_anchor: Anchor,
1088 cursor_position: Point,
1089 scroll_anchor: ScrollAnchor,
1090 scroll_top_row: u32,
1091}
1092
1093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1094pub enum GotoDefinitionKind {
1095 Symbol,
1096 Declaration,
1097 Type,
1098 Implementation,
1099}
1100
1101#[derive(Debug, Clone)]
1102enum InlayHintRefreshReason {
1103 ModifiersChanged(bool),
1104 Toggle(bool),
1105 SettingsChange(InlayHintSettings),
1106 NewLinesShown,
1107 BufferEdited(HashSet<Arc<Language>>),
1108 RefreshRequested,
1109 ExcerptsRemoved(Vec<ExcerptId>),
1110}
1111
1112impl InlayHintRefreshReason {
1113 fn description(&self) -> &'static str {
1114 match self {
1115 Self::ModifiersChanged(_) => "modifiers changed",
1116 Self::Toggle(_) => "toggle",
1117 Self::SettingsChange(_) => "settings change",
1118 Self::NewLinesShown => "new lines shown",
1119 Self::BufferEdited(_) => "buffer edited",
1120 Self::RefreshRequested => "refresh requested",
1121 Self::ExcerptsRemoved(_) => "excerpts removed",
1122 }
1123 }
1124}
1125
1126pub enum FormatTarget {
1127 Buffers,
1128 Ranges(Vec<Range<MultiBufferPoint>>),
1129}
1130
1131pub(crate) struct FocusedBlock {
1132 id: BlockId,
1133 focus_handle: WeakFocusHandle,
1134}
1135
1136#[derive(Clone)]
1137enum JumpData {
1138 MultiBufferRow {
1139 row: MultiBufferRow,
1140 line_offset_from_top: u32,
1141 },
1142 MultiBufferPoint {
1143 excerpt_id: ExcerptId,
1144 position: Point,
1145 anchor: text::Anchor,
1146 line_offset_from_top: u32,
1147 },
1148}
1149
1150pub enum MultibufferSelectionMode {
1151 First,
1152 All,
1153}
1154
1155#[derive(Clone, Copy, Debug, Default)]
1156pub struct RewrapOptions {
1157 pub override_language_settings: bool,
1158 pub preserve_existing_whitespace: bool,
1159}
1160
1161impl Editor {
1162 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1163 let buffer = cx.new(|cx| Buffer::local("", cx));
1164 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1165 Self::new(
1166 EditorMode::SingleLine { auto_width: false },
1167 buffer,
1168 None,
1169 window,
1170 cx,
1171 )
1172 }
1173
1174 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1175 let buffer = cx.new(|cx| Buffer::local("", cx));
1176 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1177 Self::new(EditorMode::Full, buffer, None, window, cx)
1178 }
1179
1180 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1181 let buffer = cx.new(|cx| Buffer::local("", cx));
1182 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1183 Self::new(
1184 EditorMode::SingleLine { auto_width: true },
1185 buffer,
1186 None,
1187 window,
1188 cx,
1189 )
1190 }
1191
1192 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1193 let buffer = cx.new(|cx| Buffer::local("", cx));
1194 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1195 Self::new(
1196 EditorMode::AutoHeight { max_lines },
1197 buffer,
1198 None,
1199 window,
1200 cx,
1201 )
1202 }
1203
1204 pub fn for_buffer(
1205 buffer: Entity<Buffer>,
1206 project: Option<Entity<Project>>,
1207 window: &mut Window,
1208 cx: &mut Context<Self>,
1209 ) -> Self {
1210 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1211 Self::new(EditorMode::Full, buffer, project, window, cx)
1212 }
1213
1214 pub fn for_multibuffer(
1215 buffer: Entity<MultiBuffer>,
1216 project: Option<Entity<Project>>,
1217 window: &mut Window,
1218 cx: &mut Context<Self>,
1219 ) -> Self {
1220 Self::new(EditorMode::Full, buffer, project, window, cx)
1221 }
1222
1223 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1224 let mut clone = Self::new(
1225 self.mode,
1226 self.buffer.clone(),
1227 self.project.clone(),
1228 window,
1229 cx,
1230 );
1231 self.display_map.update(cx, |display_map, cx| {
1232 let snapshot = display_map.snapshot(cx);
1233 clone.display_map.update(cx, |display_map, cx| {
1234 display_map.set_state(&snapshot, cx);
1235 });
1236 });
1237 clone.folds_did_change(cx);
1238 clone.selections.clone_state(&self.selections);
1239 clone.scroll_manager.clone_state(&self.scroll_manager);
1240 clone.searchable = self.searchable;
1241 clone
1242 }
1243
1244 pub fn new(
1245 mode: EditorMode,
1246 buffer: Entity<MultiBuffer>,
1247 project: Option<Entity<Project>>,
1248 window: &mut Window,
1249 cx: &mut Context<Self>,
1250 ) -> Self {
1251 let style = window.text_style();
1252 let font_size = style.font_size.to_pixels(window.rem_size());
1253 let editor = cx.entity().downgrade();
1254 let fold_placeholder = FoldPlaceholder {
1255 constrain_width: true,
1256 render: Arc::new(move |fold_id, fold_range, cx| {
1257 let editor = editor.clone();
1258 div()
1259 .id(fold_id)
1260 .bg(cx.theme().colors().ghost_element_background)
1261 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1262 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1263 .rounded_xs()
1264 .size_full()
1265 .cursor_pointer()
1266 .child("⋯")
1267 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1268 .on_click(move |_, _window, cx| {
1269 editor
1270 .update(cx, |editor, cx| {
1271 editor.unfold_ranges(
1272 &[fold_range.start..fold_range.end],
1273 true,
1274 false,
1275 cx,
1276 );
1277 cx.stop_propagation();
1278 })
1279 .ok();
1280 })
1281 .into_any()
1282 }),
1283 merge_adjacent: true,
1284 ..Default::default()
1285 };
1286 let display_map = cx.new(|cx| {
1287 DisplayMap::new(
1288 buffer.clone(),
1289 style.font(),
1290 font_size,
1291 None,
1292 FILE_HEADER_HEIGHT,
1293 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1294 fold_placeholder,
1295 cx,
1296 )
1297 });
1298
1299 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1300
1301 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1302
1303 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1304 .then(|| language_settings::SoftWrap::None);
1305
1306 let mut project_subscriptions = Vec::new();
1307 if mode == EditorMode::Full {
1308 if let Some(project) = project.as_ref() {
1309 project_subscriptions.push(cx.subscribe_in(
1310 project,
1311 window,
1312 |editor, _, event, window, cx| match event {
1313 project::Event::RefreshCodeLens => {
1314 // we always query lens with actions, without storing them, always refreshing them
1315 }
1316 project::Event::RefreshInlayHints => {
1317 editor
1318 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1319 }
1320 project::Event::SnippetEdit(id, snippet_edits) => {
1321 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1322 let focus_handle = editor.focus_handle(cx);
1323 if focus_handle.is_focused(window) {
1324 let snapshot = buffer.read(cx).snapshot();
1325 for (range, snippet) in snippet_edits {
1326 let editor_range =
1327 language::range_from_lsp(*range).to_offset(&snapshot);
1328 editor
1329 .insert_snippet(
1330 &[editor_range],
1331 snippet.clone(),
1332 window,
1333 cx,
1334 )
1335 .ok();
1336 }
1337 }
1338 }
1339 }
1340 _ => {}
1341 },
1342 ));
1343 if let Some(task_inventory) = project
1344 .read(cx)
1345 .task_store()
1346 .read(cx)
1347 .task_inventory()
1348 .cloned()
1349 {
1350 project_subscriptions.push(cx.observe_in(
1351 &task_inventory,
1352 window,
1353 |editor, _, window, cx| {
1354 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1355 },
1356 ));
1357 };
1358
1359 project_subscriptions.push(cx.subscribe_in(
1360 &project.read(cx).breakpoint_store(),
1361 window,
1362 |editor, _, event, window, cx| match event {
1363 BreakpointStoreEvent::ActiveDebugLineChanged => {
1364 editor.go_to_active_debug_line(window, cx);
1365 }
1366 _ => {}
1367 },
1368 ));
1369 }
1370 }
1371
1372 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1373
1374 let inlay_hint_settings =
1375 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1376 let focus_handle = cx.focus_handle();
1377 cx.on_focus(&focus_handle, window, Self::handle_focus)
1378 .detach();
1379 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1380 .detach();
1381 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1382 .detach();
1383 cx.on_blur(&focus_handle, window, Self::handle_blur)
1384 .detach();
1385
1386 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1387 Some(false)
1388 } else {
1389 None
1390 };
1391
1392 let breakpoint_store = match (mode, project.as_ref()) {
1393 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1394 _ => None,
1395 };
1396
1397 let mut code_action_providers = Vec::new();
1398 let mut load_uncommitted_diff = None;
1399 if let Some(project) = project.clone() {
1400 load_uncommitted_diff = Some(
1401 get_uncommitted_diff_for_buffer(
1402 &project,
1403 buffer.read(cx).all_buffers(),
1404 buffer.clone(),
1405 cx,
1406 )
1407 .shared(),
1408 );
1409 code_action_providers.push(Rc::new(project) as Rc<_>);
1410 }
1411
1412 let mut this = Self {
1413 focus_handle,
1414 show_cursor_when_unfocused: false,
1415 last_focused_descendant: None,
1416 buffer: buffer.clone(),
1417 display_map: display_map.clone(),
1418 selections,
1419 scroll_manager: ScrollManager::new(cx),
1420 columnar_selection_tail: None,
1421 add_selections_state: None,
1422 select_next_state: None,
1423 select_prev_state: None,
1424 selection_history: Default::default(),
1425 autoclose_regions: Default::default(),
1426 snippet_stack: Default::default(),
1427 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1428 ime_transaction: Default::default(),
1429 active_diagnostics: None,
1430 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1431 inline_diagnostics_update: Task::ready(()),
1432 inline_diagnostics: Vec::new(),
1433 soft_wrap_mode_override,
1434 hard_wrap: None,
1435 completion_provider: project.clone().map(|project| Box::new(project) as _),
1436 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1437 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1438 project,
1439 blink_manager: blink_manager.clone(),
1440 show_local_selections: true,
1441 show_scrollbars: true,
1442 mode,
1443 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1444 show_gutter: mode == EditorMode::Full,
1445 show_line_numbers: None,
1446 use_relative_line_numbers: None,
1447 show_git_diff_gutter: None,
1448 show_code_actions: None,
1449 show_runnables: None,
1450 show_breakpoints: None,
1451 show_wrap_guides: None,
1452 show_indent_guides,
1453 placeholder_text: None,
1454 highlight_order: 0,
1455 highlighted_rows: HashMap::default(),
1456 background_highlights: Default::default(),
1457 gutter_highlights: TreeMap::default(),
1458 scrollbar_marker_state: ScrollbarMarkerState::default(),
1459 active_indent_guides_state: ActiveIndentGuidesState::default(),
1460 nav_history: None,
1461 context_menu: RefCell::new(None),
1462 context_menu_options: None,
1463 mouse_context_menu: None,
1464 completion_tasks: Default::default(),
1465 signature_help_state: SignatureHelpState::default(),
1466 auto_signature_help: None,
1467 find_all_references_task_sources: Vec::new(),
1468 next_completion_id: 0,
1469 next_inlay_id: 0,
1470 code_action_providers,
1471 available_code_actions: Default::default(),
1472 code_actions_task: Default::default(),
1473 selection_highlight_task: Default::default(),
1474 document_highlights_task: Default::default(),
1475 linked_editing_range_task: Default::default(),
1476 pending_rename: Default::default(),
1477 searchable: true,
1478 cursor_shape: EditorSettings::get_global(cx)
1479 .cursor_shape
1480 .unwrap_or_default(),
1481 current_line_highlight: None,
1482 autoindent_mode: Some(AutoindentMode::EachLine),
1483 collapse_matches: false,
1484 workspace: None,
1485 input_enabled: true,
1486 use_modal_editing: mode == EditorMode::Full,
1487 read_only: false,
1488 use_autoclose: true,
1489 use_auto_surround: true,
1490 auto_replace_emoji_shortcode: false,
1491 jsx_tag_auto_close_enabled_in_any_buffer: false,
1492 leader_peer_id: None,
1493 remote_id: None,
1494 hover_state: Default::default(),
1495 pending_mouse_down: None,
1496 hovered_link_state: Default::default(),
1497 edit_prediction_provider: None,
1498 active_inline_completion: None,
1499 stale_inline_completion_in_menu: None,
1500 edit_prediction_preview: EditPredictionPreview::Inactive {
1501 released_too_fast: false,
1502 },
1503 inline_diagnostics_enabled: mode == EditorMode::Full,
1504 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1505
1506 gutter_hovered: false,
1507 pixel_position_of_newest_cursor: None,
1508 last_bounds: None,
1509 last_position_map: None,
1510 expect_bounds_change: None,
1511 gutter_dimensions: GutterDimensions::default(),
1512 style: None,
1513 show_cursor_names: false,
1514 hovered_cursors: Default::default(),
1515 next_editor_action_id: EditorActionId::default(),
1516 editor_actions: Rc::default(),
1517 inline_completions_hidden_for_vim_mode: false,
1518 show_inline_completions_override: None,
1519 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1520 edit_prediction_settings: EditPredictionSettings::Disabled,
1521 edit_prediction_indent_conflict: false,
1522 edit_prediction_requires_modifier_in_indent_conflict: true,
1523 custom_context_menu: None,
1524 show_git_blame_gutter: false,
1525 show_git_blame_inline: false,
1526 show_selection_menu: None,
1527 show_git_blame_inline_delay_task: None,
1528 git_blame_inline_tooltip: None,
1529 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1530 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1531 .session
1532 .restore_unsaved_buffers,
1533 blame: None,
1534 blame_subscription: None,
1535 tasks: Default::default(),
1536
1537 breakpoint_store,
1538 gutter_breakpoint_indicator: None,
1539 _subscriptions: vec![
1540 cx.observe(&buffer, Self::on_buffer_changed),
1541 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1542 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1543 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1544 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1545 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1546 cx.observe_window_activation(window, |editor, window, cx| {
1547 let active = window.is_window_active();
1548 editor.blink_manager.update(cx, |blink_manager, cx| {
1549 if active {
1550 blink_manager.enable(cx);
1551 } else {
1552 blink_manager.disable(cx);
1553 }
1554 });
1555 }),
1556 ],
1557 tasks_update_task: None,
1558 linked_edit_ranges: Default::default(),
1559 in_project_search: false,
1560 previous_search_ranges: None,
1561 breadcrumb_header: None,
1562 focused_block: None,
1563 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1564 addons: HashMap::default(),
1565 registered_buffers: HashMap::default(),
1566 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1567 selection_mark_mode: false,
1568 toggle_fold_multiple_buffers: Task::ready(()),
1569 serialize_selections: Task::ready(()),
1570 serialize_folds: Task::ready(()),
1571 text_style_refinement: None,
1572 load_diff_task: load_uncommitted_diff,
1573 mouse_cursor_hidden: false,
1574 hide_mouse_while_typing: EditorSettings::get_global(cx)
1575 .hide_mouse_while_typing
1576 .unwrap_or(true),
1577 };
1578 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1579 this._subscriptions
1580 .push(cx.observe(breakpoints, |_, _, cx| {
1581 cx.notify();
1582 }));
1583 }
1584 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1585 this._subscriptions.extend(project_subscriptions);
1586
1587 this.end_selection(window, cx);
1588 this.scroll_manager.show_scrollbars(window, cx);
1589 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1590
1591 if mode == EditorMode::Full {
1592 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1593 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1594
1595 if this.git_blame_inline_enabled {
1596 this.git_blame_inline_enabled = true;
1597 this.start_git_blame_inline(false, window, cx);
1598 }
1599
1600 this.go_to_active_debug_line(window, cx);
1601
1602 if let Some(buffer) = buffer.read(cx).as_singleton() {
1603 if let Some(project) = this.project.as_ref() {
1604 let handle = project.update(cx, |project, cx| {
1605 project.register_buffer_with_language_servers(&buffer, cx)
1606 });
1607 this.registered_buffers
1608 .insert(buffer.read(cx).remote_id(), handle);
1609 }
1610 }
1611 }
1612
1613 this.report_editor_event("Editor Opened", None, cx);
1614 this
1615 }
1616
1617 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1618 self.mouse_context_menu
1619 .as_ref()
1620 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1621 }
1622
1623 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1624 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1625 }
1626
1627 fn key_context_internal(
1628 &self,
1629 has_active_edit_prediction: bool,
1630 window: &Window,
1631 cx: &App,
1632 ) -> KeyContext {
1633 let mut key_context = KeyContext::new_with_defaults();
1634 key_context.add("Editor");
1635 let mode = match self.mode {
1636 EditorMode::SingleLine { .. } => "single_line",
1637 EditorMode::AutoHeight { .. } => "auto_height",
1638 EditorMode::Full => "full",
1639 };
1640
1641 if EditorSettings::jupyter_enabled(cx) {
1642 key_context.add("jupyter");
1643 }
1644
1645 key_context.set("mode", mode);
1646 if self.pending_rename.is_some() {
1647 key_context.add("renaming");
1648 }
1649
1650 match self.context_menu.borrow().as_ref() {
1651 Some(CodeContextMenu::Completions(_)) => {
1652 key_context.add("menu");
1653 key_context.add("showing_completions");
1654 }
1655 Some(CodeContextMenu::CodeActions(_)) => {
1656 key_context.add("menu");
1657 key_context.add("showing_code_actions")
1658 }
1659 None => {}
1660 }
1661
1662 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1663 if !self.focus_handle(cx).contains_focused(window, cx)
1664 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1665 {
1666 for addon in self.addons.values() {
1667 addon.extend_key_context(&mut key_context, cx)
1668 }
1669 }
1670
1671 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1672 if let Some(extension) = singleton_buffer
1673 .read(cx)
1674 .file()
1675 .and_then(|file| file.path().extension()?.to_str())
1676 {
1677 key_context.set("extension", extension.to_string());
1678 }
1679 } else {
1680 key_context.add("multibuffer");
1681 }
1682
1683 if has_active_edit_prediction {
1684 if self.edit_prediction_in_conflict() {
1685 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1686 } else {
1687 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1688 key_context.add("copilot_suggestion");
1689 }
1690 }
1691
1692 if self.selection_mark_mode {
1693 key_context.add("selection_mode");
1694 }
1695
1696 key_context
1697 }
1698
1699 pub fn edit_prediction_in_conflict(&self) -> bool {
1700 if !self.show_edit_predictions_in_menu() {
1701 return false;
1702 }
1703
1704 let showing_completions = self
1705 .context_menu
1706 .borrow()
1707 .as_ref()
1708 .map_or(false, |context| {
1709 matches!(context, CodeContextMenu::Completions(_))
1710 });
1711
1712 showing_completions
1713 || self.edit_prediction_requires_modifier()
1714 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1715 // bindings to insert tab characters.
1716 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1717 }
1718
1719 pub fn accept_edit_prediction_keybind(
1720 &self,
1721 window: &Window,
1722 cx: &App,
1723 ) -> AcceptEditPredictionBinding {
1724 let key_context = self.key_context_internal(true, window, cx);
1725 let in_conflict = self.edit_prediction_in_conflict();
1726
1727 AcceptEditPredictionBinding(
1728 window
1729 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1730 .into_iter()
1731 .filter(|binding| {
1732 !in_conflict
1733 || binding
1734 .keystrokes()
1735 .first()
1736 .map_or(false, |keystroke| keystroke.modifiers.modified())
1737 })
1738 .rev()
1739 .min_by_key(|binding| {
1740 binding
1741 .keystrokes()
1742 .first()
1743 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1744 }),
1745 )
1746 }
1747
1748 pub fn new_file(
1749 workspace: &mut Workspace,
1750 _: &workspace::NewFile,
1751 window: &mut Window,
1752 cx: &mut Context<Workspace>,
1753 ) {
1754 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1755 "Failed to create buffer",
1756 window,
1757 cx,
1758 |e, _, _| match e.error_code() {
1759 ErrorCode::RemoteUpgradeRequired => Some(format!(
1760 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1761 e.error_tag("required").unwrap_or("the latest version")
1762 )),
1763 _ => None,
1764 },
1765 );
1766 }
1767
1768 pub fn new_in_workspace(
1769 workspace: &mut Workspace,
1770 window: &mut Window,
1771 cx: &mut Context<Workspace>,
1772 ) -> Task<Result<Entity<Editor>>> {
1773 let project = workspace.project().clone();
1774 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1775
1776 cx.spawn_in(window, async move |workspace, cx| {
1777 let buffer = create.await?;
1778 workspace.update_in(cx, |workspace, window, cx| {
1779 let editor =
1780 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1781 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1782 editor
1783 })
1784 })
1785 }
1786
1787 fn new_file_vertical(
1788 workspace: &mut Workspace,
1789 _: &workspace::NewFileSplitVertical,
1790 window: &mut Window,
1791 cx: &mut Context<Workspace>,
1792 ) {
1793 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1794 }
1795
1796 fn new_file_horizontal(
1797 workspace: &mut Workspace,
1798 _: &workspace::NewFileSplitHorizontal,
1799 window: &mut Window,
1800 cx: &mut Context<Workspace>,
1801 ) {
1802 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1803 }
1804
1805 fn new_file_in_direction(
1806 workspace: &mut Workspace,
1807 direction: SplitDirection,
1808 window: &mut Window,
1809 cx: &mut Context<Workspace>,
1810 ) {
1811 let project = workspace.project().clone();
1812 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1813
1814 cx.spawn_in(window, async move |workspace, cx| {
1815 let buffer = create.await?;
1816 workspace.update_in(cx, move |workspace, window, cx| {
1817 workspace.split_item(
1818 direction,
1819 Box::new(
1820 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1821 ),
1822 window,
1823 cx,
1824 )
1825 })?;
1826 anyhow::Ok(())
1827 })
1828 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1829 match e.error_code() {
1830 ErrorCode::RemoteUpgradeRequired => Some(format!(
1831 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1832 e.error_tag("required").unwrap_or("the latest version")
1833 )),
1834 _ => None,
1835 }
1836 });
1837 }
1838
1839 pub fn leader_peer_id(&self) -> Option<PeerId> {
1840 self.leader_peer_id
1841 }
1842
1843 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1844 &self.buffer
1845 }
1846
1847 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1848 self.workspace.as_ref()?.0.upgrade()
1849 }
1850
1851 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1852 self.buffer().read(cx).title(cx)
1853 }
1854
1855 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1856 let git_blame_gutter_max_author_length = self
1857 .render_git_blame_gutter(cx)
1858 .then(|| {
1859 if let Some(blame) = self.blame.as_ref() {
1860 let max_author_length =
1861 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1862 Some(max_author_length)
1863 } else {
1864 None
1865 }
1866 })
1867 .flatten();
1868
1869 EditorSnapshot {
1870 mode: self.mode,
1871 show_gutter: self.show_gutter,
1872 show_line_numbers: self.show_line_numbers,
1873 show_git_diff_gutter: self.show_git_diff_gutter,
1874 show_code_actions: self.show_code_actions,
1875 show_runnables: self.show_runnables,
1876 show_breakpoints: self.show_breakpoints,
1877 git_blame_gutter_max_author_length,
1878 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1879 scroll_anchor: self.scroll_manager.anchor(),
1880 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1881 placeholder_text: self.placeholder_text.clone(),
1882 is_focused: self.focus_handle.is_focused(window),
1883 current_line_highlight: self
1884 .current_line_highlight
1885 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1886 gutter_hovered: self.gutter_hovered,
1887 }
1888 }
1889
1890 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1891 self.buffer.read(cx).language_at(point, cx)
1892 }
1893
1894 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1895 self.buffer.read(cx).read(cx).file_at(point).cloned()
1896 }
1897
1898 pub fn active_excerpt(
1899 &self,
1900 cx: &App,
1901 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1902 self.buffer
1903 .read(cx)
1904 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1905 }
1906
1907 pub fn mode(&self) -> EditorMode {
1908 self.mode
1909 }
1910
1911 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1912 self.collaboration_hub.as_deref()
1913 }
1914
1915 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1916 self.collaboration_hub = Some(hub);
1917 }
1918
1919 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1920 self.in_project_search = in_project_search;
1921 }
1922
1923 pub fn set_custom_context_menu(
1924 &mut self,
1925 f: impl 'static
1926 + Fn(
1927 &mut Self,
1928 DisplayPoint,
1929 &mut Window,
1930 &mut Context<Self>,
1931 ) -> Option<Entity<ui::ContextMenu>>,
1932 ) {
1933 self.custom_context_menu = Some(Box::new(f))
1934 }
1935
1936 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1937 self.completion_provider = provider;
1938 }
1939
1940 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1941 self.semantics_provider.clone()
1942 }
1943
1944 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1945 self.semantics_provider = provider;
1946 }
1947
1948 pub fn set_edit_prediction_provider<T>(
1949 &mut self,
1950 provider: Option<Entity<T>>,
1951 window: &mut Window,
1952 cx: &mut Context<Self>,
1953 ) where
1954 T: EditPredictionProvider,
1955 {
1956 self.edit_prediction_provider =
1957 provider.map(|provider| RegisteredInlineCompletionProvider {
1958 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1959 if this.focus_handle.is_focused(window) {
1960 this.update_visible_inline_completion(window, cx);
1961 }
1962 }),
1963 provider: Arc::new(provider),
1964 });
1965 self.update_edit_prediction_settings(cx);
1966 self.refresh_inline_completion(false, false, window, cx);
1967 }
1968
1969 pub fn placeholder_text(&self) -> Option<&str> {
1970 self.placeholder_text.as_deref()
1971 }
1972
1973 pub fn set_placeholder_text(
1974 &mut self,
1975 placeholder_text: impl Into<Arc<str>>,
1976 cx: &mut Context<Self>,
1977 ) {
1978 let placeholder_text = Some(placeholder_text.into());
1979 if self.placeholder_text != placeholder_text {
1980 self.placeholder_text = placeholder_text;
1981 cx.notify();
1982 }
1983 }
1984
1985 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1986 self.cursor_shape = cursor_shape;
1987
1988 // Disrupt blink for immediate user feedback that the cursor shape has changed
1989 self.blink_manager.update(cx, BlinkManager::show_cursor);
1990
1991 cx.notify();
1992 }
1993
1994 pub fn set_current_line_highlight(
1995 &mut self,
1996 current_line_highlight: Option<CurrentLineHighlight>,
1997 ) {
1998 self.current_line_highlight = current_line_highlight;
1999 }
2000
2001 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2002 self.collapse_matches = collapse_matches;
2003 }
2004
2005 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2006 let buffers = self.buffer.read(cx).all_buffers();
2007 let Some(project) = self.project.as_ref() else {
2008 return;
2009 };
2010 project.update(cx, |project, cx| {
2011 for buffer in buffers {
2012 self.registered_buffers
2013 .entry(buffer.read(cx).remote_id())
2014 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2015 }
2016 })
2017 }
2018
2019 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2020 if self.collapse_matches {
2021 return range.start..range.start;
2022 }
2023 range.clone()
2024 }
2025
2026 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2027 if self.display_map.read(cx).clip_at_line_ends != clip {
2028 self.display_map
2029 .update(cx, |map, _| map.clip_at_line_ends = clip);
2030 }
2031 }
2032
2033 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2034 self.input_enabled = input_enabled;
2035 }
2036
2037 pub fn set_inline_completions_hidden_for_vim_mode(
2038 &mut self,
2039 hidden: bool,
2040 window: &mut Window,
2041 cx: &mut Context<Self>,
2042 ) {
2043 if hidden != self.inline_completions_hidden_for_vim_mode {
2044 self.inline_completions_hidden_for_vim_mode = hidden;
2045 if hidden {
2046 self.update_visible_inline_completion(window, cx);
2047 } else {
2048 self.refresh_inline_completion(true, false, window, cx);
2049 }
2050 }
2051 }
2052
2053 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2054 self.menu_inline_completions_policy = value;
2055 }
2056
2057 pub fn set_autoindent(&mut self, autoindent: bool) {
2058 if autoindent {
2059 self.autoindent_mode = Some(AutoindentMode::EachLine);
2060 } else {
2061 self.autoindent_mode = None;
2062 }
2063 }
2064
2065 pub fn read_only(&self, cx: &App) -> bool {
2066 self.read_only || self.buffer.read(cx).read_only()
2067 }
2068
2069 pub fn set_read_only(&mut self, read_only: bool) {
2070 self.read_only = read_only;
2071 }
2072
2073 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2074 self.use_autoclose = autoclose;
2075 }
2076
2077 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2078 self.use_auto_surround = auto_surround;
2079 }
2080
2081 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2082 self.auto_replace_emoji_shortcode = auto_replace;
2083 }
2084
2085 pub fn toggle_edit_predictions(
2086 &mut self,
2087 _: &ToggleEditPrediction,
2088 window: &mut Window,
2089 cx: &mut Context<Self>,
2090 ) {
2091 if self.show_inline_completions_override.is_some() {
2092 self.set_show_edit_predictions(None, window, cx);
2093 } else {
2094 let show_edit_predictions = !self.edit_predictions_enabled();
2095 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2096 }
2097 }
2098
2099 pub fn set_show_edit_predictions(
2100 &mut self,
2101 show_edit_predictions: Option<bool>,
2102 window: &mut Window,
2103 cx: &mut Context<Self>,
2104 ) {
2105 self.show_inline_completions_override = show_edit_predictions;
2106 self.update_edit_prediction_settings(cx);
2107
2108 if let Some(false) = show_edit_predictions {
2109 self.discard_inline_completion(false, cx);
2110 } else {
2111 self.refresh_inline_completion(false, true, window, cx);
2112 }
2113 }
2114
2115 fn inline_completions_disabled_in_scope(
2116 &self,
2117 buffer: &Entity<Buffer>,
2118 buffer_position: language::Anchor,
2119 cx: &App,
2120 ) -> bool {
2121 let snapshot = buffer.read(cx).snapshot();
2122 let settings = snapshot.settings_at(buffer_position, cx);
2123
2124 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2125 return false;
2126 };
2127
2128 scope.override_name().map_or(false, |scope_name| {
2129 settings
2130 .edit_predictions_disabled_in
2131 .iter()
2132 .any(|s| s == scope_name)
2133 })
2134 }
2135
2136 pub fn set_use_modal_editing(&mut self, to: bool) {
2137 self.use_modal_editing = to;
2138 }
2139
2140 pub fn use_modal_editing(&self) -> bool {
2141 self.use_modal_editing
2142 }
2143
2144 fn selections_did_change(
2145 &mut self,
2146 local: bool,
2147 old_cursor_position: &Anchor,
2148 show_completions: bool,
2149 window: &mut Window,
2150 cx: &mut Context<Self>,
2151 ) {
2152 window.invalidate_character_coordinates();
2153
2154 // Copy selections to primary selection buffer
2155 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2156 if local {
2157 let selections = self.selections.all::<usize>(cx);
2158 let buffer_handle = self.buffer.read(cx).read(cx);
2159
2160 let mut text = String::new();
2161 for (index, selection) in selections.iter().enumerate() {
2162 let text_for_selection = buffer_handle
2163 .text_for_range(selection.start..selection.end)
2164 .collect::<String>();
2165
2166 text.push_str(&text_for_selection);
2167 if index != selections.len() - 1 {
2168 text.push('\n');
2169 }
2170 }
2171
2172 if !text.is_empty() {
2173 cx.write_to_primary(ClipboardItem::new_string(text));
2174 }
2175 }
2176
2177 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2178 self.buffer.update(cx, |buffer, cx| {
2179 buffer.set_active_selections(
2180 &self.selections.disjoint_anchors(),
2181 self.selections.line_mode,
2182 self.cursor_shape,
2183 cx,
2184 )
2185 });
2186 }
2187 let display_map = self
2188 .display_map
2189 .update(cx, |display_map, cx| display_map.snapshot(cx));
2190 let buffer = &display_map.buffer_snapshot;
2191 self.add_selections_state = None;
2192 self.select_next_state = None;
2193 self.select_prev_state = None;
2194 self.select_syntax_node_history.try_clear();
2195 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2196 self.snippet_stack
2197 .invalidate(&self.selections.disjoint_anchors(), buffer);
2198 self.take_rename(false, window, cx);
2199
2200 let new_cursor_position = self.selections.newest_anchor().head();
2201
2202 self.push_to_nav_history(
2203 *old_cursor_position,
2204 Some(new_cursor_position.to_point(buffer)),
2205 false,
2206 cx,
2207 );
2208
2209 if local {
2210 let new_cursor_position = self.selections.newest_anchor().head();
2211 let mut context_menu = self.context_menu.borrow_mut();
2212 let completion_menu = match context_menu.as_ref() {
2213 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2214 _ => {
2215 *context_menu = None;
2216 None
2217 }
2218 };
2219 if let Some(buffer_id) = new_cursor_position.buffer_id {
2220 if !self.registered_buffers.contains_key(&buffer_id) {
2221 if let Some(project) = self.project.as_ref() {
2222 project.update(cx, |project, cx| {
2223 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2224 return;
2225 };
2226 self.registered_buffers.insert(
2227 buffer_id,
2228 project.register_buffer_with_language_servers(&buffer, cx),
2229 );
2230 })
2231 }
2232 }
2233 }
2234
2235 if let Some(completion_menu) = completion_menu {
2236 let cursor_position = new_cursor_position.to_offset(buffer);
2237 let (word_range, kind) =
2238 buffer.surrounding_word(completion_menu.initial_position, true);
2239 if kind == Some(CharKind::Word)
2240 && word_range.to_inclusive().contains(&cursor_position)
2241 {
2242 let mut completion_menu = completion_menu.clone();
2243 drop(context_menu);
2244
2245 let query = Self::completion_query(buffer, cursor_position);
2246 cx.spawn(async move |this, cx| {
2247 completion_menu
2248 .filter(query.as_deref(), cx.background_executor().clone())
2249 .await;
2250
2251 this.update(cx, |this, cx| {
2252 let mut context_menu = this.context_menu.borrow_mut();
2253 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2254 else {
2255 return;
2256 };
2257
2258 if menu.id > completion_menu.id {
2259 return;
2260 }
2261
2262 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2263 drop(context_menu);
2264 cx.notify();
2265 })
2266 })
2267 .detach();
2268
2269 if show_completions {
2270 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2271 }
2272 } else {
2273 drop(context_menu);
2274 self.hide_context_menu(window, cx);
2275 }
2276 } else {
2277 drop(context_menu);
2278 }
2279
2280 hide_hover(self, cx);
2281
2282 if old_cursor_position.to_display_point(&display_map).row()
2283 != new_cursor_position.to_display_point(&display_map).row()
2284 {
2285 self.available_code_actions.take();
2286 }
2287 self.refresh_code_actions(window, cx);
2288 self.refresh_document_highlights(cx);
2289 self.refresh_selected_text_highlights(window, cx);
2290 refresh_matching_bracket_highlights(self, window, cx);
2291 self.update_visible_inline_completion(window, cx);
2292 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2293 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2294 if self.git_blame_inline_enabled {
2295 self.start_inline_blame_timer(window, cx);
2296 }
2297 }
2298
2299 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2300 cx.emit(EditorEvent::SelectionsChanged { local });
2301
2302 let selections = &self.selections.disjoint;
2303 if selections.len() == 1 {
2304 cx.emit(SearchEvent::ActiveMatchChanged)
2305 }
2306 if local
2307 && self.is_singleton(cx)
2308 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2309 {
2310 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2311 let background_executor = cx.background_executor().clone();
2312 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2313 let snapshot = self.buffer().read(cx).snapshot(cx);
2314 let selections = selections.clone();
2315 self.serialize_selections = cx.background_spawn(async move {
2316 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2317 let selections = selections
2318 .iter()
2319 .map(|selection| {
2320 (
2321 selection.start.to_offset(&snapshot),
2322 selection.end.to_offset(&snapshot),
2323 )
2324 })
2325 .collect();
2326
2327 DB.save_editor_selections(editor_id, workspace_id, selections)
2328 .await
2329 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2330 .log_err();
2331 });
2332 }
2333 }
2334
2335 cx.notify();
2336 }
2337
2338 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2339 if !self.is_singleton(cx)
2340 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2341 {
2342 return;
2343 }
2344
2345 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2346 return;
2347 };
2348 let background_executor = cx.background_executor().clone();
2349 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2350 let snapshot = self.buffer().read(cx).snapshot(cx);
2351 let folds = self.display_map.update(cx, |display_map, cx| {
2352 display_map
2353 .snapshot(cx)
2354 .folds_in_range(0..snapshot.len())
2355 .map(|fold| {
2356 (
2357 fold.range.start.to_offset(&snapshot),
2358 fold.range.end.to_offset(&snapshot),
2359 )
2360 })
2361 .collect()
2362 });
2363 self.serialize_folds = cx.background_spawn(async move {
2364 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2365 DB.save_editor_folds(editor_id, workspace_id, folds)
2366 .await
2367 .with_context(|| format!("persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"))
2368 .log_err();
2369 });
2370 }
2371
2372 pub fn sync_selections(
2373 &mut self,
2374 other: Entity<Editor>,
2375 cx: &mut Context<Self>,
2376 ) -> gpui::Subscription {
2377 let other_selections = other.read(cx).selections.disjoint.to_vec();
2378 self.selections.change_with(cx, |selections| {
2379 selections.select_anchors(other_selections);
2380 });
2381
2382 let other_subscription =
2383 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2384 EditorEvent::SelectionsChanged { local: true } => {
2385 let other_selections = other.read(cx).selections.disjoint.to_vec();
2386 if other_selections.is_empty() {
2387 return;
2388 }
2389 this.selections.change_with(cx, |selections| {
2390 selections.select_anchors(other_selections);
2391 });
2392 }
2393 _ => {}
2394 });
2395
2396 let this_subscription =
2397 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2398 EditorEvent::SelectionsChanged { local: true } => {
2399 let these_selections = this.selections.disjoint.to_vec();
2400 if these_selections.is_empty() {
2401 return;
2402 }
2403 other.update(cx, |other_editor, cx| {
2404 other_editor.selections.change_with(cx, |selections| {
2405 selections.select_anchors(these_selections);
2406 })
2407 });
2408 }
2409 _ => {}
2410 });
2411
2412 Subscription::join(other_subscription, this_subscription)
2413 }
2414
2415 pub fn change_selections<R>(
2416 &mut self,
2417 autoscroll: Option<Autoscroll>,
2418 window: &mut Window,
2419 cx: &mut Context<Self>,
2420 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2421 ) -> R {
2422 self.change_selections_inner(autoscroll, true, window, cx, change)
2423 }
2424
2425 fn change_selections_inner<R>(
2426 &mut self,
2427 autoscroll: Option<Autoscroll>,
2428 request_completions: bool,
2429 window: &mut Window,
2430 cx: &mut Context<Self>,
2431 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2432 ) -> R {
2433 let old_cursor_position = self.selections.newest_anchor().head();
2434 self.push_to_selection_history();
2435
2436 let (changed, result) = self.selections.change_with(cx, change);
2437
2438 if changed {
2439 if let Some(autoscroll) = autoscroll {
2440 self.request_autoscroll(autoscroll, cx);
2441 }
2442 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2443
2444 if self.should_open_signature_help_automatically(
2445 &old_cursor_position,
2446 self.signature_help_state.backspace_pressed(),
2447 cx,
2448 ) {
2449 self.show_signature_help(&ShowSignatureHelp, window, cx);
2450 }
2451 self.signature_help_state.set_backspace_pressed(false);
2452 }
2453
2454 result
2455 }
2456
2457 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2458 where
2459 I: IntoIterator<Item = (Range<S>, T)>,
2460 S: ToOffset,
2461 T: Into<Arc<str>>,
2462 {
2463 if self.read_only(cx) {
2464 return;
2465 }
2466
2467 self.buffer
2468 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2469 }
2470
2471 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2472 where
2473 I: IntoIterator<Item = (Range<S>, T)>,
2474 S: ToOffset,
2475 T: Into<Arc<str>>,
2476 {
2477 if self.read_only(cx) {
2478 return;
2479 }
2480
2481 self.buffer.update(cx, |buffer, cx| {
2482 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2483 });
2484 }
2485
2486 pub fn edit_with_block_indent<I, S, T>(
2487 &mut self,
2488 edits: I,
2489 original_indent_columns: Vec<Option<u32>>,
2490 cx: &mut Context<Self>,
2491 ) where
2492 I: IntoIterator<Item = (Range<S>, T)>,
2493 S: ToOffset,
2494 T: Into<Arc<str>>,
2495 {
2496 if self.read_only(cx) {
2497 return;
2498 }
2499
2500 self.buffer.update(cx, |buffer, cx| {
2501 buffer.edit(
2502 edits,
2503 Some(AutoindentMode::Block {
2504 original_indent_columns,
2505 }),
2506 cx,
2507 )
2508 });
2509 }
2510
2511 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2512 self.hide_context_menu(window, cx);
2513
2514 match phase {
2515 SelectPhase::Begin {
2516 position,
2517 add,
2518 click_count,
2519 } => self.begin_selection(position, add, click_count, window, cx),
2520 SelectPhase::BeginColumnar {
2521 position,
2522 goal_column,
2523 reset,
2524 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2525 SelectPhase::Extend {
2526 position,
2527 click_count,
2528 } => self.extend_selection(position, click_count, window, cx),
2529 SelectPhase::Update {
2530 position,
2531 goal_column,
2532 scroll_delta,
2533 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2534 SelectPhase::End => self.end_selection(window, cx),
2535 }
2536 }
2537
2538 fn extend_selection(
2539 &mut self,
2540 position: DisplayPoint,
2541 click_count: usize,
2542 window: &mut Window,
2543 cx: &mut Context<Self>,
2544 ) {
2545 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2546 let tail = self.selections.newest::<usize>(cx).tail();
2547 self.begin_selection(position, false, click_count, window, cx);
2548
2549 let position = position.to_offset(&display_map, Bias::Left);
2550 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2551
2552 let mut pending_selection = self
2553 .selections
2554 .pending_anchor()
2555 .expect("extend_selection not called with pending selection");
2556 if position >= tail {
2557 pending_selection.start = tail_anchor;
2558 } else {
2559 pending_selection.end = tail_anchor;
2560 pending_selection.reversed = true;
2561 }
2562
2563 let mut pending_mode = self.selections.pending_mode().unwrap();
2564 match &mut pending_mode {
2565 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2566 _ => {}
2567 }
2568
2569 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2570 s.set_pending(pending_selection, pending_mode)
2571 });
2572 }
2573
2574 fn begin_selection(
2575 &mut self,
2576 position: DisplayPoint,
2577 add: bool,
2578 click_count: usize,
2579 window: &mut Window,
2580 cx: &mut Context<Self>,
2581 ) {
2582 if !self.focus_handle.is_focused(window) {
2583 self.last_focused_descendant = None;
2584 window.focus(&self.focus_handle);
2585 }
2586
2587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2588 let buffer = &display_map.buffer_snapshot;
2589 let newest_selection = self.selections.newest_anchor().clone();
2590 let position = display_map.clip_point(position, Bias::Left);
2591
2592 let start;
2593 let end;
2594 let mode;
2595 let mut auto_scroll;
2596 match click_count {
2597 1 => {
2598 start = buffer.anchor_before(position.to_point(&display_map));
2599 end = start;
2600 mode = SelectMode::Character;
2601 auto_scroll = true;
2602 }
2603 2 => {
2604 let range = movement::surrounding_word(&display_map, position);
2605 start = buffer.anchor_before(range.start.to_point(&display_map));
2606 end = buffer.anchor_before(range.end.to_point(&display_map));
2607 mode = SelectMode::Word(start..end);
2608 auto_scroll = true;
2609 }
2610 3 => {
2611 let position = display_map
2612 .clip_point(position, Bias::Left)
2613 .to_point(&display_map);
2614 let line_start = display_map.prev_line_boundary(position).0;
2615 let next_line_start = buffer.clip_point(
2616 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2617 Bias::Left,
2618 );
2619 start = buffer.anchor_before(line_start);
2620 end = buffer.anchor_before(next_line_start);
2621 mode = SelectMode::Line(start..end);
2622 auto_scroll = true;
2623 }
2624 _ => {
2625 start = buffer.anchor_before(0);
2626 end = buffer.anchor_before(buffer.len());
2627 mode = SelectMode::All;
2628 auto_scroll = false;
2629 }
2630 }
2631 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2632
2633 let point_to_delete: Option<usize> = {
2634 let selected_points: Vec<Selection<Point>> =
2635 self.selections.disjoint_in_range(start..end, cx);
2636
2637 if !add || click_count > 1 {
2638 None
2639 } else if !selected_points.is_empty() {
2640 Some(selected_points[0].id)
2641 } else {
2642 let clicked_point_already_selected =
2643 self.selections.disjoint.iter().find(|selection| {
2644 selection.start.to_point(buffer) == start.to_point(buffer)
2645 || selection.end.to_point(buffer) == end.to_point(buffer)
2646 });
2647
2648 clicked_point_already_selected.map(|selection| selection.id)
2649 }
2650 };
2651
2652 let selections_count = self.selections.count();
2653
2654 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2655 if let Some(point_to_delete) = point_to_delete {
2656 s.delete(point_to_delete);
2657
2658 if selections_count == 1 {
2659 s.set_pending_anchor_range(start..end, mode);
2660 }
2661 } else {
2662 if !add {
2663 s.clear_disjoint();
2664 } else if click_count > 1 {
2665 s.delete(newest_selection.id)
2666 }
2667
2668 s.set_pending_anchor_range(start..end, mode);
2669 }
2670 });
2671 }
2672
2673 fn begin_columnar_selection(
2674 &mut self,
2675 position: DisplayPoint,
2676 goal_column: u32,
2677 reset: bool,
2678 window: &mut Window,
2679 cx: &mut Context<Self>,
2680 ) {
2681 if !self.focus_handle.is_focused(window) {
2682 self.last_focused_descendant = None;
2683 window.focus(&self.focus_handle);
2684 }
2685
2686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2687
2688 if reset {
2689 let pointer_position = display_map
2690 .buffer_snapshot
2691 .anchor_before(position.to_point(&display_map));
2692
2693 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2694 s.clear_disjoint();
2695 s.set_pending_anchor_range(
2696 pointer_position..pointer_position,
2697 SelectMode::Character,
2698 );
2699 });
2700 }
2701
2702 let tail = self.selections.newest::<Point>(cx).tail();
2703 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2704
2705 if !reset {
2706 self.select_columns(
2707 tail.to_display_point(&display_map),
2708 position,
2709 goal_column,
2710 &display_map,
2711 window,
2712 cx,
2713 );
2714 }
2715 }
2716
2717 fn update_selection(
2718 &mut self,
2719 position: DisplayPoint,
2720 goal_column: u32,
2721 scroll_delta: gpui::Point<f32>,
2722 window: &mut Window,
2723 cx: &mut Context<Self>,
2724 ) {
2725 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2726
2727 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2728 let tail = tail.to_display_point(&display_map);
2729 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2730 } else if let Some(mut pending) = self.selections.pending_anchor() {
2731 let buffer = self.buffer.read(cx).snapshot(cx);
2732 let head;
2733 let tail;
2734 let mode = self.selections.pending_mode().unwrap();
2735 match &mode {
2736 SelectMode::Character => {
2737 head = position.to_point(&display_map);
2738 tail = pending.tail().to_point(&buffer);
2739 }
2740 SelectMode::Word(original_range) => {
2741 let original_display_range = original_range.start.to_display_point(&display_map)
2742 ..original_range.end.to_display_point(&display_map);
2743 let original_buffer_range = original_display_range.start.to_point(&display_map)
2744 ..original_display_range.end.to_point(&display_map);
2745 if movement::is_inside_word(&display_map, position)
2746 || original_display_range.contains(&position)
2747 {
2748 let word_range = movement::surrounding_word(&display_map, position);
2749 if word_range.start < original_display_range.start {
2750 head = word_range.start.to_point(&display_map);
2751 } else {
2752 head = word_range.end.to_point(&display_map);
2753 }
2754 } else {
2755 head = position.to_point(&display_map);
2756 }
2757
2758 if head <= original_buffer_range.start {
2759 tail = original_buffer_range.end;
2760 } else {
2761 tail = original_buffer_range.start;
2762 }
2763 }
2764 SelectMode::Line(original_range) => {
2765 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2766
2767 let position = display_map
2768 .clip_point(position, Bias::Left)
2769 .to_point(&display_map);
2770 let line_start = display_map.prev_line_boundary(position).0;
2771 let next_line_start = buffer.clip_point(
2772 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2773 Bias::Left,
2774 );
2775
2776 if line_start < original_range.start {
2777 head = line_start
2778 } else {
2779 head = next_line_start
2780 }
2781
2782 if head <= original_range.start {
2783 tail = original_range.end;
2784 } else {
2785 tail = original_range.start;
2786 }
2787 }
2788 SelectMode::All => {
2789 return;
2790 }
2791 };
2792
2793 if head < tail {
2794 pending.start = buffer.anchor_before(head);
2795 pending.end = buffer.anchor_before(tail);
2796 pending.reversed = true;
2797 } else {
2798 pending.start = buffer.anchor_before(tail);
2799 pending.end = buffer.anchor_before(head);
2800 pending.reversed = false;
2801 }
2802
2803 self.change_selections(None, window, cx, |s| {
2804 s.set_pending(pending, mode);
2805 });
2806 } else {
2807 log::error!("update_selection dispatched with no pending selection");
2808 return;
2809 }
2810
2811 self.apply_scroll_delta(scroll_delta, window, cx);
2812 cx.notify();
2813 }
2814
2815 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2816 self.columnar_selection_tail.take();
2817 if self.selections.pending_anchor().is_some() {
2818 let selections = self.selections.all::<usize>(cx);
2819 self.change_selections(None, window, cx, |s| {
2820 s.select(selections);
2821 s.clear_pending();
2822 });
2823 }
2824 }
2825
2826 fn select_columns(
2827 &mut self,
2828 tail: DisplayPoint,
2829 head: DisplayPoint,
2830 goal_column: u32,
2831 display_map: &DisplaySnapshot,
2832 window: &mut Window,
2833 cx: &mut Context<Self>,
2834 ) {
2835 let start_row = cmp::min(tail.row(), head.row());
2836 let end_row = cmp::max(tail.row(), head.row());
2837 let start_column = cmp::min(tail.column(), goal_column);
2838 let end_column = cmp::max(tail.column(), goal_column);
2839 let reversed = start_column < tail.column();
2840
2841 let selection_ranges = (start_row.0..=end_row.0)
2842 .map(DisplayRow)
2843 .filter_map(|row| {
2844 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2845 let start = display_map
2846 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2847 .to_point(display_map);
2848 let end = display_map
2849 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2850 .to_point(display_map);
2851 if reversed {
2852 Some(end..start)
2853 } else {
2854 Some(start..end)
2855 }
2856 } else {
2857 None
2858 }
2859 })
2860 .collect::<Vec<_>>();
2861
2862 self.change_selections(None, window, cx, |s| {
2863 s.select_ranges(selection_ranges);
2864 });
2865 cx.notify();
2866 }
2867
2868 pub fn has_pending_nonempty_selection(&self) -> bool {
2869 let pending_nonempty_selection = match self.selections.pending_anchor() {
2870 Some(Selection { start, end, .. }) => start != end,
2871 None => false,
2872 };
2873
2874 pending_nonempty_selection
2875 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2876 }
2877
2878 pub fn has_pending_selection(&self) -> bool {
2879 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2880 }
2881
2882 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2883 self.selection_mark_mode = false;
2884
2885 if self.clear_expanded_diff_hunks(cx) {
2886 cx.notify();
2887 return;
2888 }
2889 if self.dismiss_menus_and_popups(true, window, cx) {
2890 return;
2891 }
2892
2893 if self.mode == EditorMode::Full
2894 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2895 {
2896 return;
2897 }
2898
2899 cx.propagate();
2900 }
2901
2902 pub fn dismiss_menus_and_popups(
2903 &mut self,
2904 is_user_requested: bool,
2905 window: &mut Window,
2906 cx: &mut Context<Self>,
2907 ) -> bool {
2908 if self.take_rename(false, window, cx).is_some() {
2909 return true;
2910 }
2911
2912 if hide_hover(self, cx) {
2913 return true;
2914 }
2915
2916 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2917 return true;
2918 }
2919
2920 if self.hide_context_menu(window, cx).is_some() {
2921 return true;
2922 }
2923
2924 if self.mouse_context_menu.take().is_some() {
2925 return true;
2926 }
2927
2928 if is_user_requested && self.discard_inline_completion(true, cx) {
2929 return true;
2930 }
2931
2932 if self.snippet_stack.pop().is_some() {
2933 return true;
2934 }
2935
2936 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2937 self.dismiss_diagnostics(cx);
2938 return true;
2939 }
2940
2941 false
2942 }
2943
2944 fn linked_editing_ranges_for(
2945 &self,
2946 selection: Range<text::Anchor>,
2947 cx: &App,
2948 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2949 if self.linked_edit_ranges.is_empty() {
2950 return None;
2951 }
2952 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2953 selection.end.buffer_id.and_then(|end_buffer_id| {
2954 if selection.start.buffer_id != Some(end_buffer_id) {
2955 return None;
2956 }
2957 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2958 let snapshot = buffer.read(cx).snapshot();
2959 self.linked_edit_ranges
2960 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2961 .map(|ranges| (ranges, snapshot, buffer))
2962 })?;
2963 use text::ToOffset as TO;
2964 // find offset from the start of current range to current cursor position
2965 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2966
2967 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2968 let start_difference = start_offset - start_byte_offset;
2969 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2970 let end_difference = end_offset - start_byte_offset;
2971 // Current range has associated linked ranges.
2972 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2973 for range in linked_ranges.iter() {
2974 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2975 let end_offset = start_offset + end_difference;
2976 let start_offset = start_offset + start_difference;
2977 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2978 continue;
2979 }
2980 if self.selections.disjoint_anchor_ranges().any(|s| {
2981 if s.start.buffer_id != selection.start.buffer_id
2982 || s.end.buffer_id != selection.end.buffer_id
2983 {
2984 return false;
2985 }
2986 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2987 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2988 }) {
2989 continue;
2990 }
2991 let start = buffer_snapshot.anchor_after(start_offset);
2992 let end = buffer_snapshot.anchor_after(end_offset);
2993 linked_edits
2994 .entry(buffer.clone())
2995 .or_default()
2996 .push(start..end);
2997 }
2998 Some(linked_edits)
2999 }
3000
3001 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3002 let text: Arc<str> = text.into();
3003
3004 if self.read_only(cx) {
3005 return;
3006 }
3007
3008 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3009
3010 let selections = self.selections.all_adjusted(cx);
3011 let mut bracket_inserted = false;
3012 let mut edits = Vec::new();
3013 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3014 let mut new_selections = Vec::with_capacity(selections.len());
3015 let mut new_autoclose_regions = Vec::new();
3016 let snapshot = self.buffer.read(cx).read(cx);
3017
3018 for (selection, autoclose_region) in
3019 self.selections_with_autoclose_regions(selections, &snapshot)
3020 {
3021 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3022 // Determine if the inserted text matches the opening or closing
3023 // bracket of any of this language's bracket pairs.
3024 let mut bracket_pair = None;
3025 let mut is_bracket_pair_start = false;
3026 let mut is_bracket_pair_end = false;
3027 if !text.is_empty() {
3028 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3029 // and they are removing the character that triggered IME popup.
3030 for (pair, enabled) in scope.brackets() {
3031 if !pair.close && !pair.surround {
3032 continue;
3033 }
3034
3035 if enabled && pair.start.ends_with(text.as_ref()) {
3036 let prefix_len = pair.start.len() - text.len();
3037 let preceding_text_matches_prefix = prefix_len == 0
3038 || (selection.start.column >= (prefix_len as u32)
3039 && snapshot.contains_str_at(
3040 Point::new(
3041 selection.start.row,
3042 selection.start.column - (prefix_len as u32),
3043 ),
3044 &pair.start[..prefix_len],
3045 ));
3046 if preceding_text_matches_prefix {
3047 bracket_pair = Some(pair.clone());
3048 is_bracket_pair_start = true;
3049 break;
3050 }
3051 }
3052 if pair.end.as_str() == text.as_ref() {
3053 bracket_pair = Some(pair.clone());
3054 is_bracket_pair_end = true;
3055 break;
3056 }
3057 }
3058 }
3059
3060 if let Some(bracket_pair) = bracket_pair {
3061 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3062 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3063 let auto_surround =
3064 self.use_auto_surround && snapshot_settings.use_auto_surround;
3065 if selection.is_empty() {
3066 if is_bracket_pair_start {
3067 // If the inserted text is a suffix of an opening bracket and the
3068 // selection is preceded by the rest of the opening bracket, then
3069 // insert the closing bracket.
3070 let following_text_allows_autoclose = snapshot
3071 .chars_at(selection.start)
3072 .next()
3073 .map_or(true, |c| scope.should_autoclose_before(c));
3074
3075 let preceding_text_allows_autoclose = selection.start.column == 0
3076 || snapshot.reversed_chars_at(selection.start).next().map_or(
3077 true,
3078 |c| {
3079 bracket_pair.start != bracket_pair.end
3080 || !snapshot
3081 .char_classifier_at(selection.start)
3082 .is_word(c)
3083 },
3084 );
3085
3086 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3087 && bracket_pair.start.len() == 1
3088 {
3089 let target = bracket_pair.start.chars().next().unwrap();
3090 let current_line_count = snapshot
3091 .reversed_chars_at(selection.start)
3092 .take_while(|&c| c != '\n')
3093 .filter(|&c| c == target)
3094 .count();
3095 current_line_count % 2 == 1
3096 } else {
3097 false
3098 };
3099
3100 if autoclose
3101 && bracket_pair.close
3102 && following_text_allows_autoclose
3103 && preceding_text_allows_autoclose
3104 && !is_closing_quote
3105 {
3106 let anchor = snapshot.anchor_before(selection.end);
3107 new_selections.push((selection.map(|_| anchor), text.len()));
3108 new_autoclose_regions.push((
3109 anchor,
3110 text.len(),
3111 selection.id,
3112 bracket_pair.clone(),
3113 ));
3114 edits.push((
3115 selection.range(),
3116 format!("{}{}", text, bracket_pair.end).into(),
3117 ));
3118 bracket_inserted = true;
3119 continue;
3120 }
3121 }
3122
3123 if let Some(region) = autoclose_region {
3124 // If the selection is followed by an auto-inserted closing bracket,
3125 // then don't insert that closing bracket again; just move the selection
3126 // past the closing bracket.
3127 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3128 && text.as_ref() == region.pair.end.as_str();
3129 if should_skip {
3130 let anchor = snapshot.anchor_after(selection.end);
3131 new_selections
3132 .push((selection.map(|_| anchor), region.pair.end.len()));
3133 continue;
3134 }
3135 }
3136
3137 let always_treat_brackets_as_autoclosed = snapshot
3138 .language_settings_at(selection.start, cx)
3139 .always_treat_brackets_as_autoclosed;
3140 if always_treat_brackets_as_autoclosed
3141 && is_bracket_pair_end
3142 && snapshot.contains_str_at(selection.end, text.as_ref())
3143 {
3144 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3145 // and the inserted text is a closing bracket and the selection is followed
3146 // by the closing bracket then move the selection past the closing bracket.
3147 let anchor = snapshot.anchor_after(selection.end);
3148 new_selections.push((selection.map(|_| anchor), text.len()));
3149 continue;
3150 }
3151 }
3152 // If an opening bracket is 1 character long and is typed while
3153 // text is selected, then surround that text with the bracket pair.
3154 else if auto_surround
3155 && bracket_pair.surround
3156 && is_bracket_pair_start
3157 && bracket_pair.start.chars().count() == 1
3158 {
3159 edits.push((selection.start..selection.start, text.clone()));
3160 edits.push((
3161 selection.end..selection.end,
3162 bracket_pair.end.as_str().into(),
3163 ));
3164 bracket_inserted = true;
3165 new_selections.push((
3166 Selection {
3167 id: selection.id,
3168 start: snapshot.anchor_after(selection.start),
3169 end: snapshot.anchor_before(selection.end),
3170 reversed: selection.reversed,
3171 goal: selection.goal,
3172 },
3173 0,
3174 ));
3175 continue;
3176 }
3177 }
3178 }
3179
3180 if self.auto_replace_emoji_shortcode
3181 && selection.is_empty()
3182 && text.as_ref().ends_with(':')
3183 {
3184 if let Some(possible_emoji_short_code) =
3185 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3186 {
3187 if !possible_emoji_short_code.is_empty() {
3188 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3189 let emoji_shortcode_start = Point::new(
3190 selection.start.row,
3191 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3192 );
3193
3194 // Remove shortcode from buffer
3195 edits.push((
3196 emoji_shortcode_start..selection.start,
3197 "".to_string().into(),
3198 ));
3199 new_selections.push((
3200 Selection {
3201 id: selection.id,
3202 start: snapshot.anchor_after(emoji_shortcode_start),
3203 end: snapshot.anchor_before(selection.start),
3204 reversed: selection.reversed,
3205 goal: selection.goal,
3206 },
3207 0,
3208 ));
3209
3210 // Insert emoji
3211 let selection_start_anchor = snapshot.anchor_after(selection.start);
3212 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3213 edits.push((selection.start..selection.end, emoji.to_string().into()));
3214
3215 continue;
3216 }
3217 }
3218 }
3219 }
3220
3221 // If not handling any auto-close operation, then just replace the selected
3222 // text with the given input and move the selection to the end of the
3223 // newly inserted text.
3224 let anchor = snapshot.anchor_after(selection.end);
3225 if !self.linked_edit_ranges.is_empty() {
3226 let start_anchor = snapshot.anchor_before(selection.start);
3227
3228 let is_word_char = text.chars().next().map_or(true, |char| {
3229 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3230 classifier.is_word(char)
3231 });
3232
3233 if is_word_char {
3234 if let Some(ranges) = self
3235 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3236 {
3237 for (buffer, edits) in ranges {
3238 linked_edits
3239 .entry(buffer.clone())
3240 .or_default()
3241 .extend(edits.into_iter().map(|range| (range, text.clone())));
3242 }
3243 }
3244 }
3245 }
3246
3247 new_selections.push((selection.map(|_| anchor), 0));
3248 edits.push((selection.start..selection.end, text.clone()));
3249 }
3250
3251 drop(snapshot);
3252
3253 self.transact(window, cx, |this, window, cx| {
3254 let initial_buffer_versions =
3255 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3256
3257 this.buffer.update(cx, |buffer, cx| {
3258 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3259 });
3260 for (buffer, edits) in linked_edits {
3261 buffer.update(cx, |buffer, cx| {
3262 let snapshot = buffer.snapshot();
3263 let edits = edits
3264 .into_iter()
3265 .map(|(range, text)| {
3266 use text::ToPoint as TP;
3267 let end_point = TP::to_point(&range.end, &snapshot);
3268 let start_point = TP::to_point(&range.start, &snapshot);
3269 (start_point..end_point, text)
3270 })
3271 .sorted_by_key(|(range, _)| range.start);
3272 buffer.edit(edits, None, cx);
3273 })
3274 }
3275 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3276 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3277 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3278 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3279 .zip(new_selection_deltas)
3280 .map(|(selection, delta)| Selection {
3281 id: selection.id,
3282 start: selection.start + delta,
3283 end: selection.end + delta,
3284 reversed: selection.reversed,
3285 goal: SelectionGoal::None,
3286 })
3287 .collect::<Vec<_>>();
3288
3289 let mut i = 0;
3290 for (position, delta, selection_id, pair) in new_autoclose_regions {
3291 let position = position.to_offset(&map.buffer_snapshot) + delta;
3292 let start = map.buffer_snapshot.anchor_before(position);
3293 let end = map.buffer_snapshot.anchor_after(position);
3294 while let Some(existing_state) = this.autoclose_regions.get(i) {
3295 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3296 Ordering::Less => i += 1,
3297 Ordering::Greater => break,
3298 Ordering::Equal => {
3299 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3300 Ordering::Less => i += 1,
3301 Ordering::Equal => break,
3302 Ordering::Greater => break,
3303 }
3304 }
3305 }
3306 }
3307 this.autoclose_regions.insert(
3308 i,
3309 AutocloseRegion {
3310 selection_id,
3311 range: start..end,
3312 pair,
3313 },
3314 );
3315 }
3316
3317 let had_active_inline_completion = this.has_active_inline_completion();
3318 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3319 s.select(new_selections)
3320 });
3321
3322 if !bracket_inserted {
3323 if let Some(on_type_format_task) =
3324 this.trigger_on_type_formatting(text.to_string(), window, cx)
3325 {
3326 on_type_format_task.detach_and_log_err(cx);
3327 }
3328 }
3329
3330 let editor_settings = EditorSettings::get_global(cx);
3331 if bracket_inserted
3332 && (editor_settings.auto_signature_help
3333 || editor_settings.show_signature_help_after_edits)
3334 {
3335 this.show_signature_help(&ShowSignatureHelp, window, cx);
3336 }
3337
3338 let trigger_in_words =
3339 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3340 if this.hard_wrap.is_some() {
3341 let latest: Range<Point> = this.selections.newest(cx).range();
3342 if latest.is_empty()
3343 && this
3344 .buffer()
3345 .read(cx)
3346 .snapshot(cx)
3347 .line_len(MultiBufferRow(latest.start.row))
3348 == latest.start.column
3349 {
3350 this.rewrap_impl(
3351 RewrapOptions {
3352 override_language_settings: true,
3353 preserve_existing_whitespace: true,
3354 },
3355 cx,
3356 )
3357 }
3358 }
3359 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3360 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3361 this.refresh_inline_completion(true, false, window, cx);
3362 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3363 });
3364 }
3365
3366 fn find_possible_emoji_shortcode_at_position(
3367 snapshot: &MultiBufferSnapshot,
3368 position: Point,
3369 ) -> Option<String> {
3370 let mut chars = Vec::new();
3371 let mut found_colon = false;
3372 for char in snapshot.reversed_chars_at(position).take(100) {
3373 // Found a possible emoji shortcode in the middle of the buffer
3374 if found_colon {
3375 if char.is_whitespace() {
3376 chars.reverse();
3377 return Some(chars.iter().collect());
3378 }
3379 // If the previous character is not a whitespace, we are in the middle of a word
3380 // and we only want to complete the shortcode if the word is made up of other emojis
3381 let mut containing_word = String::new();
3382 for ch in snapshot
3383 .reversed_chars_at(position)
3384 .skip(chars.len() + 1)
3385 .take(100)
3386 {
3387 if ch.is_whitespace() {
3388 break;
3389 }
3390 containing_word.push(ch);
3391 }
3392 let containing_word = containing_word.chars().rev().collect::<String>();
3393 if util::word_consists_of_emojis(containing_word.as_str()) {
3394 chars.reverse();
3395 return Some(chars.iter().collect());
3396 }
3397 }
3398
3399 if char.is_whitespace() || !char.is_ascii() {
3400 return None;
3401 }
3402 if char == ':' {
3403 found_colon = true;
3404 } else {
3405 chars.push(char);
3406 }
3407 }
3408 // Found a possible emoji shortcode at the beginning of the buffer
3409 chars.reverse();
3410 Some(chars.iter().collect())
3411 }
3412
3413 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3414 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3415 self.transact(window, cx, |this, window, cx| {
3416 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3417 let selections = this.selections.all::<usize>(cx);
3418 let multi_buffer = this.buffer.read(cx);
3419 let buffer = multi_buffer.snapshot(cx);
3420 selections
3421 .iter()
3422 .map(|selection| {
3423 let start_point = selection.start.to_point(&buffer);
3424 let mut indent =
3425 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3426 indent.len = cmp::min(indent.len, start_point.column);
3427 let start = selection.start;
3428 let end = selection.end;
3429 let selection_is_empty = start == end;
3430 let language_scope = buffer.language_scope_at(start);
3431 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3432 &language_scope
3433 {
3434 let insert_extra_newline =
3435 insert_extra_newline_brackets(&buffer, start..end, language)
3436 || insert_extra_newline_tree_sitter(&buffer, start..end);
3437
3438 // Comment extension on newline is allowed only for cursor selections
3439 let comment_delimiter = maybe!({
3440 if !selection_is_empty {
3441 return None;
3442 }
3443
3444 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3445 return None;
3446 }
3447
3448 let delimiters = language.line_comment_prefixes();
3449 let max_len_of_delimiter =
3450 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3451 let (snapshot, range) =
3452 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3453
3454 let mut index_of_first_non_whitespace = 0;
3455 let comment_candidate = snapshot
3456 .chars_for_range(range)
3457 .skip_while(|c| {
3458 let should_skip = c.is_whitespace();
3459 if should_skip {
3460 index_of_first_non_whitespace += 1;
3461 }
3462 should_skip
3463 })
3464 .take(max_len_of_delimiter)
3465 .collect::<String>();
3466 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3467 comment_candidate.starts_with(comment_prefix.as_ref())
3468 })?;
3469 let cursor_is_placed_after_comment_marker =
3470 index_of_first_non_whitespace + comment_prefix.len()
3471 <= start_point.column as usize;
3472 if cursor_is_placed_after_comment_marker {
3473 Some(comment_prefix.clone())
3474 } else {
3475 None
3476 }
3477 });
3478 (comment_delimiter, insert_extra_newline)
3479 } else {
3480 (None, false)
3481 };
3482
3483 let capacity_for_delimiter = comment_delimiter
3484 .as_deref()
3485 .map(str::len)
3486 .unwrap_or_default();
3487 let mut new_text =
3488 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3489 new_text.push('\n');
3490 new_text.extend(indent.chars());
3491 if let Some(delimiter) = &comment_delimiter {
3492 new_text.push_str(delimiter);
3493 }
3494 if insert_extra_newline {
3495 new_text = new_text.repeat(2);
3496 }
3497
3498 let anchor = buffer.anchor_after(end);
3499 let new_selection = selection.map(|_| anchor);
3500 (
3501 (start..end, new_text),
3502 (insert_extra_newline, new_selection),
3503 )
3504 })
3505 .unzip()
3506 };
3507
3508 this.edit_with_autoindent(edits, cx);
3509 let buffer = this.buffer.read(cx).snapshot(cx);
3510 let new_selections = selection_fixup_info
3511 .into_iter()
3512 .map(|(extra_newline_inserted, new_selection)| {
3513 let mut cursor = new_selection.end.to_point(&buffer);
3514 if extra_newline_inserted {
3515 cursor.row -= 1;
3516 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3517 }
3518 new_selection.map(|_| cursor)
3519 })
3520 .collect();
3521
3522 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3523 s.select(new_selections)
3524 });
3525 this.refresh_inline_completion(true, false, window, cx);
3526 });
3527 }
3528
3529 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3530 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3531
3532 let buffer = self.buffer.read(cx);
3533 let snapshot = buffer.snapshot(cx);
3534
3535 let mut edits = Vec::new();
3536 let mut rows = Vec::new();
3537
3538 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3539 let cursor = selection.head();
3540 let row = cursor.row;
3541
3542 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3543
3544 let newline = "\n".to_string();
3545 edits.push((start_of_line..start_of_line, newline));
3546
3547 rows.push(row + rows_inserted as u32);
3548 }
3549
3550 self.transact(window, cx, |editor, window, cx| {
3551 editor.edit(edits, cx);
3552
3553 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3554 let mut index = 0;
3555 s.move_cursors_with(|map, _, _| {
3556 let row = rows[index];
3557 index += 1;
3558
3559 let point = Point::new(row, 0);
3560 let boundary = map.next_line_boundary(point).1;
3561 let clipped = map.clip_point(boundary, Bias::Left);
3562
3563 (clipped, SelectionGoal::None)
3564 });
3565 });
3566
3567 let mut indent_edits = Vec::new();
3568 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3569 for row in rows {
3570 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3571 for (row, indent) in indents {
3572 if indent.len == 0 {
3573 continue;
3574 }
3575
3576 let text = match indent.kind {
3577 IndentKind::Space => " ".repeat(indent.len as usize),
3578 IndentKind::Tab => "\t".repeat(indent.len as usize),
3579 };
3580 let point = Point::new(row.0, 0);
3581 indent_edits.push((point..point, text));
3582 }
3583 }
3584 editor.edit(indent_edits, cx);
3585 });
3586 }
3587
3588 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3589 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3590
3591 let buffer = self.buffer.read(cx);
3592 let snapshot = buffer.snapshot(cx);
3593
3594 let mut edits = Vec::new();
3595 let mut rows = Vec::new();
3596 let mut rows_inserted = 0;
3597
3598 for selection in self.selections.all_adjusted(cx) {
3599 let cursor = selection.head();
3600 let row = cursor.row;
3601
3602 let point = Point::new(row + 1, 0);
3603 let start_of_line = snapshot.clip_point(point, Bias::Left);
3604
3605 let newline = "\n".to_string();
3606 edits.push((start_of_line..start_of_line, newline));
3607
3608 rows_inserted += 1;
3609 rows.push(row + rows_inserted);
3610 }
3611
3612 self.transact(window, cx, |editor, window, cx| {
3613 editor.edit(edits, cx);
3614
3615 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3616 let mut index = 0;
3617 s.move_cursors_with(|map, _, _| {
3618 let row = rows[index];
3619 index += 1;
3620
3621 let point = Point::new(row, 0);
3622 let boundary = map.next_line_boundary(point).1;
3623 let clipped = map.clip_point(boundary, Bias::Left);
3624
3625 (clipped, SelectionGoal::None)
3626 });
3627 });
3628
3629 let mut indent_edits = Vec::new();
3630 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3631 for row in rows {
3632 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3633 for (row, indent) in indents {
3634 if indent.len == 0 {
3635 continue;
3636 }
3637
3638 let text = match indent.kind {
3639 IndentKind::Space => " ".repeat(indent.len as usize),
3640 IndentKind::Tab => "\t".repeat(indent.len as usize),
3641 };
3642 let point = Point::new(row.0, 0);
3643 indent_edits.push((point..point, text));
3644 }
3645 }
3646 editor.edit(indent_edits, cx);
3647 });
3648 }
3649
3650 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3651 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3652 original_indent_columns: Vec::new(),
3653 });
3654 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3655 }
3656
3657 fn insert_with_autoindent_mode(
3658 &mut self,
3659 text: &str,
3660 autoindent_mode: Option<AutoindentMode>,
3661 window: &mut Window,
3662 cx: &mut Context<Self>,
3663 ) {
3664 if self.read_only(cx) {
3665 return;
3666 }
3667
3668 let text: Arc<str> = text.into();
3669 self.transact(window, cx, |this, window, cx| {
3670 let old_selections = this.selections.all_adjusted(cx);
3671 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3672 let anchors = {
3673 let snapshot = buffer.read(cx);
3674 old_selections
3675 .iter()
3676 .map(|s| {
3677 let anchor = snapshot.anchor_after(s.head());
3678 s.map(|_| anchor)
3679 })
3680 .collect::<Vec<_>>()
3681 };
3682 buffer.edit(
3683 old_selections
3684 .iter()
3685 .map(|s| (s.start..s.end, text.clone())),
3686 autoindent_mode,
3687 cx,
3688 );
3689 anchors
3690 });
3691
3692 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3693 s.select_anchors(selection_anchors);
3694 });
3695
3696 cx.notify();
3697 });
3698 }
3699
3700 fn trigger_completion_on_input(
3701 &mut self,
3702 text: &str,
3703 trigger_in_words: bool,
3704 window: &mut Window,
3705 cx: &mut Context<Self>,
3706 ) {
3707 let ignore_completion_provider = self
3708 .context_menu
3709 .borrow()
3710 .as_ref()
3711 .map(|menu| match menu {
3712 CodeContextMenu::Completions(completions_menu) => {
3713 completions_menu.ignore_completion_provider
3714 }
3715 CodeContextMenu::CodeActions(_) => false,
3716 })
3717 .unwrap_or(false);
3718
3719 if ignore_completion_provider {
3720 self.show_word_completions(&ShowWordCompletions, window, cx);
3721 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3722 self.show_completions(
3723 &ShowCompletions {
3724 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3725 },
3726 window,
3727 cx,
3728 );
3729 } else {
3730 self.hide_context_menu(window, cx);
3731 }
3732 }
3733
3734 fn is_completion_trigger(
3735 &self,
3736 text: &str,
3737 trigger_in_words: bool,
3738 cx: &mut Context<Self>,
3739 ) -> bool {
3740 let position = self.selections.newest_anchor().head();
3741 let multibuffer = self.buffer.read(cx);
3742 let Some(buffer) = position
3743 .buffer_id
3744 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3745 else {
3746 return false;
3747 };
3748
3749 if let Some(completion_provider) = &self.completion_provider {
3750 completion_provider.is_completion_trigger(
3751 &buffer,
3752 position.text_anchor,
3753 text,
3754 trigger_in_words,
3755 cx,
3756 )
3757 } else {
3758 false
3759 }
3760 }
3761
3762 /// If any empty selections is touching the start of its innermost containing autoclose
3763 /// region, expand it to select the brackets.
3764 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3765 let selections = self.selections.all::<usize>(cx);
3766 let buffer = self.buffer.read(cx).read(cx);
3767 let new_selections = self
3768 .selections_with_autoclose_regions(selections, &buffer)
3769 .map(|(mut selection, region)| {
3770 if !selection.is_empty() {
3771 return selection;
3772 }
3773
3774 if let Some(region) = region {
3775 let mut range = region.range.to_offset(&buffer);
3776 if selection.start == range.start && range.start >= region.pair.start.len() {
3777 range.start -= region.pair.start.len();
3778 if buffer.contains_str_at(range.start, ®ion.pair.start)
3779 && buffer.contains_str_at(range.end, ®ion.pair.end)
3780 {
3781 range.end += region.pair.end.len();
3782 selection.start = range.start;
3783 selection.end = range.end;
3784
3785 return selection;
3786 }
3787 }
3788 }
3789
3790 let always_treat_brackets_as_autoclosed = buffer
3791 .language_settings_at(selection.start, cx)
3792 .always_treat_brackets_as_autoclosed;
3793
3794 if !always_treat_brackets_as_autoclosed {
3795 return selection;
3796 }
3797
3798 if let Some(scope) = buffer.language_scope_at(selection.start) {
3799 for (pair, enabled) in scope.brackets() {
3800 if !enabled || !pair.close {
3801 continue;
3802 }
3803
3804 if buffer.contains_str_at(selection.start, &pair.end) {
3805 let pair_start_len = pair.start.len();
3806 if buffer.contains_str_at(
3807 selection.start.saturating_sub(pair_start_len),
3808 &pair.start,
3809 ) {
3810 selection.start -= pair_start_len;
3811 selection.end += pair.end.len();
3812
3813 return selection;
3814 }
3815 }
3816 }
3817 }
3818
3819 selection
3820 })
3821 .collect();
3822
3823 drop(buffer);
3824 self.change_selections(None, window, cx, |selections| {
3825 selections.select(new_selections)
3826 });
3827 }
3828
3829 /// Iterate the given selections, and for each one, find the smallest surrounding
3830 /// autoclose region. This uses the ordering of the selections and the autoclose
3831 /// regions to avoid repeated comparisons.
3832 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3833 &'a self,
3834 selections: impl IntoIterator<Item = Selection<D>>,
3835 buffer: &'a MultiBufferSnapshot,
3836 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3837 let mut i = 0;
3838 let mut regions = self.autoclose_regions.as_slice();
3839 selections.into_iter().map(move |selection| {
3840 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3841
3842 let mut enclosing = None;
3843 while let Some(pair_state) = regions.get(i) {
3844 if pair_state.range.end.to_offset(buffer) < range.start {
3845 regions = ®ions[i + 1..];
3846 i = 0;
3847 } else if pair_state.range.start.to_offset(buffer) > range.end {
3848 break;
3849 } else {
3850 if pair_state.selection_id == selection.id {
3851 enclosing = Some(pair_state);
3852 }
3853 i += 1;
3854 }
3855 }
3856
3857 (selection, enclosing)
3858 })
3859 }
3860
3861 /// Remove any autoclose regions that no longer contain their selection.
3862 fn invalidate_autoclose_regions(
3863 &mut self,
3864 mut selections: &[Selection<Anchor>],
3865 buffer: &MultiBufferSnapshot,
3866 ) {
3867 self.autoclose_regions.retain(|state| {
3868 let mut i = 0;
3869 while let Some(selection) = selections.get(i) {
3870 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3871 selections = &selections[1..];
3872 continue;
3873 }
3874 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3875 break;
3876 }
3877 if selection.id == state.selection_id {
3878 return true;
3879 } else {
3880 i += 1;
3881 }
3882 }
3883 false
3884 });
3885 }
3886
3887 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3888 let offset = position.to_offset(buffer);
3889 let (word_range, kind) = buffer.surrounding_word(offset, true);
3890 if offset > word_range.start && kind == Some(CharKind::Word) {
3891 Some(
3892 buffer
3893 .text_for_range(word_range.start..offset)
3894 .collect::<String>(),
3895 )
3896 } else {
3897 None
3898 }
3899 }
3900
3901 pub fn toggle_inlay_hints(
3902 &mut self,
3903 _: &ToggleInlayHints,
3904 _: &mut Window,
3905 cx: &mut Context<Self>,
3906 ) {
3907 self.refresh_inlay_hints(
3908 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3909 cx,
3910 );
3911 }
3912
3913 pub fn inlay_hints_enabled(&self) -> bool {
3914 self.inlay_hint_cache.enabled
3915 }
3916
3917 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3918 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3919 return;
3920 }
3921
3922 let reason_description = reason.description();
3923 let ignore_debounce = matches!(
3924 reason,
3925 InlayHintRefreshReason::SettingsChange(_)
3926 | InlayHintRefreshReason::Toggle(_)
3927 | InlayHintRefreshReason::ExcerptsRemoved(_)
3928 | InlayHintRefreshReason::ModifiersChanged(_)
3929 );
3930 let (invalidate_cache, required_languages) = match reason {
3931 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3932 match self.inlay_hint_cache.modifiers_override(enabled) {
3933 Some(enabled) => {
3934 if enabled {
3935 (InvalidationStrategy::RefreshRequested, None)
3936 } else {
3937 self.splice_inlays(
3938 &self
3939 .visible_inlay_hints(cx)
3940 .iter()
3941 .map(|inlay| inlay.id)
3942 .collect::<Vec<InlayId>>(),
3943 Vec::new(),
3944 cx,
3945 );
3946 return;
3947 }
3948 }
3949 None => return,
3950 }
3951 }
3952 InlayHintRefreshReason::Toggle(enabled) => {
3953 if self.inlay_hint_cache.toggle(enabled) {
3954 if enabled {
3955 (InvalidationStrategy::RefreshRequested, None)
3956 } else {
3957 self.splice_inlays(
3958 &self
3959 .visible_inlay_hints(cx)
3960 .iter()
3961 .map(|inlay| inlay.id)
3962 .collect::<Vec<InlayId>>(),
3963 Vec::new(),
3964 cx,
3965 );
3966 return;
3967 }
3968 } else {
3969 return;
3970 }
3971 }
3972 InlayHintRefreshReason::SettingsChange(new_settings) => {
3973 match self.inlay_hint_cache.update_settings(
3974 &self.buffer,
3975 new_settings,
3976 self.visible_inlay_hints(cx),
3977 cx,
3978 ) {
3979 ControlFlow::Break(Some(InlaySplice {
3980 to_remove,
3981 to_insert,
3982 })) => {
3983 self.splice_inlays(&to_remove, to_insert, cx);
3984 return;
3985 }
3986 ControlFlow::Break(None) => return,
3987 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3988 }
3989 }
3990 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3991 if let Some(InlaySplice {
3992 to_remove,
3993 to_insert,
3994 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3995 {
3996 self.splice_inlays(&to_remove, to_insert, cx);
3997 }
3998 return;
3999 }
4000 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4001 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4002 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4003 }
4004 InlayHintRefreshReason::RefreshRequested => {
4005 (InvalidationStrategy::RefreshRequested, None)
4006 }
4007 };
4008
4009 if let Some(InlaySplice {
4010 to_remove,
4011 to_insert,
4012 }) = self.inlay_hint_cache.spawn_hint_refresh(
4013 reason_description,
4014 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4015 invalidate_cache,
4016 ignore_debounce,
4017 cx,
4018 ) {
4019 self.splice_inlays(&to_remove, to_insert, cx);
4020 }
4021 }
4022
4023 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4024 self.display_map
4025 .read(cx)
4026 .current_inlays()
4027 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4028 .cloned()
4029 .collect()
4030 }
4031
4032 pub fn excerpts_for_inlay_hints_query(
4033 &self,
4034 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4035 cx: &mut Context<Editor>,
4036 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4037 let Some(project) = self.project.as_ref() else {
4038 return HashMap::default();
4039 };
4040 let project = project.read(cx);
4041 let multi_buffer = self.buffer().read(cx);
4042 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4043 let multi_buffer_visible_start = self
4044 .scroll_manager
4045 .anchor()
4046 .anchor
4047 .to_point(&multi_buffer_snapshot);
4048 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4049 multi_buffer_visible_start
4050 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4051 Bias::Left,
4052 );
4053 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4054 multi_buffer_snapshot
4055 .range_to_buffer_ranges(multi_buffer_visible_range)
4056 .into_iter()
4057 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4058 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4059 let buffer_file = project::File::from_dyn(buffer.file())?;
4060 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4061 let worktree_entry = buffer_worktree
4062 .read(cx)
4063 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4064 if worktree_entry.is_ignored {
4065 return None;
4066 }
4067
4068 let language = buffer.language()?;
4069 if let Some(restrict_to_languages) = restrict_to_languages {
4070 if !restrict_to_languages.contains(language) {
4071 return None;
4072 }
4073 }
4074 Some((
4075 excerpt_id,
4076 (
4077 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4078 buffer.version().clone(),
4079 excerpt_visible_range,
4080 ),
4081 ))
4082 })
4083 .collect()
4084 }
4085
4086 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4087 TextLayoutDetails {
4088 text_system: window.text_system().clone(),
4089 editor_style: self.style.clone().unwrap(),
4090 rem_size: window.rem_size(),
4091 scroll_anchor: self.scroll_manager.anchor(),
4092 visible_rows: self.visible_line_count(),
4093 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4094 }
4095 }
4096
4097 pub fn splice_inlays(
4098 &self,
4099 to_remove: &[InlayId],
4100 to_insert: Vec<Inlay>,
4101 cx: &mut Context<Self>,
4102 ) {
4103 self.display_map.update(cx, |display_map, cx| {
4104 display_map.splice_inlays(to_remove, to_insert, cx)
4105 });
4106 cx.notify();
4107 }
4108
4109 fn trigger_on_type_formatting(
4110 &self,
4111 input: String,
4112 window: &mut Window,
4113 cx: &mut Context<Self>,
4114 ) -> Option<Task<Result<()>>> {
4115 if input.len() != 1 {
4116 return None;
4117 }
4118
4119 let project = self.project.as_ref()?;
4120 let position = self.selections.newest_anchor().head();
4121 let (buffer, buffer_position) = self
4122 .buffer
4123 .read(cx)
4124 .text_anchor_for_position(position, cx)?;
4125
4126 let settings = language_settings::language_settings(
4127 buffer
4128 .read(cx)
4129 .language_at(buffer_position)
4130 .map(|l| l.name()),
4131 buffer.read(cx).file(),
4132 cx,
4133 );
4134 if !settings.use_on_type_format {
4135 return None;
4136 }
4137
4138 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4139 // hence we do LSP request & edit on host side only — add formats to host's history.
4140 let push_to_lsp_host_history = true;
4141 // If this is not the host, append its history with new edits.
4142 let push_to_client_history = project.read(cx).is_via_collab();
4143
4144 let on_type_formatting = project.update(cx, |project, cx| {
4145 project.on_type_format(
4146 buffer.clone(),
4147 buffer_position,
4148 input,
4149 push_to_lsp_host_history,
4150 cx,
4151 )
4152 });
4153 Some(cx.spawn_in(window, async move |editor, cx| {
4154 if let Some(transaction) = on_type_formatting.await? {
4155 if push_to_client_history {
4156 buffer
4157 .update(cx, |buffer, _| {
4158 buffer.push_transaction(transaction, Instant::now());
4159 })
4160 .ok();
4161 }
4162 editor.update(cx, |editor, cx| {
4163 editor.refresh_document_highlights(cx);
4164 })?;
4165 }
4166 Ok(())
4167 }))
4168 }
4169
4170 pub fn show_word_completions(
4171 &mut self,
4172 _: &ShowWordCompletions,
4173 window: &mut Window,
4174 cx: &mut Context<Self>,
4175 ) {
4176 self.open_completions_menu(true, None, window, cx);
4177 }
4178
4179 pub fn show_completions(
4180 &mut self,
4181 options: &ShowCompletions,
4182 window: &mut Window,
4183 cx: &mut Context<Self>,
4184 ) {
4185 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4186 }
4187
4188 fn open_completions_menu(
4189 &mut self,
4190 ignore_completion_provider: bool,
4191 trigger: Option<&str>,
4192 window: &mut Window,
4193 cx: &mut Context<Self>,
4194 ) {
4195 if self.pending_rename.is_some() {
4196 return;
4197 }
4198 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4199 return;
4200 }
4201
4202 let position = self.selections.newest_anchor().head();
4203 if position.diff_base_anchor.is_some() {
4204 return;
4205 }
4206 let (buffer, buffer_position) =
4207 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4208 output
4209 } else {
4210 return;
4211 };
4212 let buffer_snapshot = buffer.read(cx).snapshot();
4213 let show_completion_documentation = buffer_snapshot
4214 .settings_at(buffer_position, cx)
4215 .show_completion_documentation;
4216
4217 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4218
4219 let trigger_kind = match trigger {
4220 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4221 CompletionTriggerKind::TRIGGER_CHARACTER
4222 }
4223 _ => CompletionTriggerKind::INVOKED,
4224 };
4225 let completion_context = CompletionContext {
4226 trigger_character: trigger.and_then(|trigger| {
4227 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4228 Some(String::from(trigger))
4229 } else {
4230 None
4231 }
4232 }),
4233 trigger_kind,
4234 };
4235
4236 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4237 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4238 let word_to_exclude = buffer_snapshot
4239 .text_for_range(old_range.clone())
4240 .collect::<String>();
4241 (
4242 buffer_snapshot.anchor_before(old_range.start)
4243 ..buffer_snapshot.anchor_after(old_range.end),
4244 Some(word_to_exclude),
4245 )
4246 } else {
4247 (buffer_position..buffer_position, None)
4248 };
4249
4250 let completion_settings = language_settings(
4251 buffer_snapshot
4252 .language_at(buffer_position)
4253 .map(|language| language.name()),
4254 buffer_snapshot.file(),
4255 cx,
4256 )
4257 .completions;
4258
4259 // The document can be large, so stay in reasonable bounds when searching for words,
4260 // otherwise completion pop-up might be slow to appear.
4261 const WORD_LOOKUP_ROWS: u32 = 5_000;
4262 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4263 let min_word_search = buffer_snapshot.clip_point(
4264 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4265 Bias::Left,
4266 );
4267 let max_word_search = buffer_snapshot.clip_point(
4268 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4269 Bias::Right,
4270 );
4271 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4272 ..buffer_snapshot.point_to_offset(max_word_search);
4273
4274 let provider = self
4275 .completion_provider
4276 .as_ref()
4277 .filter(|_| !ignore_completion_provider);
4278 let skip_digits = query
4279 .as_ref()
4280 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4281
4282 let (mut words, provided_completions) = match provider {
4283 Some(provider) => {
4284 let completions = provider.completions(
4285 position.excerpt_id,
4286 &buffer,
4287 buffer_position,
4288 completion_context,
4289 window,
4290 cx,
4291 );
4292
4293 let words = match completion_settings.words {
4294 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4295 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4296 .background_spawn(async move {
4297 buffer_snapshot.words_in_range(WordsQuery {
4298 fuzzy_contents: None,
4299 range: word_search_range,
4300 skip_digits,
4301 })
4302 }),
4303 };
4304
4305 (words, completions)
4306 }
4307 None => (
4308 cx.background_spawn(async move {
4309 buffer_snapshot.words_in_range(WordsQuery {
4310 fuzzy_contents: None,
4311 range: word_search_range,
4312 skip_digits,
4313 })
4314 }),
4315 Task::ready(Ok(None)),
4316 ),
4317 };
4318
4319 let sort_completions = provider
4320 .as_ref()
4321 .map_or(true, |provider| provider.sort_completions());
4322
4323 let filter_completions = provider
4324 .as_ref()
4325 .map_or(true, |provider| provider.filter_completions());
4326
4327 let id = post_inc(&mut self.next_completion_id);
4328 let task = cx.spawn_in(window, async move |editor, cx| {
4329 async move {
4330 editor.update(cx, |this, _| {
4331 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4332 })?;
4333
4334 let mut completions = Vec::new();
4335 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4336 completions.extend(provided_completions);
4337 if completion_settings.words == WordsCompletionMode::Fallback {
4338 words = Task::ready(HashMap::default());
4339 }
4340 }
4341
4342 let mut words = words.await;
4343 if let Some(word_to_exclude) = &word_to_exclude {
4344 words.remove(word_to_exclude);
4345 }
4346 for lsp_completion in &completions {
4347 words.remove(&lsp_completion.new_text);
4348 }
4349 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4350 old_range: old_range.clone(),
4351 new_text: word.clone(),
4352 label: CodeLabel::plain(word, None),
4353 icon_path: None,
4354 documentation: None,
4355 source: CompletionSource::BufferWord {
4356 word_range,
4357 resolved: false,
4358 },
4359 confirm: None,
4360 }));
4361
4362 let menu = if completions.is_empty() {
4363 None
4364 } else {
4365 let mut menu = CompletionsMenu::new(
4366 id,
4367 sort_completions,
4368 show_completion_documentation,
4369 ignore_completion_provider,
4370 position,
4371 buffer.clone(),
4372 completions.into(),
4373 );
4374
4375 menu.filter(
4376 if filter_completions {
4377 query.as_deref()
4378 } else {
4379 None
4380 },
4381 cx.background_executor().clone(),
4382 )
4383 .await;
4384
4385 menu.visible().then_some(menu)
4386 };
4387
4388 editor.update_in(cx, |editor, window, cx| {
4389 match editor.context_menu.borrow().as_ref() {
4390 None => {}
4391 Some(CodeContextMenu::Completions(prev_menu)) => {
4392 if prev_menu.id > id {
4393 return;
4394 }
4395 }
4396 _ => return,
4397 }
4398
4399 if editor.focus_handle.is_focused(window) && menu.is_some() {
4400 let mut menu = menu.unwrap();
4401 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4402
4403 *editor.context_menu.borrow_mut() =
4404 Some(CodeContextMenu::Completions(menu));
4405
4406 if editor.show_edit_predictions_in_menu() {
4407 editor.update_visible_inline_completion(window, cx);
4408 } else {
4409 editor.discard_inline_completion(false, cx);
4410 }
4411
4412 cx.notify();
4413 } else if editor.completion_tasks.len() <= 1 {
4414 // If there are no more completion tasks and the last menu was
4415 // empty, we should hide it.
4416 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4417 // If it was already hidden and we don't show inline
4418 // completions in the menu, we should also show the
4419 // inline-completion when available.
4420 if was_hidden && editor.show_edit_predictions_in_menu() {
4421 editor.update_visible_inline_completion(window, cx);
4422 }
4423 }
4424 })?;
4425
4426 anyhow::Ok(())
4427 }
4428 .log_err()
4429 .await
4430 });
4431
4432 self.completion_tasks.push((id, task));
4433 }
4434
4435 #[cfg(feature = "test-support")]
4436 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4437 let menu = self.context_menu.borrow();
4438 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4439 let completions = menu.completions.borrow();
4440 Some(completions.to_vec())
4441 } else {
4442 None
4443 }
4444 }
4445
4446 pub fn confirm_completion(
4447 &mut self,
4448 action: &ConfirmCompletion,
4449 window: &mut Window,
4450 cx: &mut Context<Self>,
4451 ) -> Option<Task<Result<()>>> {
4452 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4453 }
4454
4455 pub fn compose_completion(
4456 &mut self,
4457 action: &ComposeCompletion,
4458 window: &mut Window,
4459 cx: &mut Context<Self>,
4460 ) -> Option<Task<Result<()>>> {
4461 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4462 }
4463
4464 fn do_completion(
4465 &mut self,
4466 item_ix: Option<usize>,
4467 intent: CompletionIntent,
4468 window: &mut Window,
4469 cx: &mut Context<Editor>,
4470 ) -> Option<Task<Result<()>>> {
4471 use language::ToOffset as _;
4472
4473 let completions_menu =
4474 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4475 menu
4476 } else {
4477 return None;
4478 };
4479
4480 let candidate_id = {
4481 let entries = completions_menu.entries.borrow();
4482 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4483 if self.show_edit_predictions_in_menu() {
4484 self.discard_inline_completion(true, cx);
4485 }
4486 mat.candidate_id
4487 };
4488
4489 let buffer_handle = completions_menu.buffer;
4490 let completion = completions_menu
4491 .completions
4492 .borrow()
4493 .get(candidate_id)?
4494 .clone();
4495 cx.stop_propagation();
4496
4497 let snippet;
4498 let new_text;
4499 if completion.is_snippet() {
4500 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4501 new_text = snippet.as_ref().unwrap().text.clone();
4502 } else {
4503 snippet = None;
4504 new_text = completion.new_text.clone();
4505 };
4506 let selections = self.selections.all::<usize>(cx);
4507 let buffer = buffer_handle.read(cx);
4508 let old_range = completion.old_range.to_offset(buffer);
4509 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4510
4511 let newest_selection = self.selections.newest_anchor();
4512 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4513 return None;
4514 }
4515
4516 let lookbehind = newest_selection
4517 .start
4518 .text_anchor
4519 .to_offset(buffer)
4520 .saturating_sub(old_range.start);
4521 let lookahead = old_range
4522 .end
4523 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4524 let mut common_prefix_len = old_text
4525 .bytes()
4526 .zip(new_text.bytes())
4527 .take_while(|(a, b)| a == b)
4528 .count();
4529
4530 let snapshot = self.buffer.read(cx).snapshot(cx);
4531 let mut range_to_replace: Option<Range<isize>> = None;
4532 let mut ranges = Vec::new();
4533 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4534 for selection in &selections {
4535 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4536 let start = selection.start.saturating_sub(lookbehind);
4537 let end = selection.end + lookahead;
4538 if selection.id == newest_selection.id {
4539 range_to_replace = Some(
4540 ((start + common_prefix_len) as isize - selection.start as isize)
4541 ..(end as isize - selection.start as isize),
4542 );
4543 }
4544 ranges.push(start + common_prefix_len..end);
4545 } else {
4546 common_prefix_len = 0;
4547 ranges.clear();
4548 ranges.extend(selections.iter().map(|s| {
4549 if s.id == newest_selection.id {
4550 range_to_replace = Some(
4551 old_range.start.to_offset_utf16(&snapshot).0 as isize
4552 - selection.start as isize
4553 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4554 - selection.start as isize,
4555 );
4556 old_range.clone()
4557 } else {
4558 s.start..s.end
4559 }
4560 }));
4561 break;
4562 }
4563 if !self.linked_edit_ranges.is_empty() {
4564 let start_anchor = snapshot.anchor_before(selection.head());
4565 let end_anchor = snapshot.anchor_after(selection.tail());
4566 if let Some(ranges) = self
4567 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4568 {
4569 for (buffer, edits) in ranges {
4570 linked_edits.entry(buffer.clone()).or_default().extend(
4571 edits
4572 .into_iter()
4573 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4574 );
4575 }
4576 }
4577 }
4578 }
4579 let text = &new_text[common_prefix_len..];
4580
4581 cx.emit(EditorEvent::InputHandled {
4582 utf16_range_to_replace: range_to_replace,
4583 text: text.into(),
4584 });
4585
4586 self.transact(window, cx, |this, window, cx| {
4587 if let Some(mut snippet) = snippet {
4588 snippet.text = text.to_string();
4589 for tabstop in snippet
4590 .tabstops
4591 .iter_mut()
4592 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4593 {
4594 tabstop.start -= common_prefix_len as isize;
4595 tabstop.end -= common_prefix_len as isize;
4596 }
4597
4598 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4599 } else {
4600 this.buffer.update(cx, |buffer, cx| {
4601 let edits = ranges.iter().map(|range| (range.clone(), text));
4602 buffer.edit(edits, this.autoindent_mode.clone(), cx);
4603 });
4604 }
4605 for (buffer, edits) in linked_edits {
4606 buffer.update(cx, |buffer, cx| {
4607 let snapshot = buffer.snapshot();
4608 let edits = edits
4609 .into_iter()
4610 .map(|(range, text)| {
4611 use text::ToPoint as TP;
4612 let end_point = TP::to_point(&range.end, &snapshot);
4613 let start_point = TP::to_point(&range.start, &snapshot);
4614 (start_point..end_point, text)
4615 })
4616 .sorted_by_key(|(range, _)| range.start);
4617 buffer.edit(edits, None, cx);
4618 })
4619 }
4620
4621 this.refresh_inline_completion(true, false, window, cx);
4622 });
4623
4624 let show_new_completions_on_confirm = completion
4625 .confirm
4626 .as_ref()
4627 .map_or(false, |confirm| confirm(intent, window, cx));
4628 if show_new_completions_on_confirm {
4629 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4630 }
4631
4632 let provider = self.completion_provider.as_ref()?;
4633 drop(completion);
4634 let apply_edits = provider.apply_additional_edits_for_completion(
4635 buffer_handle,
4636 completions_menu.completions.clone(),
4637 candidate_id,
4638 true,
4639 cx,
4640 );
4641
4642 let editor_settings = EditorSettings::get_global(cx);
4643 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4644 // After the code completion is finished, users often want to know what signatures are needed.
4645 // so we should automatically call signature_help
4646 self.show_signature_help(&ShowSignatureHelp, window, cx);
4647 }
4648
4649 Some(cx.foreground_executor().spawn(async move {
4650 apply_edits.await?;
4651 Ok(())
4652 }))
4653 }
4654
4655 pub fn toggle_code_actions(
4656 &mut self,
4657 action: &ToggleCodeActions,
4658 window: &mut Window,
4659 cx: &mut Context<Self>,
4660 ) {
4661 let mut context_menu = self.context_menu.borrow_mut();
4662 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4663 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4664 // Toggle if we're selecting the same one
4665 *context_menu = None;
4666 cx.notify();
4667 return;
4668 } else {
4669 // Otherwise, clear it and start a new one
4670 *context_menu = None;
4671 cx.notify();
4672 }
4673 }
4674 drop(context_menu);
4675 let snapshot = self.snapshot(window, cx);
4676 let deployed_from_indicator = action.deployed_from_indicator;
4677 let mut task = self.code_actions_task.take();
4678 let action = action.clone();
4679 cx.spawn_in(window, async move |editor, cx| {
4680 while let Some(prev_task) = task {
4681 prev_task.await.log_err();
4682 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4683 }
4684
4685 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4686 if editor.focus_handle.is_focused(window) {
4687 let multibuffer_point = action
4688 .deployed_from_indicator
4689 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4690 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4691 let (buffer, buffer_row) = snapshot
4692 .buffer_snapshot
4693 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4694 .and_then(|(buffer_snapshot, range)| {
4695 editor
4696 .buffer
4697 .read(cx)
4698 .buffer(buffer_snapshot.remote_id())
4699 .map(|buffer| (buffer, range.start.row))
4700 })?;
4701 let (_, code_actions) = editor
4702 .available_code_actions
4703 .clone()
4704 .and_then(|(location, code_actions)| {
4705 let snapshot = location.buffer.read(cx).snapshot();
4706 let point_range = location.range.to_point(&snapshot);
4707 let point_range = point_range.start.row..=point_range.end.row;
4708 if point_range.contains(&buffer_row) {
4709 Some((location, code_actions))
4710 } else {
4711 None
4712 }
4713 })
4714 .unzip();
4715 let buffer_id = buffer.read(cx).remote_id();
4716 let tasks = editor
4717 .tasks
4718 .get(&(buffer_id, buffer_row))
4719 .map(|t| Arc::new(t.to_owned()));
4720 if tasks.is_none() && code_actions.is_none() {
4721 return None;
4722 }
4723
4724 editor.completion_tasks.clear();
4725 editor.discard_inline_completion(false, cx);
4726 let task_context =
4727 tasks
4728 .as_ref()
4729 .zip(editor.project.clone())
4730 .map(|(tasks, project)| {
4731 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4732 });
4733
4734 Some(cx.spawn_in(window, async move |editor, cx| {
4735 let task_context = match task_context {
4736 Some(task_context) => task_context.await,
4737 None => None,
4738 };
4739 let resolved_tasks =
4740 tasks.zip(task_context).map(|(tasks, task_context)| {
4741 Rc::new(ResolvedTasks {
4742 templates: tasks.resolve(&task_context).collect(),
4743 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4744 multibuffer_point.row,
4745 tasks.column,
4746 )),
4747 })
4748 });
4749 let spawn_straight_away = resolved_tasks
4750 .as_ref()
4751 .map_or(false, |tasks| tasks.templates.len() == 1)
4752 && code_actions
4753 .as_ref()
4754 .map_or(true, |actions| actions.is_empty());
4755 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4756 *editor.context_menu.borrow_mut() =
4757 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4758 buffer,
4759 actions: CodeActionContents {
4760 tasks: resolved_tasks,
4761 actions: code_actions,
4762 },
4763 selected_item: Default::default(),
4764 scroll_handle: UniformListScrollHandle::default(),
4765 deployed_from_indicator,
4766 }));
4767 if spawn_straight_away {
4768 if let Some(task) = editor.confirm_code_action(
4769 &ConfirmCodeAction { item_ix: Some(0) },
4770 window,
4771 cx,
4772 ) {
4773 cx.notify();
4774 return task;
4775 }
4776 }
4777 cx.notify();
4778 Task::ready(Ok(()))
4779 }) {
4780 task.await
4781 } else {
4782 Ok(())
4783 }
4784 }))
4785 } else {
4786 Some(Task::ready(Ok(())))
4787 }
4788 })?;
4789 if let Some(task) = spawned_test_task {
4790 task.await?;
4791 }
4792
4793 Ok::<_, anyhow::Error>(())
4794 })
4795 .detach_and_log_err(cx);
4796 }
4797
4798 pub fn confirm_code_action(
4799 &mut self,
4800 action: &ConfirmCodeAction,
4801 window: &mut Window,
4802 cx: &mut Context<Self>,
4803 ) -> Option<Task<Result<()>>> {
4804 let actions_menu =
4805 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4806 menu
4807 } else {
4808 return None;
4809 };
4810 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4811 let action = actions_menu.actions.get(action_ix)?;
4812 let title = action.label();
4813 let buffer = actions_menu.buffer;
4814 let workspace = self.workspace()?;
4815
4816 match action {
4817 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4818 workspace.update(cx, |workspace, cx| {
4819 workspace::tasks::schedule_resolved_task(
4820 workspace,
4821 task_source_kind,
4822 resolved_task,
4823 false,
4824 cx,
4825 );
4826
4827 Some(Task::ready(Ok(())))
4828 })
4829 }
4830 CodeActionsItem::CodeAction {
4831 excerpt_id,
4832 action,
4833 provider,
4834 } => {
4835 let apply_code_action =
4836 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4837 let workspace = workspace.downgrade();
4838 Some(cx.spawn_in(window, async move |editor, cx| {
4839 let project_transaction = apply_code_action.await?;
4840 Self::open_project_transaction(
4841 &editor,
4842 workspace,
4843 project_transaction,
4844 title,
4845 cx,
4846 )
4847 .await
4848 }))
4849 }
4850 }
4851 }
4852
4853 pub async fn open_project_transaction(
4854 this: &WeakEntity<Editor>,
4855 workspace: WeakEntity<Workspace>,
4856 transaction: ProjectTransaction,
4857 title: String,
4858 cx: &mut AsyncWindowContext,
4859 ) -> Result<()> {
4860 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4861 cx.update(|_, cx| {
4862 entries.sort_unstable_by_key(|(buffer, _)| {
4863 buffer.read(cx).file().map(|f| f.path().clone())
4864 });
4865 })?;
4866
4867 // If the project transaction's edits are all contained within this editor, then
4868 // avoid opening a new editor to display them.
4869
4870 if let Some((buffer, transaction)) = entries.first() {
4871 if entries.len() == 1 {
4872 let excerpt = this.update(cx, |editor, cx| {
4873 editor
4874 .buffer()
4875 .read(cx)
4876 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4877 })?;
4878 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4879 if excerpted_buffer == *buffer {
4880 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
4881 let excerpt_range = excerpt_range.to_offset(buffer);
4882 buffer
4883 .edited_ranges_for_transaction::<usize>(transaction)
4884 .all(|range| {
4885 excerpt_range.start <= range.start
4886 && excerpt_range.end >= range.end
4887 })
4888 })?;
4889
4890 if all_edits_within_excerpt {
4891 return Ok(());
4892 }
4893 }
4894 }
4895 }
4896 } else {
4897 return Ok(());
4898 }
4899
4900 let mut ranges_to_highlight = Vec::new();
4901 let excerpt_buffer = cx.new(|cx| {
4902 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4903 for (buffer_handle, transaction) in &entries {
4904 let buffer = buffer_handle.read(cx);
4905 ranges_to_highlight.extend(
4906 multibuffer.push_excerpts_with_context_lines(
4907 buffer_handle.clone(),
4908 buffer
4909 .edited_ranges_for_transaction::<usize>(transaction)
4910 .collect(),
4911 DEFAULT_MULTIBUFFER_CONTEXT,
4912 cx,
4913 ),
4914 );
4915 }
4916 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4917 multibuffer
4918 })?;
4919
4920 workspace.update_in(cx, |workspace, window, cx| {
4921 let project = workspace.project().clone();
4922 let editor =
4923 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4924 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4925 editor.update(cx, |editor, cx| {
4926 editor.highlight_background::<Self>(
4927 &ranges_to_highlight,
4928 |theme| theme.editor_highlighted_line_background,
4929 cx,
4930 );
4931 });
4932 })?;
4933
4934 Ok(())
4935 }
4936
4937 pub fn clear_code_action_providers(&mut self) {
4938 self.code_action_providers.clear();
4939 self.available_code_actions.take();
4940 }
4941
4942 pub fn add_code_action_provider(
4943 &mut self,
4944 provider: Rc<dyn CodeActionProvider>,
4945 window: &mut Window,
4946 cx: &mut Context<Self>,
4947 ) {
4948 if self
4949 .code_action_providers
4950 .iter()
4951 .any(|existing_provider| existing_provider.id() == provider.id())
4952 {
4953 return;
4954 }
4955
4956 self.code_action_providers.push(provider);
4957 self.refresh_code_actions(window, cx);
4958 }
4959
4960 pub fn remove_code_action_provider(
4961 &mut self,
4962 id: Arc<str>,
4963 window: &mut Window,
4964 cx: &mut Context<Self>,
4965 ) {
4966 self.code_action_providers
4967 .retain(|provider| provider.id() != id);
4968 self.refresh_code_actions(window, cx);
4969 }
4970
4971 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4972 let buffer = self.buffer.read(cx);
4973 let newest_selection = self.selections.newest_anchor().clone();
4974 if newest_selection.head().diff_base_anchor.is_some() {
4975 return None;
4976 }
4977 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4978 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4979 if start_buffer != end_buffer {
4980 return None;
4981 }
4982
4983 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
4984 cx.background_executor()
4985 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4986 .await;
4987
4988 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
4989 let providers = this.code_action_providers.clone();
4990 let tasks = this
4991 .code_action_providers
4992 .iter()
4993 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4994 .collect::<Vec<_>>();
4995 (providers, tasks)
4996 })?;
4997
4998 let mut actions = Vec::new();
4999 for (provider, provider_actions) in
5000 providers.into_iter().zip(future::join_all(tasks).await)
5001 {
5002 if let Some(provider_actions) = provider_actions.log_err() {
5003 actions.extend(provider_actions.into_iter().map(|action| {
5004 AvailableCodeAction {
5005 excerpt_id: newest_selection.start.excerpt_id,
5006 action,
5007 provider: provider.clone(),
5008 }
5009 }));
5010 }
5011 }
5012
5013 this.update(cx, |this, cx| {
5014 this.available_code_actions = if actions.is_empty() {
5015 None
5016 } else {
5017 Some((
5018 Location {
5019 buffer: start_buffer,
5020 range: start..end,
5021 },
5022 actions.into(),
5023 ))
5024 };
5025 cx.notify();
5026 })
5027 }));
5028 None
5029 }
5030
5031 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5032 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5033 self.show_git_blame_inline = false;
5034
5035 self.show_git_blame_inline_delay_task =
5036 Some(cx.spawn_in(window, async move |this, cx| {
5037 cx.background_executor().timer(delay).await;
5038
5039 this.update(cx, |this, cx| {
5040 this.show_git_blame_inline = true;
5041 cx.notify();
5042 })
5043 .log_err();
5044 }));
5045 }
5046 }
5047
5048 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5049 if self.pending_rename.is_some() {
5050 return None;
5051 }
5052
5053 let provider = self.semantics_provider.clone()?;
5054 let buffer = self.buffer.read(cx);
5055 let newest_selection = self.selections.newest_anchor().clone();
5056 let cursor_position = newest_selection.head();
5057 let (cursor_buffer, cursor_buffer_position) =
5058 buffer.text_anchor_for_position(cursor_position, cx)?;
5059 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5060 if cursor_buffer != tail_buffer {
5061 return None;
5062 }
5063 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5064 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5065 cx.background_executor()
5066 .timer(Duration::from_millis(debounce))
5067 .await;
5068
5069 let highlights = if let Some(highlights) = cx
5070 .update(|cx| {
5071 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5072 })
5073 .ok()
5074 .flatten()
5075 {
5076 highlights.await.log_err()
5077 } else {
5078 None
5079 };
5080
5081 if let Some(highlights) = highlights {
5082 this.update(cx, |this, cx| {
5083 if this.pending_rename.is_some() {
5084 return;
5085 }
5086
5087 let buffer_id = cursor_position.buffer_id;
5088 let buffer = this.buffer.read(cx);
5089 if !buffer
5090 .text_anchor_for_position(cursor_position, cx)
5091 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5092 {
5093 return;
5094 }
5095
5096 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5097 let mut write_ranges = Vec::new();
5098 let mut read_ranges = Vec::new();
5099 for highlight in highlights {
5100 for (excerpt_id, excerpt_range) in
5101 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5102 {
5103 let start = highlight
5104 .range
5105 .start
5106 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5107 let end = highlight
5108 .range
5109 .end
5110 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5111 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5112 continue;
5113 }
5114
5115 let range = Anchor {
5116 buffer_id,
5117 excerpt_id,
5118 text_anchor: start,
5119 diff_base_anchor: None,
5120 }..Anchor {
5121 buffer_id,
5122 excerpt_id,
5123 text_anchor: end,
5124 diff_base_anchor: None,
5125 };
5126 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5127 write_ranges.push(range);
5128 } else {
5129 read_ranges.push(range);
5130 }
5131 }
5132 }
5133
5134 this.highlight_background::<DocumentHighlightRead>(
5135 &read_ranges,
5136 |theme| theme.editor_document_highlight_read_background,
5137 cx,
5138 );
5139 this.highlight_background::<DocumentHighlightWrite>(
5140 &write_ranges,
5141 |theme| theme.editor_document_highlight_write_background,
5142 cx,
5143 );
5144 cx.notify();
5145 })
5146 .log_err();
5147 }
5148 }));
5149 None
5150 }
5151
5152 pub fn refresh_selected_text_highlights(
5153 &mut self,
5154 window: &mut Window,
5155 cx: &mut Context<Editor>,
5156 ) {
5157 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5158 return;
5159 }
5160 self.selection_highlight_task.take();
5161 if !EditorSettings::get_global(cx).selection_highlight {
5162 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5163 return;
5164 }
5165 if self.selections.count() != 1 || self.selections.line_mode {
5166 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5167 return;
5168 }
5169 let selection = self.selections.newest::<Point>(cx);
5170 if selection.is_empty() || selection.start.row != selection.end.row {
5171 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5172 return;
5173 }
5174 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5175 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5176 cx.background_executor()
5177 .timer(Duration::from_millis(debounce))
5178 .await;
5179 let Some(Some(matches_task)) = editor
5180 .update_in(cx, |editor, _, cx| {
5181 if editor.selections.count() != 1 || editor.selections.line_mode {
5182 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5183 return None;
5184 }
5185 let selection = editor.selections.newest::<Point>(cx);
5186 if selection.is_empty() || selection.start.row != selection.end.row {
5187 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5188 return None;
5189 }
5190 let buffer = editor.buffer().read(cx).snapshot(cx);
5191 let query = buffer.text_for_range(selection.range()).collect::<String>();
5192 if query.trim().is_empty() {
5193 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5194 return None;
5195 }
5196 Some(cx.background_spawn(async move {
5197 let mut ranges = Vec::new();
5198 let selection_anchors = selection.range().to_anchors(&buffer);
5199 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5200 for (search_buffer, search_range, excerpt_id) in
5201 buffer.range_to_buffer_ranges(range)
5202 {
5203 ranges.extend(
5204 project::search::SearchQuery::text(
5205 query.clone(),
5206 false,
5207 false,
5208 false,
5209 Default::default(),
5210 Default::default(),
5211 None,
5212 )
5213 .unwrap()
5214 .search(search_buffer, Some(search_range.clone()))
5215 .await
5216 .into_iter()
5217 .filter_map(
5218 |match_range| {
5219 let start = search_buffer.anchor_after(
5220 search_range.start + match_range.start,
5221 );
5222 let end = search_buffer.anchor_before(
5223 search_range.start + match_range.end,
5224 );
5225 let range = Anchor::range_in_buffer(
5226 excerpt_id,
5227 search_buffer.remote_id(),
5228 start..end,
5229 );
5230 (range != selection_anchors).then_some(range)
5231 },
5232 ),
5233 );
5234 }
5235 }
5236 ranges
5237 }))
5238 })
5239 .log_err()
5240 else {
5241 return;
5242 };
5243 let matches = matches_task.await;
5244 editor
5245 .update_in(cx, |editor, _, cx| {
5246 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5247 if !matches.is_empty() {
5248 editor.highlight_background::<SelectedTextHighlight>(
5249 &matches,
5250 |theme| theme.editor_document_highlight_bracket_background,
5251 cx,
5252 )
5253 }
5254 })
5255 .log_err();
5256 }));
5257 }
5258
5259 pub fn refresh_inline_completion(
5260 &mut self,
5261 debounce: bool,
5262 user_requested: bool,
5263 window: &mut Window,
5264 cx: &mut Context<Self>,
5265 ) -> Option<()> {
5266 let provider = self.edit_prediction_provider()?;
5267 let cursor = self.selections.newest_anchor().head();
5268 let (buffer, cursor_buffer_position) =
5269 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5270
5271 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5272 self.discard_inline_completion(false, cx);
5273 return None;
5274 }
5275
5276 if !user_requested
5277 && (!self.should_show_edit_predictions()
5278 || !self.is_focused(window)
5279 || buffer.read(cx).is_empty())
5280 {
5281 self.discard_inline_completion(false, cx);
5282 return None;
5283 }
5284
5285 self.update_visible_inline_completion(window, cx);
5286 provider.refresh(
5287 self.project.clone(),
5288 buffer,
5289 cursor_buffer_position,
5290 debounce,
5291 cx,
5292 );
5293 Some(())
5294 }
5295
5296 fn show_edit_predictions_in_menu(&self) -> bool {
5297 match self.edit_prediction_settings {
5298 EditPredictionSettings::Disabled => false,
5299 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5300 }
5301 }
5302
5303 pub fn edit_predictions_enabled(&self) -> bool {
5304 match self.edit_prediction_settings {
5305 EditPredictionSettings::Disabled => false,
5306 EditPredictionSettings::Enabled { .. } => true,
5307 }
5308 }
5309
5310 fn edit_prediction_requires_modifier(&self) -> bool {
5311 match self.edit_prediction_settings {
5312 EditPredictionSettings::Disabled => false,
5313 EditPredictionSettings::Enabled {
5314 preview_requires_modifier,
5315 ..
5316 } => preview_requires_modifier,
5317 }
5318 }
5319
5320 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5321 if self.edit_prediction_provider.is_none() {
5322 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5323 } else {
5324 let selection = self.selections.newest_anchor();
5325 let cursor = selection.head();
5326
5327 if let Some((buffer, cursor_buffer_position)) =
5328 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5329 {
5330 self.edit_prediction_settings =
5331 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5332 }
5333 }
5334 }
5335
5336 fn edit_prediction_settings_at_position(
5337 &self,
5338 buffer: &Entity<Buffer>,
5339 buffer_position: language::Anchor,
5340 cx: &App,
5341 ) -> EditPredictionSettings {
5342 if self.mode != EditorMode::Full
5343 || !self.show_inline_completions_override.unwrap_or(true)
5344 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5345 {
5346 return EditPredictionSettings::Disabled;
5347 }
5348
5349 let buffer = buffer.read(cx);
5350
5351 let file = buffer.file();
5352
5353 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5354 return EditPredictionSettings::Disabled;
5355 };
5356
5357 let by_provider = matches!(
5358 self.menu_inline_completions_policy,
5359 MenuInlineCompletionsPolicy::ByProvider
5360 );
5361
5362 let show_in_menu = by_provider
5363 && self
5364 .edit_prediction_provider
5365 .as_ref()
5366 .map_or(false, |provider| {
5367 provider.provider.show_completions_in_menu()
5368 });
5369
5370 let preview_requires_modifier =
5371 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5372
5373 EditPredictionSettings::Enabled {
5374 show_in_menu,
5375 preview_requires_modifier,
5376 }
5377 }
5378
5379 fn should_show_edit_predictions(&self) -> bool {
5380 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5381 }
5382
5383 pub fn edit_prediction_preview_is_active(&self) -> bool {
5384 matches!(
5385 self.edit_prediction_preview,
5386 EditPredictionPreview::Active { .. }
5387 )
5388 }
5389
5390 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5391 let cursor = self.selections.newest_anchor().head();
5392 if let Some((buffer, cursor_position)) =
5393 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5394 {
5395 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5396 } else {
5397 false
5398 }
5399 }
5400
5401 fn edit_predictions_enabled_in_buffer(
5402 &self,
5403 buffer: &Entity<Buffer>,
5404 buffer_position: language::Anchor,
5405 cx: &App,
5406 ) -> bool {
5407 maybe!({
5408 if self.read_only(cx) {
5409 return Some(false);
5410 }
5411 let provider = self.edit_prediction_provider()?;
5412 if !provider.is_enabled(&buffer, buffer_position, cx) {
5413 return Some(false);
5414 }
5415 let buffer = buffer.read(cx);
5416 let Some(file) = buffer.file() else {
5417 return Some(true);
5418 };
5419 let settings = all_language_settings(Some(file), cx);
5420 Some(settings.edit_predictions_enabled_for_file(file, cx))
5421 })
5422 .unwrap_or(false)
5423 }
5424
5425 fn cycle_inline_completion(
5426 &mut self,
5427 direction: Direction,
5428 window: &mut Window,
5429 cx: &mut Context<Self>,
5430 ) -> Option<()> {
5431 let provider = self.edit_prediction_provider()?;
5432 let cursor = self.selections.newest_anchor().head();
5433 let (buffer, cursor_buffer_position) =
5434 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5435 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5436 return None;
5437 }
5438
5439 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5440 self.update_visible_inline_completion(window, cx);
5441
5442 Some(())
5443 }
5444
5445 pub fn show_inline_completion(
5446 &mut self,
5447 _: &ShowEditPrediction,
5448 window: &mut Window,
5449 cx: &mut Context<Self>,
5450 ) {
5451 if !self.has_active_inline_completion() {
5452 self.refresh_inline_completion(false, true, window, cx);
5453 return;
5454 }
5455
5456 self.update_visible_inline_completion(window, cx);
5457 }
5458
5459 pub fn display_cursor_names(
5460 &mut self,
5461 _: &DisplayCursorNames,
5462 window: &mut Window,
5463 cx: &mut Context<Self>,
5464 ) {
5465 self.show_cursor_names(window, cx);
5466 }
5467
5468 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5469 self.show_cursor_names = true;
5470 cx.notify();
5471 cx.spawn_in(window, async move |this, cx| {
5472 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5473 this.update(cx, |this, cx| {
5474 this.show_cursor_names = false;
5475 cx.notify()
5476 })
5477 .ok()
5478 })
5479 .detach();
5480 }
5481
5482 pub fn next_edit_prediction(
5483 &mut self,
5484 _: &NextEditPrediction,
5485 window: &mut Window,
5486 cx: &mut Context<Self>,
5487 ) {
5488 if self.has_active_inline_completion() {
5489 self.cycle_inline_completion(Direction::Next, window, cx);
5490 } else {
5491 let is_copilot_disabled = self
5492 .refresh_inline_completion(false, true, window, cx)
5493 .is_none();
5494 if is_copilot_disabled {
5495 cx.propagate();
5496 }
5497 }
5498 }
5499
5500 pub fn previous_edit_prediction(
5501 &mut self,
5502 _: &PreviousEditPrediction,
5503 window: &mut Window,
5504 cx: &mut Context<Self>,
5505 ) {
5506 if self.has_active_inline_completion() {
5507 self.cycle_inline_completion(Direction::Prev, window, cx);
5508 } else {
5509 let is_copilot_disabled = self
5510 .refresh_inline_completion(false, true, window, cx)
5511 .is_none();
5512 if is_copilot_disabled {
5513 cx.propagate();
5514 }
5515 }
5516 }
5517
5518 pub fn accept_edit_prediction(
5519 &mut self,
5520 _: &AcceptEditPrediction,
5521 window: &mut Window,
5522 cx: &mut Context<Self>,
5523 ) {
5524 if self.show_edit_predictions_in_menu() {
5525 self.hide_context_menu(window, cx);
5526 }
5527
5528 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5529 return;
5530 };
5531
5532 self.report_inline_completion_event(
5533 active_inline_completion.completion_id.clone(),
5534 true,
5535 cx,
5536 );
5537
5538 match &active_inline_completion.completion {
5539 InlineCompletion::Move { target, .. } => {
5540 let target = *target;
5541
5542 if let Some(position_map) = &self.last_position_map {
5543 if position_map
5544 .visible_row_range
5545 .contains(&target.to_display_point(&position_map.snapshot).row())
5546 || !self.edit_prediction_requires_modifier()
5547 {
5548 self.unfold_ranges(&[target..target], true, false, cx);
5549 // Note that this is also done in vim's handler of the Tab action.
5550 self.change_selections(
5551 Some(Autoscroll::newest()),
5552 window,
5553 cx,
5554 |selections| {
5555 selections.select_anchor_ranges([target..target]);
5556 },
5557 );
5558 self.clear_row_highlights::<EditPredictionPreview>();
5559
5560 self.edit_prediction_preview
5561 .set_previous_scroll_position(None);
5562 } else {
5563 self.edit_prediction_preview
5564 .set_previous_scroll_position(Some(
5565 position_map.snapshot.scroll_anchor,
5566 ));
5567
5568 self.highlight_rows::<EditPredictionPreview>(
5569 target..target,
5570 cx.theme().colors().editor_highlighted_line_background,
5571 true,
5572 cx,
5573 );
5574 self.request_autoscroll(Autoscroll::fit(), cx);
5575 }
5576 }
5577 }
5578 InlineCompletion::Edit { edits, .. } => {
5579 if let Some(provider) = self.edit_prediction_provider() {
5580 provider.accept(cx);
5581 }
5582
5583 let snapshot = self.buffer.read(cx).snapshot(cx);
5584 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5585
5586 self.buffer.update(cx, |buffer, cx| {
5587 buffer.edit(edits.iter().cloned(), None, cx)
5588 });
5589
5590 self.change_selections(None, window, cx, |s| {
5591 s.select_anchor_ranges([last_edit_end..last_edit_end])
5592 });
5593
5594 self.update_visible_inline_completion(window, cx);
5595 if self.active_inline_completion.is_none() {
5596 self.refresh_inline_completion(true, true, window, cx);
5597 }
5598
5599 cx.notify();
5600 }
5601 }
5602
5603 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5604 }
5605
5606 pub fn accept_partial_inline_completion(
5607 &mut self,
5608 _: &AcceptPartialEditPrediction,
5609 window: &mut Window,
5610 cx: &mut Context<Self>,
5611 ) {
5612 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5613 return;
5614 };
5615 if self.selections.count() != 1 {
5616 return;
5617 }
5618
5619 self.report_inline_completion_event(
5620 active_inline_completion.completion_id.clone(),
5621 true,
5622 cx,
5623 );
5624
5625 match &active_inline_completion.completion {
5626 InlineCompletion::Move { target, .. } => {
5627 let target = *target;
5628 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5629 selections.select_anchor_ranges([target..target]);
5630 });
5631 }
5632 InlineCompletion::Edit { edits, .. } => {
5633 // Find an insertion that starts at the cursor position.
5634 let snapshot = self.buffer.read(cx).snapshot(cx);
5635 let cursor_offset = self.selections.newest::<usize>(cx).head();
5636 let insertion = edits.iter().find_map(|(range, text)| {
5637 let range = range.to_offset(&snapshot);
5638 if range.is_empty() && range.start == cursor_offset {
5639 Some(text)
5640 } else {
5641 None
5642 }
5643 });
5644
5645 if let Some(text) = insertion {
5646 let mut partial_completion = text
5647 .chars()
5648 .by_ref()
5649 .take_while(|c| c.is_alphabetic())
5650 .collect::<String>();
5651 if partial_completion.is_empty() {
5652 partial_completion = text
5653 .chars()
5654 .by_ref()
5655 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5656 .collect::<String>();
5657 }
5658
5659 cx.emit(EditorEvent::InputHandled {
5660 utf16_range_to_replace: None,
5661 text: partial_completion.clone().into(),
5662 });
5663
5664 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5665
5666 self.refresh_inline_completion(true, true, window, cx);
5667 cx.notify();
5668 } else {
5669 self.accept_edit_prediction(&Default::default(), window, cx);
5670 }
5671 }
5672 }
5673 }
5674
5675 fn discard_inline_completion(
5676 &mut self,
5677 should_report_inline_completion_event: bool,
5678 cx: &mut Context<Self>,
5679 ) -> bool {
5680 if should_report_inline_completion_event {
5681 let completion_id = self
5682 .active_inline_completion
5683 .as_ref()
5684 .and_then(|active_completion| active_completion.completion_id.clone());
5685
5686 self.report_inline_completion_event(completion_id, false, cx);
5687 }
5688
5689 if let Some(provider) = self.edit_prediction_provider() {
5690 provider.discard(cx);
5691 }
5692
5693 self.take_active_inline_completion(cx)
5694 }
5695
5696 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5697 let Some(provider) = self.edit_prediction_provider() else {
5698 return;
5699 };
5700
5701 let Some((_, buffer, _)) = self
5702 .buffer
5703 .read(cx)
5704 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5705 else {
5706 return;
5707 };
5708
5709 let extension = buffer
5710 .read(cx)
5711 .file()
5712 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5713
5714 let event_type = match accepted {
5715 true => "Edit Prediction Accepted",
5716 false => "Edit Prediction Discarded",
5717 };
5718 telemetry::event!(
5719 event_type,
5720 provider = provider.name(),
5721 prediction_id = id,
5722 suggestion_accepted = accepted,
5723 file_extension = extension,
5724 );
5725 }
5726
5727 pub fn has_active_inline_completion(&self) -> bool {
5728 self.active_inline_completion.is_some()
5729 }
5730
5731 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5732 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5733 return false;
5734 };
5735
5736 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5737 self.clear_highlights::<InlineCompletionHighlight>(cx);
5738 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5739 true
5740 }
5741
5742 /// Returns true when we're displaying the edit prediction popover below the cursor
5743 /// like we are not previewing and the LSP autocomplete menu is visible
5744 /// or we are in `when_holding_modifier` mode.
5745 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5746 if self.edit_prediction_preview_is_active()
5747 || !self.show_edit_predictions_in_menu()
5748 || !self.edit_predictions_enabled()
5749 {
5750 return false;
5751 }
5752
5753 if self.has_visible_completions_menu() {
5754 return true;
5755 }
5756
5757 has_completion && self.edit_prediction_requires_modifier()
5758 }
5759
5760 fn handle_modifiers_changed(
5761 &mut self,
5762 modifiers: Modifiers,
5763 position_map: &PositionMap,
5764 window: &mut Window,
5765 cx: &mut Context<Self>,
5766 ) {
5767 if self.show_edit_predictions_in_menu() {
5768 self.update_edit_prediction_preview(&modifiers, window, cx);
5769 }
5770
5771 self.update_selection_mode(&modifiers, position_map, window, cx);
5772
5773 let mouse_position = window.mouse_position();
5774 if !position_map.text_hitbox.is_hovered(window) {
5775 return;
5776 }
5777
5778 self.update_hovered_link(
5779 position_map.point_for_position(mouse_position),
5780 &position_map.snapshot,
5781 modifiers,
5782 window,
5783 cx,
5784 )
5785 }
5786
5787 fn update_selection_mode(
5788 &mut self,
5789 modifiers: &Modifiers,
5790 position_map: &PositionMap,
5791 window: &mut Window,
5792 cx: &mut Context<Self>,
5793 ) {
5794 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5795 return;
5796 }
5797
5798 let mouse_position = window.mouse_position();
5799 let point_for_position = position_map.point_for_position(mouse_position);
5800 let position = point_for_position.previous_valid;
5801
5802 self.select(
5803 SelectPhase::BeginColumnar {
5804 position,
5805 reset: false,
5806 goal_column: point_for_position.exact_unclipped.column(),
5807 },
5808 window,
5809 cx,
5810 );
5811 }
5812
5813 fn update_edit_prediction_preview(
5814 &mut self,
5815 modifiers: &Modifiers,
5816 window: &mut Window,
5817 cx: &mut Context<Self>,
5818 ) {
5819 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5820 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5821 return;
5822 };
5823
5824 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5825 if matches!(
5826 self.edit_prediction_preview,
5827 EditPredictionPreview::Inactive { .. }
5828 ) {
5829 self.edit_prediction_preview = EditPredictionPreview::Active {
5830 previous_scroll_position: None,
5831 since: Instant::now(),
5832 };
5833
5834 self.update_visible_inline_completion(window, cx);
5835 cx.notify();
5836 }
5837 } else if let EditPredictionPreview::Active {
5838 previous_scroll_position,
5839 since,
5840 } = self.edit_prediction_preview
5841 {
5842 if let (Some(previous_scroll_position), Some(position_map)) =
5843 (previous_scroll_position, self.last_position_map.as_ref())
5844 {
5845 self.set_scroll_position(
5846 previous_scroll_position
5847 .scroll_position(&position_map.snapshot.display_snapshot),
5848 window,
5849 cx,
5850 );
5851 }
5852
5853 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5854 released_too_fast: since.elapsed() < Duration::from_millis(200),
5855 };
5856 self.clear_row_highlights::<EditPredictionPreview>();
5857 self.update_visible_inline_completion(window, cx);
5858 cx.notify();
5859 }
5860 }
5861
5862 fn update_visible_inline_completion(
5863 &mut self,
5864 _window: &mut Window,
5865 cx: &mut Context<Self>,
5866 ) -> Option<()> {
5867 let selection = self.selections.newest_anchor();
5868 let cursor = selection.head();
5869 let multibuffer = self.buffer.read(cx).snapshot(cx);
5870 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5871 let excerpt_id = cursor.excerpt_id;
5872
5873 let show_in_menu = self.show_edit_predictions_in_menu();
5874 let completions_menu_has_precedence = !show_in_menu
5875 && (self.context_menu.borrow().is_some()
5876 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5877
5878 if completions_menu_has_precedence
5879 || !offset_selection.is_empty()
5880 || self
5881 .active_inline_completion
5882 .as_ref()
5883 .map_or(false, |completion| {
5884 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5885 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5886 !invalidation_range.contains(&offset_selection.head())
5887 })
5888 {
5889 self.discard_inline_completion(false, cx);
5890 return None;
5891 }
5892
5893 self.take_active_inline_completion(cx);
5894 let Some(provider) = self.edit_prediction_provider() else {
5895 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5896 return None;
5897 };
5898
5899 let (buffer, cursor_buffer_position) =
5900 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5901
5902 self.edit_prediction_settings =
5903 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5904
5905 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5906
5907 if self.edit_prediction_indent_conflict {
5908 let cursor_point = cursor.to_point(&multibuffer);
5909
5910 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5911
5912 if let Some((_, indent)) = indents.iter().next() {
5913 if indent.len == cursor_point.column {
5914 self.edit_prediction_indent_conflict = false;
5915 }
5916 }
5917 }
5918
5919 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5920 let edits = inline_completion
5921 .edits
5922 .into_iter()
5923 .flat_map(|(range, new_text)| {
5924 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5925 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5926 Some((start..end, new_text))
5927 })
5928 .collect::<Vec<_>>();
5929 if edits.is_empty() {
5930 return None;
5931 }
5932
5933 let first_edit_start = edits.first().unwrap().0.start;
5934 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5935 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5936
5937 let last_edit_end = edits.last().unwrap().0.end;
5938 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5939 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5940
5941 let cursor_row = cursor.to_point(&multibuffer).row;
5942
5943 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5944
5945 let mut inlay_ids = Vec::new();
5946 let invalidation_row_range;
5947 let move_invalidation_row_range = if cursor_row < edit_start_row {
5948 Some(cursor_row..edit_end_row)
5949 } else if cursor_row > edit_end_row {
5950 Some(edit_start_row..cursor_row)
5951 } else {
5952 None
5953 };
5954 let is_move =
5955 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5956 let completion = if is_move {
5957 invalidation_row_range =
5958 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5959 let target = first_edit_start;
5960 InlineCompletion::Move { target, snapshot }
5961 } else {
5962 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5963 && !self.inline_completions_hidden_for_vim_mode;
5964
5965 if show_completions_in_buffer {
5966 if edits
5967 .iter()
5968 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5969 {
5970 let mut inlays = Vec::new();
5971 for (range, new_text) in &edits {
5972 let inlay = Inlay::inline_completion(
5973 post_inc(&mut self.next_inlay_id),
5974 range.start,
5975 new_text.as_str(),
5976 );
5977 inlay_ids.push(inlay.id);
5978 inlays.push(inlay);
5979 }
5980
5981 self.splice_inlays(&[], inlays, cx);
5982 } else {
5983 let background_color = cx.theme().status().deleted_background;
5984 self.highlight_text::<InlineCompletionHighlight>(
5985 edits.iter().map(|(range, _)| range.clone()).collect(),
5986 HighlightStyle {
5987 background_color: Some(background_color),
5988 ..Default::default()
5989 },
5990 cx,
5991 );
5992 }
5993 }
5994
5995 invalidation_row_range = edit_start_row..edit_end_row;
5996
5997 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5998 if provider.show_tab_accept_marker() {
5999 EditDisplayMode::TabAccept
6000 } else {
6001 EditDisplayMode::Inline
6002 }
6003 } else {
6004 EditDisplayMode::DiffPopover
6005 };
6006
6007 InlineCompletion::Edit {
6008 edits,
6009 edit_preview: inline_completion.edit_preview,
6010 display_mode,
6011 snapshot,
6012 }
6013 };
6014
6015 let invalidation_range = multibuffer
6016 .anchor_before(Point::new(invalidation_row_range.start, 0))
6017 ..multibuffer.anchor_after(Point::new(
6018 invalidation_row_range.end,
6019 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6020 ));
6021
6022 self.stale_inline_completion_in_menu = None;
6023 self.active_inline_completion = Some(InlineCompletionState {
6024 inlay_ids,
6025 completion,
6026 completion_id: inline_completion.id,
6027 invalidation_range,
6028 });
6029
6030 cx.notify();
6031
6032 Some(())
6033 }
6034
6035 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6036 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6037 }
6038
6039 fn render_code_actions_indicator(
6040 &self,
6041 _style: &EditorStyle,
6042 row: DisplayRow,
6043 is_active: bool,
6044 breakpoint: Option<&(Anchor, Breakpoint)>,
6045 cx: &mut Context<Self>,
6046 ) -> Option<IconButton> {
6047 let color = Color::Muted;
6048 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6049
6050 if self.available_code_actions.is_some() {
6051 Some(
6052 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6053 .shape(ui::IconButtonShape::Square)
6054 .icon_size(IconSize::XSmall)
6055 .icon_color(color)
6056 .toggle_state(is_active)
6057 .tooltip({
6058 let focus_handle = self.focus_handle.clone();
6059 move |window, cx| {
6060 Tooltip::for_action_in(
6061 "Toggle Code Actions",
6062 &ToggleCodeActions {
6063 deployed_from_indicator: None,
6064 },
6065 &focus_handle,
6066 window,
6067 cx,
6068 )
6069 }
6070 })
6071 .on_click(cx.listener(move |editor, _e, window, cx| {
6072 window.focus(&editor.focus_handle(cx));
6073 editor.toggle_code_actions(
6074 &ToggleCodeActions {
6075 deployed_from_indicator: Some(row),
6076 },
6077 window,
6078 cx,
6079 );
6080 }))
6081 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6082 editor.set_breakpoint_context_menu(
6083 row,
6084 position,
6085 event.down.position,
6086 window,
6087 cx,
6088 );
6089 })),
6090 )
6091 } else {
6092 None
6093 }
6094 }
6095
6096 fn clear_tasks(&mut self) {
6097 self.tasks.clear()
6098 }
6099
6100 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6101 if self.tasks.insert(key, value).is_some() {
6102 // This case should hopefully be rare, but just in case...
6103 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
6104 }
6105 }
6106
6107 /// Get all display points of breakpoints that will be rendered within editor
6108 ///
6109 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6110 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6111 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6112 fn active_breakpoints(
6113 &mut self,
6114 range: Range<DisplayRow>,
6115 window: &mut Window,
6116 cx: &mut Context<Self>,
6117 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6118 let mut breakpoint_display_points = HashMap::default();
6119
6120 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6121 return breakpoint_display_points;
6122 };
6123
6124 let snapshot = self.snapshot(window, cx);
6125
6126 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6127 let Some(project) = self.project.as_ref() else {
6128 return breakpoint_display_points;
6129 };
6130
6131 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6132 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6133
6134 for (buffer_snapshot, range, excerpt_id) in
6135 multi_buffer_snapshot.range_to_buffer_ranges(range)
6136 {
6137 let Some(buffer) = project.read_with(cx, |this, cx| {
6138 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6139 }) else {
6140 continue;
6141 };
6142 let breakpoints = breakpoint_store.read(cx).breakpoints(
6143 &buffer,
6144 Some(
6145 buffer_snapshot.anchor_before(range.start)
6146 ..buffer_snapshot.anchor_after(range.end),
6147 ),
6148 buffer_snapshot,
6149 cx,
6150 );
6151 for (anchor, breakpoint) in breakpoints {
6152 let multi_buffer_anchor =
6153 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6154 let position = multi_buffer_anchor
6155 .to_point(&multi_buffer_snapshot)
6156 .to_display_point(&snapshot);
6157
6158 breakpoint_display_points
6159 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6160 }
6161 }
6162
6163 breakpoint_display_points
6164 }
6165
6166 fn breakpoint_context_menu(
6167 &self,
6168 anchor: Anchor,
6169 window: &mut Window,
6170 cx: &mut Context<Self>,
6171 ) -> Entity<ui::ContextMenu> {
6172 let weak_editor = cx.weak_entity();
6173 let focus_handle = self.focus_handle(cx);
6174
6175 let row = self
6176 .buffer
6177 .read(cx)
6178 .snapshot(cx)
6179 .summary_for_anchor::<Point>(&anchor)
6180 .row;
6181
6182 let breakpoint = self
6183 .breakpoint_at_row(row, window, cx)
6184 .map(|(_, bp)| Arc::from(bp));
6185
6186 let log_breakpoint_msg = if breakpoint
6187 .as_ref()
6188 .is_some_and(|bp| bp.kind.log_message().is_some())
6189 {
6190 "Edit Log Breakpoint"
6191 } else {
6192 "Set Log Breakpoint"
6193 };
6194
6195 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6196 "Unset Breakpoint"
6197 } else {
6198 "Set Breakpoint"
6199 };
6200
6201 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.state {
6202 BreakpointState::Enabled => Some("Disable"),
6203 BreakpointState::Disabled => Some("Enable"),
6204 });
6205
6206 let breakpoint = breakpoint.unwrap_or_else(|| {
6207 Arc::new(Breakpoint {
6208 state: BreakpointState::Enabled,
6209 kind: BreakpointKind::Standard,
6210 })
6211 });
6212
6213 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6214 menu.on_blur_subscription(Subscription::new(|| {}))
6215 .context(focus_handle)
6216 .when_some(toggle_state_msg, |this, msg| {
6217 this.entry(msg, None, {
6218 let weak_editor = weak_editor.clone();
6219 let breakpoint = breakpoint.clone();
6220 move |_window, cx| {
6221 weak_editor
6222 .update(cx, |this, cx| {
6223 this.edit_breakpoint_at_anchor(
6224 anchor,
6225 breakpoint.as_ref().clone(),
6226 BreakpointEditAction::InvertState,
6227 cx,
6228 );
6229 })
6230 .log_err();
6231 }
6232 })
6233 })
6234 .entry(set_breakpoint_msg, None, {
6235 let weak_editor = weak_editor.clone();
6236 let breakpoint = breakpoint.clone();
6237 move |_window, cx| {
6238 weak_editor
6239 .update(cx, |this, cx| {
6240 this.edit_breakpoint_at_anchor(
6241 anchor,
6242 breakpoint.as_ref().clone(),
6243 BreakpointEditAction::Toggle,
6244 cx,
6245 );
6246 })
6247 .log_err();
6248 }
6249 })
6250 .entry(log_breakpoint_msg, None, move |window, cx| {
6251 weak_editor
6252 .update(cx, |this, cx| {
6253 this.add_edit_breakpoint_block(anchor, breakpoint.as_ref(), window, cx);
6254 })
6255 .log_err();
6256 })
6257 })
6258 }
6259
6260 fn render_breakpoint(
6261 &self,
6262 position: Anchor,
6263 row: DisplayRow,
6264 breakpoint: &Breakpoint,
6265 cx: &mut Context<Self>,
6266 ) -> IconButton {
6267 let (color, icon) = {
6268 let color = if self
6269 .gutter_breakpoint_indicator
6270 .is_some_and(|point| point.row() == row)
6271 {
6272 Color::Hint
6273 } else if breakpoint.is_disabled() {
6274 Color::Custom(Color::Debugger.color(cx).opacity(0.5))
6275 } else {
6276 Color::Debugger
6277 };
6278 let icon = match &breakpoint.kind {
6279 BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
6280 BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
6281 };
6282 (color, icon)
6283 };
6284
6285 let breakpoint = Arc::from(breakpoint.clone());
6286
6287 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6288 .icon_size(IconSize::XSmall)
6289 .size(ui::ButtonSize::None)
6290 .icon_color(color)
6291 .style(ButtonStyle::Transparent)
6292 .on_click(cx.listener({
6293 let breakpoint = breakpoint.clone();
6294
6295 move |editor, _e, window, cx| {
6296 window.focus(&editor.focus_handle(cx));
6297 editor.edit_breakpoint_at_anchor(
6298 position,
6299 breakpoint.as_ref().clone(),
6300 BreakpointEditAction::Toggle,
6301 cx,
6302 );
6303 }
6304 }))
6305 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6306 editor.set_breakpoint_context_menu(
6307 row,
6308 Some(position),
6309 event.down.position,
6310 window,
6311 cx,
6312 );
6313 }))
6314 }
6315
6316 fn build_tasks_context(
6317 project: &Entity<Project>,
6318 buffer: &Entity<Buffer>,
6319 buffer_row: u32,
6320 tasks: &Arc<RunnableTasks>,
6321 cx: &mut Context<Self>,
6322 ) -> Task<Option<task::TaskContext>> {
6323 let position = Point::new(buffer_row, tasks.column);
6324 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6325 let location = Location {
6326 buffer: buffer.clone(),
6327 range: range_start..range_start,
6328 };
6329 // Fill in the environmental variables from the tree-sitter captures
6330 let mut captured_task_variables = TaskVariables::default();
6331 for (capture_name, value) in tasks.extra_variables.clone() {
6332 captured_task_variables.insert(
6333 task::VariableName::Custom(capture_name.into()),
6334 value.clone(),
6335 );
6336 }
6337 project.update(cx, |project, cx| {
6338 project.task_store().update(cx, |task_store, cx| {
6339 task_store.task_context_for_location(captured_task_variables, location, cx)
6340 })
6341 })
6342 }
6343
6344 pub fn spawn_nearest_task(
6345 &mut self,
6346 action: &SpawnNearestTask,
6347 window: &mut Window,
6348 cx: &mut Context<Self>,
6349 ) {
6350 let Some((workspace, _)) = self.workspace.clone() else {
6351 return;
6352 };
6353 let Some(project) = self.project.clone() else {
6354 return;
6355 };
6356
6357 // Try to find a closest, enclosing node using tree-sitter that has a
6358 // task
6359 let Some((buffer, buffer_row, tasks)) = self
6360 .find_enclosing_node_task(cx)
6361 // Or find the task that's closest in row-distance.
6362 .or_else(|| self.find_closest_task(cx))
6363 else {
6364 return;
6365 };
6366
6367 let reveal_strategy = action.reveal;
6368 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6369 cx.spawn_in(window, async move |_, cx| {
6370 let context = task_context.await?;
6371 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6372
6373 let resolved = resolved_task.resolved.as_mut()?;
6374 resolved.reveal = reveal_strategy;
6375
6376 workspace
6377 .update(cx, |workspace, cx| {
6378 workspace::tasks::schedule_resolved_task(
6379 workspace,
6380 task_source_kind,
6381 resolved_task,
6382 false,
6383 cx,
6384 );
6385 })
6386 .ok()
6387 })
6388 .detach();
6389 }
6390
6391 fn find_closest_task(
6392 &mut self,
6393 cx: &mut Context<Self>,
6394 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6395 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6396
6397 let ((buffer_id, row), tasks) = self
6398 .tasks
6399 .iter()
6400 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6401
6402 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6403 let tasks = Arc::new(tasks.to_owned());
6404 Some((buffer, *row, tasks))
6405 }
6406
6407 fn find_enclosing_node_task(
6408 &mut self,
6409 cx: &mut Context<Self>,
6410 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6411 let snapshot = self.buffer.read(cx).snapshot(cx);
6412 let offset = self.selections.newest::<usize>(cx).head();
6413 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6414 let buffer_id = excerpt.buffer().remote_id();
6415
6416 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6417 let mut cursor = layer.node().walk();
6418
6419 while cursor.goto_first_child_for_byte(offset).is_some() {
6420 if cursor.node().end_byte() == offset {
6421 cursor.goto_next_sibling();
6422 }
6423 }
6424
6425 // Ascend to the smallest ancestor that contains the range and has a task.
6426 loop {
6427 let node = cursor.node();
6428 let node_range = node.byte_range();
6429 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6430
6431 // Check if this node contains our offset
6432 if node_range.start <= offset && node_range.end >= offset {
6433 // If it contains offset, check for task
6434 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6435 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6436 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6437 }
6438 }
6439
6440 if !cursor.goto_parent() {
6441 break;
6442 }
6443 }
6444 None
6445 }
6446
6447 fn render_run_indicator(
6448 &self,
6449 _style: &EditorStyle,
6450 is_active: bool,
6451 row: DisplayRow,
6452 breakpoint: Option<(Anchor, Breakpoint)>,
6453 cx: &mut Context<Self>,
6454 ) -> IconButton {
6455 let color = Color::Muted;
6456 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6457
6458 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6459 .shape(ui::IconButtonShape::Square)
6460 .icon_size(IconSize::XSmall)
6461 .icon_color(color)
6462 .toggle_state(is_active)
6463 .on_click(cx.listener(move |editor, _e, window, cx| {
6464 window.focus(&editor.focus_handle(cx));
6465 editor.toggle_code_actions(
6466 &ToggleCodeActions {
6467 deployed_from_indicator: Some(row),
6468 },
6469 window,
6470 cx,
6471 );
6472 }))
6473 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6474 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6475 }))
6476 }
6477
6478 pub fn context_menu_visible(&self) -> bool {
6479 !self.edit_prediction_preview_is_active()
6480 && self
6481 .context_menu
6482 .borrow()
6483 .as_ref()
6484 .map_or(false, |menu| menu.visible())
6485 }
6486
6487 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6488 self.context_menu
6489 .borrow()
6490 .as_ref()
6491 .map(|menu| menu.origin())
6492 }
6493
6494 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6495 self.context_menu_options = Some(options);
6496 }
6497
6498 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6499 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6500
6501 fn render_edit_prediction_popover(
6502 &mut self,
6503 text_bounds: &Bounds<Pixels>,
6504 content_origin: gpui::Point<Pixels>,
6505 editor_snapshot: &EditorSnapshot,
6506 visible_row_range: Range<DisplayRow>,
6507 scroll_top: f32,
6508 scroll_bottom: f32,
6509 line_layouts: &[LineWithInvisibles],
6510 line_height: Pixels,
6511 scroll_pixel_position: gpui::Point<Pixels>,
6512 newest_selection_head: Option<DisplayPoint>,
6513 editor_width: Pixels,
6514 style: &EditorStyle,
6515 window: &mut Window,
6516 cx: &mut App,
6517 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6518 let active_inline_completion = self.active_inline_completion.as_ref()?;
6519
6520 if self.edit_prediction_visible_in_cursor_popover(true) {
6521 return None;
6522 }
6523
6524 match &active_inline_completion.completion {
6525 InlineCompletion::Move { target, .. } => {
6526 let target_display_point = target.to_display_point(editor_snapshot);
6527
6528 if self.edit_prediction_requires_modifier() {
6529 if !self.edit_prediction_preview_is_active() {
6530 return None;
6531 }
6532
6533 self.render_edit_prediction_modifier_jump_popover(
6534 text_bounds,
6535 content_origin,
6536 visible_row_range,
6537 line_layouts,
6538 line_height,
6539 scroll_pixel_position,
6540 newest_selection_head,
6541 target_display_point,
6542 window,
6543 cx,
6544 )
6545 } else {
6546 self.render_edit_prediction_eager_jump_popover(
6547 text_bounds,
6548 content_origin,
6549 editor_snapshot,
6550 visible_row_range,
6551 scroll_top,
6552 scroll_bottom,
6553 line_height,
6554 scroll_pixel_position,
6555 target_display_point,
6556 editor_width,
6557 window,
6558 cx,
6559 )
6560 }
6561 }
6562 InlineCompletion::Edit {
6563 display_mode: EditDisplayMode::Inline,
6564 ..
6565 } => None,
6566 InlineCompletion::Edit {
6567 display_mode: EditDisplayMode::TabAccept,
6568 edits,
6569 ..
6570 } => {
6571 let range = &edits.first()?.0;
6572 let target_display_point = range.end.to_display_point(editor_snapshot);
6573
6574 self.render_edit_prediction_end_of_line_popover(
6575 "Accept",
6576 editor_snapshot,
6577 visible_row_range,
6578 target_display_point,
6579 line_height,
6580 scroll_pixel_position,
6581 content_origin,
6582 editor_width,
6583 window,
6584 cx,
6585 )
6586 }
6587 InlineCompletion::Edit {
6588 edits,
6589 edit_preview,
6590 display_mode: EditDisplayMode::DiffPopover,
6591 snapshot,
6592 } => self.render_edit_prediction_diff_popover(
6593 text_bounds,
6594 content_origin,
6595 editor_snapshot,
6596 visible_row_range,
6597 line_layouts,
6598 line_height,
6599 scroll_pixel_position,
6600 newest_selection_head,
6601 editor_width,
6602 style,
6603 edits,
6604 edit_preview,
6605 snapshot,
6606 window,
6607 cx,
6608 ),
6609 }
6610 }
6611
6612 fn render_edit_prediction_modifier_jump_popover(
6613 &mut self,
6614 text_bounds: &Bounds<Pixels>,
6615 content_origin: gpui::Point<Pixels>,
6616 visible_row_range: Range<DisplayRow>,
6617 line_layouts: &[LineWithInvisibles],
6618 line_height: Pixels,
6619 scroll_pixel_position: gpui::Point<Pixels>,
6620 newest_selection_head: Option<DisplayPoint>,
6621 target_display_point: DisplayPoint,
6622 window: &mut Window,
6623 cx: &mut App,
6624 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6625 let scrolled_content_origin =
6626 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6627
6628 const SCROLL_PADDING_Y: Pixels = px(12.);
6629
6630 if target_display_point.row() < visible_row_range.start {
6631 return self.render_edit_prediction_scroll_popover(
6632 |_| SCROLL_PADDING_Y,
6633 IconName::ArrowUp,
6634 visible_row_range,
6635 line_layouts,
6636 newest_selection_head,
6637 scrolled_content_origin,
6638 window,
6639 cx,
6640 );
6641 } else if target_display_point.row() >= visible_row_range.end {
6642 return self.render_edit_prediction_scroll_popover(
6643 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6644 IconName::ArrowDown,
6645 visible_row_range,
6646 line_layouts,
6647 newest_selection_head,
6648 scrolled_content_origin,
6649 window,
6650 cx,
6651 );
6652 }
6653
6654 const POLE_WIDTH: Pixels = px(2.);
6655
6656 let line_layout =
6657 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6658 let target_column = target_display_point.column() as usize;
6659
6660 let target_x = line_layout.x_for_index(target_column);
6661 let target_y =
6662 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6663
6664 let flag_on_right = target_x < text_bounds.size.width / 2.;
6665
6666 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6667 border_color.l += 0.001;
6668
6669 let mut element = v_flex()
6670 .items_end()
6671 .when(flag_on_right, |el| el.items_start())
6672 .child(if flag_on_right {
6673 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6674 .rounded_bl(px(0.))
6675 .rounded_tl(px(0.))
6676 .border_l_2()
6677 .border_color(border_color)
6678 } else {
6679 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6680 .rounded_br(px(0.))
6681 .rounded_tr(px(0.))
6682 .border_r_2()
6683 .border_color(border_color)
6684 })
6685 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6686 .into_any();
6687
6688 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6689
6690 let mut origin = scrolled_content_origin + point(target_x, target_y)
6691 - point(
6692 if flag_on_right {
6693 POLE_WIDTH
6694 } else {
6695 size.width - POLE_WIDTH
6696 },
6697 size.height - line_height,
6698 );
6699
6700 origin.x = origin.x.max(content_origin.x);
6701
6702 element.prepaint_at(origin, window, cx);
6703
6704 Some((element, origin))
6705 }
6706
6707 fn render_edit_prediction_scroll_popover(
6708 &mut self,
6709 to_y: impl Fn(Size<Pixels>) -> Pixels,
6710 scroll_icon: IconName,
6711 visible_row_range: Range<DisplayRow>,
6712 line_layouts: &[LineWithInvisibles],
6713 newest_selection_head: Option<DisplayPoint>,
6714 scrolled_content_origin: gpui::Point<Pixels>,
6715 window: &mut Window,
6716 cx: &mut App,
6717 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6718 let mut element = self
6719 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6720 .into_any();
6721
6722 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6723
6724 let cursor = newest_selection_head?;
6725 let cursor_row_layout =
6726 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6727 let cursor_column = cursor.column() as usize;
6728
6729 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6730
6731 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6732
6733 element.prepaint_at(origin, window, cx);
6734 Some((element, origin))
6735 }
6736
6737 fn render_edit_prediction_eager_jump_popover(
6738 &mut self,
6739 text_bounds: &Bounds<Pixels>,
6740 content_origin: gpui::Point<Pixels>,
6741 editor_snapshot: &EditorSnapshot,
6742 visible_row_range: Range<DisplayRow>,
6743 scroll_top: f32,
6744 scroll_bottom: f32,
6745 line_height: Pixels,
6746 scroll_pixel_position: gpui::Point<Pixels>,
6747 target_display_point: DisplayPoint,
6748 editor_width: Pixels,
6749 window: &mut Window,
6750 cx: &mut App,
6751 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6752 if target_display_point.row().as_f32() < scroll_top {
6753 let mut element = self
6754 .render_edit_prediction_line_popover(
6755 "Jump to Edit",
6756 Some(IconName::ArrowUp),
6757 window,
6758 cx,
6759 )?
6760 .into_any();
6761
6762 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6763 let offset = point(
6764 (text_bounds.size.width - size.width) / 2.,
6765 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6766 );
6767
6768 let origin = text_bounds.origin + offset;
6769 element.prepaint_at(origin, window, cx);
6770 Some((element, origin))
6771 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6772 let mut element = self
6773 .render_edit_prediction_line_popover(
6774 "Jump to Edit",
6775 Some(IconName::ArrowDown),
6776 window,
6777 cx,
6778 )?
6779 .into_any();
6780
6781 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6782 let offset = point(
6783 (text_bounds.size.width - size.width) / 2.,
6784 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6785 );
6786
6787 let origin = text_bounds.origin + offset;
6788 element.prepaint_at(origin, window, cx);
6789 Some((element, origin))
6790 } else {
6791 self.render_edit_prediction_end_of_line_popover(
6792 "Jump to Edit",
6793 editor_snapshot,
6794 visible_row_range,
6795 target_display_point,
6796 line_height,
6797 scroll_pixel_position,
6798 content_origin,
6799 editor_width,
6800 window,
6801 cx,
6802 )
6803 }
6804 }
6805
6806 fn render_edit_prediction_end_of_line_popover(
6807 self: &mut Editor,
6808 label: &'static str,
6809 editor_snapshot: &EditorSnapshot,
6810 visible_row_range: Range<DisplayRow>,
6811 target_display_point: DisplayPoint,
6812 line_height: Pixels,
6813 scroll_pixel_position: gpui::Point<Pixels>,
6814 content_origin: gpui::Point<Pixels>,
6815 editor_width: Pixels,
6816 window: &mut Window,
6817 cx: &mut App,
6818 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6819 let target_line_end = DisplayPoint::new(
6820 target_display_point.row(),
6821 editor_snapshot.line_len(target_display_point.row()),
6822 );
6823
6824 let mut element = self
6825 .render_edit_prediction_line_popover(label, None, window, cx)?
6826 .into_any();
6827
6828 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6829
6830 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6831
6832 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6833 let mut origin = start_point
6834 + line_origin
6835 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6836 origin.x = origin.x.max(content_origin.x);
6837
6838 let max_x = content_origin.x + editor_width - size.width;
6839
6840 if origin.x > max_x {
6841 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6842
6843 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6844 origin.y += offset;
6845 IconName::ArrowUp
6846 } else {
6847 origin.y -= offset;
6848 IconName::ArrowDown
6849 };
6850
6851 element = self
6852 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6853 .into_any();
6854
6855 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6856
6857 origin.x = content_origin.x + editor_width - size.width - px(2.);
6858 }
6859
6860 element.prepaint_at(origin, window, cx);
6861 Some((element, origin))
6862 }
6863
6864 fn render_edit_prediction_diff_popover(
6865 self: &Editor,
6866 text_bounds: &Bounds<Pixels>,
6867 content_origin: gpui::Point<Pixels>,
6868 editor_snapshot: &EditorSnapshot,
6869 visible_row_range: Range<DisplayRow>,
6870 line_layouts: &[LineWithInvisibles],
6871 line_height: Pixels,
6872 scroll_pixel_position: gpui::Point<Pixels>,
6873 newest_selection_head: Option<DisplayPoint>,
6874 editor_width: Pixels,
6875 style: &EditorStyle,
6876 edits: &Vec<(Range<Anchor>, String)>,
6877 edit_preview: &Option<language::EditPreview>,
6878 snapshot: &language::BufferSnapshot,
6879 window: &mut Window,
6880 cx: &mut App,
6881 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6882 let edit_start = edits
6883 .first()
6884 .unwrap()
6885 .0
6886 .start
6887 .to_display_point(editor_snapshot);
6888 let edit_end = edits
6889 .last()
6890 .unwrap()
6891 .0
6892 .end
6893 .to_display_point(editor_snapshot);
6894
6895 let is_visible = visible_row_range.contains(&edit_start.row())
6896 || visible_row_range.contains(&edit_end.row());
6897 if !is_visible {
6898 return None;
6899 }
6900
6901 let highlighted_edits =
6902 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6903
6904 let styled_text = highlighted_edits.to_styled_text(&style.text);
6905 let line_count = highlighted_edits.text.lines().count();
6906
6907 const BORDER_WIDTH: Pixels = px(1.);
6908
6909 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6910 let has_keybind = keybind.is_some();
6911
6912 let mut element = h_flex()
6913 .items_start()
6914 .child(
6915 h_flex()
6916 .bg(cx.theme().colors().editor_background)
6917 .border(BORDER_WIDTH)
6918 .shadow_sm()
6919 .border_color(cx.theme().colors().border)
6920 .rounded_l_lg()
6921 .when(line_count > 1, |el| el.rounded_br_lg())
6922 .pr_1()
6923 .child(styled_text),
6924 )
6925 .child(
6926 h_flex()
6927 .h(line_height + BORDER_WIDTH * 2.)
6928 .px_1p5()
6929 .gap_1()
6930 // Workaround: For some reason, there's a gap if we don't do this
6931 .ml(-BORDER_WIDTH)
6932 .shadow(smallvec![gpui::BoxShadow {
6933 color: gpui::black().opacity(0.05),
6934 offset: point(px(1.), px(1.)),
6935 blur_radius: px(2.),
6936 spread_radius: px(0.),
6937 }])
6938 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6939 .border(BORDER_WIDTH)
6940 .border_color(cx.theme().colors().border)
6941 .rounded_r_lg()
6942 .id("edit_prediction_diff_popover_keybind")
6943 .when(!has_keybind, |el| {
6944 let status_colors = cx.theme().status();
6945
6946 el.bg(status_colors.error_background)
6947 .border_color(status_colors.error.opacity(0.6))
6948 .child(Icon::new(IconName::Info).color(Color::Error))
6949 .cursor_default()
6950 .hoverable_tooltip(move |_window, cx| {
6951 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6952 })
6953 })
6954 .children(keybind),
6955 )
6956 .into_any();
6957
6958 let longest_row =
6959 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6960 let longest_line_width = if visible_row_range.contains(&longest_row) {
6961 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6962 } else {
6963 layout_line(
6964 longest_row,
6965 editor_snapshot,
6966 style,
6967 editor_width,
6968 |_| false,
6969 window,
6970 cx,
6971 )
6972 .width
6973 };
6974
6975 let viewport_bounds =
6976 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6977 right: -EditorElement::SCROLLBAR_WIDTH,
6978 ..Default::default()
6979 });
6980
6981 let x_after_longest =
6982 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6983 - scroll_pixel_position.x;
6984
6985 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6986
6987 // Fully visible if it can be displayed within the window (allow overlapping other
6988 // panes). However, this is only allowed if the popover starts within text_bounds.
6989 let can_position_to_the_right = x_after_longest < text_bounds.right()
6990 && x_after_longest + element_bounds.width < viewport_bounds.right();
6991
6992 let mut origin = if can_position_to_the_right {
6993 point(
6994 x_after_longest,
6995 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6996 - scroll_pixel_position.y,
6997 )
6998 } else {
6999 let cursor_row = newest_selection_head.map(|head| head.row());
7000 let above_edit = edit_start
7001 .row()
7002 .0
7003 .checked_sub(line_count as u32)
7004 .map(DisplayRow);
7005 let below_edit = Some(edit_end.row() + 1);
7006 let above_cursor =
7007 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7008 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7009
7010 // Place the edit popover adjacent to the edit if there is a location
7011 // available that is onscreen and does not obscure the cursor. Otherwise,
7012 // place it adjacent to the cursor.
7013 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7014 .into_iter()
7015 .flatten()
7016 .find(|&start_row| {
7017 let end_row = start_row + line_count as u32;
7018 visible_row_range.contains(&start_row)
7019 && visible_row_range.contains(&end_row)
7020 && cursor_row.map_or(true, |cursor_row| {
7021 !((start_row..end_row).contains(&cursor_row))
7022 })
7023 })?;
7024
7025 content_origin
7026 + point(
7027 -scroll_pixel_position.x,
7028 row_target.as_f32() * line_height - scroll_pixel_position.y,
7029 )
7030 };
7031
7032 origin.x -= BORDER_WIDTH;
7033
7034 window.defer_draw(element, origin, 1);
7035
7036 // Do not return an element, since it will already be drawn due to defer_draw.
7037 None
7038 }
7039
7040 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7041 px(30.)
7042 }
7043
7044 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7045 if self.read_only(cx) {
7046 cx.theme().players().read_only()
7047 } else {
7048 self.style.as_ref().unwrap().local_player
7049 }
7050 }
7051
7052 fn render_edit_prediction_accept_keybind(
7053 &self,
7054 window: &mut Window,
7055 cx: &App,
7056 ) -> Option<AnyElement> {
7057 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7058 let accept_keystroke = accept_binding.keystroke()?;
7059
7060 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7061
7062 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7063 Color::Accent
7064 } else {
7065 Color::Muted
7066 };
7067
7068 h_flex()
7069 .px_0p5()
7070 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7071 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7072 .text_size(TextSize::XSmall.rems(cx))
7073 .child(h_flex().children(ui::render_modifiers(
7074 &accept_keystroke.modifiers,
7075 PlatformStyle::platform(),
7076 Some(modifiers_color),
7077 Some(IconSize::XSmall.rems().into()),
7078 true,
7079 )))
7080 .when(is_platform_style_mac, |parent| {
7081 parent.child(accept_keystroke.key.clone())
7082 })
7083 .when(!is_platform_style_mac, |parent| {
7084 parent.child(
7085 Key::new(
7086 util::capitalize(&accept_keystroke.key),
7087 Some(Color::Default),
7088 )
7089 .size(Some(IconSize::XSmall.rems().into())),
7090 )
7091 })
7092 .into_any()
7093 .into()
7094 }
7095
7096 fn render_edit_prediction_line_popover(
7097 &self,
7098 label: impl Into<SharedString>,
7099 icon: Option<IconName>,
7100 window: &mut Window,
7101 cx: &App,
7102 ) -> Option<Stateful<Div>> {
7103 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7104
7105 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7106 let has_keybind = keybind.is_some();
7107
7108 let result = h_flex()
7109 .id("ep-line-popover")
7110 .py_0p5()
7111 .pl_1()
7112 .pr(padding_right)
7113 .gap_1()
7114 .rounded_md()
7115 .border_1()
7116 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7117 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7118 .shadow_sm()
7119 .when(!has_keybind, |el| {
7120 let status_colors = cx.theme().status();
7121
7122 el.bg(status_colors.error_background)
7123 .border_color(status_colors.error.opacity(0.6))
7124 .pl_2()
7125 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7126 .cursor_default()
7127 .hoverable_tooltip(move |_window, cx| {
7128 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7129 })
7130 })
7131 .children(keybind)
7132 .child(
7133 Label::new(label)
7134 .size(LabelSize::Small)
7135 .when(!has_keybind, |el| {
7136 el.color(cx.theme().status().error.into()).strikethrough()
7137 }),
7138 )
7139 .when(!has_keybind, |el| {
7140 el.child(
7141 h_flex().ml_1().child(
7142 Icon::new(IconName::Info)
7143 .size(IconSize::Small)
7144 .color(cx.theme().status().error.into()),
7145 ),
7146 )
7147 })
7148 .when_some(icon, |element, icon| {
7149 element.child(
7150 div()
7151 .mt(px(1.5))
7152 .child(Icon::new(icon).size(IconSize::Small)),
7153 )
7154 });
7155
7156 Some(result)
7157 }
7158
7159 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7160 let accent_color = cx.theme().colors().text_accent;
7161 let editor_bg_color = cx.theme().colors().editor_background;
7162 editor_bg_color.blend(accent_color.opacity(0.1))
7163 }
7164
7165 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7166 let accent_color = cx.theme().colors().text_accent;
7167 let editor_bg_color = cx.theme().colors().editor_background;
7168 editor_bg_color.blend(accent_color.opacity(0.6))
7169 }
7170
7171 fn render_edit_prediction_cursor_popover(
7172 &self,
7173 min_width: Pixels,
7174 max_width: Pixels,
7175 cursor_point: Point,
7176 style: &EditorStyle,
7177 accept_keystroke: Option<&gpui::Keystroke>,
7178 _window: &Window,
7179 cx: &mut Context<Editor>,
7180 ) -> Option<AnyElement> {
7181 let provider = self.edit_prediction_provider.as_ref()?;
7182
7183 if provider.provider.needs_terms_acceptance(cx) {
7184 return Some(
7185 h_flex()
7186 .min_w(min_width)
7187 .flex_1()
7188 .px_2()
7189 .py_1()
7190 .gap_3()
7191 .elevation_2(cx)
7192 .hover(|style| style.bg(cx.theme().colors().element_hover))
7193 .id("accept-terms")
7194 .cursor_pointer()
7195 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7196 .on_click(cx.listener(|this, _event, window, cx| {
7197 cx.stop_propagation();
7198 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7199 window.dispatch_action(
7200 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7201 cx,
7202 );
7203 }))
7204 .child(
7205 h_flex()
7206 .flex_1()
7207 .gap_2()
7208 .child(Icon::new(IconName::ZedPredict))
7209 .child(Label::new("Accept Terms of Service"))
7210 .child(div().w_full())
7211 .child(
7212 Icon::new(IconName::ArrowUpRight)
7213 .color(Color::Muted)
7214 .size(IconSize::Small),
7215 )
7216 .into_any_element(),
7217 )
7218 .into_any(),
7219 );
7220 }
7221
7222 let is_refreshing = provider.provider.is_refreshing(cx);
7223
7224 fn pending_completion_container() -> Div {
7225 h_flex()
7226 .h_full()
7227 .flex_1()
7228 .gap_2()
7229 .child(Icon::new(IconName::ZedPredict))
7230 }
7231
7232 let completion = match &self.active_inline_completion {
7233 Some(prediction) => {
7234 if !self.has_visible_completions_menu() {
7235 const RADIUS: Pixels = px(6.);
7236 const BORDER_WIDTH: Pixels = px(1.);
7237
7238 return Some(
7239 h_flex()
7240 .elevation_2(cx)
7241 .border(BORDER_WIDTH)
7242 .border_color(cx.theme().colors().border)
7243 .when(accept_keystroke.is_none(), |el| {
7244 el.border_color(cx.theme().status().error)
7245 })
7246 .rounded(RADIUS)
7247 .rounded_tl(px(0.))
7248 .overflow_hidden()
7249 .child(div().px_1p5().child(match &prediction.completion {
7250 InlineCompletion::Move { target, snapshot } => {
7251 use text::ToPoint as _;
7252 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7253 {
7254 Icon::new(IconName::ZedPredictDown)
7255 } else {
7256 Icon::new(IconName::ZedPredictUp)
7257 }
7258 }
7259 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7260 }))
7261 .child(
7262 h_flex()
7263 .gap_1()
7264 .py_1()
7265 .px_2()
7266 .rounded_r(RADIUS - BORDER_WIDTH)
7267 .border_l_1()
7268 .border_color(cx.theme().colors().border)
7269 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7270 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7271 el.child(
7272 Label::new("Hold")
7273 .size(LabelSize::Small)
7274 .when(accept_keystroke.is_none(), |el| {
7275 el.strikethrough()
7276 })
7277 .line_height_style(LineHeightStyle::UiLabel),
7278 )
7279 })
7280 .id("edit_prediction_cursor_popover_keybind")
7281 .when(accept_keystroke.is_none(), |el| {
7282 let status_colors = cx.theme().status();
7283
7284 el.bg(status_colors.error_background)
7285 .border_color(status_colors.error.opacity(0.6))
7286 .child(Icon::new(IconName::Info).color(Color::Error))
7287 .cursor_default()
7288 .hoverable_tooltip(move |_window, cx| {
7289 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7290 .into()
7291 })
7292 })
7293 .when_some(
7294 accept_keystroke.as_ref(),
7295 |el, accept_keystroke| {
7296 el.child(h_flex().children(ui::render_modifiers(
7297 &accept_keystroke.modifiers,
7298 PlatformStyle::platform(),
7299 Some(Color::Default),
7300 Some(IconSize::XSmall.rems().into()),
7301 false,
7302 )))
7303 },
7304 ),
7305 )
7306 .into_any(),
7307 );
7308 }
7309
7310 self.render_edit_prediction_cursor_popover_preview(
7311 prediction,
7312 cursor_point,
7313 style,
7314 cx,
7315 )?
7316 }
7317
7318 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7319 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7320 stale_completion,
7321 cursor_point,
7322 style,
7323 cx,
7324 )?,
7325
7326 None => {
7327 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7328 }
7329 },
7330
7331 None => pending_completion_container().child(Label::new("No Prediction")),
7332 };
7333
7334 let completion = if is_refreshing {
7335 completion
7336 .with_animation(
7337 "loading-completion",
7338 Animation::new(Duration::from_secs(2))
7339 .repeat()
7340 .with_easing(pulsating_between(0.4, 0.8)),
7341 |label, delta| label.opacity(delta),
7342 )
7343 .into_any_element()
7344 } else {
7345 completion.into_any_element()
7346 };
7347
7348 let has_completion = self.active_inline_completion.is_some();
7349
7350 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7351 Some(
7352 h_flex()
7353 .min_w(min_width)
7354 .max_w(max_width)
7355 .flex_1()
7356 .elevation_2(cx)
7357 .border_color(cx.theme().colors().border)
7358 .child(
7359 div()
7360 .flex_1()
7361 .py_1()
7362 .px_2()
7363 .overflow_hidden()
7364 .child(completion),
7365 )
7366 .when_some(accept_keystroke, |el, accept_keystroke| {
7367 if !accept_keystroke.modifiers.modified() {
7368 return el;
7369 }
7370
7371 el.child(
7372 h_flex()
7373 .h_full()
7374 .border_l_1()
7375 .rounded_r_lg()
7376 .border_color(cx.theme().colors().border)
7377 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7378 .gap_1()
7379 .py_1()
7380 .px_2()
7381 .child(
7382 h_flex()
7383 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7384 .when(is_platform_style_mac, |parent| parent.gap_1())
7385 .child(h_flex().children(ui::render_modifiers(
7386 &accept_keystroke.modifiers,
7387 PlatformStyle::platform(),
7388 Some(if !has_completion {
7389 Color::Muted
7390 } else {
7391 Color::Default
7392 }),
7393 None,
7394 false,
7395 ))),
7396 )
7397 .child(Label::new("Preview").into_any_element())
7398 .opacity(if has_completion { 1.0 } else { 0.4 }),
7399 )
7400 })
7401 .into_any(),
7402 )
7403 }
7404
7405 fn render_edit_prediction_cursor_popover_preview(
7406 &self,
7407 completion: &InlineCompletionState,
7408 cursor_point: Point,
7409 style: &EditorStyle,
7410 cx: &mut Context<Editor>,
7411 ) -> Option<Div> {
7412 use text::ToPoint as _;
7413
7414 fn render_relative_row_jump(
7415 prefix: impl Into<String>,
7416 current_row: u32,
7417 target_row: u32,
7418 ) -> Div {
7419 let (row_diff, arrow) = if target_row < current_row {
7420 (current_row - target_row, IconName::ArrowUp)
7421 } else {
7422 (target_row - current_row, IconName::ArrowDown)
7423 };
7424
7425 h_flex()
7426 .child(
7427 Label::new(format!("{}{}", prefix.into(), row_diff))
7428 .color(Color::Muted)
7429 .size(LabelSize::Small),
7430 )
7431 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7432 }
7433
7434 match &completion.completion {
7435 InlineCompletion::Move {
7436 target, snapshot, ..
7437 } => Some(
7438 h_flex()
7439 .px_2()
7440 .gap_2()
7441 .flex_1()
7442 .child(
7443 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7444 Icon::new(IconName::ZedPredictDown)
7445 } else {
7446 Icon::new(IconName::ZedPredictUp)
7447 },
7448 )
7449 .child(Label::new("Jump to Edit")),
7450 ),
7451
7452 InlineCompletion::Edit {
7453 edits,
7454 edit_preview,
7455 snapshot,
7456 display_mode: _,
7457 } => {
7458 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7459
7460 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7461 &snapshot,
7462 &edits,
7463 edit_preview.as_ref()?,
7464 true,
7465 cx,
7466 )
7467 .first_line_preview();
7468
7469 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7470 .with_default_highlights(&style.text, highlighted_edits.highlights);
7471
7472 let preview = h_flex()
7473 .gap_1()
7474 .min_w_16()
7475 .child(styled_text)
7476 .when(has_more_lines, |parent| parent.child("…"));
7477
7478 let left = if first_edit_row != cursor_point.row {
7479 render_relative_row_jump("", cursor_point.row, first_edit_row)
7480 .into_any_element()
7481 } else {
7482 Icon::new(IconName::ZedPredict).into_any_element()
7483 };
7484
7485 Some(
7486 h_flex()
7487 .h_full()
7488 .flex_1()
7489 .gap_2()
7490 .pr_1()
7491 .overflow_x_hidden()
7492 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7493 .child(left)
7494 .child(preview),
7495 )
7496 }
7497 }
7498 }
7499
7500 fn render_context_menu(
7501 &self,
7502 style: &EditorStyle,
7503 max_height_in_lines: u32,
7504 y_flipped: bool,
7505 window: &mut Window,
7506 cx: &mut Context<Editor>,
7507 ) -> Option<AnyElement> {
7508 let menu = self.context_menu.borrow();
7509 let menu = menu.as_ref()?;
7510 if !menu.visible() {
7511 return None;
7512 };
7513 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7514 }
7515
7516 fn render_context_menu_aside(
7517 &mut self,
7518 max_size: Size<Pixels>,
7519 window: &mut Window,
7520 cx: &mut Context<Editor>,
7521 ) -> Option<AnyElement> {
7522 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7523 if menu.visible() {
7524 menu.render_aside(self, max_size, window, cx)
7525 } else {
7526 None
7527 }
7528 })
7529 }
7530
7531 fn hide_context_menu(
7532 &mut self,
7533 window: &mut Window,
7534 cx: &mut Context<Self>,
7535 ) -> Option<CodeContextMenu> {
7536 cx.notify();
7537 self.completion_tasks.clear();
7538 let context_menu = self.context_menu.borrow_mut().take();
7539 self.stale_inline_completion_in_menu.take();
7540 self.update_visible_inline_completion(window, cx);
7541 context_menu
7542 }
7543
7544 fn show_snippet_choices(
7545 &mut self,
7546 choices: &Vec<String>,
7547 selection: Range<Anchor>,
7548 cx: &mut Context<Self>,
7549 ) {
7550 if selection.start.buffer_id.is_none() {
7551 return;
7552 }
7553 let buffer_id = selection.start.buffer_id.unwrap();
7554 let buffer = self.buffer().read(cx).buffer(buffer_id);
7555 let id = post_inc(&mut self.next_completion_id);
7556
7557 if let Some(buffer) = buffer {
7558 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7559 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7560 ));
7561 }
7562 }
7563
7564 pub fn insert_snippet(
7565 &mut self,
7566 insertion_ranges: &[Range<usize>],
7567 snippet: Snippet,
7568 window: &mut Window,
7569 cx: &mut Context<Self>,
7570 ) -> Result<()> {
7571 struct Tabstop<T> {
7572 is_end_tabstop: bool,
7573 ranges: Vec<Range<T>>,
7574 choices: Option<Vec<String>>,
7575 }
7576
7577 let tabstops = self.buffer.update(cx, |buffer, cx| {
7578 let snippet_text: Arc<str> = snippet.text.clone().into();
7579 let edits = insertion_ranges
7580 .iter()
7581 .cloned()
7582 .map(|range| (range, snippet_text.clone()));
7583 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7584
7585 let snapshot = &*buffer.read(cx);
7586 let snippet = &snippet;
7587 snippet
7588 .tabstops
7589 .iter()
7590 .map(|tabstop| {
7591 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7592 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7593 });
7594 let mut tabstop_ranges = tabstop
7595 .ranges
7596 .iter()
7597 .flat_map(|tabstop_range| {
7598 let mut delta = 0_isize;
7599 insertion_ranges.iter().map(move |insertion_range| {
7600 let insertion_start = insertion_range.start as isize + delta;
7601 delta +=
7602 snippet.text.len() as isize - insertion_range.len() as isize;
7603
7604 let start = ((insertion_start + tabstop_range.start) as usize)
7605 .min(snapshot.len());
7606 let end = ((insertion_start + tabstop_range.end) as usize)
7607 .min(snapshot.len());
7608 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7609 })
7610 })
7611 .collect::<Vec<_>>();
7612 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7613
7614 Tabstop {
7615 is_end_tabstop,
7616 ranges: tabstop_ranges,
7617 choices: tabstop.choices.clone(),
7618 }
7619 })
7620 .collect::<Vec<_>>()
7621 });
7622 if let Some(tabstop) = tabstops.first() {
7623 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7624 s.select_ranges(tabstop.ranges.iter().cloned());
7625 });
7626
7627 if let Some(choices) = &tabstop.choices {
7628 if let Some(selection) = tabstop.ranges.first() {
7629 self.show_snippet_choices(choices, selection.clone(), cx)
7630 }
7631 }
7632
7633 // If we're already at the last tabstop and it's at the end of the snippet,
7634 // we're done, we don't need to keep the state around.
7635 if !tabstop.is_end_tabstop {
7636 let choices = tabstops
7637 .iter()
7638 .map(|tabstop| tabstop.choices.clone())
7639 .collect();
7640
7641 let ranges = tabstops
7642 .into_iter()
7643 .map(|tabstop| tabstop.ranges)
7644 .collect::<Vec<_>>();
7645
7646 self.snippet_stack.push(SnippetState {
7647 active_index: 0,
7648 ranges,
7649 choices,
7650 });
7651 }
7652
7653 // Check whether the just-entered snippet ends with an auto-closable bracket.
7654 if self.autoclose_regions.is_empty() {
7655 let snapshot = self.buffer.read(cx).snapshot(cx);
7656 for selection in &mut self.selections.all::<Point>(cx) {
7657 let selection_head = selection.head();
7658 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7659 continue;
7660 };
7661
7662 let mut bracket_pair = None;
7663 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7664 let prev_chars = snapshot
7665 .reversed_chars_at(selection_head)
7666 .collect::<String>();
7667 for (pair, enabled) in scope.brackets() {
7668 if enabled
7669 && pair.close
7670 && prev_chars.starts_with(pair.start.as_str())
7671 && next_chars.starts_with(pair.end.as_str())
7672 {
7673 bracket_pair = Some(pair.clone());
7674 break;
7675 }
7676 }
7677 if let Some(pair) = bracket_pair {
7678 let start = snapshot.anchor_after(selection_head);
7679 let end = snapshot.anchor_after(selection_head);
7680 self.autoclose_regions.push(AutocloseRegion {
7681 selection_id: selection.id,
7682 range: start..end,
7683 pair,
7684 });
7685 }
7686 }
7687 }
7688 }
7689 Ok(())
7690 }
7691
7692 pub fn move_to_next_snippet_tabstop(
7693 &mut self,
7694 window: &mut Window,
7695 cx: &mut Context<Self>,
7696 ) -> bool {
7697 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7698 }
7699
7700 pub fn move_to_prev_snippet_tabstop(
7701 &mut self,
7702 window: &mut Window,
7703 cx: &mut Context<Self>,
7704 ) -> bool {
7705 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7706 }
7707
7708 pub fn move_to_snippet_tabstop(
7709 &mut self,
7710 bias: Bias,
7711 window: &mut Window,
7712 cx: &mut Context<Self>,
7713 ) -> bool {
7714 if let Some(mut snippet) = self.snippet_stack.pop() {
7715 match bias {
7716 Bias::Left => {
7717 if snippet.active_index > 0 {
7718 snippet.active_index -= 1;
7719 } else {
7720 self.snippet_stack.push(snippet);
7721 return false;
7722 }
7723 }
7724 Bias::Right => {
7725 if snippet.active_index + 1 < snippet.ranges.len() {
7726 snippet.active_index += 1;
7727 } else {
7728 self.snippet_stack.push(snippet);
7729 return false;
7730 }
7731 }
7732 }
7733 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7734 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7735 s.select_anchor_ranges(current_ranges.iter().cloned())
7736 });
7737
7738 if let Some(choices) = &snippet.choices[snippet.active_index] {
7739 if let Some(selection) = current_ranges.first() {
7740 self.show_snippet_choices(&choices, selection.clone(), cx);
7741 }
7742 }
7743
7744 // If snippet state is not at the last tabstop, push it back on the stack
7745 if snippet.active_index + 1 < snippet.ranges.len() {
7746 self.snippet_stack.push(snippet);
7747 }
7748 return true;
7749 }
7750 }
7751
7752 false
7753 }
7754
7755 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7756 self.transact(window, cx, |this, window, cx| {
7757 this.select_all(&SelectAll, window, cx);
7758 this.insert("", window, cx);
7759 });
7760 }
7761
7762 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7763 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7764 self.transact(window, cx, |this, window, cx| {
7765 this.select_autoclose_pair(window, cx);
7766 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7767 if !this.linked_edit_ranges.is_empty() {
7768 let selections = this.selections.all::<MultiBufferPoint>(cx);
7769 let snapshot = this.buffer.read(cx).snapshot(cx);
7770
7771 for selection in selections.iter() {
7772 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7773 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7774 if selection_start.buffer_id != selection_end.buffer_id {
7775 continue;
7776 }
7777 if let Some(ranges) =
7778 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7779 {
7780 for (buffer, entries) in ranges {
7781 linked_ranges.entry(buffer).or_default().extend(entries);
7782 }
7783 }
7784 }
7785 }
7786
7787 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7788 if !this.selections.line_mode {
7789 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7790 for selection in &mut selections {
7791 if selection.is_empty() {
7792 let old_head = selection.head();
7793 let mut new_head =
7794 movement::left(&display_map, old_head.to_display_point(&display_map))
7795 .to_point(&display_map);
7796 if let Some((buffer, line_buffer_range)) = display_map
7797 .buffer_snapshot
7798 .buffer_line_for_row(MultiBufferRow(old_head.row))
7799 {
7800 let indent_size =
7801 buffer.indent_size_for_line(line_buffer_range.start.row);
7802 let indent_len = match indent_size.kind {
7803 IndentKind::Space => {
7804 buffer.settings_at(line_buffer_range.start, cx).tab_size
7805 }
7806 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7807 };
7808 if old_head.column <= indent_size.len && old_head.column > 0 {
7809 let indent_len = indent_len.get();
7810 new_head = cmp::min(
7811 new_head,
7812 MultiBufferPoint::new(
7813 old_head.row,
7814 ((old_head.column - 1) / indent_len) * indent_len,
7815 ),
7816 );
7817 }
7818 }
7819
7820 selection.set_head(new_head, SelectionGoal::None);
7821 }
7822 }
7823 }
7824
7825 this.signature_help_state.set_backspace_pressed(true);
7826 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7827 s.select(selections)
7828 });
7829 this.insert("", window, cx);
7830 let empty_str: Arc<str> = Arc::from("");
7831 for (buffer, edits) in linked_ranges {
7832 let snapshot = buffer.read(cx).snapshot();
7833 use text::ToPoint as TP;
7834
7835 let edits = edits
7836 .into_iter()
7837 .map(|range| {
7838 let end_point = TP::to_point(&range.end, &snapshot);
7839 let mut start_point = TP::to_point(&range.start, &snapshot);
7840
7841 if end_point == start_point {
7842 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7843 .saturating_sub(1);
7844 start_point =
7845 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7846 };
7847
7848 (start_point..end_point, empty_str.clone())
7849 })
7850 .sorted_by_key(|(range, _)| range.start)
7851 .collect::<Vec<_>>();
7852 buffer.update(cx, |this, cx| {
7853 this.edit(edits, None, cx);
7854 })
7855 }
7856 this.refresh_inline_completion(true, false, window, cx);
7857 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7858 });
7859 }
7860
7861 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7862 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7863 self.transact(window, cx, |this, window, cx| {
7864 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7865 let line_mode = s.line_mode;
7866 s.move_with(|map, selection| {
7867 if selection.is_empty() && !line_mode {
7868 let cursor = movement::right(map, selection.head());
7869 selection.end = cursor;
7870 selection.reversed = true;
7871 selection.goal = SelectionGoal::None;
7872 }
7873 })
7874 });
7875 this.insert("", window, cx);
7876 this.refresh_inline_completion(true, false, window, cx);
7877 });
7878 }
7879
7880 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7881 if self.move_to_prev_snippet_tabstop(window, cx) {
7882 return;
7883 }
7884 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7885 self.outdent(&Outdent, window, cx);
7886 }
7887
7888 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7889 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7890 return;
7891 }
7892 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7893 let mut selections = self.selections.all_adjusted(cx);
7894 let buffer = self.buffer.read(cx);
7895 let snapshot = buffer.snapshot(cx);
7896 let rows_iter = selections.iter().map(|s| s.head().row);
7897 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7898
7899 let mut edits = Vec::new();
7900 let mut prev_edited_row = 0;
7901 let mut row_delta = 0;
7902 for selection in &mut selections {
7903 if selection.start.row != prev_edited_row {
7904 row_delta = 0;
7905 }
7906 prev_edited_row = selection.end.row;
7907
7908 // If the selection is non-empty, then increase the indentation of the selected lines.
7909 if !selection.is_empty() {
7910 row_delta =
7911 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7912 continue;
7913 }
7914
7915 // If the selection is empty and the cursor is in the leading whitespace before the
7916 // suggested indentation, then auto-indent the line.
7917 let cursor = selection.head();
7918 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7919 if let Some(suggested_indent) =
7920 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7921 {
7922 if cursor.column < suggested_indent.len
7923 && cursor.column <= current_indent.len
7924 && current_indent.len <= suggested_indent.len
7925 {
7926 selection.start = Point::new(cursor.row, suggested_indent.len);
7927 selection.end = selection.start;
7928 if row_delta == 0 {
7929 edits.extend(Buffer::edit_for_indent_size_adjustment(
7930 cursor.row,
7931 current_indent,
7932 suggested_indent,
7933 ));
7934 row_delta = suggested_indent.len - current_indent.len;
7935 }
7936 continue;
7937 }
7938 }
7939
7940 // Otherwise, insert a hard or soft tab.
7941 let settings = buffer.language_settings_at(cursor, cx);
7942 let tab_size = if settings.hard_tabs {
7943 IndentSize::tab()
7944 } else {
7945 let tab_size = settings.tab_size.get();
7946 let char_column = snapshot
7947 .text_for_range(Point::new(cursor.row, 0)..cursor)
7948 .flat_map(str::chars)
7949 .count()
7950 + row_delta as usize;
7951 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7952 IndentSize::spaces(chars_to_next_tab_stop)
7953 };
7954 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7955 selection.end = selection.start;
7956 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7957 row_delta += tab_size.len;
7958 }
7959
7960 self.transact(window, cx, |this, window, cx| {
7961 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7962 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7963 s.select(selections)
7964 });
7965 this.refresh_inline_completion(true, false, window, cx);
7966 });
7967 }
7968
7969 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7970 if self.read_only(cx) {
7971 return;
7972 }
7973 let mut selections = self.selections.all::<Point>(cx);
7974 let mut prev_edited_row = 0;
7975 let mut row_delta = 0;
7976 let mut edits = Vec::new();
7977 let buffer = self.buffer.read(cx);
7978 let snapshot = buffer.snapshot(cx);
7979 for selection in &mut selections {
7980 if selection.start.row != prev_edited_row {
7981 row_delta = 0;
7982 }
7983 prev_edited_row = selection.end.row;
7984
7985 row_delta =
7986 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7987 }
7988
7989 self.transact(window, cx, |this, window, cx| {
7990 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7991 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7992 s.select(selections)
7993 });
7994 });
7995 }
7996
7997 fn indent_selection(
7998 buffer: &MultiBuffer,
7999 snapshot: &MultiBufferSnapshot,
8000 selection: &mut Selection<Point>,
8001 edits: &mut Vec<(Range<Point>, String)>,
8002 delta_for_start_row: u32,
8003 cx: &App,
8004 ) -> u32 {
8005 let settings = buffer.language_settings_at(selection.start, cx);
8006 let tab_size = settings.tab_size.get();
8007 let indent_kind = if settings.hard_tabs {
8008 IndentKind::Tab
8009 } else {
8010 IndentKind::Space
8011 };
8012 let mut start_row = selection.start.row;
8013 let mut end_row = selection.end.row + 1;
8014
8015 // If a selection ends at the beginning of a line, don't indent
8016 // that last line.
8017 if selection.end.column == 0 && selection.end.row > selection.start.row {
8018 end_row -= 1;
8019 }
8020
8021 // Avoid re-indenting a row that has already been indented by a
8022 // previous selection, but still update this selection's column
8023 // to reflect that indentation.
8024 if delta_for_start_row > 0 {
8025 start_row += 1;
8026 selection.start.column += delta_for_start_row;
8027 if selection.end.row == selection.start.row {
8028 selection.end.column += delta_for_start_row;
8029 }
8030 }
8031
8032 let mut delta_for_end_row = 0;
8033 let has_multiple_rows = start_row + 1 != end_row;
8034 for row in start_row..end_row {
8035 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8036 let indent_delta = match (current_indent.kind, indent_kind) {
8037 (IndentKind::Space, IndentKind::Space) => {
8038 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8039 IndentSize::spaces(columns_to_next_tab_stop)
8040 }
8041 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8042 (_, IndentKind::Tab) => IndentSize::tab(),
8043 };
8044
8045 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8046 0
8047 } else {
8048 selection.start.column
8049 };
8050 let row_start = Point::new(row, start);
8051 edits.push((
8052 row_start..row_start,
8053 indent_delta.chars().collect::<String>(),
8054 ));
8055
8056 // Update this selection's endpoints to reflect the indentation.
8057 if row == selection.start.row {
8058 selection.start.column += indent_delta.len;
8059 }
8060 if row == selection.end.row {
8061 selection.end.column += indent_delta.len;
8062 delta_for_end_row = indent_delta.len;
8063 }
8064 }
8065
8066 if selection.start.row == selection.end.row {
8067 delta_for_start_row + delta_for_end_row
8068 } else {
8069 delta_for_end_row
8070 }
8071 }
8072
8073 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8074 if self.read_only(cx) {
8075 return;
8076 }
8077 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8078 let selections = self.selections.all::<Point>(cx);
8079 let mut deletion_ranges = Vec::new();
8080 let mut last_outdent = None;
8081 {
8082 let buffer = self.buffer.read(cx);
8083 let snapshot = buffer.snapshot(cx);
8084 for selection in &selections {
8085 let settings = buffer.language_settings_at(selection.start, cx);
8086 let tab_size = settings.tab_size.get();
8087 let mut rows = selection.spanned_rows(false, &display_map);
8088
8089 // Avoid re-outdenting a row that has already been outdented by a
8090 // previous selection.
8091 if let Some(last_row) = last_outdent {
8092 if last_row == rows.start {
8093 rows.start = rows.start.next_row();
8094 }
8095 }
8096 let has_multiple_rows = rows.len() > 1;
8097 for row in rows.iter_rows() {
8098 let indent_size = snapshot.indent_size_for_line(row);
8099 if indent_size.len > 0 {
8100 let deletion_len = match indent_size.kind {
8101 IndentKind::Space => {
8102 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8103 if columns_to_prev_tab_stop == 0 {
8104 tab_size
8105 } else {
8106 columns_to_prev_tab_stop
8107 }
8108 }
8109 IndentKind::Tab => 1,
8110 };
8111 let start = if has_multiple_rows
8112 || deletion_len > selection.start.column
8113 || indent_size.len < selection.start.column
8114 {
8115 0
8116 } else {
8117 selection.start.column - deletion_len
8118 };
8119 deletion_ranges.push(
8120 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8121 );
8122 last_outdent = Some(row);
8123 }
8124 }
8125 }
8126 }
8127
8128 self.transact(window, cx, |this, window, cx| {
8129 this.buffer.update(cx, |buffer, cx| {
8130 let empty_str: Arc<str> = Arc::default();
8131 buffer.edit(
8132 deletion_ranges
8133 .into_iter()
8134 .map(|range| (range, empty_str.clone())),
8135 None,
8136 cx,
8137 );
8138 });
8139 let selections = this.selections.all::<usize>(cx);
8140 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8141 s.select(selections)
8142 });
8143 });
8144 }
8145
8146 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8147 if self.read_only(cx) {
8148 return;
8149 }
8150 let selections = self
8151 .selections
8152 .all::<usize>(cx)
8153 .into_iter()
8154 .map(|s| s.range());
8155
8156 self.transact(window, cx, |this, window, cx| {
8157 this.buffer.update(cx, |buffer, cx| {
8158 buffer.autoindent_ranges(selections, cx);
8159 });
8160 let selections = this.selections.all::<usize>(cx);
8161 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8162 s.select(selections)
8163 });
8164 });
8165 }
8166
8167 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8168 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8169 let selections = self.selections.all::<Point>(cx);
8170
8171 let mut new_cursors = Vec::new();
8172 let mut edit_ranges = Vec::new();
8173 let mut selections = selections.iter().peekable();
8174 while let Some(selection) = selections.next() {
8175 let mut rows = selection.spanned_rows(false, &display_map);
8176 let goal_display_column = selection.head().to_display_point(&display_map).column();
8177
8178 // Accumulate contiguous regions of rows that we want to delete.
8179 while let Some(next_selection) = selections.peek() {
8180 let next_rows = next_selection.spanned_rows(false, &display_map);
8181 if next_rows.start <= rows.end {
8182 rows.end = next_rows.end;
8183 selections.next().unwrap();
8184 } else {
8185 break;
8186 }
8187 }
8188
8189 let buffer = &display_map.buffer_snapshot;
8190 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8191 let edit_end;
8192 let cursor_buffer_row;
8193 if buffer.max_point().row >= rows.end.0 {
8194 // If there's a line after the range, delete the \n from the end of the row range
8195 // and position the cursor on the next line.
8196 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8197 cursor_buffer_row = rows.end;
8198 } else {
8199 // If there isn't a line after the range, delete the \n from the line before the
8200 // start of the row range and position the cursor there.
8201 edit_start = edit_start.saturating_sub(1);
8202 edit_end = buffer.len();
8203 cursor_buffer_row = rows.start.previous_row();
8204 }
8205
8206 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8207 *cursor.column_mut() =
8208 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8209
8210 new_cursors.push((
8211 selection.id,
8212 buffer.anchor_after(cursor.to_point(&display_map)),
8213 ));
8214 edit_ranges.push(edit_start..edit_end);
8215 }
8216
8217 self.transact(window, cx, |this, window, cx| {
8218 let buffer = this.buffer.update(cx, |buffer, cx| {
8219 let empty_str: Arc<str> = Arc::default();
8220 buffer.edit(
8221 edit_ranges
8222 .into_iter()
8223 .map(|range| (range, empty_str.clone())),
8224 None,
8225 cx,
8226 );
8227 buffer.snapshot(cx)
8228 });
8229 let new_selections = new_cursors
8230 .into_iter()
8231 .map(|(id, cursor)| {
8232 let cursor = cursor.to_point(&buffer);
8233 Selection {
8234 id,
8235 start: cursor,
8236 end: cursor,
8237 reversed: false,
8238 goal: SelectionGoal::None,
8239 }
8240 })
8241 .collect();
8242
8243 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8244 s.select(new_selections);
8245 });
8246 });
8247 }
8248
8249 pub fn join_lines_impl(
8250 &mut self,
8251 insert_whitespace: bool,
8252 window: &mut Window,
8253 cx: &mut Context<Self>,
8254 ) {
8255 if self.read_only(cx) {
8256 return;
8257 }
8258 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8259 for selection in self.selections.all::<Point>(cx) {
8260 let start = MultiBufferRow(selection.start.row);
8261 // Treat single line selections as if they include the next line. Otherwise this action
8262 // would do nothing for single line selections individual cursors.
8263 let end = if selection.start.row == selection.end.row {
8264 MultiBufferRow(selection.start.row + 1)
8265 } else {
8266 MultiBufferRow(selection.end.row)
8267 };
8268
8269 if let Some(last_row_range) = row_ranges.last_mut() {
8270 if start <= last_row_range.end {
8271 last_row_range.end = end;
8272 continue;
8273 }
8274 }
8275 row_ranges.push(start..end);
8276 }
8277
8278 let snapshot = self.buffer.read(cx).snapshot(cx);
8279 let mut cursor_positions = Vec::new();
8280 for row_range in &row_ranges {
8281 let anchor = snapshot.anchor_before(Point::new(
8282 row_range.end.previous_row().0,
8283 snapshot.line_len(row_range.end.previous_row()),
8284 ));
8285 cursor_positions.push(anchor..anchor);
8286 }
8287
8288 self.transact(window, cx, |this, window, cx| {
8289 for row_range in row_ranges.into_iter().rev() {
8290 for row in row_range.iter_rows().rev() {
8291 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8292 let next_line_row = row.next_row();
8293 let indent = snapshot.indent_size_for_line(next_line_row);
8294 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8295
8296 let replace =
8297 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8298 " "
8299 } else {
8300 ""
8301 };
8302
8303 this.buffer.update(cx, |buffer, cx| {
8304 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8305 });
8306 }
8307 }
8308
8309 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8310 s.select_anchor_ranges(cursor_positions)
8311 });
8312 });
8313 }
8314
8315 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8316 self.join_lines_impl(true, window, cx);
8317 }
8318
8319 pub fn sort_lines_case_sensitive(
8320 &mut self,
8321 _: &SortLinesCaseSensitive,
8322 window: &mut Window,
8323 cx: &mut Context<Self>,
8324 ) {
8325 self.manipulate_lines(window, cx, |lines| lines.sort())
8326 }
8327
8328 pub fn sort_lines_case_insensitive(
8329 &mut self,
8330 _: &SortLinesCaseInsensitive,
8331 window: &mut Window,
8332 cx: &mut Context<Self>,
8333 ) {
8334 self.manipulate_lines(window, cx, |lines| {
8335 lines.sort_by_key(|line| line.to_lowercase())
8336 })
8337 }
8338
8339 pub fn unique_lines_case_insensitive(
8340 &mut self,
8341 _: &UniqueLinesCaseInsensitive,
8342 window: &mut Window,
8343 cx: &mut Context<Self>,
8344 ) {
8345 self.manipulate_lines(window, cx, |lines| {
8346 let mut seen = HashSet::default();
8347 lines.retain(|line| seen.insert(line.to_lowercase()));
8348 })
8349 }
8350
8351 pub fn unique_lines_case_sensitive(
8352 &mut self,
8353 _: &UniqueLinesCaseSensitive,
8354 window: &mut Window,
8355 cx: &mut Context<Self>,
8356 ) {
8357 self.manipulate_lines(window, cx, |lines| {
8358 let mut seen = HashSet::default();
8359 lines.retain(|line| seen.insert(*line));
8360 })
8361 }
8362
8363 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8364 let Some(project) = self.project.clone() else {
8365 return;
8366 };
8367 self.reload(project, window, cx)
8368 .detach_and_notify_err(window, cx);
8369 }
8370
8371 pub fn restore_file(
8372 &mut self,
8373 _: &::git::RestoreFile,
8374 window: &mut Window,
8375 cx: &mut Context<Self>,
8376 ) {
8377 let mut buffer_ids = HashSet::default();
8378 let snapshot = self.buffer().read(cx).snapshot(cx);
8379 for selection in self.selections.all::<usize>(cx) {
8380 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8381 }
8382
8383 let buffer = self.buffer().read(cx);
8384 let ranges = buffer_ids
8385 .into_iter()
8386 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8387 .collect::<Vec<_>>();
8388
8389 self.restore_hunks_in_ranges(ranges, window, cx);
8390 }
8391
8392 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8393 let selections = self
8394 .selections
8395 .all(cx)
8396 .into_iter()
8397 .map(|s| s.range())
8398 .collect();
8399 self.restore_hunks_in_ranges(selections, window, cx);
8400 }
8401
8402 fn restore_hunks_in_ranges(
8403 &mut self,
8404 ranges: Vec<Range<Point>>,
8405 window: &mut Window,
8406 cx: &mut Context<Editor>,
8407 ) {
8408 let mut revert_changes = HashMap::default();
8409 let chunk_by = self
8410 .snapshot(window, cx)
8411 .hunks_for_ranges(ranges)
8412 .into_iter()
8413 .chunk_by(|hunk| hunk.buffer_id);
8414 for (buffer_id, hunks) in &chunk_by {
8415 let hunks = hunks.collect::<Vec<_>>();
8416 for hunk in &hunks {
8417 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8418 }
8419 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8420 }
8421 drop(chunk_by);
8422 if !revert_changes.is_empty() {
8423 self.transact(window, cx, |editor, window, cx| {
8424 editor.restore(revert_changes, window, cx);
8425 });
8426 }
8427 }
8428
8429 pub fn open_active_item_in_terminal(
8430 &mut self,
8431 _: &OpenInTerminal,
8432 window: &mut Window,
8433 cx: &mut Context<Self>,
8434 ) {
8435 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8436 let project_path = buffer.read(cx).project_path(cx)?;
8437 let project = self.project.as_ref()?.read(cx);
8438 let entry = project.entry_for_path(&project_path, cx)?;
8439 let parent = match &entry.canonical_path {
8440 Some(canonical_path) => canonical_path.to_path_buf(),
8441 None => project.absolute_path(&project_path, cx)?,
8442 }
8443 .parent()?
8444 .to_path_buf();
8445 Some(parent)
8446 }) {
8447 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8448 }
8449 }
8450
8451 fn set_breakpoint_context_menu(
8452 &mut self,
8453 display_row: DisplayRow,
8454 position: Option<Anchor>,
8455 clicked_point: gpui::Point<Pixels>,
8456 window: &mut Window,
8457 cx: &mut Context<Self>,
8458 ) {
8459 if !cx.has_flag::<Debugger>() {
8460 return;
8461 }
8462 let source = self
8463 .buffer
8464 .read(cx)
8465 .snapshot(cx)
8466 .anchor_before(Point::new(display_row.0, 0u32));
8467
8468 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8469
8470 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8471 self,
8472 source,
8473 clicked_point,
8474 context_menu,
8475 window,
8476 cx,
8477 );
8478 }
8479
8480 fn add_edit_breakpoint_block(
8481 &mut self,
8482 anchor: Anchor,
8483 breakpoint: &Breakpoint,
8484 window: &mut Window,
8485 cx: &mut Context<Self>,
8486 ) {
8487 let weak_editor = cx.weak_entity();
8488 let bp_prompt = cx.new(|cx| {
8489 BreakpointPromptEditor::new(weak_editor, anchor, breakpoint.clone(), window, cx)
8490 });
8491
8492 let height = bp_prompt.update(cx, |this, cx| {
8493 this.prompt
8494 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8495 });
8496 let cloned_prompt = bp_prompt.clone();
8497 let blocks = vec![BlockProperties {
8498 style: BlockStyle::Sticky,
8499 placement: BlockPlacement::Above(anchor),
8500 height,
8501 render: Arc::new(move |cx| {
8502 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8503 cloned_prompt.clone().into_any_element()
8504 }),
8505 priority: 0,
8506 }];
8507
8508 let focus_handle = bp_prompt.focus_handle(cx);
8509 window.focus(&focus_handle);
8510
8511 let block_ids = self.insert_blocks(blocks, None, cx);
8512 bp_prompt.update(cx, |prompt, _| {
8513 prompt.add_block_ids(block_ids);
8514 });
8515 }
8516
8517 fn breakpoint_at_cursor_head(
8518 &self,
8519 window: &mut Window,
8520 cx: &mut Context<Self>,
8521 ) -> Option<(Anchor, Breakpoint)> {
8522 let cursor_position: Point = self.selections.newest(cx).head();
8523 self.breakpoint_at_row(cursor_position.row, window, cx)
8524 }
8525
8526 pub(crate) fn breakpoint_at_row(
8527 &self,
8528 row: u32,
8529 window: &mut Window,
8530 cx: &mut Context<Self>,
8531 ) -> Option<(Anchor, Breakpoint)> {
8532 let snapshot = self.snapshot(window, cx);
8533 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8534
8535 let project = self.project.clone()?;
8536
8537 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8538 snapshot
8539 .buffer_snapshot
8540 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8541 })?;
8542
8543 let enclosing_excerpt = breakpoint_position.excerpt_id;
8544 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8545 let buffer_snapshot = buffer.read(cx).snapshot();
8546
8547 let row = buffer_snapshot
8548 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8549 .row;
8550
8551 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8552 let anchor_end = snapshot
8553 .buffer_snapshot
8554 .anchor_before(Point::new(row, line_len));
8555
8556 let bp = self
8557 .breakpoint_store
8558 .as_ref()?
8559 .read_with(cx, |breakpoint_store, cx| {
8560 breakpoint_store
8561 .breakpoints(
8562 &buffer,
8563 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8564 &buffer_snapshot,
8565 cx,
8566 )
8567 .next()
8568 .and_then(|(anchor, bp)| {
8569 let breakpoint_row = buffer_snapshot
8570 .summary_for_anchor::<text::PointUtf16>(anchor)
8571 .row;
8572
8573 if breakpoint_row == row {
8574 snapshot
8575 .buffer_snapshot
8576 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8577 .map(|anchor| (anchor, bp.clone()))
8578 } else {
8579 None
8580 }
8581 })
8582 });
8583 bp
8584 }
8585
8586 pub fn edit_log_breakpoint(
8587 &mut self,
8588 _: &EditLogBreakpoint,
8589 window: &mut Window,
8590 cx: &mut Context<Self>,
8591 ) {
8592 let (anchor, bp) = self
8593 .breakpoint_at_cursor_head(window, cx)
8594 .unwrap_or_else(|| {
8595 let cursor_position: Point = self.selections.newest(cx).head();
8596
8597 let breakpoint_position = self
8598 .snapshot(window, cx)
8599 .display_snapshot
8600 .buffer_snapshot
8601 .anchor_before(Point::new(cursor_position.row, 0));
8602
8603 (
8604 breakpoint_position,
8605 Breakpoint {
8606 kind: BreakpointKind::Standard,
8607 state: BreakpointState::Enabled,
8608 },
8609 )
8610 });
8611
8612 self.add_edit_breakpoint_block(anchor, &bp, window, cx);
8613 }
8614
8615 pub fn enable_breakpoint(
8616 &mut self,
8617 _: &crate::actions::EnableBreakpoint,
8618 window: &mut Window,
8619 cx: &mut Context<Self>,
8620 ) {
8621 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8622 if breakpoint.is_disabled() {
8623 self.edit_breakpoint_at_anchor(
8624 anchor,
8625 breakpoint,
8626 BreakpointEditAction::InvertState,
8627 cx,
8628 );
8629 }
8630 }
8631 }
8632
8633 pub fn disable_breakpoint(
8634 &mut self,
8635 _: &crate::actions::DisableBreakpoint,
8636 window: &mut Window,
8637 cx: &mut Context<Self>,
8638 ) {
8639 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8640 if breakpoint.is_enabled() {
8641 self.edit_breakpoint_at_anchor(
8642 anchor,
8643 breakpoint,
8644 BreakpointEditAction::InvertState,
8645 cx,
8646 );
8647 }
8648 }
8649 }
8650
8651 pub fn toggle_breakpoint(
8652 &mut self,
8653 _: &crate::actions::ToggleBreakpoint,
8654 window: &mut Window,
8655 cx: &mut Context<Self>,
8656 ) {
8657 let edit_action = BreakpointEditAction::Toggle;
8658
8659 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8660 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8661 } else {
8662 let cursor_position: Point = self.selections.newest(cx).head();
8663
8664 let breakpoint_position = self
8665 .snapshot(window, cx)
8666 .display_snapshot
8667 .buffer_snapshot
8668 .anchor_before(Point::new(cursor_position.row, 0));
8669
8670 self.edit_breakpoint_at_anchor(
8671 breakpoint_position,
8672 Breakpoint::new_standard(),
8673 edit_action,
8674 cx,
8675 );
8676 }
8677 }
8678
8679 pub fn edit_breakpoint_at_anchor(
8680 &mut self,
8681 breakpoint_position: Anchor,
8682 breakpoint: Breakpoint,
8683 edit_action: BreakpointEditAction,
8684 cx: &mut Context<Self>,
8685 ) {
8686 let Some(breakpoint_store) = &self.breakpoint_store else {
8687 return;
8688 };
8689
8690 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8691 if breakpoint_position == Anchor::min() {
8692 self.buffer()
8693 .read(cx)
8694 .excerpt_buffer_ids()
8695 .into_iter()
8696 .next()
8697 } else {
8698 None
8699 }
8700 }) else {
8701 return;
8702 };
8703
8704 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8705 return;
8706 };
8707
8708 breakpoint_store.update(cx, |breakpoint_store, cx| {
8709 breakpoint_store.toggle_breakpoint(
8710 buffer,
8711 (breakpoint_position.text_anchor, breakpoint),
8712 edit_action,
8713 cx,
8714 );
8715 });
8716
8717 cx.notify();
8718 }
8719
8720 #[cfg(any(test, feature = "test-support"))]
8721 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8722 self.breakpoint_store.clone()
8723 }
8724
8725 pub fn prepare_restore_change(
8726 &self,
8727 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8728 hunk: &MultiBufferDiffHunk,
8729 cx: &mut App,
8730 ) -> Option<()> {
8731 if hunk.is_created_file() {
8732 return None;
8733 }
8734 let buffer = self.buffer.read(cx);
8735 let diff = buffer.diff_for(hunk.buffer_id)?;
8736 let buffer = buffer.buffer(hunk.buffer_id)?;
8737 let buffer = buffer.read(cx);
8738 let original_text = diff
8739 .read(cx)
8740 .base_text()
8741 .as_rope()
8742 .slice(hunk.diff_base_byte_range.clone());
8743 let buffer_snapshot = buffer.snapshot();
8744 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8745 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8746 probe
8747 .0
8748 .start
8749 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8750 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8751 }) {
8752 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8753 Some(())
8754 } else {
8755 None
8756 }
8757 }
8758
8759 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8760 self.manipulate_lines(window, cx, |lines| lines.reverse())
8761 }
8762
8763 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8764 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8765 }
8766
8767 fn manipulate_lines<Fn>(
8768 &mut self,
8769 window: &mut Window,
8770 cx: &mut Context<Self>,
8771 mut callback: Fn,
8772 ) where
8773 Fn: FnMut(&mut Vec<&str>),
8774 {
8775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8776 let buffer = self.buffer.read(cx).snapshot(cx);
8777
8778 let mut edits = Vec::new();
8779
8780 let selections = self.selections.all::<Point>(cx);
8781 let mut selections = selections.iter().peekable();
8782 let mut contiguous_row_selections = Vec::new();
8783 let mut new_selections = Vec::new();
8784 let mut added_lines = 0;
8785 let mut removed_lines = 0;
8786
8787 while let Some(selection) = selections.next() {
8788 let (start_row, end_row) = consume_contiguous_rows(
8789 &mut contiguous_row_selections,
8790 selection,
8791 &display_map,
8792 &mut selections,
8793 );
8794
8795 let start_point = Point::new(start_row.0, 0);
8796 let end_point = Point::new(
8797 end_row.previous_row().0,
8798 buffer.line_len(end_row.previous_row()),
8799 );
8800 let text = buffer
8801 .text_for_range(start_point..end_point)
8802 .collect::<String>();
8803
8804 let mut lines = text.split('\n').collect_vec();
8805
8806 let lines_before = lines.len();
8807 callback(&mut lines);
8808 let lines_after = lines.len();
8809
8810 edits.push((start_point..end_point, lines.join("\n")));
8811
8812 // Selections must change based on added and removed line count
8813 let start_row =
8814 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8815 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8816 new_selections.push(Selection {
8817 id: selection.id,
8818 start: start_row,
8819 end: end_row,
8820 goal: SelectionGoal::None,
8821 reversed: selection.reversed,
8822 });
8823
8824 if lines_after > lines_before {
8825 added_lines += lines_after - lines_before;
8826 } else if lines_before > lines_after {
8827 removed_lines += lines_before - lines_after;
8828 }
8829 }
8830
8831 self.transact(window, cx, |this, window, cx| {
8832 let buffer = this.buffer.update(cx, |buffer, cx| {
8833 buffer.edit(edits, None, cx);
8834 buffer.snapshot(cx)
8835 });
8836
8837 // Recalculate offsets on newly edited buffer
8838 let new_selections = new_selections
8839 .iter()
8840 .map(|s| {
8841 let start_point = Point::new(s.start.0, 0);
8842 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8843 Selection {
8844 id: s.id,
8845 start: buffer.point_to_offset(start_point),
8846 end: buffer.point_to_offset(end_point),
8847 goal: s.goal,
8848 reversed: s.reversed,
8849 }
8850 })
8851 .collect();
8852
8853 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8854 s.select(new_selections);
8855 });
8856
8857 this.request_autoscroll(Autoscroll::fit(), cx);
8858 });
8859 }
8860
8861 pub fn convert_to_upper_case(
8862 &mut self,
8863 _: &ConvertToUpperCase,
8864 window: &mut Window,
8865 cx: &mut Context<Self>,
8866 ) {
8867 self.manipulate_text(window, cx, |text| text.to_uppercase())
8868 }
8869
8870 pub fn convert_to_lower_case(
8871 &mut self,
8872 _: &ConvertToLowerCase,
8873 window: &mut Window,
8874 cx: &mut Context<Self>,
8875 ) {
8876 self.manipulate_text(window, cx, |text| text.to_lowercase())
8877 }
8878
8879 pub fn convert_to_title_case(
8880 &mut self,
8881 _: &ConvertToTitleCase,
8882 window: &mut Window,
8883 cx: &mut Context<Self>,
8884 ) {
8885 self.manipulate_text(window, cx, |text| {
8886 text.split('\n')
8887 .map(|line| line.to_case(Case::Title))
8888 .join("\n")
8889 })
8890 }
8891
8892 pub fn convert_to_snake_case(
8893 &mut self,
8894 _: &ConvertToSnakeCase,
8895 window: &mut Window,
8896 cx: &mut Context<Self>,
8897 ) {
8898 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8899 }
8900
8901 pub fn convert_to_kebab_case(
8902 &mut self,
8903 _: &ConvertToKebabCase,
8904 window: &mut Window,
8905 cx: &mut Context<Self>,
8906 ) {
8907 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8908 }
8909
8910 pub fn convert_to_upper_camel_case(
8911 &mut self,
8912 _: &ConvertToUpperCamelCase,
8913 window: &mut Window,
8914 cx: &mut Context<Self>,
8915 ) {
8916 self.manipulate_text(window, cx, |text| {
8917 text.split('\n')
8918 .map(|line| line.to_case(Case::UpperCamel))
8919 .join("\n")
8920 })
8921 }
8922
8923 pub fn convert_to_lower_camel_case(
8924 &mut self,
8925 _: &ConvertToLowerCamelCase,
8926 window: &mut Window,
8927 cx: &mut Context<Self>,
8928 ) {
8929 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8930 }
8931
8932 pub fn convert_to_opposite_case(
8933 &mut self,
8934 _: &ConvertToOppositeCase,
8935 window: &mut Window,
8936 cx: &mut Context<Self>,
8937 ) {
8938 self.manipulate_text(window, cx, |text| {
8939 text.chars()
8940 .fold(String::with_capacity(text.len()), |mut t, c| {
8941 if c.is_uppercase() {
8942 t.extend(c.to_lowercase());
8943 } else {
8944 t.extend(c.to_uppercase());
8945 }
8946 t
8947 })
8948 })
8949 }
8950
8951 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8952 where
8953 Fn: FnMut(&str) -> String,
8954 {
8955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8956 let buffer = self.buffer.read(cx).snapshot(cx);
8957
8958 let mut new_selections = Vec::new();
8959 let mut edits = Vec::new();
8960 let mut selection_adjustment = 0i32;
8961
8962 for selection in self.selections.all::<usize>(cx) {
8963 let selection_is_empty = selection.is_empty();
8964
8965 let (start, end) = if selection_is_empty {
8966 let word_range = movement::surrounding_word(
8967 &display_map,
8968 selection.start.to_display_point(&display_map),
8969 );
8970 let start = word_range.start.to_offset(&display_map, Bias::Left);
8971 let end = word_range.end.to_offset(&display_map, Bias::Left);
8972 (start, end)
8973 } else {
8974 (selection.start, selection.end)
8975 };
8976
8977 let text = buffer.text_for_range(start..end).collect::<String>();
8978 let old_length = text.len() as i32;
8979 let text = callback(&text);
8980
8981 new_selections.push(Selection {
8982 start: (start as i32 - selection_adjustment) as usize,
8983 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8984 goal: SelectionGoal::None,
8985 ..selection
8986 });
8987
8988 selection_adjustment += old_length - text.len() as i32;
8989
8990 edits.push((start..end, text));
8991 }
8992
8993 self.transact(window, cx, |this, window, cx| {
8994 this.buffer.update(cx, |buffer, cx| {
8995 buffer.edit(edits, None, cx);
8996 });
8997
8998 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8999 s.select(new_selections);
9000 });
9001
9002 this.request_autoscroll(Autoscroll::fit(), cx);
9003 });
9004 }
9005
9006 pub fn duplicate(
9007 &mut self,
9008 upwards: bool,
9009 whole_lines: bool,
9010 window: &mut Window,
9011 cx: &mut Context<Self>,
9012 ) {
9013 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9014 let buffer = &display_map.buffer_snapshot;
9015 let selections = self.selections.all::<Point>(cx);
9016
9017 let mut edits = Vec::new();
9018 let mut selections_iter = selections.iter().peekable();
9019 while let Some(selection) = selections_iter.next() {
9020 let mut rows = selection.spanned_rows(false, &display_map);
9021 // duplicate line-wise
9022 if whole_lines || selection.start == selection.end {
9023 // Avoid duplicating the same lines twice.
9024 while let Some(next_selection) = selections_iter.peek() {
9025 let next_rows = next_selection.spanned_rows(false, &display_map);
9026 if next_rows.start < rows.end {
9027 rows.end = next_rows.end;
9028 selections_iter.next().unwrap();
9029 } else {
9030 break;
9031 }
9032 }
9033
9034 // Copy the text from the selected row region and splice it either at the start
9035 // or end of the region.
9036 let start = Point::new(rows.start.0, 0);
9037 let end = Point::new(
9038 rows.end.previous_row().0,
9039 buffer.line_len(rows.end.previous_row()),
9040 );
9041 let text = buffer
9042 .text_for_range(start..end)
9043 .chain(Some("\n"))
9044 .collect::<String>();
9045 let insert_location = if upwards {
9046 Point::new(rows.end.0, 0)
9047 } else {
9048 start
9049 };
9050 edits.push((insert_location..insert_location, text));
9051 } else {
9052 // duplicate character-wise
9053 let start = selection.start;
9054 let end = selection.end;
9055 let text = buffer.text_for_range(start..end).collect::<String>();
9056 edits.push((selection.end..selection.end, text));
9057 }
9058 }
9059
9060 self.transact(window, cx, |this, _, cx| {
9061 this.buffer.update(cx, |buffer, cx| {
9062 buffer.edit(edits, None, cx);
9063 });
9064
9065 this.request_autoscroll(Autoscroll::fit(), cx);
9066 });
9067 }
9068
9069 pub fn duplicate_line_up(
9070 &mut self,
9071 _: &DuplicateLineUp,
9072 window: &mut Window,
9073 cx: &mut Context<Self>,
9074 ) {
9075 self.duplicate(true, true, window, cx);
9076 }
9077
9078 pub fn duplicate_line_down(
9079 &mut self,
9080 _: &DuplicateLineDown,
9081 window: &mut Window,
9082 cx: &mut Context<Self>,
9083 ) {
9084 self.duplicate(false, true, window, cx);
9085 }
9086
9087 pub fn duplicate_selection(
9088 &mut self,
9089 _: &DuplicateSelection,
9090 window: &mut Window,
9091 cx: &mut Context<Self>,
9092 ) {
9093 self.duplicate(false, false, window, cx);
9094 }
9095
9096 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9097 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9098 let buffer = self.buffer.read(cx).snapshot(cx);
9099
9100 let mut edits = Vec::new();
9101 let mut unfold_ranges = Vec::new();
9102 let mut refold_creases = Vec::new();
9103
9104 let selections = self.selections.all::<Point>(cx);
9105 let mut selections = selections.iter().peekable();
9106 let mut contiguous_row_selections = Vec::new();
9107 let mut new_selections = Vec::new();
9108
9109 while let Some(selection) = selections.next() {
9110 // Find all the selections that span a contiguous row range
9111 let (start_row, end_row) = consume_contiguous_rows(
9112 &mut contiguous_row_selections,
9113 selection,
9114 &display_map,
9115 &mut selections,
9116 );
9117
9118 // Move the text spanned by the row range to be before the line preceding the row range
9119 if start_row.0 > 0 {
9120 let range_to_move = Point::new(
9121 start_row.previous_row().0,
9122 buffer.line_len(start_row.previous_row()),
9123 )
9124 ..Point::new(
9125 end_row.previous_row().0,
9126 buffer.line_len(end_row.previous_row()),
9127 );
9128 let insertion_point = display_map
9129 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9130 .0;
9131
9132 // Don't move lines across excerpts
9133 if buffer
9134 .excerpt_containing(insertion_point..range_to_move.end)
9135 .is_some()
9136 {
9137 let text = buffer
9138 .text_for_range(range_to_move.clone())
9139 .flat_map(|s| s.chars())
9140 .skip(1)
9141 .chain(['\n'])
9142 .collect::<String>();
9143
9144 edits.push((
9145 buffer.anchor_after(range_to_move.start)
9146 ..buffer.anchor_before(range_to_move.end),
9147 String::new(),
9148 ));
9149 let insertion_anchor = buffer.anchor_after(insertion_point);
9150 edits.push((insertion_anchor..insertion_anchor, text));
9151
9152 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9153
9154 // Move selections up
9155 new_selections.extend(contiguous_row_selections.drain(..).map(
9156 |mut selection| {
9157 selection.start.row -= row_delta;
9158 selection.end.row -= row_delta;
9159 selection
9160 },
9161 ));
9162
9163 // Move folds up
9164 unfold_ranges.push(range_to_move.clone());
9165 for fold in display_map.folds_in_range(
9166 buffer.anchor_before(range_to_move.start)
9167 ..buffer.anchor_after(range_to_move.end),
9168 ) {
9169 let mut start = fold.range.start.to_point(&buffer);
9170 let mut end = fold.range.end.to_point(&buffer);
9171 start.row -= row_delta;
9172 end.row -= row_delta;
9173 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9174 }
9175 }
9176 }
9177
9178 // If we didn't move line(s), preserve the existing selections
9179 new_selections.append(&mut contiguous_row_selections);
9180 }
9181
9182 self.transact(window, cx, |this, window, cx| {
9183 this.unfold_ranges(&unfold_ranges, true, true, cx);
9184 this.buffer.update(cx, |buffer, cx| {
9185 for (range, text) in edits {
9186 buffer.edit([(range, text)], None, cx);
9187 }
9188 });
9189 this.fold_creases(refold_creases, true, window, cx);
9190 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9191 s.select(new_selections);
9192 })
9193 });
9194 }
9195
9196 pub fn move_line_down(
9197 &mut self,
9198 _: &MoveLineDown,
9199 window: &mut Window,
9200 cx: &mut Context<Self>,
9201 ) {
9202 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9203 let buffer = self.buffer.read(cx).snapshot(cx);
9204
9205 let mut edits = Vec::new();
9206 let mut unfold_ranges = Vec::new();
9207 let mut refold_creases = Vec::new();
9208
9209 let selections = self.selections.all::<Point>(cx);
9210 let mut selections = selections.iter().peekable();
9211 let mut contiguous_row_selections = Vec::new();
9212 let mut new_selections = Vec::new();
9213
9214 while let Some(selection) = selections.next() {
9215 // Find all the selections that span a contiguous row range
9216 let (start_row, end_row) = consume_contiguous_rows(
9217 &mut contiguous_row_selections,
9218 selection,
9219 &display_map,
9220 &mut selections,
9221 );
9222
9223 // Move the text spanned by the row range to be after the last line of the row range
9224 if end_row.0 <= buffer.max_point().row {
9225 let range_to_move =
9226 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9227 let insertion_point = display_map
9228 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9229 .0;
9230
9231 // Don't move lines across excerpt boundaries
9232 if buffer
9233 .excerpt_containing(range_to_move.start..insertion_point)
9234 .is_some()
9235 {
9236 let mut text = String::from("\n");
9237 text.extend(buffer.text_for_range(range_to_move.clone()));
9238 text.pop(); // Drop trailing newline
9239 edits.push((
9240 buffer.anchor_after(range_to_move.start)
9241 ..buffer.anchor_before(range_to_move.end),
9242 String::new(),
9243 ));
9244 let insertion_anchor = buffer.anchor_after(insertion_point);
9245 edits.push((insertion_anchor..insertion_anchor, text));
9246
9247 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9248
9249 // Move selections down
9250 new_selections.extend(contiguous_row_selections.drain(..).map(
9251 |mut selection| {
9252 selection.start.row += row_delta;
9253 selection.end.row += row_delta;
9254 selection
9255 },
9256 ));
9257
9258 // Move folds down
9259 unfold_ranges.push(range_to_move.clone());
9260 for fold in display_map.folds_in_range(
9261 buffer.anchor_before(range_to_move.start)
9262 ..buffer.anchor_after(range_to_move.end),
9263 ) {
9264 let mut start = fold.range.start.to_point(&buffer);
9265 let mut end = fold.range.end.to_point(&buffer);
9266 start.row += row_delta;
9267 end.row += row_delta;
9268 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9269 }
9270 }
9271 }
9272
9273 // If we didn't move line(s), preserve the existing selections
9274 new_selections.append(&mut contiguous_row_selections);
9275 }
9276
9277 self.transact(window, cx, |this, window, cx| {
9278 this.unfold_ranges(&unfold_ranges, true, true, cx);
9279 this.buffer.update(cx, |buffer, cx| {
9280 for (range, text) in edits {
9281 buffer.edit([(range, text)], None, cx);
9282 }
9283 });
9284 this.fold_creases(refold_creases, true, window, cx);
9285 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9286 s.select(new_selections)
9287 });
9288 });
9289 }
9290
9291 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9292 let text_layout_details = &self.text_layout_details(window);
9293 self.transact(window, cx, |this, window, cx| {
9294 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9295 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9296 let line_mode = s.line_mode;
9297 s.move_with(|display_map, selection| {
9298 if !selection.is_empty() || line_mode {
9299 return;
9300 }
9301
9302 let mut head = selection.head();
9303 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9304 if head.column() == display_map.line_len(head.row()) {
9305 transpose_offset = display_map
9306 .buffer_snapshot
9307 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9308 }
9309
9310 if transpose_offset == 0 {
9311 return;
9312 }
9313
9314 *head.column_mut() += 1;
9315 head = display_map.clip_point(head, Bias::Right);
9316 let goal = SelectionGoal::HorizontalPosition(
9317 display_map
9318 .x_for_display_point(head, text_layout_details)
9319 .into(),
9320 );
9321 selection.collapse_to(head, goal);
9322
9323 let transpose_start = display_map
9324 .buffer_snapshot
9325 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9326 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9327 let transpose_end = display_map
9328 .buffer_snapshot
9329 .clip_offset(transpose_offset + 1, Bias::Right);
9330 if let Some(ch) =
9331 display_map.buffer_snapshot.chars_at(transpose_start).next()
9332 {
9333 edits.push((transpose_start..transpose_offset, String::new()));
9334 edits.push((transpose_end..transpose_end, ch.to_string()));
9335 }
9336 }
9337 });
9338 edits
9339 });
9340 this.buffer
9341 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9342 let selections = this.selections.all::<usize>(cx);
9343 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9344 s.select(selections);
9345 });
9346 });
9347 }
9348
9349 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9350 self.rewrap_impl(RewrapOptions::default(), cx)
9351 }
9352
9353 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9354 let buffer = self.buffer.read(cx).snapshot(cx);
9355 let selections = self.selections.all::<Point>(cx);
9356 let mut selections = selections.iter().peekable();
9357
9358 let mut edits = Vec::new();
9359 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9360
9361 while let Some(selection) = selections.next() {
9362 let mut start_row = selection.start.row;
9363 let mut end_row = selection.end.row;
9364
9365 // Skip selections that overlap with a range that has already been rewrapped.
9366 let selection_range = start_row..end_row;
9367 if rewrapped_row_ranges
9368 .iter()
9369 .any(|range| range.overlaps(&selection_range))
9370 {
9371 continue;
9372 }
9373
9374 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9375
9376 // Since not all lines in the selection may be at the same indent
9377 // level, choose the indent size that is the most common between all
9378 // of the lines.
9379 //
9380 // If there is a tie, we use the deepest indent.
9381 let (indent_size, indent_end) = {
9382 let mut indent_size_occurrences = HashMap::default();
9383 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9384
9385 for row in start_row..=end_row {
9386 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9387 rows_by_indent_size.entry(indent).or_default().push(row);
9388 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9389 }
9390
9391 let indent_size = indent_size_occurrences
9392 .into_iter()
9393 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9394 .map(|(indent, _)| indent)
9395 .unwrap_or_default();
9396 let row = rows_by_indent_size[&indent_size][0];
9397 let indent_end = Point::new(row, indent_size.len);
9398
9399 (indent_size, indent_end)
9400 };
9401
9402 let mut line_prefix = indent_size.chars().collect::<String>();
9403
9404 let mut inside_comment = false;
9405 if let Some(comment_prefix) =
9406 buffer
9407 .language_scope_at(selection.head())
9408 .and_then(|language| {
9409 language
9410 .line_comment_prefixes()
9411 .iter()
9412 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9413 .cloned()
9414 })
9415 {
9416 line_prefix.push_str(&comment_prefix);
9417 inside_comment = true;
9418 }
9419
9420 let language_settings = buffer.language_settings_at(selection.head(), cx);
9421 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9422 RewrapBehavior::InComments => inside_comment,
9423 RewrapBehavior::InSelections => !selection.is_empty(),
9424 RewrapBehavior::Anywhere => true,
9425 };
9426
9427 let should_rewrap = options.override_language_settings
9428 || allow_rewrap_based_on_language
9429 || self.hard_wrap.is_some();
9430 if !should_rewrap {
9431 continue;
9432 }
9433
9434 if selection.is_empty() {
9435 'expand_upwards: while start_row > 0 {
9436 let prev_row = start_row - 1;
9437 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9438 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9439 {
9440 start_row = prev_row;
9441 } else {
9442 break 'expand_upwards;
9443 }
9444 }
9445
9446 'expand_downwards: while end_row < buffer.max_point().row {
9447 let next_row = end_row + 1;
9448 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9449 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9450 {
9451 end_row = next_row;
9452 } else {
9453 break 'expand_downwards;
9454 }
9455 }
9456 }
9457
9458 let start = Point::new(start_row, 0);
9459 let start_offset = start.to_offset(&buffer);
9460 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9461 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9462 let Some(lines_without_prefixes) = selection_text
9463 .lines()
9464 .map(|line| {
9465 line.strip_prefix(&line_prefix)
9466 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9467 .ok_or_else(|| {
9468 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9469 })
9470 })
9471 .collect::<Result<Vec<_>, _>>()
9472 .log_err()
9473 else {
9474 continue;
9475 };
9476
9477 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9478 buffer
9479 .language_settings_at(Point::new(start_row, 0), cx)
9480 .preferred_line_length as usize
9481 });
9482 let wrapped_text = wrap_with_prefix(
9483 line_prefix,
9484 lines_without_prefixes.join("\n"),
9485 wrap_column,
9486 tab_size,
9487 options.preserve_existing_whitespace,
9488 );
9489
9490 // TODO: should always use char-based diff while still supporting cursor behavior that
9491 // matches vim.
9492 let mut diff_options = DiffOptions::default();
9493 if options.override_language_settings {
9494 diff_options.max_word_diff_len = 0;
9495 diff_options.max_word_diff_line_count = 0;
9496 } else {
9497 diff_options.max_word_diff_len = usize::MAX;
9498 diff_options.max_word_diff_line_count = usize::MAX;
9499 }
9500
9501 for (old_range, new_text) in
9502 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9503 {
9504 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9505 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9506 edits.push((edit_start..edit_end, new_text));
9507 }
9508
9509 rewrapped_row_ranges.push(start_row..=end_row);
9510 }
9511
9512 self.buffer
9513 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9514 }
9515
9516 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9517 let mut text = String::new();
9518 let buffer = self.buffer.read(cx).snapshot(cx);
9519 let mut selections = self.selections.all::<Point>(cx);
9520 let mut clipboard_selections = Vec::with_capacity(selections.len());
9521 {
9522 let max_point = buffer.max_point();
9523 let mut is_first = true;
9524 for selection in &mut selections {
9525 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9526 if is_entire_line {
9527 selection.start = Point::new(selection.start.row, 0);
9528 if !selection.is_empty() && selection.end.column == 0 {
9529 selection.end = cmp::min(max_point, selection.end);
9530 } else {
9531 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9532 }
9533 selection.goal = SelectionGoal::None;
9534 }
9535 if is_first {
9536 is_first = false;
9537 } else {
9538 text += "\n";
9539 }
9540 let mut len = 0;
9541 for chunk in buffer.text_for_range(selection.start..selection.end) {
9542 text.push_str(chunk);
9543 len += chunk.len();
9544 }
9545 clipboard_selections.push(ClipboardSelection {
9546 len,
9547 is_entire_line,
9548 first_line_indent: buffer
9549 .indent_size_for_line(MultiBufferRow(selection.start.row))
9550 .len,
9551 });
9552 }
9553 }
9554
9555 self.transact(window, cx, |this, window, cx| {
9556 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9557 s.select(selections);
9558 });
9559 this.insert("", window, cx);
9560 });
9561 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9562 }
9563
9564 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9565 let item = self.cut_common(window, cx);
9566 cx.write_to_clipboard(item);
9567 }
9568
9569 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9570 self.change_selections(None, window, cx, |s| {
9571 s.move_with(|snapshot, sel| {
9572 if sel.is_empty() {
9573 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9574 }
9575 });
9576 });
9577 let item = self.cut_common(window, cx);
9578 cx.set_global(KillRing(item))
9579 }
9580
9581 pub fn kill_ring_yank(
9582 &mut self,
9583 _: &KillRingYank,
9584 window: &mut Window,
9585 cx: &mut Context<Self>,
9586 ) {
9587 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9588 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9589 (kill_ring.text().to_string(), kill_ring.metadata_json())
9590 } else {
9591 return;
9592 }
9593 } else {
9594 return;
9595 };
9596 self.do_paste(&text, metadata, false, window, cx);
9597 }
9598
9599 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9600 self.do_copy(true, cx);
9601 }
9602
9603 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9604 self.do_copy(false, cx);
9605 }
9606
9607 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9608 let selections = self.selections.all::<Point>(cx);
9609 let buffer = self.buffer.read(cx).read(cx);
9610 let mut text = String::new();
9611
9612 let mut clipboard_selections = Vec::with_capacity(selections.len());
9613 {
9614 let max_point = buffer.max_point();
9615 let mut is_first = true;
9616 for selection in &selections {
9617 let mut start = selection.start;
9618 let mut end = selection.end;
9619 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9620 if is_entire_line {
9621 start = Point::new(start.row, 0);
9622 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9623 }
9624
9625 let mut trimmed_selections = Vec::new();
9626 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9627 let row = MultiBufferRow(start.row);
9628 let first_indent = buffer.indent_size_for_line(row);
9629 if first_indent.len == 0 || start.column > first_indent.len {
9630 trimmed_selections.push(start..end);
9631 } else {
9632 trimmed_selections.push(
9633 Point::new(row.0, first_indent.len)
9634 ..Point::new(row.0, buffer.line_len(row)),
9635 );
9636 for row in start.row + 1..=end.row {
9637 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9638 if row_indent_size.len >= first_indent.len {
9639 trimmed_selections.push(
9640 Point::new(row, first_indent.len)
9641 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9642 );
9643 } else {
9644 trimmed_selections.clear();
9645 trimmed_selections.push(start..end);
9646 break;
9647 }
9648 }
9649 }
9650 } else {
9651 trimmed_selections.push(start..end);
9652 }
9653
9654 for trimmed_range in trimmed_selections {
9655 if is_first {
9656 is_first = false;
9657 } else {
9658 text += "\n";
9659 }
9660 let mut len = 0;
9661 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9662 text.push_str(chunk);
9663 len += chunk.len();
9664 }
9665 clipboard_selections.push(ClipboardSelection {
9666 len,
9667 is_entire_line,
9668 first_line_indent: buffer
9669 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9670 .len,
9671 });
9672 }
9673 }
9674 }
9675
9676 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9677 text,
9678 clipboard_selections,
9679 ));
9680 }
9681
9682 pub fn do_paste(
9683 &mut self,
9684 text: &String,
9685 clipboard_selections: Option<Vec<ClipboardSelection>>,
9686 handle_entire_lines: bool,
9687 window: &mut Window,
9688 cx: &mut Context<Self>,
9689 ) {
9690 if self.read_only(cx) {
9691 return;
9692 }
9693
9694 let clipboard_text = Cow::Borrowed(text);
9695
9696 self.transact(window, cx, |this, window, cx| {
9697 if let Some(mut clipboard_selections) = clipboard_selections {
9698 let old_selections = this.selections.all::<usize>(cx);
9699 let all_selections_were_entire_line =
9700 clipboard_selections.iter().all(|s| s.is_entire_line);
9701 let first_selection_indent_column =
9702 clipboard_selections.first().map(|s| s.first_line_indent);
9703 if clipboard_selections.len() != old_selections.len() {
9704 clipboard_selections.drain(..);
9705 }
9706 let cursor_offset = this.selections.last::<usize>(cx).head();
9707 let mut auto_indent_on_paste = true;
9708
9709 this.buffer.update(cx, |buffer, cx| {
9710 let snapshot = buffer.read(cx);
9711 auto_indent_on_paste = snapshot
9712 .language_settings_at(cursor_offset, cx)
9713 .auto_indent_on_paste;
9714
9715 let mut start_offset = 0;
9716 let mut edits = Vec::new();
9717 let mut original_indent_columns = Vec::new();
9718 for (ix, selection) in old_selections.iter().enumerate() {
9719 let to_insert;
9720 let entire_line;
9721 let original_indent_column;
9722 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9723 let end_offset = start_offset + clipboard_selection.len;
9724 to_insert = &clipboard_text[start_offset..end_offset];
9725 entire_line = clipboard_selection.is_entire_line;
9726 start_offset = end_offset + 1;
9727 original_indent_column = Some(clipboard_selection.first_line_indent);
9728 } else {
9729 to_insert = clipboard_text.as_str();
9730 entire_line = all_selections_were_entire_line;
9731 original_indent_column = first_selection_indent_column
9732 }
9733
9734 // If the corresponding selection was empty when this slice of the
9735 // clipboard text was written, then the entire line containing the
9736 // selection was copied. If this selection is also currently empty,
9737 // then paste the line before the current line of the buffer.
9738 let range = if selection.is_empty() && handle_entire_lines && entire_line {
9739 let column = selection.start.to_point(&snapshot).column as usize;
9740 let line_start = selection.start - column;
9741 line_start..line_start
9742 } else {
9743 selection.range()
9744 };
9745
9746 edits.push((range, to_insert));
9747 original_indent_columns.push(original_indent_column);
9748 }
9749 drop(snapshot);
9750
9751 buffer.edit(
9752 edits,
9753 if auto_indent_on_paste {
9754 Some(AutoindentMode::Block {
9755 original_indent_columns,
9756 })
9757 } else {
9758 None
9759 },
9760 cx,
9761 );
9762 });
9763
9764 let selections = this.selections.all::<usize>(cx);
9765 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9766 s.select(selections)
9767 });
9768 } else {
9769 this.insert(&clipboard_text, window, cx);
9770 }
9771 });
9772 }
9773
9774 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9775 if let Some(item) = cx.read_from_clipboard() {
9776 let entries = item.entries();
9777
9778 match entries.first() {
9779 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9780 // of all the pasted entries.
9781 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9782 .do_paste(
9783 clipboard_string.text(),
9784 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9785 true,
9786 window,
9787 cx,
9788 ),
9789 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9790 }
9791 }
9792 }
9793
9794 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9795 if self.read_only(cx) {
9796 return;
9797 }
9798
9799 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9800 if let Some((selections, _)) =
9801 self.selection_history.transaction(transaction_id).cloned()
9802 {
9803 self.change_selections(None, window, cx, |s| {
9804 s.select_anchors(selections.to_vec());
9805 });
9806 } else {
9807 log::error!(
9808 "No entry in selection_history found for undo. \
9809 This may correspond to a bug where undo does not update the selection. \
9810 If this is occurring, please add details to \
9811 https://github.com/zed-industries/zed/issues/22692"
9812 );
9813 }
9814 self.request_autoscroll(Autoscroll::fit(), cx);
9815 self.unmark_text(window, cx);
9816 self.refresh_inline_completion(true, false, window, cx);
9817 cx.emit(EditorEvent::Edited { transaction_id });
9818 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9819 }
9820 }
9821
9822 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9823 if self.read_only(cx) {
9824 return;
9825 }
9826
9827 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9828 if let Some((_, Some(selections))) =
9829 self.selection_history.transaction(transaction_id).cloned()
9830 {
9831 self.change_selections(None, window, cx, |s| {
9832 s.select_anchors(selections.to_vec());
9833 });
9834 } else {
9835 log::error!(
9836 "No entry in selection_history found for redo. \
9837 This may correspond to a bug where undo does not update the selection. \
9838 If this is occurring, please add details to \
9839 https://github.com/zed-industries/zed/issues/22692"
9840 );
9841 }
9842 self.request_autoscroll(Autoscroll::fit(), cx);
9843 self.unmark_text(window, cx);
9844 self.refresh_inline_completion(true, false, window, cx);
9845 cx.emit(EditorEvent::Edited { transaction_id });
9846 }
9847 }
9848
9849 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9850 self.buffer
9851 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9852 }
9853
9854 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9855 self.buffer
9856 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9857 }
9858
9859 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9860 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9861 let line_mode = s.line_mode;
9862 s.move_with(|map, selection| {
9863 let cursor = if selection.is_empty() && !line_mode {
9864 movement::left(map, selection.start)
9865 } else {
9866 selection.start
9867 };
9868 selection.collapse_to(cursor, SelectionGoal::None);
9869 });
9870 })
9871 }
9872
9873 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9874 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9875 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9876 })
9877 }
9878
9879 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9881 let line_mode = s.line_mode;
9882 s.move_with(|map, selection| {
9883 let cursor = if selection.is_empty() && !line_mode {
9884 movement::right(map, selection.end)
9885 } else {
9886 selection.end
9887 };
9888 selection.collapse_to(cursor, SelectionGoal::None)
9889 });
9890 })
9891 }
9892
9893 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9894 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9895 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9896 })
9897 }
9898
9899 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9900 if self.take_rename(true, window, cx).is_some() {
9901 return;
9902 }
9903
9904 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9905 cx.propagate();
9906 return;
9907 }
9908
9909 let text_layout_details = &self.text_layout_details(window);
9910 let selection_count = self.selections.count();
9911 let first_selection = self.selections.first_anchor();
9912
9913 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9914 let line_mode = s.line_mode;
9915 s.move_with(|map, selection| {
9916 if !selection.is_empty() && !line_mode {
9917 selection.goal = SelectionGoal::None;
9918 }
9919 let (cursor, goal) = movement::up(
9920 map,
9921 selection.start,
9922 selection.goal,
9923 false,
9924 text_layout_details,
9925 );
9926 selection.collapse_to(cursor, goal);
9927 });
9928 });
9929
9930 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9931 {
9932 cx.propagate();
9933 }
9934 }
9935
9936 pub fn move_up_by_lines(
9937 &mut self,
9938 action: &MoveUpByLines,
9939 window: &mut Window,
9940 cx: &mut Context<Self>,
9941 ) {
9942 if self.take_rename(true, window, cx).is_some() {
9943 return;
9944 }
9945
9946 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9947 cx.propagate();
9948 return;
9949 }
9950
9951 let text_layout_details = &self.text_layout_details(window);
9952
9953 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9954 let line_mode = s.line_mode;
9955 s.move_with(|map, selection| {
9956 if !selection.is_empty() && !line_mode {
9957 selection.goal = SelectionGoal::None;
9958 }
9959 let (cursor, goal) = movement::up_by_rows(
9960 map,
9961 selection.start,
9962 action.lines,
9963 selection.goal,
9964 false,
9965 text_layout_details,
9966 );
9967 selection.collapse_to(cursor, goal);
9968 });
9969 })
9970 }
9971
9972 pub fn move_down_by_lines(
9973 &mut self,
9974 action: &MoveDownByLines,
9975 window: &mut Window,
9976 cx: &mut Context<Self>,
9977 ) {
9978 if self.take_rename(true, window, cx).is_some() {
9979 return;
9980 }
9981
9982 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9983 cx.propagate();
9984 return;
9985 }
9986
9987 let text_layout_details = &self.text_layout_details(window);
9988
9989 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9990 let line_mode = s.line_mode;
9991 s.move_with(|map, selection| {
9992 if !selection.is_empty() && !line_mode {
9993 selection.goal = SelectionGoal::None;
9994 }
9995 let (cursor, goal) = movement::down_by_rows(
9996 map,
9997 selection.start,
9998 action.lines,
9999 selection.goal,
10000 false,
10001 text_layout_details,
10002 );
10003 selection.collapse_to(cursor, goal);
10004 });
10005 })
10006 }
10007
10008 pub fn select_down_by_lines(
10009 &mut self,
10010 action: &SelectDownByLines,
10011 window: &mut Window,
10012 cx: &mut Context<Self>,
10013 ) {
10014 let text_layout_details = &self.text_layout_details(window);
10015 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10016 s.move_heads_with(|map, head, goal| {
10017 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10018 })
10019 })
10020 }
10021
10022 pub fn select_up_by_lines(
10023 &mut self,
10024 action: &SelectUpByLines,
10025 window: &mut Window,
10026 cx: &mut Context<Self>,
10027 ) {
10028 let text_layout_details = &self.text_layout_details(window);
10029 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10030 s.move_heads_with(|map, head, goal| {
10031 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10032 })
10033 })
10034 }
10035
10036 pub fn select_page_up(
10037 &mut self,
10038 _: &SelectPageUp,
10039 window: &mut Window,
10040 cx: &mut Context<Self>,
10041 ) {
10042 let Some(row_count) = self.visible_row_count() else {
10043 return;
10044 };
10045
10046 let text_layout_details = &self.text_layout_details(window);
10047
10048 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10049 s.move_heads_with(|map, head, goal| {
10050 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10051 })
10052 })
10053 }
10054
10055 pub fn move_page_up(
10056 &mut self,
10057 action: &MovePageUp,
10058 window: &mut Window,
10059 cx: &mut Context<Self>,
10060 ) {
10061 if self.take_rename(true, window, cx).is_some() {
10062 return;
10063 }
10064
10065 if self
10066 .context_menu
10067 .borrow_mut()
10068 .as_mut()
10069 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10070 .unwrap_or(false)
10071 {
10072 return;
10073 }
10074
10075 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10076 cx.propagate();
10077 return;
10078 }
10079
10080 let Some(row_count) = self.visible_row_count() else {
10081 return;
10082 };
10083
10084 let autoscroll = if action.center_cursor {
10085 Autoscroll::center()
10086 } else {
10087 Autoscroll::fit()
10088 };
10089
10090 let text_layout_details = &self.text_layout_details(window);
10091
10092 self.change_selections(Some(autoscroll), window, cx, |s| {
10093 let line_mode = s.line_mode;
10094 s.move_with(|map, selection| {
10095 if !selection.is_empty() && !line_mode {
10096 selection.goal = SelectionGoal::None;
10097 }
10098 let (cursor, goal) = movement::up_by_rows(
10099 map,
10100 selection.end,
10101 row_count,
10102 selection.goal,
10103 false,
10104 text_layout_details,
10105 );
10106 selection.collapse_to(cursor, goal);
10107 });
10108 });
10109 }
10110
10111 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10112 let text_layout_details = &self.text_layout_details(window);
10113 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10114 s.move_heads_with(|map, head, goal| {
10115 movement::up(map, head, goal, false, text_layout_details)
10116 })
10117 })
10118 }
10119
10120 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10121 self.take_rename(true, window, cx);
10122
10123 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10124 cx.propagate();
10125 return;
10126 }
10127
10128 let text_layout_details = &self.text_layout_details(window);
10129 let selection_count = self.selections.count();
10130 let first_selection = self.selections.first_anchor();
10131
10132 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10133 let line_mode = s.line_mode;
10134 s.move_with(|map, selection| {
10135 if !selection.is_empty() && !line_mode {
10136 selection.goal = SelectionGoal::None;
10137 }
10138 let (cursor, goal) = movement::down(
10139 map,
10140 selection.end,
10141 selection.goal,
10142 false,
10143 text_layout_details,
10144 );
10145 selection.collapse_to(cursor, goal);
10146 });
10147 });
10148
10149 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10150 {
10151 cx.propagate();
10152 }
10153 }
10154
10155 pub fn select_page_down(
10156 &mut self,
10157 _: &SelectPageDown,
10158 window: &mut Window,
10159 cx: &mut Context<Self>,
10160 ) {
10161 let Some(row_count) = self.visible_row_count() else {
10162 return;
10163 };
10164
10165 let text_layout_details = &self.text_layout_details(window);
10166
10167 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10168 s.move_heads_with(|map, head, goal| {
10169 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10170 })
10171 })
10172 }
10173
10174 pub fn move_page_down(
10175 &mut self,
10176 action: &MovePageDown,
10177 window: &mut Window,
10178 cx: &mut Context<Self>,
10179 ) {
10180 if self.take_rename(true, window, cx).is_some() {
10181 return;
10182 }
10183
10184 if self
10185 .context_menu
10186 .borrow_mut()
10187 .as_mut()
10188 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10189 .unwrap_or(false)
10190 {
10191 return;
10192 }
10193
10194 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10195 cx.propagate();
10196 return;
10197 }
10198
10199 let Some(row_count) = self.visible_row_count() else {
10200 return;
10201 };
10202
10203 let autoscroll = if action.center_cursor {
10204 Autoscroll::center()
10205 } else {
10206 Autoscroll::fit()
10207 };
10208
10209 let text_layout_details = &self.text_layout_details(window);
10210 self.change_selections(Some(autoscroll), window, cx, |s| {
10211 let line_mode = s.line_mode;
10212 s.move_with(|map, selection| {
10213 if !selection.is_empty() && !line_mode {
10214 selection.goal = SelectionGoal::None;
10215 }
10216 let (cursor, goal) = movement::down_by_rows(
10217 map,
10218 selection.end,
10219 row_count,
10220 selection.goal,
10221 false,
10222 text_layout_details,
10223 );
10224 selection.collapse_to(cursor, goal);
10225 });
10226 });
10227 }
10228
10229 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10230 let text_layout_details = &self.text_layout_details(window);
10231 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10232 s.move_heads_with(|map, head, goal| {
10233 movement::down(map, head, goal, false, text_layout_details)
10234 })
10235 });
10236 }
10237
10238 pub fn context_menu_first(
10239 &mut self,
10240 _: &ContextMenuFirst,
10241 _window: &mut Window,
10242 cx: &mut Context<Self>,
10243 ) {
10244 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10245 context_menu.select_first(self.completion_provider.as_deref(), cx);
10246 }
10247 }
10248
10249 pub fn context_menu_prev(
10250 &mut self,
10251 _: &ContextMenuPrevious,
10252 _window: &mut Window,
10253 cx: &mut Context<Self>,
10254 ) {
10255 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10256 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10257 }
10258 }
10259
10260 pub fn context_menu_next(
10261 &mut self,
10262 _: &ContextMenuNext,
10263 _window: &mut Window,
10264 cx: &mut Context<Self>,
10265 ) {
10266 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10267 context_menu.select_next(self.completion_provider.as_deref(), cx);
10268 }
10269 }
10270
10271 pub fn context_menu_last(
10272 &mut self,
10273 _: &ContextMenuLast,
10274 _window: &mut Window,
10275 cx: &mut Context<Self>,
10276 ) {
10277 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10278 context_menu.select_last(self.completion_provider.as_deref(), cx);
10279 }
10280 }
10281
10282 pub fn move_to_previous_word_start(
10283 &mut self,
10284 _: &MoveToPreviousWordStart,
10285 window: &mut Window,
10286 cx: &mut Context<Self>,
10287 ) {
10288 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10289 s.move_cursors_with(|map, head, _| {
10290 (
10291 movement::previous_word_start(map, head),
10292 SelectionGoal::None,
10293 )
10294 });
10295 })
10296 }
10297
10298 pub fn move_to_previous_subword_start(
10299 &mut self,
10300 _: &MoveToPreviousSubwordStart,
10301 window: &mut Window,
10302 cx: &mut Context<Self>,
10303 ) {
10304 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10305 s.move_cursors_with(|map, head, _| {
10306 (
10307 movement::previous_subword_start(map, head),
10308 SelectionGoal::None,
10309 )
10310 });
10311 })
10312 }
10313
10314 pub fn select_to_previous_word_start(
10315 &mut self,
10316 _: &SelectToPreviousWordStart,
10317 window: &mut Window,
10318 cx: &mut Context<Self>,
10319 ) {
10320 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10321 s.move_heads_with(|map, head, _| {
10322 (
10323 movement::previous_word_start(map, head),
10324 SelectionGoal::None,
10325 )
10326 });
10327 })
10328 }
10329
10330 pub fn select_to_previous_subword_start(
10331 &mut self,
10332 _: &SelectToPreviousSubwordStart,
10333 window: &mut Window,
10334 cx: &mut Context<Self>,
10335 ) {
10336 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10337 s.move_heads_with(|map, head, _| {
10338 (
10339 movement::previous_subword_start(map, head),
10340 SelectionGoal::None,
10341 )
10342 });
10343 })
10344 }
10345
10346 pub fn delete_to_previous_word_start(
10347 &mut self,
10348 action: &DeleteToPreviousWordStart,
10349 window: &mut Window,
10350 cx: &mut Context<Self>,
10351 ) {
10352 self.transact(window, cx, |this, window, cx| {
10353 this.select_autoclose_pair(window, cx);
10354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10355 let line_mode = s.line_mode;
10356 s.move_with(|map, selection| {
10357 if selection.is_empty() && !line_mode {
10358 let cursor = if action.ignore_newlines {
10359 movement::previous_word_start(map, selection.head())
10360 } else {
10361 movement::previous_word_start_or_newline(map, selection.head())
10362 };
10363 selection.set_head(cursor, SelectionGoal::None);
10364 }
10365 });
10366 });
10367 this.insert("", window, cx);
10368 });
10369 }
10370
10371 pub fn delete_to_previous_subword_start(
10372 &mut self,
10373 _: &DeleteToPreviousSubwordStart,
10374 window: &mut Window,
10375 cx: &mut Context<Self>,
10376 ) {
10377 self.transact(window, cx, |this, window, cx| {
10378 this.select_autoclose_pair(window, cx);
10379 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10380 let line_mode = s.line_mode;
10381 s.move_with(|map, selection| {
10382 if selection.is_empty() && !line_mode {
10383 let cursor = movement::previous_subword_start(map, selection.head());
10384 selection.set_head(cursor, SelectionGoal::None);
10385 }
10386 });
10387 });
10388 this.insert("", window, cx);
10389 });
10390 }
10391
10392 pub fn move_to_next_word_end(
10393 &mut self,
10394 _: &MoveToNextWordEnd,
10395 window: &mut Window,
10396 cx: &mut Context<Self>,
10397 ) {
10398 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10399 s.move_cursors_with(|map, head, _| {
10400 (movement::next_word_end(map, head), SelectionGoal::None)
10401 });
10402 })
10403 }
10404
10405 pub fn move_to_next_subword_end(
10406 &mut self,
10407 _: &MoveToNextSubwordEnd,
10408 window: &mut Window,
10409 cx: &mut Context<Self>,
10410 ) {
10411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10412 s.move_cursors_with(|map, head, _| {
10413 (movement::next_subword_end(map, head), SelectionGoal::None)
10414 });
10415 })
10416 }
10417
10418 pub fn select_to_next_word_end(
10419 &mut self,
10420 _: &SelectToNextWordEnd,
10421 window: &mut Window,
10422 cx: &mut Context<Self>,
10423 ) {
10424 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10425 s.move_heads_with(|map, head, _| {
10426 (movement::next_word_end(map, head), SelectionGoal::None)
10427 });
10428 })
10429 }
10430
10431 pub fn select_to_next_subword_end(
10432 &mut self,
10433 _: &SelectToNextSubwordEnd,
10434 window: &mut Window,
10435 cx: &mut Context<Self>,
10436 ) {
10437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10438 s.move_heads_with(|map, head, _| {
10439 (movement::next_subword_end(map, head), SelectionGoal::None)
10440 });
10441 })
10442 }
10443
10444 pub fn delete_to_next_word_end(
10445 &mut self,
10446 action: &DeleteToNextWordEnd,
10447 window: &mut Window,
10448 cx: &mut Context<Self>,
10449 ) {
10450 self.transact(window, cx, |this, window, cx| {
10451 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10452 let line_mode = s.line_mode;
10453 s.move_with(|map, selection| {
10454 if selection.is_empty() && !line_mode {
10455 let cursor = if action.ignore_newlines {
10456 movement::next_word_end(map, selection.head())
10457 } else {
10458 movement::next_word_end_or_newline(map, selection.head())
10459 };
10460 selection.set_head(cursor, SelectionGoal::None);
10461 }
10462 });
10463 });
10464 this.insert("", window, cx);
10465 });
10466 }
10467
10468 pub fn delete_to_next_subword_end(
10469 &mut self,
10470 _: &DeleteToNextSubwordEnd,
10471 window: &mut Window,
10472 cx: &mut Context<Self>,
10473 ) {
10474 self.transact(window, cx, |this, window, cx| {
10475 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10476 s.move_with(|map, selection| {
10477 if selection.is_empty() {
10478 let cursor = movement::next_subword_end(map, selection.head());
10479 selection.set_head(cursor, SelectionGoal::None);
10480 }
10481 });
10482 });
10483 this.insert("", window, cx);
10484 });
10485 }
10486
10487 pub fn move_to_beginning_of_line(
10488 &mut self,
10489 action: &MoveToBeginningOfLine,
10490 window: &mut Window,
10491 cx: &mut Context<Self>,
10492 ) {
10493 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10494 s.move_cursors_with(|map, head, _| {
10495 (
10496 movement::indented_line_beginning(
10497 map,
10498 head,
10499 action.stop_at_soft_wraps,
10500 action.stop_at_indent,
10501 ),
10502 SelectionGoal::None,
10503 )
10504 });
10505 })
10506 }
10507
10508 pub fn select_to_beginning_of_line(
10509 &mut self,
10510 action: &SelectToBeginningOfLine,
10511 window: &mut Window,
10512 cx: &mut Context<Self>,
10513 ) {
10514 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10515 s.move_heads_with(|map, head, _| {
10516 (
10517 movement::indented_line_beginning(
10518 map,
10519 head,
10520 action.stop_at_soft_wraps,
10521 action.stop_at_indent,
10522 ),
10523 SelectionGoal::None,
10524 )
10525 });
10526 });
10527 }
10528
10529 pub fn delete_to_beginning_of_line(
10530 &mut self,
10531 action: &DeleteToBeginningOfLine,
10532 window: &mut Window,
10533 cx: &mut Context<Self>,
10534 ) {
10535 self.transact(window, cx, |this, window, cx| {
10536 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10537 s.move_with(|_, selection| {
10538 selection.reversed = true;
10539 });
10540 });
10541
10542 this.select_to_beginning_of_line(
10543 &SelectToBeginningOfLine {
10544 stop_at_soft_wraps: false,
10545 stop_at_indent: action.stop_at_indent,
10546 },
10547 window,
10548 cx,
10549 );
10550 this.backspace(&Backspace, window, cx);
10551 });
10552 }
10553
10554 pub fn move_to_end_of_line(
10555 &mut self,
10556 action: &MoveToEndOfLine,
10557 window: &mut Window,
10558 cx: &mut Context<Self>,
10559 ) {
10560 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10561 s.move_cursors_with(|map, head, _| {
10562 (
10563 movement::line_end(map, head, action.stop_at_soft_wraps),
10564 SelectionGoal::None,
10565 )
10566 });
10567 })
10568 }
10569
10570 pub fn select_to_end_of_line(
10571 &mut self,
10572 action: &SelectToEndOfLine,
10573 window: &mut Window,
10574 cx: &mut Context<Self>,
10575 ) {
10576 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10577 s.move_heads_with(|map, head, _| {
10578 (
10579 movement::line_end(map, head, action.stop_at_soft_wraps),
10580 SelectionGoal::None,
10581 )
10582 });
10583 })
10584 }
10585
10586 pub fn delete_to_end_of_line(
10587 &mut self,
10588 _: &DeleteToEndOfLine,
10589 window: &mut Window,
10590 cx: &mut Context<Self>,
10591 ) {
10592 self.transact(window, cx, |this, window, cx| {
10593 this.select_to_end_of_line(
10594 &SelectToEndOfLine {
10595 stop_at_soft_wraps: false,
10596 },
10597 window,
10598 cx,
10599 );
10600 this.delete(&Delete, window, cx);
10601 });
10602 }
10603
10604 pub fn cut_to_end_of_line(
10605 &mut self,
10606 _: &CutToEndOfLine,
10607 window: &mut Window,
10608 cx: &mut Context<Self>,
10609 ) {
10610 self.transact(window, cx, |this, window, cx| {
10611 this.select_to_end_of_line(
10612 &SelectToEndOfLine {
10613 stop_at_soft_wraps: false,
10614 },
10615 window,
10616 cx,
10617 );
10618 this.cut(&Cut, window, cx);
10619 });
10620 }
10621
10622 pub fn move_to_start_of_paragraph(
10623 &mut self,
10624 _: &MoveToStartOfParagraph,
10625 window: &mut Window,
10626 cx: &mut Context<Self>,
10627 ) {
10628 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10629 cx.propagate();
10630 return;
10631 }
10632
10633 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10634 s.move_with(|map, selection| {
10635 selection.collapse_to(
10636 movement::start_of_paragraph(map, selection.head(), 1),
10637 SelectionGoal::None,
10638 )
10639 });
10640 })
10641 }
10642
10643 pub fn move_to_end_of_paragraph(
10644 &mut self,
10645 _: &MoveToEndOfParagraph,
10646 window: &mut Window,
10647 cx: &mut Context<Self>,
10648 ) {
10649 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10650 cx.propagate();
10651 return;
10652 }
10653
10654 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10655 s.move_with(|map, selection| {
10656 selection.collapse_to(
10657 movement::end_of_paragraph(map, selection.head(), 1),
10658 SelectionGoal::None,
10659 )
10660 });
10661 })
10662 }
10663
10664 pub fn select_to_start_of_paragraph(
10665 &mut self,
10666 _: &SelectToStartOfParagraph,
10667 window: &mut Window,
10668 cx: &mut Context<Self>,
10669 ) {
10670 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10671 cx.propagate();
10672 return;
10673 }
10674
10675 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10676 s.move_heads_with(|map, head, _| {
10677 (
10678 movement::start_of_paragraph(map, head, 1),
10679 SelectionGoal::None,
10680 )
10681 });
10682 })
10683 }
10684
10685 pub fn select_to_end_of_paragraph(
10686 &mut self,
10687 _: &SelectToEndOfParagraph,
10688 window: &mut Window,
10689 cx: &mut Context<Self>,
10690 ) {
10691 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10692 cx.propagate();
10693 return;
10694 }
10695
10696 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10697 s.move_heads_with(|map, head, _| {
10698 (
10699 movement::end_of_paragraph(map, head, 1),
10700 SelectionGoal::None,
10701 )
10702 });
10703 })
10704 }
10705
10706 pub fn move_to_start_of_excerpt(
10707 &mut self,
10708 _: &MoveToStartOfExcerpt,
10709 window: &mut Window,
10710 cx: &mut Context<Self>,
10711 ) {
10712 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10713 cx.propagate();
10714 return;
10715 }
10716
10717 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10718 s.move_with(|map, selection| {
10719 selection.collapse_to(
10720 movement::start_of_excerpt(
10721 map,
10722 selection.head(),
10723 workspace::searchable::Direction::Prev,
10724 ),
10725 SelectionGoal::None,
10726 )
10727 });
10728 })
10729 }
10730
10731 pub fn move_to_start_of_next_excerpt(
10732 &mut self,
10733 _: &MoveToStartOfNextExcerpt,
10734 window: &mut Window,
10735 cx: &mut Context<Self>,
10736 ) {
10737 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10738 cx.propagate();
10739 return;
10740 }
10741
10742 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10743 s.move_with(|map, selection| {
10744 selection.collapse_to(
10745 movement::start_of_excerpt(
10746 map,
10747 selection.head(),
10748 workspace::searchable::Direction::Next,
10749 ),
10750 SelectionGoal::None,
10751 )
10752 });
10753 })
10754 }
10755
10756 pub fn move_to_end_of_excerpt(
10757 &mut self,
10758 _: &MoveToEndOfExcerpt,
10759 window: &mut Window,
10760 cx: &mut Context<Self>,
10761 ) {
10762 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10763 cx.propagate();
10764 return;
10765 }
10766
10767 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10768 s.move_with(|map, selection| {
10769 selection.collapse_to(
10770 movement::end_of_excerpt(
10771 map,
10772 selection.head(),
10773 workspace::searchable::Direction::Next,
10774 ),
10775 SelectionGoal::None,
10776 )
10777 });
10778 })
10779 }
10780
10781 pub fn move_to_end_of_previous_excerpt(
10782 &mut self,
10783 _: &MoveToEndOfPreviousExcerpt,
10784 window: &mut Window,
10785 cx: &mut Context<Self>,
10786 ) {
10787 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10788 cx.propagate();
10789 return;
10790 }
10791
10792 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10793 s.move_with(|map, selection| {
10794 selection.collapse_to(
10795 movement::end_of_excerpt(
10796 map,
10797 selection.head(),
10798 workspace::searchable::Direction::Prev,
10799 ),
10800 SelectionGoal::None,
10801 )
10802 });
10803 })
10804 }
10805
10806 pub fn select_to_start_of_excerpt(
10807 &mut self,
10808 _: &SelectToStartOfExcerpt,
10809 window: &mut Window,
10810 cx: &mut Context<Self>,
10811 ) {
10812 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10813 cx.propagate();
10814 return;
10815 }
10816
10817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10818 s.move_heads_with(|map, head, _| {
10819 (
10820 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10821 SelectionGoal::None,
10822 )
10823 });
10824 })
10825 }
10826
10827 pub fn select_to_start_of_next_excerpt(
10828 &mut self,
10829 _: &SelectToStartOfNextExcerpt,
10830 window: &mut Window,
10831 cx: &mut Context<Self>,
10832 ) {
10833 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10834 cx.propagate();
10835 return;
10836 }
10837
10838 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10839 s.move_heads_with(|map, head, _| {
10840 (
10841 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10842 SelectionGoal::None,
10843 )
10844 });
10845 })
10846 }
10847
10848 pub fn select_to_end_of_excerpt(
10849 &mut self,
10850 _: &SelectToEndOfExcerpt,
10851 window: &mut Window,
10852 cx: &mut Context<Self>,
10853 ) {
10854 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10855 cx.propagate();
10856 return;
10857 }
10858
10859 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10860 s.move_heads_with(|map, head, _| {
10861 (
10862 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10863 SelectionGoal::None,
10864 )
10865 });
10866 })
10867 }
10868
10869 pub fn select_to_end_of_previous_excerpt(
10870 &mut self,
10871 _: &SelectToEndOfPreviousExcerpt,
10872 window: &mut Window,
10873 cx: &mut Context<Self>,
10874 ) {
10875 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10876 cx.propagate();
10877 return;
10878 }
10879
10880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10881 s.move_heads_with(|map, head, _| {
10882 (
10883 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10884 SelectionGoal::None,
10885 )
10886 });
10887 })
10888 }
10889
10890 pub fn move_to_beginning(
10891 &mut self,
10892 _: &MoveToBeginning,
10893 window: &mut Window,
10894 cx: &mut Context<Self>,
10895 ) {
10896 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10897 cx.propagate();
10898 return;
10899 }
10900
10901 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10902 s.select_ranges(vec![0..0]);
10903 });
10904 }
10905
10906 pub fn select_to_beginning(
10907 &mut self,
10908 _: &SelectToBeginning,
10909 window: &mut Window,
10910 cx: &mut Context<Self>,
10911 ) {
10912 let mut selection = self.selections.last::<Point>(cx);
10913 selection.set_head(Point::zero(), SelectionGoal::None);
10914
10915 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10916 s.select(vec![selection]);
10917 });
10918 }
10919
10920 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10921 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10922 cx.propagate();
10923 return;
10924 }
10925
10926 let cursor = self.buffer.read(cx).read(cx).len();
10927 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10928 s.select_ranges(vec![cursor..cursor])
10929 });
10930 }
10931
10932 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10933 self.nav_history = nav_history;
10934 }
10935
10936 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10937 self.nav_history.as_ref()
10938 }
10939
10940 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
10941 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
10942 }
10943
10944 fn push_to_nav_history(
10945 &mut self,
10946 cursor_anchor: Anchor,
10947 new_position: Option<Point>,
10948 is_deactivate: bool,
10949 cx: &mut Context<Self>,
10950 ) {
10951 if let Some(nav_history) = self.nav_history.as_mut() {
10952 let buffer = self.buffer.read(cx).read(cx);
10953 let cursor_position = cursor_anchor.to_point(&buffer);
10954 let scroll_state = self.scroll_manager.anchor();
10955 let scroll_top_row = scroll_state.top_row(&buffer);
10956 drop(buffer);
10957
10958 if let Some(new_position) = new_position {
10959 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10960 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10961 return;
10962 }
10963 }
10964
10965 nav_history.push(
10966 Some(NavigationData {
10967 cursor_anchor,
10968 cursor_position,
10969 scroll_anchor: scroll_state,
10970 scroll_top_row,
10971 }),
10972 cx,
10973 );
10974 cx.emit(EditorEvent::PushedToNavHistory {
10975 anchor: cursor_anchor,
10976 is_deactivate,
10977 })
10978 }
10979 }
10980
10981 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10982 let buffer = self.buffer.read(cx).snapshot(cx);
10983 let mut selection = self.selections.first::<usize>(cx);
10984 selection.set_head(buffer.len(), SelectionGoal::None);
10985 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10986 s.select(vec![selection]);
10987 });
10988 }
10989
10990 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10991 let end = self.buffer.read(cx).read(cx).len();
10992 self.change_selections(None, window, cx, |s| {
10993 s.select_ranges(vec![0..end]);
10994 });
10995 }
10996
10997 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10999 let mut selections = self.selections.all::<Point>(cx);
11000 let max_point = display_map.buffer_snapshot.max_point();
11001 for selection in &mut selections {
11002 let rows = selection.spanned_rows(true, &display_map);
11003 selection.start = Point::new(rows.start.0, 0);
11004 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11005 selection.reversed = false;
11006 }
11007 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11008 s.select(selections);
11009 });
11010 }
11011
11012 pub fn split_selection_into_lines(
11013 &mut self,
11014 _: &SplitSelectionIntoLines,
11015 window: &mut Window,
11016 cx: &mut Context<Self>,
11017 ) {
11018 let selections = self
11019 .selections
11020 .all::<Point>(cx)
11021 .into_iter()
11022 .map(|selection| selection.start..selection.end)
11023 .collect::<Vec<_>>();
11024 self.unfold_ranges(&selections, true, true, cx);
11025
11026 let mut new_selection_ranges = Vec::new();
11027 {
11028 let buffer = self.buffer.read(cx).read(cx);
11029 for selection in selections {
11030 for row in selection.start.row..selection.end.row {
11031 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11032 new_selection_ranges.push(cursor..cursor);
11033 }
11034
11035 let is_multiline_selection = selection.start.row != selection.end.row;
11036 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11037 // so this action feels more ergonomic when paired with other selection operations
11038 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11039 if !should_skip_last {
11040 new_selection_ranges.push(selection.end..selection.end);
11041 }
11042 }
11043 }
11044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11045 s.select_ranges(new_selection_ranges);
11046 });
11047 }
11048
11049 pub fn add_selection_above(
11050 &mut self,
11051 _: &AddSelectionAbove,
11052 window: &mut Window,
11053 cx: &mut Context<Self>,
11054 ) {
11055 self.add_selection(true, window, cx);
11056 }
11057
11058 pub fn add_selection_below(
11059 &mut self,
11060 _: &AddSelectionBelow,
11061 window: &mut Window,
11062 cx: &mut Context<Self>,
11063 ) {
11064 self.add_selection(false, window, cx);
11065 }
11066
11067 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11069 let mut selections = self.selections.all::<Point>(cx);
11070 let text_layout_details = self.text_layout_details(window);
11071 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11072 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11073 let range = oldest_selection.display_range(&display_map).sorted();
11074
11075 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11076 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11077 let positions = start_x.min(end_x)..start_x.max(end_x);
11078
11079 selections.clear();
11080 let mut stack = Vec::new();
11081 for row in range.start.row().0..=range.end.row().0 {
11082 if let Some(selection) = self.selections.build_columnar_selection(
11083 &display_map,
11084 DisplayRow(row),
11085 &positions,
11086 oldest_selection.reversed,
11087 &text_layout_details,
11088 ) {
11089 stack.push(selection.id);
11090 selections.push(selection);
11091 }
11092 }
11093
11094 if above {
11095 stack.reverse();
11096 }
11097
11098 AddSelectionsState { above, stack }
11099 });
11100
11101 let last_added_selection = *state.stack.last().unwrap();
11102 let mut new_selections = Vec::new();
11103 if above == state.above {
11104 let end_row = if above {
11105 DisplayRow(0)
11106 } else {
11107 display_map.max_point().row()
11108 };
11109
11110 'outer: for selection in selections {
11111 if selection.id == last_added_selection {
11112 let range = selection.display_range(&display_map).sorted();
11113 debug_assert_eq!(range.start.row(), range.end.row());
11114 let mut row = range.start.row();
11115 let positions =
11116 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11117 px(start)..px(end)
11118 } else {
11119 let start_x =
11120 display_map.x_for_display_point(range.start, &text_layout_details);
11121 let end_x =
11122 display_map.x_for_display_point(range.end, &text_layout_details);
11123 start_x.min(end_x)..start_x.max(end_x)
11124 };
11125
11126 while row != end_row {
11127 if above {
11128 row.0 -= 1;
11129 } else {
11130 row.0 += 1;
11131 }
11132
11133 if let Some(new_selection) = self.selections.build_columnar_selection(
11134 &display_map,
11135 row,
11136 &positions,
11137 selection.reversed,
11138 &text_layout_details,
11139 ) {
11140 state.stack.push(new_selection.id);
11141 if above {
11142 new_selections.push(new_selection);
11143 new_selections.push(selection);
11144 } else {
11145 new_selections.push(selection);
11146 new_selections.push(new_selection);
11147 }
11148
11149 continue 'outer;
11150 }
11151 }
11152 }
11153
11154 new_selections.push(selection);
11155 }
11156 } else {
11157 new_selections = selections;
11158 new_selections.retain(|s| s.id != last_added_selection);
11159 state.stack.pop();
11160 }
11161
11162 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11163 s.select(new_selections);
11164 });
11165 if state.stack.len() > 1 {
11166 self.add_selections_state = Some(state);
11167 }
11168 }
11169
11170 pub fn select_next_match_internal(
11171 &mut self,
11172 display_map: &DisplaySnapshot,
11173 replace_newest: bool,
11174 autoscroll: Option<Autoscroll>,
11175 window: &mut Window,
11176 cx: &mut Context<Self>,
11177 ) -> Result<()> {
11178 fn select_next_match_ranges(
11179 this: &mut Editor,
11180 range: Range<usize>,
11181 replace_newest: bool,
11182 auto_scroll: Option<Autoscroll>,
11183 window: &mut Window,
11184 cx: &mut Context<Editor>,
11185 ) {
11186 this.unfold_ranges(&[range.clone()], false, true, cx);
11187 this.change_selections(auto_scroll, window, cx, |s| {
11188 if replace_newest {
11189 s.delete(s.newest_anchor().id);
11190 }
11191 s.insert_range(range.clone());
11192 });
11193 }
11194
11195 let buffer = &display_map.buffer_snapshot;
11196 let mut selections = self.selections.all::<usize>(cx);
11197 if let Some(mut select_next_state) = self.select_next_state.take() {
11198 let query = &select_next_state.query;
11199 if !select_next_state.done {
11200 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11201 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11202 let mut next_selected_range = None;
11203
11204 let bytes_after_last_selection =
11205 buffer.bytes_in_range(last_selection.end..buffer.len());
11206 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11207 let query_matches = query
11208 .stream_find_iter(bytes_after_last_selection)
11209 .map(|result| (last_selection.end, result))
11210 .chain(
11211 query
11212 .stream_find_iter(bytes_before_first_selection)
11213 .map(|result| (0, result)),
11214 );
11215
11216 for (start_offset, query_match) in query_matches {
11217 let query_match = query_match.unwrap(); // can only fail due to I/O
11218 let offset_range =
11219 start_offset + query_match.start()..start_offset + query_match.end();
11220 let display_range = offset_range.start.to_display_point(display_map)
11221 ..offset_range.end.to_display_point(display_map);
11222
11223 if !select_next_state.wordwise
11224 || (!movement::is_inside_word(display_map, display_range.start)
11225 && !movement::is_inside_word(display_map, display_range.end))
11226 {
11227 // TODO: This is n^2, because we might check all the selections
11228 if !selections
11229 .iter()
11230 .any(|selection| selection.range().overlaps(&offset_range))
11231 {
11232 next_selected_range = Some(offset_range);
11233 break;
11234 }
11235 }
11236 }
11237
11238 if let Some(next_selected_range) = next_selected_range {
11239 select_next_match_ranges(
11240 self,
11241 next_selected_range,
11242 replace_newest,
11243 autoscroll,
11244 window,
11245 cx,
11246 );
11247 } else {
11248 select_next_state.done = true;
11249 }
11250 }
11251
11252 self.select_next_state = Some(select_next_state);
11253 } else {
11254 let mut only_carets = true;
11255 let mut same_text_selected = true;
11256 let mut selected_text = None;
11257
11258 let mut selections_iter = selections.iter().peekable();
11259 while let Some(selection) = selections_iter.next() {
11260 if selection.start != selection.end {
11261 only_carets = false;
11262 }
11263
11264 if same_text_selected {
11265 if selected_text.is_none() {
11266 selected_text =
11267 Some(buffer.text_for_range(selection.range()).collect::<String>());
11268 }
11269
11270 if let Some(next_selection) = selections_iter.peek() {
11271 if next_selection.range().len() == selection.range().len() {
11272 let next_selected_text = buffer
11273 .text_for_range(next_selection.range())
11274 .collect::<String>();
11275 if Some(next_selected_text) != selected_text {
11276 same_text_selected = false;
11277 selected_text = None;
11278 }
11279 } else {
11280 same_text_selected = false;
11281 selected_text = None;
11282 }
11283 }
11284 }
11285 }
11286
11287 if only_carets {
11288 for selection in &mut selections {
11289 let word_range = movement::surrounding_word(
11290 display_map,
11291 selection.start.to_display_point(display_map),
11292 );
11293 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11294 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11295 selection.goal = SelectionGoal::None;
11296 selection.reversed = false;
11297 select_next_match_ranges(
11298 self,
11299 selection.start..selection.end,
11300 replace_newest,
11301 autoscroll,
11302 window,
11303 cx,
11304 );
11305 }
11306
11307 if selections.len() == 1 {
11308 let selection = selections
11309 .last()
11310 .expect("ensured that there's only one selection");
11311 let query = buffer
11312 .text_for_range(selection.start..selection.end)
11313 .collect::<String>();
11314 let is_empty = query.is_empty();
11315 let select_state = SelectNextState {
11316 query: AhoCorasick::new(&[query])?,
11317 wordwise: true,
11318 done: is_empty,
11319 };
11320 self.select_next_state = Some(select_state);
11321 } else {
11322 self.select_next_state = None;
11323 }
11324 } else if let Some(selected_text) = selected_text {
11325 self.select_next_state = Some(SelectNextState {
11326 query: AhoCorasick::new(&[selected_text])?,
11327 wordwise: false,
11328 done: false,
11329 });
11330 self.select_next_match_internal(
11331 display_map,
11332 replace_newest,
11333 autoscroll,
11334 window,
11335 cx,
11336 )?;
11337 }
11338 }
11339 Ok(())
11340 }
11341
11342 pub fn select_all_matches(
11343 &mut self,
11344 _action: &SelectAllMatches,
11345 window: &mut Window,
11346 cx: &mut Context<Self>,
11347 ) -> Result<()> {
11348 self.push_to_selection_history();
11349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11350
11351 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11352 let Some(select_next_state) = self.select_next_state.as_mut() else {
11353 return Ok(());
11354 };
11355 if select_next_state.done {
11356 return Ok(());
11357 }
11358
11359 let mut new_selections = self.selections.all::<usize>(cx);
11360
11361 let buffer = &display_map.buffer_snapshot;
11362 let query_matches = select_next_state
11363 .query
11364 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11365
11366 for query_match in query_matches {
11367 let query_match = query_match.unwrap(); // can only fail due to I/O
11368 let offset_range = query_match.start()..query_match.end();
11369 let display_range = offset_range.start.to_display_point(&display_map)
11370 ..offset_range.end.to_display_point(&display_map);
11371
11372 if !select_next_state.wordwise
11373 || (!movement::is_inside_word(&display_map, display_range.start)
11374 && !movement::is_inside_word(&display_map, display_range.end))
11375 {
11376 self.selections.change_with(cx, |selections| {
11377 new_selections.push(Selection {
11378 id: selections.new_selection_id(),
11379 start: offset_range.start,
11380 end: offset_range.end,
11381 reversed: false,
11382 goal: SelectionGoal::None,
11383 });
11384 });
11385 }
11386 }
11387
11388 new_selections.sort_by_key(|selection| selection.start);
11389 let mut ix = 0;
11390 while ix + 1 < new_selections.len() {
11391 let current_selection = &new_selections[ix];
11392 let next_selection = &new_selections[ix + 1];
11393 if current_selection.range().overlaps(&next_selection.range()) {
11394 if current_selection.id < next_selection.id {
11395 new_selections.remove(ix + 1);
11396 } else {
11397 new_selections.remove(ix);
11398 }
11399 } else {
11400 ix += 1;
11401 }
11402 }
11403
11404 let reversed = self.selections.oldest::<usize>(cx).reversed;
11405
11406 for selection in new_selections.iter_mut() {
11407 selection.reversed = reversed;
11408 }
11409
11410 select_next_state.done = true;
11411 self.unfold_ranges(
11412 &new_selections
11413 .iter()
11414 .map(|selection| selection.range())
11415 .collect::<Vec<_>>(),
11416 false,
11417 false,
11418 cx,
11419 );
11420 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11421 selections.select(new_selections)
11422 });
11423
11424 Ok(())
11425 }
11426
11427 pub fn select_next(
11428 &mut self,
11429 action: &SelectNext,
11430 window: &mut Window,
11431 cx: &mut Context<Self>,
11432 ) -> Result<()> {
11433 self.push_to_selection_history();
11434 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11435 self.select_next_match_internal(
11436 &display_map,
11437 action.replace_newest,
11438 Some(Autoscroll::newest()),
11439 window,
11440 cx,
11441 )?;
11442 Ok(())
11443 }
11444
11445 pub fn select_previous(
11446 &mut self,
11447 action: &SelectPrevious,
11448 window: &mut Window,
11449 cx: &mut Context<Self>,
11450 ) -> Result<()> {
11451 self.push_to_selection_history();
11452 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11453 let buffer = &display_map.buffer_snapshot;
11454 let mut selections = self.selections.all::<usize>(cx);
11455 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11456 let query = &select_prev_state.query;
11457 if !select_prev_state.done {
11458 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11459 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11460 let mut next_selected_range = None;
11461 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11462 let bytes_before_last_selection =
11463 buffer.reversed_bytes_in_range(0..last_selection.start);
11464 let bytes_after_first_selection =
11465 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11466 let query_matches = query
11467 .stream_find_iter(bytes_before_last_selection)
11468 .map(|result| (last_selection.start, result))
11469 .chain(
11470 query
11471 .stream_find_iter(bytes_after_first_selection)
11472 .map(|result| (buffer.len(), result)),
11473 );
11474 for (end_offset, query_match) in query_matches {
11475 let query_match = query_match.unwrap(); // can only fail due to I/O
11476 let offset_range =
11477 end_offset - query_match.end()..end_offset - query_match.start();
11478 let display_range = offset_range.start.to_display_point(&display_map)
11479 ..offset_range.end.to_display_point(&display_map);
11480
11481 if !select_prev_state.wordwise
11482 || (!movement::is_inside_word(&display_map, display_range.start)
11483 && !movement::is_inside_word(&display_map, display_range.end))
11484 {
11485 next_selected_range = Some(offset_range);
11486 break;
11487 }
11488 }
11489
11490 if let Some(next_selected_range) = next_selected_range {
11491 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11492 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11493 if action.replace_newest {
11494 s.delete(s.newest_anchor().id);
11495 }
11496 s.insert_range(next_selected_range);
11497 });
11498 } else {
11499 select_prev_state.done = true;
11500 }
11501 }
11502
11503 self.select_prev_state = Some(select_prev_state);
11504 } else {
11505 let mut only_carets = true;
11506 let mut same_text_selected = true;
11507 let mut selected_text = None;
11508
11509 let mut selections_iter = selections.iter().peekable();
11510 while let Some(selection) = selections_iter.next() {
11511 if selection.start != selection.end {
11512 only_carets = false;
11513 }
11514
11515 if same_text_selected {
11516 if selected_text.is_none() {
11517 selected_text =
11518 Some(buffer.text_for_range(selection.range()).collect::<String>());
11519 }
11520
11521 if let Some(next_selection) = selections_iter.peek() {
11522 if next_selection.range().len() == selection.range().len() {
11523 let next_selected_text = buffer
11524 .text_for_range(next_selection.range())
11525 .collect::<String>();
11526 if Some(next_selected_text) != selected_text {
11527 same_text_selected = false;
11528 selected_text = None;
11529 }
11530 } else {
11531 same_text_selected = false;
11532 selected_text = None;
11533 }
11534 }
11535 }
11536 }
11537
11538 if only_carets {
11539 for selection in &mut selections {
11540 let word_range = movement::surrounding_word(
11541 &display_map,
11542 selection.start.to_display_point(&display_map),
11543 );
11544 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11545 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11546 selection.goal = SelectionGoal::None;
11547 selection.reversed = false;
11548 }
11549 if selections.len() == 1 {
11550 let selection = selections
11551 .last()
11552 .expect("ensured that there's only one selection");
11553 let query = buffer
11554 .text_for_range(selection.start..selection.end)
11555 .collect::<String>();
11556 let is_empty = query.is_empty();
11557 let select_state = SelectNextState {
11558 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11559 wordwise: true,
11560 done: is_empty,
11561 };
11562 self.select_prev_state = Some(select_state);
11563 } else {
11564 self.select_prev_state = None;
11565 }
11566
11567 self.unfold_ranges(
11568 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11569 false,
11570 true,
11571 cx,
11572 );
11573 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11574 s.select(selections);
11575 });
11576 } else if let Some(selected_text) = selected_text {
11577 self.select_prev_state = Some(SelectNextState {
11578 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11579 wordwise: false,
11580 done: false,
11581 });
11582 self.select_previous(action, window, cx)?;
11583 }
11584 }
11585 Ok(())
11586 }
11587
11588 pub fn toggle_comments(
11589 &mut self,
11590 action: &ToggleComments,
11591 window: &mut Window,
11592 cx: &mut Context<Self>,
11593 ) {
11594 if self.read_only(cx) {
11595 return;
11596 }
11597 let text_layout_details = &self.text_layout_details(window);
11598 self.transact(window, cx, |this, window, cx| {
11599 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11600 let mut edits = Vec::new();
11601 let mut selection_edit_ranges = Vec::new();
11602 let mut last_toggled_row = None;
11603 let snapshot = this.buffer.read(cx).read(cx);
11604 let empty_str: Arc<str> = Arc::default();
11605 let mut suffixes_inserted = Vec::new();
11606 let ignore_indent = action.ignore_indent;
11607
11608 fn comment_prefix_range(
11609 snapshot: &MultiBufferSnapshot,
11610 row: MultiBufferRow,
11611 comment_prefix: &str,
11612 comment_prefix_whitespace: &str,
11613 ignore_indent: bool,
11614 ) -> Range<Point> {
11615 let indent_size = if ignore_indent {
11616 0
11617 } else {
11618 snapshot.indent_size_for_line(row).len
11619 };
11620
11621 let start = Point::new(row.0, indent_size);
11622
11623 let mut line_bytes = snapshot
11624 .bytes_in_range(start..snapshot.max_point())
11625 .flatten()
11626 .copied();
11627
11628 // If this line currently begins with the line comment prefix, then record
11629 // the range containing the prefix.
11630 if line_bytes
11631 .by_ref()
11632 .take(comment_prefix.len())
11633 .eq(comment_prefix.bytes())
11634 {
11635 // Include any whitespace that matches the comment prefix.
11636 let matching_whitespace_len = line_bytes
11637 .zip(comment_prefix_whitespace.bytes())
11638 .take_while(|(a, b)| a == b)
11639 .count() as u32;
11640 let end = Point::new(
11641 start.row,
11642 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11643 );
11644 start..end
11645 } else {
11646 start..start
11647 }
11648 }
11649
11650 fn comment_suffix_range(
11651 snapshot: &MultiBufferSnapshot,
11652 row: MultiBufferRow,
11653 comment_suffix: &str,
11654 comment_suffix_has_leading_space: bool,
11655 ) -> Range<Point> {
11656 let end = Point::new(row.0, snapshot.line_len(row));
11657 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11658
11659 let mut line_end_bytes = snapshot
11660 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11661 .flatten()
11662 .copied();
11663
11664 let leading_space_len = if suffix_start_column > 0
11665 && line_end_bytes.next() == Some(b' ')
11666 && comment_suffix_has_leading_space
11667 {
11668 1
11669 } else {
11670 0
11671 };
11672
11673 // If this line currently begins with the line comment prefix, then record
11674 // the range containing the prefix.
11675 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11676 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11677 start..end
11678 } else {
11679 end..end
11680 }
11681 }
11682
11683 // TODO: Handle selections that cross excerpts
11684 for selection in &mut selections {
11685 let start_column = snapshot
11686 .indent_size_for_line(MultiBufferRow(selection.start.row))
11687 .len;
11688 let language = if let Some(language) =
11689 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11690 {
11691 language
11692 } else {
11693 continue;
11694 };
11695
11696 selection_edit_ranges.clear();
11697
11698 // If multiple selections contain a given row, avoid processing that
11699 // row more than once.
11700 let mut start_row = MultiBufferRow(selection.start.row);
11701 if last_toggled_row == Some(start_row) {
11702 start_row = start_row.next_row();
11703 }
11704 let end_row =
11705 if selection.end.row > selection.start.row && selection.end.column == 0 {
11706 MultiBufferRow(selection.end.row - 1)
11707 } else {
11708 MultiBufferRow(selection.end.row)
11709 };
11710 last_toggled_row = Some(end_row);
11711
11712 if start_row > end_row {
11713 continue;
11714 }
11715
11716 // If the language has line comments, toggle those.
11717 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11718
11719 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11720 if ignore_indent {
11721 full_comment_prefixes = full_comment_prefixes
11722 .into_iter()
11723 .map(|s| Arc::from(s.trim_end()))
11724 .collect();
11725 }
11726
11727 if !full_comment_prefixes.is_empty() {
11728 let first_prefix = full_comment_prefixes
11729 .first()
11730 .expect("prefixes is non-empty");
11731 let prefix_trimmed_lengths = full_comment_prefixes
11732 .iter()
11733 .map(|p| p.trim_end_matches(' ').len())
11734 .collect::<SmallVec<[usize; 4]>>();
11735
11736 let mut all_selection_lines_are_comments = true;
11737
11738 for row in start_row.0..=end_row.0 {
11739 let row = MultiBufferRow(row);
11740 if start_row < end_row && snapshot.is_line_blank(row) {
11741 continue;
11742 }
11743
11744 let prefix_range = full_comment_prefixes
11745 .iter()
11746 .zip(prefix_trimmed_lengths.iter().copied())
11747 .map(|(prefix, trimmed_prefix_len)| {
11748 comment_prefix_range(
11749 snapshot.deref(),
11750 row,
11751 &prefix[..trimmed_prefix_len],
11752 &prefix[trimmed_prefix_len..],
11753 ignore_indent,
11754 )
11755 })
11756 .max_by_key(|range| range.end.column - range.start.column)
11757 .expect("prefixes is non-empty");
11758
11759 if prefix_range.is_empty() {
11760 all_selection_lines_are_comments = false;
11761 }
11762
11763 selection_edit_ranges.push(prefix_range);
11764 }
11765
11766 if all_selection_lines_are_comments {
11767 edits.extend(
11768 selection_edit_ranges
11769 .iter()
11770 .cloned()
11771 .map(|range| (range, empty_str.clone())),
11772 );
11773 } else {
11774 let min_column = selection_edit_ranges
11775 .iter()
11776 .map(|range| range.start.column)
11777 .min()
11778 .unwrap_or(0);
11779 edits.extend(selection_edit_ranges.iter().map(|range| {
11780 let position = Point::new(range.start.row, min_column);
11781 (position..position, first_prefix.clone())
11782 }));
11783 }
11784 } else if let Some((full_comment_prefix, comment_suffix)) =
11785 language.block_comment_delimiters()
11786 {
11787 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11788 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11789 let prefix_range = comment_prefix_range(
11790 snapshot.deref(),
11791 start_row,
11792 comment_prefix,
11793 comment_prefix_whitespace,
11794 ignore_indent,
11795 );
11796 let suffix_range = comment_suffix_range(
11797 snapshot.deref(),
11798 end_row,
11799 comment_suffix.trim_start_matches(' '),
11800 comment_suffix.starts_with(' '),
11801 );
11802
11803 if prefix_range.is_empty() || suffix_range.is_empty() {
11804 edits.push((
11805 prefix_range.start..prefix_range.start,
11806 full_comment_prefix.clone(),
11807 ));
11808 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11809 suffixes_inserted.push((end_row, comment_suffix.len()));
11810 } else {
11811 edits.push((prefix_range, empty_str.clone()));
11812 edits.push((suffix_range, empty_str.clone()));
11813 }
11814 } else {
11815 continue;
11816 }
11817 }
11818
11819 drop(snapshot);
11820 this.buffer.update(cx, |buffer, cx| {
11821 buffer.edit(edits, None, cx);
11822 });
11823
11824 // Adjust selections so that they end before any comment suffixes that
11825 // were inserted.
11826 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11827 let mut selections = this.selections.all::<Point>(cx);
11828 let snapshot = this.buffer.read(cx).read(cx);
11829 for selection in &mut selections {
11830 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11831 match row.cmp(&MultiBufferRow(selection.end.row)) {
11832 Ordering::Less => {
11833 suffixes_inserted.next();
11834 continue;
11835 }
11836 Ordering::Greater => break,
11837 Ordering::Equal => {
11838 if selection.end.column == snapshot.line_len(row) {
11839 if selection.is_empty() {
11840 selection.start.column -= suffix_len as u32;
11841 }
11842 selection.end.column -= suffix_len as u32;
11843 }
11844 break;
11845 }
11846 }
11847 }
11848 }
11849
11850 drop(snapshot);
11851 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11852 s.select(selections)
11853 });
11854
11855 let selections = this.selections.all::<Point>(cx);
11856 let selections_on_single_row = selections.windows(2).all(|selections| {
11857 selections[0].start.row == selections[1].start.row
11858 && selections[0].end.row == selections[1].end.row
11859 && selections[0].start.row == selections[0].end.row
11860 });
11861 let selections_selecting = selections
11862 .iter()
11863 .any(|selection| selection.start != selection.end);
11864 let advance_downwards = action.advance_downwards
11865 && selections_on_single_row
11866 && !selections_selecting
11867 && !matches!(this.mode, EditorMode::SingleLine { .. });
11868
11869 if advance_downwards {
11870 let snapshot = this.buffer.read(cx).snapshot(cx);
11871
11872 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11873 s.move_cursors_with(|display_snapshot, display_point, _| {
11874 let mut point = display_point.to_point(display_snapshot);
11875 point.row += 1;
11876 point = snapshot.clip_point(point, Bias::Left);
11877 let display_point = point.to_display_point(display_snapshot);
11878 let goal = SelectionGoal::HorizontalPosition(
11879 display_snapshot
11880 .x_for_display_point(display_point, text_layout_details)
11881 .into(),
11882 );
11883 (display_point, goal)
11884 })
11885 });
11886 }
11887 });
11888 }
11889
11890 pub fn select_enclosing_symbol(
11891 &mut self,
11892 _: &SelectEnclosingSymbol,
11893 window: &mut Window,
11894 cx: &mut Context<Self>,
11895 ) {
11896 let buffer = self.buffer.read(cx).snapshot(cx);
11897 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11898
11899 fn update_selection(
11900 selection: &Selection<usize>,
11901 buffer_snap: &MultiBufferSnapshot,
11902 ) -> Option<Selection<usize>> {
11903 let cursor = selection.head();
11904 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11905 for symbol in symbols.iter().rev() {
11906 let start = symbol.range.start.to_offset(buffer_snap);
11907 let end = symbol.range.end.to_offset(buffer_snap);
11908 let new_range = start..end;
11909 if start < selection.start || end > selection.end {
11910 return Some(Selection {
11911 id: selection.id,
11912 start: new_range.start,
11913 end: new_range.end,
11914 goal: SelectionGoal::None,
11915 reversed: selection.reversed,
11916 });
11917 }
11918 }
11919 None
11920 }
11921
11922 let mut selected_larger_symbol = false;
11923 let new_selections = old_selections
11924 .iter()
11925 .map(|selection| match update_selection(selection, &buffer) {
11926 Some(new_selection) => {
11927 if new_selection.range() != selection.range() {
11928 selected_larger_symbol = true;
11929 }
11930 new_selection
11931 }
11932 None => selection.clone(),
11933 })
11934 .collect::<Vec<_>>();
11935
11936 if selected_larger_symbol {
11937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11938 s.select(new_selections);
11939 });
11940 }
11941 }
11942
11943 pub fn select_larger_syntax_node(
11944 &mut self,
11945 _: &SelectLargerSyntaxNode,
11946 window: &mut Window,
11947 cx: &mut Context<Self>,
11948 ) {
11949 let Some(visible_row_count) = self.visible_row_count() else {
11950 return;
11951 };
11952 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
11953 if old_selections.is_empty() {
11954 return;
11955 }
11956
11957 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11958 let buffer = self.buffer.read(cx).snapshot(cx);
11959
11960 let mut selected_larger_node = false;
11961 let mut new_selections = old_selections
11962 .iter()
11963 .map(|selection| {
11964 let old_range = selection.start..selection.end;
11965 let mut new_range = old_range.clone();
11966 let mut new_node = None;
11967 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11968 {
11969 new_node = Some(node);
11970 new_range = match containing_range {
11971 MultiOrSingleBufferOffsetRange::Single(_) => break,
11972 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11973 };
11974 if !display_map.intersects_fold(new_range.start)
11975 && !display_map.intersects_fold(new_range.end)
11976 {
11977 break;
11978 }
11979 }
11980
11981 if let Some(node) = new_node {
11982 // Log the ancestor, to support using this action as a way to explore TreeSitter
11983 // nodes. Parent and grandparent are also logged because this operation will not
11984 // visit nodes that have the same range as their parent.
11985 log::info!("Node: {node:?}");
11986 let parent = node.parent();
11987 log::info!("Parent: {parent:?}");
11988 let grandparent = parent.and_then(|x| x.parent());
11989 log::info!("Grandparent: {grandparent:?}");
11990 }
11991
11992 selected_larger_node |= new_range != old_range;
11993 Selection {
11994 id: selection.id,
11995 start: new_range.start,
11996 end: new_range.end,
11997 goal: SelectionGoal::None,
11998 reversed: selection.reversed,
11999 }
12000 })
12001 .collect::<Vec<_>>();
12002
12003 if !selected_larger_node {
12004 return; // don't put this call in the history
12005 }
12006
12007 // scroll based on transformation done to the last selection created by the user
12008 let (last_old, last_new) = old_selections
12009 .last()
12010 .zip(new_selections.last().cloned())
12011 .expect("old_selections isn't empty");
12012
12013 // revert selection
12014 let is_selection_reversed = {
12015 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12016 new_selections.last_mut().expect("checked above").reversed =
12017 should_newest_selection_be_reversed;
12018 should_newest_selection_be_reversed
12019 };
12020
12021 if selected_larger_node {
12022 self.select_syntax_node_history.disable_clearing = true;
12023 self.change_selections(None, window, cx, |s| {
12024 s.select(new_selections.clone());
12025 });
12026 self.select_syntax_node_history.disable_clearing = false;
12027 }
12028
12029 let start_row = last_new.start.to_display_point(&display_map).row().0;
12030 let end_row = last_new.end.to_display_point(&display_map).row().0;
12031 let selection_height = end_row - start_row + 1;
12032 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12033
12034 // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12035 let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12036 let middle_row = (end_row + start_row) / 2;
12037 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12038 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12039 SelectSyntaxNodeScrollBehavior::CenterSelection
12040 } else if is_selection_reversed {
12041 self.scroll_cursor_top(&Default::default(), window, cx);
12042 SelectSyntaxNodeScrollBehavior::CursorTop
12043 } else {
12044 self.scroll_cursor_bottom(&Default::default(), window, cx);
12045 SelectSyntaxNodeScrollBehavior::CursorBottom
12046 };
12047
12048 self.select_syntax_node_history.push((
12049 old_selections,
12050 scroll_behavior,
12051 is_selection_reversed,
12052 ));
12053 }
12054
12055 pub fn select_smaller_syntax_node(
12056 &mut self,
12057 _: &SelectSmallerSyntaxNode,
12058 window: &mut Window,
12059 cx: &mut Context<Self>,
12060 ) {
12061 let Some(visible_row_count) = self.visible_row_count() else {
12062 return;
12063 };
12064
12065 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12066 self.select_syntax_node_history.pop()
12067 {
12068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12069
12070 if let Some(selection) = selections.last_mut() {
12071 selection.reversed = is_selection_reversed;
12072 }
12073
12074 self.select_syntax_node_history.disable_clearing = true;
12075 self.change_selections(None, window, cx, |s| {
12076 s.select(selections.to_vec());
12077 });
12078 self.select_syntax_node_history.disable_clearing = false;
12079
12080 let newest = self.selections.newest::<usize>(cx);
12081 let start_row = newest.start.to_display_point(&display_map).row().0;
12082 let end_row = newest.end.to_display_point(&display_map).row().0;
12083
12084 match scroll_behavior {
12085 SelectSyntaxNodeScrollBehavior::CursorTop => {
12086 self.scroll_cursor_top(&Default::default(), window, cx);
12087 }
12088 SelectSyntaxNodeScrollBehavior::CenterSelection => {
12089 let middle_row = (end_row + start_row) / 2;
12090 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12091 // centralize the selection, not the cursor
12092 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12093 }
12094 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12095 self.scroll_cursor_bottom(&Default::default(), window, cx);
12096 }
12097 }
12098 }
12099 }
12100
12101 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12102 if !EditorSettings::get_global(cx).gutter.runnables {
12103 self.clear_tasks();
12104 return Task::ready(());
12105 }
12106 let project = self.project.as_ref().map(Entity::downgrade);
12107 cx.spawn_in(window, async move |this, cx| {
12108 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12109 let Some(project) = project.and_then(|p| p.upgrade()) else {
12110 return;
12111 };
12112 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12113 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12114 }) else {
12115 return;
12116 };
12117
12118 let hide_runnables = project
12119 .update(cx, |project, cx| {
12120 // Do not display any test indicators in non-dev server remote projects.
12121 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12122 })
12123 .unwrap_or(true);
12124 if hide_runnables {
12125 return;
12126 }
12127 let new_rows =
12128 cx.background_spawn({
12129 let snapshot = display_snapshot.clone();
12130 async move {
12131 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12132 }
12133 })
12134 .await;
12135
12136 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12137 this.update(cx, |this, _| {
12138 this.clear_tasks();
12139 for (key, value) in rows {
12140 this.insert_tasks(key, value);
12141 }
12142 })
12143 .ok();
12144 })
12145 }
12146 fn fetch_runnable_ranges(
12147 snapshot: &DisplaySnapshot,
12148 range: Range<Anchor>,
12149 ) -> Vec<language::RunnableRange> {
12150 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12151 }
12152
12153 fn runnable_rows(
12154 project: Entity<Project>,
12155 snapshot: DisplaySnapshot,
12156 runnable_ranges: Vec<RunnableRange>,
12157 mut cx: AsyncWindowContext,
12158 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12159 runnable_ranges
12160 .into_iter()
12161 .filter_map(|mut runnable| {
12162 let tasks = cx
12163 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12164 .ok()?;
12165 if tasks.is_empty() {
12166 return None;
12167 }
12168
12169 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12170
12171 let row = snapshot
12172 .buffer_snapshot
12173 .buffer_line_for_row(MultiBufferRow(point.row))?
12174 .1
12175 .start
12176 .row;
12177
12178 let context_range =
12179 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12180 Some((
12181 (runnable.buffer_id, row),
12182 RunnableTasks {
12183 templates: tasks,
12184 offset: snapshot
12185 .buffer_snapshot
12186 .anchor_before(runnable.run_range.start),
12187 context_range,
12188 column: point.column,
12189 extra_variables: runnable.extra_captures,
12190 },
12191 ))
12192 })
12193 .collect()
12194 }
12195
12196 fn templates_with_tags(
12197 project: &Entity<Project>,
12198 runnable: &mut Runnable,
12199 cx: &mut App,
12200 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12201 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12202 let (worktree_id, file) = project
12203 .buffer_for_id(runnable.buffer, cx)
12204 .and_then(|buffer| buffer.read(cx).file())
12205 .map(|file| (file.worktree_id(cx), file.clone()))
12206 .unzip();
12207
12208 (
12209 project.task_store().read(cx).task_inventory().cloned(),
12210 worktree_id,
12211 file,
12212 )
12213 });
12214
12215 let tags = mem::take(&mut runnable.tags);
12216 let mut tags: Vec<_> = tags
12217 .into_iter()
12218 .flat_map(|tag| {
12219 let tag = tag.0.clone();
12220 inventory
12221 .as_ref()
12222 .into_iter()
12223 .flat_map(|inventory| {
12224 inventory.read(cx).list_tasks(
12225 file.clone(),
12226 Some(runnable.language.clone()),
12227 worktree_id,
12228 cx,
12229 )
12230 })
12231 .filter(move |(_, template)| {
12232 template.tags.iter().any(|source_tag| source_tag == &tag)
12233 })
12234 })
12235 .sorted_by_key(|(kind, _)| kind.to_owned())
12236 .collect();
12237 if let Some((leading_tag_source, _)) = tags.first() {
12238 // Strongest source wins; if we have worktree tag binding, prefer that to
12239 // global and language bindings;
12240 // if we have a global binding, prefer that to language binding.
12241 let first_mismatch = tags
12242 .iter()
12243 .position(|(tag_source, _)| tag_source != leading_tag_source);
12244 if let Some(index) = first_mismatch {
12245 tags.truncate(index);
12246 }
12247 }
12248
12249 tags
12250 }
12251
12252 pub fn move_to_enclosing_bracket(
12253 &mut self,
12254 _: &MoveToEnclosingBracket,
12255 window: &mut Window,
12256 cx: &mut Context<Self>,
12257 ) {
12258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12259 s.move_offsets_with(|snapshot, selection| {
12260 let Some(enclosing_bracket_ranges) =
12261 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12262 else {
12263 return;
12264 };
12265
12266 let mut best_length = usize::MAX;
12267 let mut best_inside = false;
12268 let mut best_in_bracket_range = false;
12269 let mut best_destination = None;
12270 for (open, close) in enclosing_bracket_ranges {
12271 let close = close.to_inclusive();
12272 let length = close.end() - open.start;
12273 let inside = selection.start >= open.end && selection.end <= *close.start();
12274 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12275 || close.contains(&selection.head());
12276
12277 // If best is next to a bracket and current isn't, skip
12278 if !in_bracket_range && best_in_bracket_range {
12279 continue;
12280 }
12281
12282 // Prefer smaller lengths unless best is inside and current isn't
12283 if length > best_length && (best_inside || !inside) {
12284 continue;
12285 }
12286
12287 best_length = length;
12288 best_inside = inside;
12289 best_in_bracket_range = in_bracket_range;
12290 best_destination = Some(
12291 if close.contains(&selection.start) && close.contains(&selection.end) {
12292 if inside {
12293 open.end
12294 } else {
12295 open.start
12296 }
12297 } else if inside {
12298 *close.start()
12299 } else {
12300 *close.end()
12301 },
12302 );
12303 }
12304
12305 if let Some(destination) = best_destination {
12306 selection.collapse_to(destination, SelectionGoal::None);
12307 }
12308 })
12309 });
12310 }
12311
12312 pub fn undo_selection(
12313 &mut self,
12314 _: &UndoSelection,
12315 window: &mut Window,
12316 cx: &mut Context<Self>,
12317 ) {
12318 self.end_selection(window, cx);
12319 self.selection_history.mode = SelectionHistoryMode::Undoing;
12320 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12321 self.change_selections(None, window, cx, |s| {
12322 s.select_anchors(entry.selections.to_vec())
12323 });
12324 self.select_next_state = entry.select_next_state;
12325 self.select_prev_state = entry.select_prev_state;
12326 self.add_selections_state = entry.add_selections_state;
12327 self.request_autoscroll(Autoscroll::newest(), cx);
12328 }
12329 self.selection_history.mode = SelectionHistoryMode::Normal;
12330 }
12331
12332 pub fn redo_selection(
12333 &mut self,
12334 _: &RedoSelection,
12335 window: &mut Window,
12336 cx: &mut Context<Self>,
12337 ) {
12338 self.end_selection(window, cx);
12339 self.selection_history.mode = SelectionHistoryMode::Redoing;
12340 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12341 self.change_selections(None, window, cx, |s| {
12342 s.select_anchors(entry.selections.to_vec())
12343 });
12344 self.select_next_state = entry.select_next_state;
12345 self.select_prev_state = entry.select_prev_state;
12346 self.add_selections_state = entry.add_selections_state;
12347 self.request_autoscroll(Autoscroll::newest(), cx);
12348 }
12349 self.selection_history.mode = SelectionHistoryMode::Normal;
12350 }
12351
12352 pub fn expand_excerpts(
12353 &mut self,
12354 action: &ExpandExcerpts,
12355 _: &mut Window,
12356 cx: &mut Context<Self>,
12357 ) {
12358 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12359 }
12360
12361 pub fn expand_excerpts_down(
12362 &mut self,
12363 action: &ExpandExcerptsDown,
12364 _: &mut Window,
12365 cx: &mut Context<Self>,
12366 ) {
12367 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12368 }
12369
12370 pub fn expand_excerpts_up(
12371 &mut self,
12372 action: &ExpandExcerptsUp,
12373 _: &mut Window,
12374 cx: &mut Context<Self>,
12375 ) {
12376 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12377 }
12378
12379 pub fn expand_excerpts_for_direction(
12380 &mut self,
12381 lines: u32,
12382 direction: ExpandExcerptDirection,
12383
12384 cx: &mut Context<Self>,
12385 ) {
12386 let selections = self.selections.disjoint_anchors();
12387
12388 let lines = if lines == 0 {
12389 EditorSettings::get_global(cx).expand_excerpt_lines
12390 } else {
12391 lines
12392 };
12393
12394 self.buffer.update(cx, |buffer, cx| {
12395 let snapshot = buffer.snapshot(cx);
12396 let mut excerpt_ids = selections
12397 .iter()
12398 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12399 .collect::<Vec<_>>();
12400 excerpt_ids.sort();
12401 excerpt_ids.dedup();
12402 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12403 })
12404 }
12405
12406 pub fn expand_excerpt(
12407 &mut self,
12408 excerpt: ExcerptId,
12409 direction: ExpandExcerptDirection,
12410 window: &mut Window,
12411 cx: &mut Context<Self>,
12412 ) {
12413 let current_scroll_position = self.scroll_position(cx);
12414 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12415 self.buffer.update(cx, |buffer, cx| {
12416 buffer.expand_excerpts([excerpt], lines, direction, cx)
12417 });
12418 if direction == ExpandExcerptDirection::Down {
12419 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12420 self.set_scroll_position(new_scroll_position, window, cx);
12421 }
12422 }
12423
12424 pub fn go_to_singleton_buffer_point(
12425 &mut self,
12426 point: Point,
12427 window: &mut Window,
12428 cx: &mut Context<Self>,
12429 ) {
12430 self.go_to_singleton_buffer_range(point..point, window, cx);
12431 }
12432
12433 pub fn go_to_singleton_buffer_range(
12434 &mut self,
12435 range: Range<Point>,
12436 window: &mut Window,
12437 cx: &mut Context<Self>,
12438 ) {
12439 let multibuffer = self.buffer().read(cx);
12440 let Some(buffer) = multibuffer.as_singleton() else {
12441 return;
12442 };
12443 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12444 return;
12445 };
12446 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12447 return;
12448 };
12449 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12450 s.select_anchor_ranges([start..end])
12451 });
12452 }
12453
12454 fn go_to_diagnostic(
12455 &mut self,
12456 _: &GoToDiagnostic,
12457 window: &mut Window,
12458 cx: &mut Context<Self>,
12459 ) {
12460 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12461 }
12462
12463 fn go_to_prev_diagnostic(
12464 &mut self,
12465 _: &GoToPreviousDiagnostic,
12466 window: &mut Window,
12467 cx: &mut Context<Self>,
12468 ) {
12469 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12470 }
12471
12472 pub fn go_to_diagnostic_impl(
12473 &mut self,
12474 direction: Direction,
12475 window: &mut Window,
12476 cx: &mut Context<Self>,
12477 ) {
12478 let buffer = self.buffer.read(cx).snapshot(cx);
12479 let selection = self.selections.newest::<usize>(cx);
12480
12481 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12482 if direction == Direction::Next {
12483 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12484 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12485 return;
12486 };
12487 self.activate_diagnostics(
12488 buffer_id,
12489 popover.local_diagnostic.diagnostic.group_id,
12490 window,
12491 cx,
12492 );
12493 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12494 let primary_range_start = active_diagnostics.primary_range.start;
12495 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12496 let mut new_selection = s.newest_anchor().clone();
12497 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12498 s.select_anchors(vec![new_selection.clone()]);
12499 });
12500 self.refresh_inline_completion(false, true, window, cx);
12501 }
12502 return;
12503 }
12504 }
12505
12506 let active_group_id = self
12507 .active_diagnostics
12508 .as_ref()
12509 .map(|active_group| active_group.group_id);
12510 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12511 active_diagnostics
12512 .primary_range
12513 .to_offset(&buffer)
12514 .to_inclusive()
12515 });
12516 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12517 if active_primary_range.contains(&selection.head()) {
12518 *active_primary_range.start()
12519 } else {
12520 selection.head()
12521 }
12522 } else {
12523 selection.head()
12524 };
12525
12526 let snapshot = self.snapshot(window, cx);
12527 let primary_diagnostics_before = buffer
12528 .diagnostics_in_range::<usize>(0..search_start)
12529 .filter(|entry| entry.diagnostic.is_primary)
12530 .filter(|entry| entry.range.start != entry.range.end)
12531 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12532 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12533 .collect::<Vec<_>>();
12534 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12535 primary_diagnostics_before
12536 .iter()
12537 .position(|entry| entry.diagnostic.group_id == active_group_id)
12538 });
12539
12540 let primary_diagnostics_after = buffer
12541 .diagnostics_in_range::<usize>(search_start..buffer.len())
12542 .filter(|entry| entry.diagnostic.is_primary)
12543 .filter(|entry| entry.range.start != entry.range.end)
12544 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12545 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12546 .collect::<Vec<_>>();
12547 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12548 primary_diagnostics_after
12549 .iter()
12550 .enumerate()
12551 .rev()
12552 .find_map(|(i, entry)| {
12553 if entry.diagnostic.group_id == active_group_id {
12554 Some(i)
12555 } else {
12556 None
12557 }
12558 })
12559 });
12560
12561 let next_primary_diagnostic = match direction {
12562 Direction::Prev => primary_diagnostics_before
12563 .iter()
12564 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12565 .rev()
12566 .next(),
12567 Direction::Next => primary_diagnostics_after
12568 .iter()
12569 .skip(
12570 last_same_group_diagnostic_after
12571 .map(|index| index + 1)
12572 .unwrap_or(0),
12573 )
12574 .next(),
12575 };
12576
12577 // Cycle around to the start of the buffer, potentially moving back to the start of
12578 // the currently active diagnostic.
12579 let cycle_around = || match direction {
12580 Direction::Prev => primary_diagnostics_after
12581 .iter()
12582 .rev()
12583 .chain(primary_diagnostics_before.iter().rev())
12584 .next(),
12585 Direction::Next => primary_diagnostics_before
12586 .iter()
12587 .chain(primary_diagnostics_after.iter())
12588 .next(),
12589 };
12590
12591 if let Some((primary_range, group_id)) = next_primary_diagnostic
12592 .or_else(cycle_around)
12593 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12594 {
12595 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12596 return;
12597 };
12598 self.activate_diagnostics(buffer_id, group_id, window, cx);
12599 if self.active_diagnostics.is_some() {
12600 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12601 s.select(vec![Selection {
12602 id: selection.id,
12603 start: primary_range.start,
12604 end: primary_range.start,
12605 reversed: false,
12606 goal: SelectionGoal::None,
12607 }]);
12608 });
12609 self.refresh_inline_completion(false, true, window, cx);
12610 }
12611 }
12612 }
12613
12614 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12615 let snapshot = self.snapshot(window, cx);
12616 let selection = self.selections.newest::<Point>(cx);
12617 self.go_to_hunk_before_or_after_position(
12618 &snapshot,
12619 selection.head(),
12620 Direction::Next,
12621 window,
12622 cx,
12623 );
12624 }
12625
12626 fn go_to_hunk_before_or_after_position(
12627 &mut self,
12628 snapshot: &EditorSnapshot,
12629 position: Point,
12630 direction: Direction,
12631 window: &mut Window,
12632 cx: &mut Context<Editor>,
12633 ) {
12634 let row = if direction == Direction::Next {
12635 self.hunk_after_position(snapshot, position)
12636 .map(|hunk| hunk.row_range.start)
12637 } else {
12638 self.hunk_before_position(snapshot, position)
12639 };
12640
12641 if let Some(row) = row {
12642 let destination = Point::new(row.0, 0);
12643 let autoscroll = Autoscroll::center();
12644
12645 self.unfold_ranges(&[destination..destination], false, false, cx);
12646 self.change_selections(Some(autoscroll), window, cx, |s| {
12647 s.select_ranges([destination..destination]);
12648 });
12649 }
12650 }
12651
12652 fn hunk_after_position(
12653 &mut self,
12654 snapshot: &EditorSnapshot,
12655 position: Point,
12656 ) -> Option<MultiBufferDiffHunk> {
12657 snapshot
12658 .buffer_snapshot
12659 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12660 .find(|hunk| hunk.row_range.start.0 > position.row)
12661 .or_else(|| {
12662 snapshot
12663 .buffer_snapshot
12664 .diff_hunks_in_range(Point::zero()..position)
12665 .find(|hunk| hunk.row_range.end.0 < position.row)
12666 })
12667 }
12668
12669 fn go_to_prev_hunk(
12670 &mut self,
12671 _: &GoToPreviousHunk,
12672 window: &mut Window,
12673 cx: &mut Context<Self>,
12674 ) {
12675 let snapshot = self.snapshot(window, cx);
12676 let selection = self.selections.newest::<Point>(cx);
12677 self.go_to_hunk_before_or_after_position(
12678 &snapshot,
12679 selection.head(),
12680 Direction::Prev,
12681 window,
12682 cx,
12683 );
12684 }
12685
12686 fn hunk_before_position(
12687 &mut self,
12688 snapshot: &EditorSnapshot,
12689 position: Point,
12690 ) -> Option<MultiBufferRow> {
12691 snapshot
12692 .buffer_snapshot
12693 .diff_hunk_before(position)
12694 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12695 }
12696
12697 fn go_to_line<T: 'static>(
12698 &mut self,
12699 position: Anchor,
12700 highlight_color: Option<Hsla>,
12701 window: &mut Window,
12702 cx: &mut Context<Self>,
12703 ) {
12704 let snapshot = self.snapshot(window, cx).display_snapshot;
12705 let position = position.to_point(&snapshot.buffer_snapshot);
12706 let start = snapshot
12707 .buffer_snapshot
12708 .clip_point(Point::new(position.row, 0), Bias::Left);
12709 let end = start + Point::new(1, 0);
12710 let start = snapshot.buffer_snapshot.anchor_before(start);
12711 let end = snapshot.buffer_snapshot.anchor_before(end);
12712
12713 self.highlight_rows::<T>(
12714 start..end,
12715 highlight_color
12716 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12717 false,
12718 cx,
12719 );
12720 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
12721 }
12722
12723 pub fn go_to_definition(
12724 &mut self,
12725 _: &GoToDefinition,
12726 window: &mut Window,
12727 cx: &mut Context<Self>,
12728 ) -> Task<Result<Navigated>> {
12729 let definition =
12730 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12731 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
12732 cx.spawn_in(window, async move |editor, cx| {
12733 if definition.await? == Navigated::Yes {
12734 return Ok(Navigated::Yes);
12735 }
12736 match fallback_strategy {
12737 GoToDefinitionFallback::None => Ok(Navigated::No),
12738 GoToDefinitionFallback::FindAllReferences => {
12739 match editor.update_in(cx, |editor, window, cx| {
12740 editor.find_all_references(&FindAllReferences, window, cx)
12741 })? {
12742 Some(references) => references.await,
12743 None => Ok(Navigated::No),
12744 }
12745 }
12746 }
12747 })
12748 }
12749
12750 pub fn go_to_declaration(
12751 &mut self,
12752 _: &GoToDeclaration,
12753 window: &mut Window,
12754 cx: &mut Context<Self>,
12755 ) -> Task<Result<Navigated>> {
12756 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12757 }
12758
12759 pub fn go_to_declaration_split(
12760 &mut self,
12761 _: &GoToDeclaration,
12762 window: &mut Window,
12763 cx: &mut Context<Self>,
12764 ) -> Task<Result<Navigated>> {
12765 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12766 }
12767
12768 pub fn go_to_implementation(
12769 &mut self,
12770 _: &GoToImplementation,
12771 window: &mut Window,
12772 cx: &mut Context<Self>,
12773 ) -> Task<Result<Navigated>> {
12774 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12775 }
12776
12777 pub fn go_to_implementation_split(
12778 &mut self,
12779 _: &GoToImplementationSplit,
12780 window: &mut Window,
12781 cx: &mut Context<Self>,
12782 ) -> Task<Result<Navigated>> {
12783 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12784 }
12785
12786 pub fn go_to_type_definition(
12787 &mut self,
12788 _: &GoToTypeDefinition,
12789 window: &mut Window,
12790 cx: &mut Context<Self>,
12791 ) -> Task<Result<Navigated>> {
12792 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12793 }
12794
12795 pub fn go_to_definition_split(
12796 &mut self,
12797 _: &GoToDefinitionSplit,
12798 window: &mut Window,
12799 cx: &mut Context<Self>,
12800 ) -> Task<Result<Navigated>> {
12801 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12802 }
12803
12804 pub fn go_to_type_definition_split(
12805 &mut self,
12806 _: &GoToTypeDefinitionSplit,
12807 window: &mut Window,
12808 cx: &mut Context<Self>,
12809 ) -> Task<Result<Navigated>> {
12810 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12811 }
12812
12813 fn go_to_definition_of_kind(
12814 &mut self,
12815 kind: GotoDefinitionKind,
12816 split: bool,
12817 window: &mut Window,
12818 cx: &mut Context<Self>,
12819 ) -> Task<Result<Navigated>> {
12820 let Some(provider) = self.semantics_provider.clone() else {
12821 return Task::ready(Ok(Navigated::No));
12822 };
12823 let head = self.selections.newest::<usize>(cx).head();
12824 let buffer = self.buffer.read(cx);
12825 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12826 text_anchor
12827 } else {
12828 return Task::ready(Ok(Navigated::No));
12829 };
12830
12831 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12832 return Task::ready(Ok(Navigated::No));
12833 };
12834
12835 cx.spawn_in(window, async move |editor, cx| {
12836 let definitions = definitions.await?;
12837 let navigated = editor
12838 .update_in(cx, |editor, window, cx| {
12839 editor.navigate_to_hover_links(
12840 Some(kind),
12841 definitions
12842 .into_iter()
12843 .filter(|location| {
12844 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12845 })
12846 .map(HoverLink::Text)
12847 .collect::<Vec<_>>(),
12848 split,
12849 window,
12850 cx,
12851 )
12852 })?
12853 .await?;
12854 anyhow::Ok(navigated)
12855 })
12856 }
12857
12858 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12859 let selection = self.selections.newest_anchor();
12860 let head = selection.head();
12861 let tail = selection.tail();
12862
12863 let Some((buffer, start_position)) =
12864 self.buffer.read(cx).text_anchor_for_position(head, cx)
12865 else {
12866 return;
12867 };
12868
12869 let end_position = if head != tail {
12870 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12871 return;
12872 };
12873 Some(pos)
12874 } else {
12875 None
12876 };
12877
12878 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12879 let url = if let Some(end_pos) = end_position {
12880 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12881 } else {
12882 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12883 };
12884
12885 if let Some(url) = url {
12886 editor.update(cx, |_, cx| {
12887 cx.open_url(&url);
12888 })
12889 } else {
12890 Ok(())
12891 }
12892 });
12893
12894 url_finder.detach();
12895 }
12896
12897 pub fn open_selected_filename(
12898 &mut self,
12899 _: &OpenSelectedFilename,
12900 window: &mut Window,
12901 cx: &mut Context<Self>,
12902 ) {
12903 let Some(workspace) = self.workspace() else {
12904 return;
12905 };
12906
12907 let position = self.selections.newest_anchor().head();
12908
12909 let Some((buffer, buffer_position)) =
12910 self.buffer.read(cx).text_anchor_for_position(position, cx)
12911 else {
12912 return;
12913 };
12914
12915 let project = self.project.clone();
12916
12917 cx.spawn_in(window, async move |_, cx| {
12918 let result = find_file(&buffer, project, buffer_position, cx).await;
12919
12920 if let Some((_, path)) = result {
12921 workspace
12922 .update_in(cx, |workspace, window, cx| {
12923 workspace.open_resolved_path(path, window, cx)
12924 })?
12925 .await?;
12926 }
12927 anyhow::Ok(())
12928 })
12929 .detach();
12930 }
12931
12932 pub(crate) fn navigate_to_hover_links(
12933 &mut self,
12934 kind: Option<GotoDefinitionKind>,
12935 mut definitions: Vec<HoverLink>,
12936 split: bool,
12937 window: &mut Window,
12938 cx: &mut Context<Editor>,
12939 ) -> Task<Result<Navigated>> {
12940 // If there is one definition, just open it directly
12941 if definitions.len() == 1 {
12942 let definition = definitions.pop().unwrap();
12943
12944 enum TargetTaskResult {
12945 Location(Option<Location>),
12946 AlreadyNavigated,
12947 }
12948
12949 let target_task = match definition {
12950 HoverLink::Text(link) => {
12951 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12952 }
12953 HoverLink::InlayHint(lsp_location, server_id) => {
12954 let computation =
12955 self.compute_target_location(lsp_location, server_id, window, cx);
12956 cx.background_spawn(async move {
12957 let location = computation.await?;
12958 Ok(TargetTaskResult::Location(location))
12959 })
12960 }
12961 HoverLink::Url(url) => {
12962 cx.open_url(&url);
12963 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12964 }
12965 HoverLink::File(path) => {
12966 if let Some(workspace) = self.workspace() {
12967 cx.spawn_in(window, async move |_, cx| {
12968 workspace
12969 .update_in(cx, |workspace, window, cx| {
12970 workspace.open_resolved_path(path, window, cx)
12971 })?
12972 .await
12973 .map(|_| TargetTaskResult::AlreadyNavigated)
12974 })
12975 } else {
12976 Task::ready(Ok(TargetTaskResult::Location(None)))
12977 }
12978 }
12979 };
12980 cx.spawn_in(window, async move |editor, cx| {
12981 let target = match target_task.await.context("target resolution task")? {
12982 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12983 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12984 TargetTaskResult::Location(Some(target)) => target,
12985 };
12986
12987 editor.update_in(cx, |editor, window, cx| {
12988 let Some(workspace) = editor.workspace() else {
12989 return Navigated::No;
12990 };
12991 let pane = workspace.read(cx).active_pane().clone();
12992
12993 let range = target.range.to_point(target.buffer.read(cx));
12994 let range = editor.range_for_match(&range);
12995 let range = collapse_multiline_range(range);
12996
12997 if !split
12998 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12999 {
13000 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13001 } else {
13002 window.defer(cx, move |window, cx| {
13003 let target_editor: Entity<Self> =
13004 workspace.update(cx, |workspace, cx| {
13005 let pane = if split {
13006 workspace.adjacent_pane(window, cx)
13007 } else {
13008 workspace.active_pane().clone()
13009 };
13010
13011 workspace.open_project_item(
13012 pane,
13013 target.buffer.clone(),
13014 true,
13015 true,
13016 window,
13017 cx,
13018 )
13019 });
13020 target_editor.update(cx, |target_editor, cx| {
13021 // When selecting a definition in a different buffer, disable the nav history
13022 // to avoid creating a history entry at the previous cursor location.
13023 pane.update(cx, |pane, _| pane.disable_history());
13024 target_editor.go_to_singleton_buffer_range(range, window, cx);
13025 pane.update(cx, |pane, _| pane.enable_history());
13026 });
13027 });
13028 }
13029 Navigated::Yes
13030 })
13031 })
13032 } else if !definitions.is_empty() {
13033 cx.spawn_in(window, async move |editor, cx| {
13034 let (title, location_tasks, workspace) = editor
13035 .update_in(cx, |editor, window, cx| {
13036 let tab_kind = match kind {
13037 Some(GotoDefinitionKind::Implementation) => "Implementations",
13038 _ => "Definitions",
13039 };
13040 let title = definitions
13041 .iter()
13042 .find_map(|definition| match definition {
13043 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13044 let buffer = origin.buffer.read(cx);
13045 format!(
13046 "{} for {}",
13047 tab_kind,
13048 buffer
13049 .text_for_range(origin.range.clone())
13050 .collect::<String>()
13051 )
13052 }),
13053 HoverLink::InlayHint(_, _) => None,
13054 HoverLink::Url(_) => None,
13055 HoverLink::File(_) => None,
13056 })
13057 .unwrap_or(tab_kind.to_string());
13058 let location_tasks = definitions
13059 .into_iter()
13060 .map(|definition| match definition {
13061 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13062 HoverLink::InlayHint(lsp_location, server_id) => editor
13063 .compute_target_location(lsp_location, server_id, window, cx),
13064 HoverLink::Url(_) => Task::ready(Ok(None)),
13065 HoverLink::File(_) => Task::ready(Ok(None)),
13066 })
13067 .collect::<Vec<_>>();
13068 (title, location_tasks, editor.workspace().clone())
13069 })
13070 .context("location tasks preparation")?;
13071
13072 let locations = future::join_all(location_tasks)
13073 .await
13074 .into_iter()
13075 .filter_map(|location| location.transpose())
13076 .collect::<Result<_>>()
13077 .context("location tasks")?;
13078
13079 let Some(workspace) = workspace else {
13080 return Ok(Navigated::No);
13081 };
13082 let opened = workspace
13083 .update_in(cx, |workspace, window, cx| {
13084 Self::open_locations_in_multibuffer(
13085 workspace,
13086 locations,
13087 title,
13088 split,
13089 MultibufferSelectionMode::First,
13090 window,
13091 cx,
13092 )
13093 })
13094 .ok();
13095
13096 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13097 })
13098 } else {
13099 Task::ready(Ok(Navigated::No))
13100 }
13101 }
13102
13103 fn compute_target_location(
13104 &self,
13105 lsp_location: lsp::Location,
13106 server_id: LanguageServerId,
13107 window: &mut Window,
13108 cx: &mut Context<Self>,
13109 ) -> Task<anyhow::Result<Option<Location>>> {
13110 let Some(project) = self.project.clone() else {
13111 return Task::ready(Ok(None));
13112 };
13113
13114 cx.spawn_in(window, async move |editor, cx| {
13115 let location_task = editor.update(cx, |_, cx| {
13116 project.update(cx, |project, cx| {
13117 let language_server_name = project
13118 .language_server_statuses(cx)
13119 .find(|(id, _)| server_id == *id)
13120 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13121 language_server_name.map(|language_server_name| {
13122 project.open_local_buffer_via_lsp(
13123 lsp_location.uri.clone(),
13124 server_id,
13125 language_server_name,
13126 cx,
13127 )
13128 })
13129 })
13130 })?;
13131 let location = match location_task {
13132 Some(task) => Some({
13133 let target_buffer_handle = task.await.context("open local buffer")?;
13134 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13135 let target_start = target_buffer
13136 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13137 let target_end = target_buffer
13138 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13139 target_buffer.anchor_after(target_start)
13140 ..target_buffer.anchor_before(target_end)
13141 })?;
13142 Location {
13143 buffer: target_buffer_handle,
13144 range,
13145 }
13146 }),
13147 None => None,
13148 };
13149 Ok(location)
13150 })
13151 }
13152
13153 pub fn find_all_references(
13154 &mut self,
13155 _: &FindAllReferences,
13156 window: &mut Window,
13157 cx: &mut Context<Self>,
13158 ) -> Option<Task<Result<Navigated>>> {
13159 let selection = self.selections.newest::<usize>(cx);
13160 let multi_buffer = self.buffer.read(cx);
13161 let head = selection.head();
13162
13163 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13164 let head_anchor = multi_buffer_snapshot.anchor_at(
13165 head,
13166 if head < selection.tail() {
13167 Bias::Right
13168 } else {
13169 Bias::Left
13170 },
13171 );
13172
13173 match self
13174 .find_all_references_task_sources
13175 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13176 {
13177 Ok(_) => {
13178 log::info!(
13179 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13180 );
13181 return None;
13182 }
13183 Err(i) => {
13184 self.find_all_references_task_sources.insert(i, head_anchor);
13185 }
13186 }
13187
13188 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13189 let workspace = self.workspace()?;
13190 let project = workspace.read(cx).project().clone();
13191 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13192 Some(cx.spawn_in(window, async move |editor, cx| {
13193 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13194 if let Ok(i) = editor
13195 .find_all_references_task_sources
13196 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13197 {
13198 editor.find_all_references_task_sources.remove(i);
13199 }
13200 });
13201
13202 let locations = references.await?;
13203 if locations.is_empty() {
13204 return anyhow::Ok(Navigated::No);
13205 }
13206
13207 workspace.update_in(cx, |workspace, window, cx| {
13208 let title = locations
13209 .first()
13210 .as_ref()
13211 .map(|location| {
13212 let buffer = location.buffer.read(cx);
13213 format!(
13214 "References to `{}`",
13215 buffer
13216 .text_for_range(location.range.clone())
13217 .collect::<String>()
13218 )
13219 })
13220 .unwrap();
13221 Self::open_locations_in_multibuffer(
13222 workspace,
13223 locations,
13224 title,
13225 false,
13226 MultibufferSelectionMode::First,
13227 window,
13228 cx,
13229 );
13230 Navigated::Yes
13231 })
13232 }))
13233 }
13234
13235 /// Opens a multibuffer with the given project locations in it
13236 pub fn open_locations_in_multibuffer(
13237 workspace: &mut Workspace,
13238 mut locations: Vec<Location>,
13239 title: String,
13240 split: bool,
13241 multibuffer_selection_mode: MultibufferSelectionMode,
13242 window: &mut Window,
13243 cx: &mut Context<Workspace>,
13244 ) {
13245 // If there are multiple definitions, open them in a multibuffer
13246 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13247 let mut locations = locations.into_iter().peekable();
13248 let mut ranges = Vec::new();
13249 let capability = workspace.project().read(cx).capability();
13250
13251 let excerpt_buffer = cx.new(|cx| {
13252 let mut multibuffer = MultiBuffer::new(capability);
13253 while let Some(location) = locations.next() {
13254 let buffer = location.buffer.read(cx);
13255 let mut ranges_for_buffer = Vec::new();
13256 let range = location.range.to_offset(buffer);
13257 ranges_for_buffer.push(range.clone());
13258
13259 while let Some(next_location) = locations.peek() {
13260 if next_location.buffer == location.buffer {
13261 ranges_for_buffer.push(next_location.range.to_offset(buffer));
13262 locations.next();
13263 } else {
13264 break;
13265 }
13266 }
13267
13268 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13269 ranges.extend(multibuffer.push_excerpts_with_context_lines(
13270 location.buffer.clone(),
13271 ranges_for_buffer,
13272 DEFAULT_MULTIBUFFER_CONTEXT,
13273 cx,
13274 ))
13275 }
13276
13277 multibuffer.with_title(title)
13278 });
13279
13280 let editor = cx.new(|cx| {
13281 Editor::for_multibuffer(
13282 excerpt_buffer,
13283 Some(workspace.project().clone()),
13284 window,
13285 cx,
13286 )
13287 });
13288 editor.update(cx, |editor, cx| {
13289 match multibuffer_selection_mode {
13290 MultibufferSelectionMode::First => {
13291 if let Some(first_range) = ranges.first() {
13292 editor.change_selections(None, window, cx, |selections| {
13293 selections.clear_disjoint();
13294 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13295 });
13296 }
13297 editor.highlight_background::<Self>(
13298 &ranges,
13299 |theme| theme.editor_highlighted_line_background,
13300 cx,
13301 );
13302 }
13303 MultibufferSelectionMode::All => {
13304 editor.change_selections(None, window, cx, |selections| {
13305 selections.clear_disjoint();
13306 selections.select_anchor_ranges(ranges);
13307 });
13308 }
13309 }
13310 editor.register_buffers_with_language_servers(cx);
13311 });
13312
13313 let item = Box::new(editor);
13314 let item_id = item.item_id();
13315
13316 if split {
13317 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13318 } else {
13319 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13320 let (preview_item_id, preview_item_idx) =
13321 workspace.active_pane().update(cx, |pane, _| {
13322 (pane.preview_item_id(), pane.preview_item_idx())
13323 });
13324
13325 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13326
13327 if let Some(preview_item_id) = preview_item_id {
13328 workspace.active_pane().update(cx, |pane, cx| {
13329 pane.remove_item(preview_item_id, false, false, window, cx);
13330 });
13331 }
13332 } else {
13333 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13334 }
13335 }
13336 workspace.active_pane().update(cx, |pane, cx| {
13337 pane.set_preview_item_id(Some(item_id), cx);
13338 });
13339 }
13340
13341 pub fn rename(
13342 &mut self,
13343 _: &Rename,
13344 window: &mut Window,
13345 cx: &mut Context<Self>,
13346 ) -> Option<Task<Result<()>>> {
13347 use language::ToOffset as _;
13348
13349 let provider = self.semantics_provider.clone()?;
13350 let selection = self.selections.newest_anchor().clone();
13351 let (cursor_buffer, cursor_buffer_position) = self
13352 .buffer
13353 .read(cx)
13354 .text_anchor_for_position(selection.head(), cx)?;
13355 let (tail_buffer, cursor_buffer_position_end) = self
13356 .buffer
13357 .read(cx)
13358 .text_anchor_for_position(selection.tail(), cx)?;
13359 if tail_buffer != cursor_buffer {
13360 return None;
13361 }
13362
13363 let snapshot = cursor_buffer.read(cx).snapshot();
13364 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13365 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13366 let prepare_rename = provider
13367 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13368 .unwrap_or_else(|| Task::ready(Ok(None)));
13369 drop(snapshot);
13370
13371 Some(cx.spawn_in(window, async move |this, cx| {
13372 let rename_range = if let Some(range) = prepare_rename.await? {
13373 Some(range)
13374 } else {
13375 this.update(cx, |this, cx| {
13376 let buffer = this.buffer.read(cx).snapshot(cx);
13377 let mut buffer_highlights = this
13378 .document_highlights_for_position(selection.head(), &buffer)
13379 .filter(|highlight| {
13380 highlight.start.excerpt_id == selection.head().excerpt_id
13381 && highlight.end.excerpt_id == selection.head().excerpt_id
13382 });
13383 buffer_highlights
13384 .next()
13385 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13386 })?
13387 };
13388 if let Some(rename_range) = rename_range {
13389 this.update_in(cx, |this, window, cx| {
13390 let snapshot = cursor_buffer.read(cx).snapshot();
13391 let rename_buffer_range = rename_range.to_offset(&snapshot);
13392 let cursor_offset_in_rename_range =
13393 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13394 let cursor_offset_in_rename_range_end =
13395 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13396
13397 this.take_rename(false, window, cx);
13398 let buffer = this.buffer.read(cx).read(cx);
13399 let cursor_offset = selection.head().to_offset(&buffer);
13400 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13401 let rename_end = rename_start + rename_buffer_range.len();
13402 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13403 let mut old_highlight_id = None;
13404 let old_name: Arc<str> = buffer
13405 .chunks(rename_start..rename_end, true)
13406 .map(|chunk| {
13407 if old_highlight_id.is_none() {
13408 old_highlight_id = chunk.syntax_highlight_id;
13409 }
13410 chunk.text
13411 })
13412 .collect::<String>()
13413 .into();
13414
13415 drop(buffer);
13416
13417 // Position the selection in the rename editor so that it matches the current selection.
13418 this.show_local_selections = false;
13419 let rename_editor = cx.new(|cx| {
13420 let mut editor = Editor::single_line(window, cx);
13421 editor.buffer.update(cx, |buffer, cx| {
13422 buffer.edit([(0..0, old_name.clone())], None, cx)
13423 });
13424 let rename_selection_range = match cursor_offset_in_rename_range
13425 .cmp(&cursor_offset_in_rename_range_end)
13426 {
13427 Ordering::Equal => {
13428 editor.select_all(&SelectAll, window, cx);
13429 return editor;
13430 }
13431 Ordering::Less => {
13432 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13433 }
13434 Ordering::Greater => {
13435 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13436 }
13437 };
13438 if rename_selection_range.end > old_name.len() {
13439 editor.select_all(&SelectAll, window, cx);
13440 } else {
13441 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13442 s.select_ranges([rename_selection_range]);
13443 });
13444 }
13445 editor
13446 });
13447 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13448 if e == &EditorEvent::Focused {
13449 cx.emit(EditorEvent::FocusedIn)
13450 }
13451 })
13452 .detach();
13453
13454 let write_highlights =
13455 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13456 let read_highlights =
13457 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13458 let ranges = write_highlights
13459 .iter()
13460 .flat_map(|(_, ranges)| ranges.iter())
13461 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13462 .cloned()
13463 .collect();
13464
13465 this.highlight_text::<Rename>(
13466 ranges,
13467 HighlightStyle {
13468 fade_out: Some(0.6),
13469 ..Default::default()
13470 },
13471 cx,
13472 );
13473 let rename_focus_handle = rename_editor.focus_handle(cx);
13474 window.focus(&rename_focus_handle);
13475 let block_id = this.insert_blocks(
13476 [BlockProperties {
13477 style: BlockStyle::Flex,
13478 placement: BlockPlacement::Below(range.start),
13479 height: 1,
13480 render: Arc::new({
13481 let rename_editor = rename_editor.clone();
13482 move |cx: &mut BlockContext| {
13483 let mut text_style = cx.editor_style.text.clone();
13484 if let Some(highlight_style) = old_highlight_id
13485 .and_then(|h| h.style(&cx.editor_style.syntax))
13486 {
13487 text_style = text_style.highlight(highlight_style);
13488 }
13489 div()
13490 .block_mouse_down()
13491 .pl(cx.anchor_x)
13492 .child(EditorElement::new(
13493 &rename_editor,
13494 EditorStyle {
13495 background: cx.theme().system().transparent,
13496 local_player: cx.editor_style.local_player,
13497 text: text_style,
13498 scrollbar_width: cx.editor_style.scrollbar_width,
13499 syntax: cx.editor_style.syntax.clone(),
13500 status: cx.editor_style.status.clone(),
13501 inlay_hints_style: HighlightStyle {
13502 font_weight: Some(FontWeight::BOLD),
13503 ..make_inlay_hints_style(cx.app)
13504 },
13505 inline_completion_styles: make_suggestion_styles(
13506 cx.app,
13507 ),
13508 ..EditorStyle::default()
13509 },
13510 ))
13511 .into_any_element()
13512 }
13513 }),
13514 priority: 0,
13515 }],
13516 Some(Autoscroll::fit()),
13517 cx,
13518 )[0];
13519 this.pending_rename = Some(RenameState {
13520 range,
13521 old_name,
13522 editor: rename_editor,
13523 block_id,
13524 });
13525 })?;
13526 }
13527
13528 Ok(())
13529 }))
13530 }
13531
13532 pub fn confirm_rename(
13533 &mut self,
13534 _: &ConfirmRename,
13535 window: &mut Window,
13536 cx: &mut Context<Self>,
13537 ) -> Option<Task<Result<()>>> {
13538 let rename = self.take_rename(false, window, cx)?;
13539 let workspace = self.workspace()?.downgrade();
13540 let (buffer, start) = self
13541 .buffer
13542 .read(cx)
13543 .text_anchor_for_position(rename.range.start, cx)?;
13544 let (end_buffer, _) = self
13545 .buffer
13546 .read(cx)
13547 .text_anchor_for_position(rename.range.end, cx)?;
13548 if buffer != end_buffer {
13549 return None;
13550 }
13551
13552 let old_name = rename.old_name;
13553 let new_name = rename.editor.read(cx).text(cx);
13554
13555 let rename = self.semantics_provider.as_ref()?.perform_rename(
13556 &buffer,
13557 start,
13558 new_name.clone(),
13559 cx,
13560 )?;
13561
13562 Some(cx.spawn_in(window, async move |editor, cx| {
13563 let project_transaction = rename.await?;
13564 Self::open_project_transaction(
13565 &editor,
13566 workspace,
13567 project_transaction,
13568 format!("Rename: {} → {}", old_name, new_name),
13569 cx,
13570 )
13571 .await?;
13572
13573 editor.update(cx, |editor, cx| {
13574 editor.refresh_document_highlights(cx);
13575 })?;
13576 Ok(())
13577 }))
13578 }
13579
13580 fn take_rename(
13581 &mut self,
13582 moving_cursor: bool,
13583 window: &mut Window,
13584 cx: &mut Context<Self>,
13585 ) -> Option<RenameState> {
13586 let rename = self.pending_rename.take()?;
13587 if rename.editor.focus_handle(cx).is_focused(window) {
13588 window.focus(&self.focus_handle);
13589 }
13590
13591 self.remove_blocks(
13592 [rename.block_id].into_iter().collect(),
13593 Some(Autoscroll::fit()),
13594 cx,
13595 );
13596 self.clear_highlights::<Rename>(cx);
13597 self.show_local_selections = true;
13598
13599 if moving_cursor {
13600 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13601 editor.selections.newest::<usize>(cx).head()
13602 });
13603
13604 // Update the selection to match the position of the selection inside
13605 // the rename editor.
13606 let snapshot = self.buffer.read(cx).read(cx);
13607 let rename_range = rename.range.to_offset(&snapshot);
13608 let cursor_in_editor = snapshot
13609 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13610 .min(rename_range.end);
13611 drop(snapshot);
13612
13613 self.change_selections(None, window, cx, |s| {
13614 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13615 });
13616 } else {
13617 self.refresh_document_highlights(cx);
13618 }
13619
13620 Some(rename)
13621 }
13622
13623 pub fn pending_rename(&self) -> Option<&RenameState> {
13624 self.pending_rename.as_ref()
13625 }
13626
13627 fn format(
13628 &mut self,
13629 _: &Format,
13630 window: &mut Window,
13631 cx: &mut Context<Self>,
13632 ) -> Option<Task<Result<()>>> {
13633 let project = match &self.project {
13634 Some(project) => project.clone(),
13635 None => return None,
13636 };
13637
13638 Some(self.perform_format(
13639 project,
13640 FormatTrigger::Manual,
13641 FormatTarget::Buffers,
13642 window,
13643 cx,
13644 ))
13645 }
13646
13647 fn format_selections(
13648 &mut self,
13649 _: &FormatSelections,
13650 window: &mut Window,
13651 cx: &mut Context<Self>,
13652 ) -> Option<Task<Result<()>>> {
13653 let project = match &self.project {
13654 Some(project) => project.clone(),
13655 None => return None,
13656 };
13657
13658 let ranges = self
13659 .selections
13660 .all_adjusted(cx)
13661 .into_iter()
13662 .map(|selection| selection.range())
13663 .collect_vec();
13664
13665 Some(self.perform_format(
13666 project,
13667 FormatTrigger::Manual,
13668 FormatTarget::Ranges(ranges),
13669 window,
13670 cx,
13671 ))
13672 }
13673
13674 fn perform_format(
13675 &mut self,
13676 project: Entity<Project>,
13677 trigger: FormatTrigger,
13678 target: FormatTarget,
13679 window: &mut Window,
13680 cx: &mut Context<Self>,
13681 ) -> Task<Result<()>> {
13682 let buffer = self.buffer.clone();
13683 let (buffers, target) = match target {
13684 FormatTarget::Buffers => {
13685 let mut buffers = buffer.read(cx).all_buffers();
13686 if trigger == FormatTrigger::Save {
13687 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13688 }
13689 (buffers, LspFormatTarget::Buffers)
13690 }
13691 FormatTarget::Ranges(selection_ranges) => {
13692 let multi_buffer = buffer.read(cx);
13693 let snapshot = multi_buffer.read(cx);
13694 let mut buffers = HashSet::default();
13695 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13696 BTreeMap::new();
13697 for selection_range in selection_ranges {
13698 for (buffer, buffer_range, _) in
13699 snapshot.range_to_buffer_ranges(selection_range)
13700 {
13701 let buffer_id = buffer.remote_id();
13702 let start = buffer.anchor_before(buffer_range.start);
13703 let end = buffer.anchor_after(buffer_range.end);
13704 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13705 buffer_id_to_ranges
13706 .entry(buffer_id)
13707 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13708 .or_insert_with(|| vec![start..end]);
13709 }
13710 }
13711 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13712 }
13713 };
13714
13715 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13716 let format = project.update(cx, |project, cx| {
13717 project.format(buffers, target, true, trigger, cx)
13718 });
13719
13720 cx.spawn_in(window, async move |_, cx| {
13721 let transaction = futures::select_biased! {
13722 transaction = format.log_err().fuse() => transaction,
13723 () = timeout => {
13724 log::warn!("timed out waiting for formatting");
13725 None
13726 }
13727 };
13728
13729 buffer
13730 .update(cx, |buffer, cx| {
13731 if let Some(transaction) = transaction {
13732 if !buffer.is_singleton() {
13733 buffer.push_transaction(&transaction.0, cx);
13734 }
13735 }
13736 cx.notify();
13737 })
13738 .ok();
13739
13740 Ok(())
13741 })
13742 }
13743
13744 fn organize_imports(
13745 &mut self,
13746 _: &OrganizeImports,
13747 window: &mut Window,
13748 cx: &mut Context<Self>,
13749 ) -> Option<Task<Result<()>>> {
13750 let project = match &self.project {
13751 Some(project) => project.clone(),
13752 None => return None,
13753 };
13754 Some(self.perform_code_action_kind(
13755 project,
13756 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13757 window,
13758 cx,
13759 ))
13760 }
13761
13762 fn perform_code_action_kind(
13763 &mut self,
13764 project: Entity<Project>,
13765 kind: CodeActionKind,
13766 window: &mut Window,
13767 cx: &mut Context<Self>,
13768 ) -> Task<Result<()>> {
13769 let buffer = self.buffer.clone();
13770 let buffers = buffer.read(cx).all_buffers();
13771 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13772 let apply_action = project.update(cx, |project, cx| {
13773 project.apply_code_action_kind(buffers, kind, true, cx)
13774 });
13775 cx.spawn_in(window, async move |_, cx| {
13776 let transaction = futures::select_biased! {
13777 () = timeout => {
13778 log::warn!("timed out waiting for executing code action");
13779 None
13780 }
13781 transaction = apply_action.log_err().fuse() => transaction,
13782 };
13783 buffer
13784 .update(cx, |buffer, cx| {
13785 // check if we need this
13786 if let Some(transaction) = transaction {
13787 if !buffer.is_singleton() {
13788 buffer.push_transaction(&transaction.0, cx);
13789 }
13790 }
13791 cx.notify();
13792 })
13793 .ok();
13794 Ok(())
13795 })
13796 }
13797
13798 fn restart_language_server(
13799 &mut self,
13800 _: &RestartLanguageServer,
13801 _: &mut Window,
13802 cx: &mut Context<Self>,
13803 ) {
13804 if let Some(project) = self.project.clone() {
13805 self.buffer.update(cx, |multi_buffer, cx| {
13806 project.update(cx, |project, cx| {
13807 project.restart_language_servers_for_buffers(
13808 multi_buffer.all_buffers().into_iter().collect(),
13809 cx,
13810 );
13811 });
13812 })
13813 }
13814 }
13815
13816 fn cancel_language_server_work(
13817 workspace: &mut Workspace,
13818 _: &actions::CancelLanguageServerWork,
13819 _: &mut Window,
13820 cx: &mut Context<Workspace>,
13821 ) {
13822 let project = workspace.project();
13823 let buffers = workspace
13824 .active_item(cx)
13825 .and_then(|item| item.act_as::<Editor>(cx))
13826 .map_or(HashSet::default(), |editor| {
13827 editor.read(cx).buffer.read(cx).all_buffers()
13828 });
13829 project.update(cx, |project, cx| {
13830 project.cancel_language_server_work_for_buffers(buffers, cx);
13831 });
13832 }
13833
13834 fn show_character_palette(
13835 &mut self,
13836 _: &ShowCharacterPalette,
13837 window: &mut Window,
13838 _: &mut Context<Self>,
13839 ) {
13840 window.show_character_palette();
13841 }
13842
13843 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13844 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13845 let buffer = self.buffer.read(cx).snapshot(cx);
13846 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13847 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13848 let is_valid = buffer
13849 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13850 .any(|entry| {
13851 entry.diagnostic.is_primary
13852 && !entry.range.is_empty()
13853 && entry.range.start == primary_range_start
13854 && entry.diagnostic.message == active_diagnostics.primary_message
13855 });
13856
13857 if is_valid != active_diagnostics.is_valid {
13858 active_diagnostics.is_valid = is_valid;
13859 if is_valid {
13860 let mut new_styles = HashMap::default();
13861 for (block_id, diagnostic) in &active_diagnostics.blocks {
13862 new_styles.insert(
13863 *block_id,
13864 diagnostic_block_renderer(diagnostic.clone(), None, true),
13865 );
13866 }
13867 self.display_map.update(cx, |display_map, _cx| {
13868 display_map.replace_blocks(new_styles);
13869 });
13870 } else {
13871 self.dismiss_diagnostics(cx);
13872 }
13873 }
13874 }
13875 }
13876
13877 fn activate_diagnostics(
13878 &mut self,
13879 buffer_id: BufferId,
13880 group_id: usize,
13881 window: &mut Window,
13882 cx: &mut Context<Self>,
13883 ) {
13884 self.dismiss_diagnostics(cx);
13885 let snapshot = self.snapshot(window, cx);
13886 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13887 let buffer = self.buffer.read(cx).snapshot(cx);
13888
13889 let mut primary_range = None;
13890 let mut primary_message = None;
13891 let diagnostic_group = buffer
13892 .diagnostic_group(buffer_id, group_id)
13893 .filter_map(|entry| {
13894 let start = entry.range.start;
13895 let end = entry.range.end;
13896 if snapshot.is_line_folded(MultiBufferRow(start.row))
13897 && (start.row == end.row
13898 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13899 {
13900 return None;
13901 }
13902 if entry.diagnostic.is_primary {
13903 primary_range = Some(entry.range.clone());
13904 primary_message = Some(entry.diagnostic.message.clone());
13905 }
13906 Some(entry)
13907 })
13908 .collect::<Vec<_>>();
13909 let primary_range = primary_range?;
13910 let primary_message = primary_message?;
13911
13912 let blocks = display_map
13913 .insert_blocks(
13914 diagnostic_group.iter().map(|entry| {
13915 let diagnostic = entry.diagnostic.clone();
13916 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13917 BlockProperties {
13918 style: BlockStyle::Fixed,
13919 placement: BlockPlacement::Below(
13920 buffer.anchor_after(entry.range.start),
13921 ),
13922 height: message_height,
13923 render: diagnostic_block_renderer(diagnostic, None, true),
13924 priority: 0,
13925 }
13926 }),
13927 cx,
13928 )
13929 .into_iter()
13930 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13931 .collect();
13932
13933 Some(ActiveDiagnosticGroup {
13934 primary_range: buffer.anchor_before(primary_range.start)
13935 ..buffer.anchor_after(primary_range.end),
13936 primary_message,
13937 group_id,
13938 blocks,
13939 is_valid: true,
13940 })
13941 });
13942 }
13943
13944 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13945 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13946 self.display_map.update(cx, |display_map, cx| {
13947 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13948 });
13949 cx.notify();
13950 }
13951 }
13952
13953 /// Disable inline diagnostics rendering for this editor.
13954 pub fn disable_inline_diagnostics(&mut self) {
13955 self.inline_diagnostics_enabled = false;
13956 self.inline_diagnostics_update = Task::ready(());
13957 self.inline_diagnostics.clear();
13958 }
13959
13960 pub fn inline_diagnostics_enabled(&self) -> bool {
13961 self.inline_diagnostics_enabled
13962 }
13963
13964 pub fn show_inline_diagnostics(&self) -> bool {
13965 self.show_inline_diagnostics
13966 }
13967
13968 pub fn toggle_inline_diagnostics(
13969 &mut self,
13970 _: &ToggleInlineDiagnostics,
13971 window: &mut Window,
13972 cx: &mut Context<'_, Editor>,
13973 ) {
13974 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13975 self.refresh_inline_diagnostics(false, window, cx);
13976 }
13977
13978 fn refresh_inline_diagnostics(
13979 &mut self,
13980 debounce: bool,
13981 window: &mut Window,
13982 cx: &mut Context<Self>,
13983 ) {
13984 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13985 self.inline_diagnostics_update = Task::ready(());
13986 self.inline_diagnostics.clear();
13987 return;
13988 }
13989
13990 let debounce_ms = ProjectSettings::get_global(cx)
13991 .diagnostics
13992 .inline
13993 .update_debounce_ms;
13994 let debounce = if debounce && debounce_ms > 0 {
13995 Some(Duration::from_millis(debounce_ms))
13996 } else {
13997 None
13998 };
13999 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14000 if let Some(debounce) = debounce {
14001 cx.background_executor().timer(debounce).await;
14002 }
14003 let Some(snapshot) = editor
14004 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14005 .ok()
14006 else {
14007 return;
14008 };
14009
14010 let new_inline_diagnostics = cx
14011 .background_spawn(async move {
14012 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14013 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14014 let message = diagnostic_entry
14015 .diagnostic
14016 .message
14017 .split_once('\n')
14018 .map(|(line, _)| line)
14019 .map(SharedString::new)
14020 .unwrap_or_else(|| {
14021 SharedString::from(diagnostic_entry.diagnostic.message)
14022 });
14023 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14024 let (Ok(i) | Err(i)) = inline_diagnostics
14025 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14026 inline_diagnostics.insert(
14027 i,
14028 (
14029 start_anchor,
14030 InlineDiagnostic {
14031 message,
14032 group_id: diagnostic_entry.diagnostic.group_id,
14033 start: diagnostic_entry.range.start.to_point(&snapshot),
14034 is_primary: diagnostic_entry.diagnostic.is_primary,
14035 severity: diagnostic_entry.diagnostic.severity,
14036 },
14037 ),
14038 );
14039 }
14040 inline_diagnostics
14041 })
14042 .await;
14043
14044 editor
14045 .update(cx, |editor, cx| {
14046 editor.inline_diagnostics = new_inline_diagnostics;
14047 cx.notify();
14048 })
14049 .ok();
14050 });
14051 }
14052
14053 pub fn set_selections_from_remote(
14054 &mut self,
14055 selections: Vec<Selection<Anchor>>,
14056 pending_selection: Option<Selection<Anchor>>,
14057 window: &mut Window,
14058 cx: &mut Context<Self>,
14059 ) {
14060 let old_cursor_position = self.selections.newest_anchor().head();
14061 self.selections.change_with(cx, |s| {
14062 s.select_anchors(selections);
14063 if let Some(pending_selection) = pending_selection {
14064 s.set_pending(pending_selection, SelectMode::Character);
14065 } else {
14066 s.clear_pending();
14067 }
14068 });
14069 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14070 }
14071
14072 fn push_to_selection_history(&mut self) {
14073 self.selection_history.push(SelectionHistoryEntry {
14074 selections: self.selections.disjoint_anchors(),
14075 select_next_state: self.select_next_state.clone(),
14076 select_prev_state: self.select_prev_state.clone(),
14077 add_selections_state: self.add_selections_state.clone(),
14078 });
14079 }
14080
14081 pub fn transact(
14082 &mut self,
14083 window: &mut Window,
14084 cx: &mut Context<Self>,
14085 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14086 ) -> Option<TransactionId> {
14087 self.start_transaction_at(Instant::now(), window, cx);
14088 update(self, window, cx);
14089 self.end_transaction_at(Instant::now(), cx)
14090 }
14091
14092 pub fn start_transaction_at(
14093 &mut self,
14094 now: Instant,
14095 window: &mut Window,
14096 cx: &mut Context<Self>,
14097 ) {
14098 self.end_selection(window, cx);
14099 if let Some(tx_id) = self
14100 .buffer
14101 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14102 {
14103 self.selection_history
14104 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14105 cx.emit(EditorEvent::TransactionBegun {
14106 transaction_id: tx_id,
14107 })
14108 }
14109 }
14110
14111 pub fn end_transaction_at(
14112 &mut self,
14113 now: Instant,
14114 cx: &mut Context<Self>,
14115 ) -> Option<TransactionId> {
14116 if let Some(transaction_id) = self
14117 .buffer
14118 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14119 {
14120 if let Some((_, end_selections)) =
14121 self.selection_history.transaction_mut(transaction_id)
14122 {
14123 *end_selections = Some(self.selections.disjoint_anchors());
14124 } else {
14125 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14126 }
14127
14128 cx.emit(EditorEvent::Edited { transaction_id });
14129 Some(transaction_id)
14130 } else {
14131 None
14132 }
14133 }
14134
14135 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14136 if self.selection_mark_mode {
14137 self.change_selections(None, window, cx, |s| {
14138 s.move_with(|_, sel| {
14139 sel.collapse_to(sel.head(), SelectionGoal::None);
14140 });
14141 })
14142 }
14143 self.selection_mark_mode = true;
14144 cx.notify();
14145 }
14146
14147 pub fn swap_selection_ends(
14148 &mut self,
14149 _: &actions::SwapSelectionEnds,
14150 window: &mut Window,
14151 cx: &mut Context<Self>,
14152 ) {
14153 self.change_selections(None, window, cx, |s| {
14154 s.move_with(|_, sel| {
14155 if sel.start != sel.end {
14156 sel.reversed = !sel.reversed
14157 }
14158 });
14159 });
14160 self.request_autoscroll(Autoscroll::newest(), cx);
14161 cx.notify();
14162 }
14163
14164 pub fn toggle_fold(
14165 &mut self,
14166 _: &actions::ToggleFold,
14167 window: &mut Window,
14168 cx: &mut Context<Self>,
14169 ) {
14170 if self.is_singleton(cx) {
14171 let selection = self.selections.newest::<Point>(cx);
14172
14173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14174 let range = if selection.is_empty() {
14175 let point = selection.head().to_display_point(&display_map);
14176 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14177 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14178 .to_point(&display_map);
14179 start..end
14180 } else {
14181 selection.range()
14182 };
14183 if display_map.folds_in_range(range).next().is_some() {
14184 self.unfold_lines(&Default::default(), window, cx)
14185 } else {
14186 self.fold(&Default::default(), window, cx)
14187 }
14188 } else {
14189 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14190 let buffer_ids: HashSet<_> = self
14191 .selections
14192 .disjoint_anchor_ranges()
14193 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14194 .collect();
14195
14196 let should_unfold = buffer_ids
14197 .iter()
14198 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14199
14200 for buffer_id in buffer_ids {
14201 if should_unfold {
14202 self.unfold_buffer(buffer_id, cx);
14203 } else {
14204 self.fold_buffer(buffer_id, cx);
14205 }
14206 }
14207 }
14208 }
14209
14210 pub fn toggle_fold_recursive(
14211 &mut self,
14212 _: &actions::ToggleFoldRecursive,
14213 window: &mut Window,
14214 cx: &mut Context<Self>,
14215 ) {
14216 let selection = self.selections.newest::<Point>(cx);
14217
14218 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14219 let range = if selection.is_empty() {
14220 let point = selection.head().to_display_point(&display_map);
14221 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14222 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14223 .to_point(&display_map);
14224 start..end
14225 } else {
14226 selection.range()
14227 };
14228 if display_map.folds_in_range(range).next().is_some() {
14229 self.unfold_recursive(&Default::default(), window, cx)
14230 } else {
14231 self.fold_recursive(&Default::default(), window, cx)
14232 }
14233 }
14234
14235 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14236 if self.is_singleton(cx) {
14237 let mut to_fold = Vec::new();
14238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14239 let selections = self.selections.all_adjusted(cx);
14240
14241 for selection in selections {
14242 let range = selection.range().sorted();
14243 let buffer_start_row = range.start.row;
14244
14245 if range.start.row != range.end.row {
14246 let mut found = false;
14247 let mut row = range.start.row;
14248 while row <= range.end.row {
14249 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14250 {
14251 found = true;
14252 row = crease.range().end.row + 1;
14253 to_fold.push(crease);
14254 } else {
14255 row += 1
14256 }
14257 }
14258 if found {
14259 continue;
14260 }
14261 }
14262
14263 for row in (0..=range.start.row).rev() {
14264 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14265 if crease.range().end.row >= buffer_start_row {
14266 to_fold.push(crease);
14267 if row <= range.start.row {
14268 break;
14269 }
14270 }
14271 }
14272 }
14273 }
14274
14275 self.fold_creases(to_fold, true, window, cx);
14276 } else {
14277 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14278 let buffer_ids = self
14279 .selections
14280 .disjoint_anchor_ranges()
14281 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14282 .collect::<HashSet<_>>();
14283 for buffer_id in buffer_ids {
14284 self.fold_buffer(buffer_id, cx);
14285 }
14286 }
14287 }
14288
14289 fn fold_at_level(
14290 &mut self,
14291 fold_at: &FoldAtLevel,
14292 window: &mut Window,
14293 cx: &mut Context<Self>,
14294 ) {
14295 if !self.buffer.read(cx).is_singleton() {
14296 return;
14297 }
14298
14299 let fold_at_level = fold_at.0;
14300 let snapshot = self.buffer.read(cx).snapshot(cx);
14301 let mut to_fold = Vec::new();
14302 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14303
14304 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14305 while start_row < end_row {
14306 match self
14307 .snapshot(window, cx)
14308 .crease_for_buffer_row(MultiBufferRow(start_row))
14309 {
14310 Some(crease) => {
14311 let nested_start_row = crease.range().start.row + 1;
14312 let nested_end_row = crease.range().end.row;
14313
14314 if current_level < fold_at_level {
14315 stack.push((nested_start_row, nested_end_row, current_level + 1));
14316 } else if current_level == fold_at_level {
14317 to_fold.push(crease);
14318 }
14319
14320 start_row = nested_end_row + 1;
14321 }
14322 None => start_row += 1,
14323 }
14324 }
14325 }
14326
14327 self.fold_creases(to_fold, true, window, cx);
14328 }
14329
14330 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14331 if self.buffer.read(cx).is_singleton() {
14332 let mut fold_ranges = Vec::new();
14333 let snapshot = self.buffer.read(cx).snapshot(cx);
14334
14335 for row in 0..snapshot.max_row().0 {
14336 if let Some(foldable_range) = self
14337 .snapshot(window, cx)
14338 .crease_for_buffer_row(MultiBufferRow(row))
14339 {
14340 fold_ranges.push(foldable_range);
14341 }
14342 }
14343
14344 self.fold_creases(fold_ranges, true, window, cx);
14345 } else {
14346 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14347 editor
14348 .update_in(cx, |editor, _, cx| {
14349 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14350 editor.fold_buffer(buffer_id, cx);
14351 }
14352 })
14353 .ok();
14354 });
14355 }
14356 }
14357
14358 pub fn fold_function_bodies(
14359 &mut self,
14360 _: &actions::FoldFunctionBodies,
14361 window: &mut Window,
14362 cx: &mut Context<Self>,
14363 ) {
14364 let snapshot = self.buffer.read(cx).snapshot(cx);
14365
14366 let ranges = snapshot
14367 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14368 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14369 .collect::<Vec<_>>();
14370
14371 let creases = ranges
14372 .into_iter()
14373 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14374 .collect();
14375
14376 self.fold_creases(creases, true, window, cx);
14377 }
14378
14379 pub fn fold_recursive(
14380 &mut self,
14381 _: &actions::FoldRecursive,
14382 window: &mut Window,
14383 cx: &mut Context<Self>,
14384 ) {
14385 let mut to_fold = Vec::new();
14386 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14387 let selections = self.selections.all_adjusted(cx);
14388
14389 for selection in selections {
14390 let range = selection.range().sorted();
14391 let buffer_start_row = range.start.row;
14392
14393 if range.start.row != range.end.row {
14394 let mut found = false;
14395 for row in range.start.row..=range.end.row {
14396 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14397 found = true;
14398 to_fold.push(crease);
14399 }
14400 }
14401 if found {
14402 continue;
14403 }
14404 }
14405
14406 for row in (0..=range.start.row).rev() {
14407 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14408 if crease.range().end.row >= buffer_start_row {
14409 to_fold.push(crease);
14410 } else {
14411 break;
14412 }
14413 }
14414 }
14415 }
14416
14417 self.fold_creases(to_fold, true, window, cx);
14418 }
14419
14420 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14421 let buffer_row = fold_at.buffer_row;
14422 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14423
14424 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14425 let autoscroll = self
14426 .selections
14427 .all::<Point>(cx)
14428 .iter()
14429 .any(|selection| crease.range().overlaps(&selection.range()));
14430
14431 self.fold_creases(vec![crease], autoscroll, window, cx);
14432 }
14433 }
14434
14435 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14436 if self.is_singleton(cx) {
14437 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14438 let buffer = &display_map.buffer_snapshot;
14439 let selections = self.selections.all::<Point>(cx);
14440 let ranges = selections
14441 .iter()
14442 .map(|s| {
14443 let range = s.display_range(&display_map).sorted();
14444 let mut start = range.start.to_point(&display_map);
14445 let mut end = range.end.to_point(&display_map);
14446 start.column = 0;
14447 end.column = buffer.line_len(MultiBufferRow(end.row));
14448 start..end
14449 })
14450 .collect::<Vec<_>>();
14451
14452 self.unfold_ranges(&ranges, true, true, cx);
14453 } else {
14454 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14455 let buffer_ids = self
14456 .selections
14457 .disjoint_anchor_ranges()
14458 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14459 .collect::<HashSet<_>>();
14460 for buffer_id in buffer_ids {
14461 self.unfold_buffer(buffer_id, cx);
14462 }
14463 }
14464 }
14465
14466 pub fn unfold_recursive(
14467 &mut self,
14468 _: &UnfoldRecursive,
14469 _window: &mut Window,
14470 cx: &mut Context<Self>,
14471 ) {
14472 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14473 let selections = self.selections.all::<Point>(cx);
14474 let ranges = selections
14475 .iter()
14476 .map(|s| {
14477 let mut range = s.display_range(&display_map).sorted();
14478 *range.start.column_mut() = 0;
14479 *range.end.column_mut() = display_map.line_len(range.end.row());
14480 let start = range.start.to_point(&display_map);
14481 let end = range.end.to_point(&display_map);
14482 start..end
14483 })
14484 .collect::<Vec<_>>();
14485
14486 self.unfold_ranges(&ranges, true, true, cx);
14487 }
14488
14489 pub fn unfold_at(
14490 &mut self,
14491 unfold_at: &UnfoldAt,
14492 _window: &mut Window,
14493 cx: &mut Context<Self>,
14494 ) {
14495 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14496
14497 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14498 ..Point::new(
14499 unfold_at.buffer_row.0,
14500 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14501 );
14502
14503 let autoscroll = self
14504 .selections
14505 .all::<Point>(cx)
14506 .iter()
14507 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14508
14509 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14510 }
14511
14512 pub fn unfold_all(
14513 &mut self,
14514 _: &actions::UnfoldAll,
14515 _window: &mut Window,
14516 cx: &mut Context<Self>,
14517 ) {
14518 if self.buffer.read(cx).is_singleton() {
14519 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14520 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14521 } else {
14522 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14523 editor
14524 .update(cx, |editor, cx| {
14525 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14526 editor.unfold_buffer(buffer_id, cx);
14527 }
14528 })
14529 .ok();
14530 });
14531 }
14532 }
14533
14534 pub fn fold_selected_ranges(
14535 &mut self,
14536 _: &FoldSelectedRanges,
14537 window: &mut Window,
14538 cx: &mut Context<Self>,
14539 ) {
14540 let selections = self.selections.all::<Point>(cx);
14541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14542 let line_mode = self.selections.line_mode;
14543 let ranges = selections
14544 .into_iter()
14545 .map(|s| {
14546 if line_mode {
14547 let start = Point::new(s.start.row, 0);
14548 let end = Point::new(
14549 s.end.row,
14550 display_map
14551 .buffer_snapshot
14552 .line_len(MultiBufferRow(s.end.row)),
14553 );
14554 Crease::simple(start..end, display_map.fold_placeholder.clone())
14555 } else {
14556 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14557 }
14558 })
14559 .collect::<Vec<_>>();
14560 self.fold_creases(ranges, true, window, cx);
14561 }
14562
14563 pub fn fold_ranges<T: ToOffset + Clone>(
14564 &mut self,
14565 ranges: Vec<Range<T>>,
14566 auto_scroll: bool,
14567 window: &mut Window,
14568 cx: &mut Context<Self>,
14569 ) {
14570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14571 let ranges = ranges
14572 .into_iter()
14573 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14574 .collect::<Vec<_>>();
14575 self.fold_creases(ranges, auto_scroll, window, cx);
14576 }
14577
14578 pub fn fold_creases<T: ToOffset + Clone>(
14579 &mut self,
14580 creases: Vec<Crease<T>>,
14581 auto_scroll: bool,
14582 window: &mut Window,
14583 cx: &mut Context<Self>,
14584 ) {
14585 if creases.is_empty() {
14586 return;
14587 }
14588
14589 let mut buffers_affected = HashSet::default();
14590 let multi_buffer = self.buffer().read(cx);
14591 for crease in &creases {
14592 if let Some((_, buffer, _)) =
14593 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14594 {
14595 buffers_affected.insert(buffer.read(cx).remote_id());
14596 };
14597 }
14598
14599 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14600
14601 if auto_scroll {
14602 self.request_autoscroll(Autoscroll::fit(), cx);
14603 }
14604
14605 cx.notify();
14606
14607 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14608 // Clear diagnostics block when folding a range that contains it.
14609 let snapshot = self.snapshot(window, cx);
14610 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14611 drop(snapshot);
14612 self.active_diagnostics = Some(active_diagnostics);
14613 self.dismiss_diagnostics(cx);
14614 } else {
14615 self.active_diagnostics = Some(active_diagnostics);
14616 }
14617 }
14618
14619 self.scrollbar_marker_state.dirty = true;
14620 self.folds_did_change(cx);
14621 }
14622
14623 /// Removes any folds whose ranges intersect any of the given ranges.
14624 pub fn unfold_ranges<T: ToOffset + Clone>(
14625 &mut self,
14626 ranges: &[Range<T>],
14627 inclusive: bool,
14628 auto_scroll: bool,
14629 cx: &mut Context<Self>,
14630 ) {
14631 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14632 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14633 });
14634 self.folds_did_change(cx);
14635 }
14636
14637 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14638 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14639 return;
14640 }
14641 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14642 self.display_map.update(cx, |display_map, cx| {
14643 display_map.fold_buffers([buffer_id], cx)
14644 });
14645 cx.emit(EditorEvent::BufferFoldToggled {
14646 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14647 folded: true,
14648 });
14649 cx.notify();
14650 }
14651
14652 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14653 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14654 return;
14655 }
14656 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14657 self.display_map.update(cx, |display_map, cx| {
14658 display_map.unfold_buffers([buffer_id], cx);
14659 });
14660 cx.emit(EditorEvent::BufferFoldToggled {
14661 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14662 folded: false,
14663 });
14664 cx.notify();
14665 }
14666
14667 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14668 self.display_map.read(cx).is_buffer_folded(buffer)
14669 }
14670
14671 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14672 self.display_map.read(cx).folded_buffers()
14673 }
14674
14675 /// Removes any folds with the given ranges.
14676 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14677 &mut self,
14678 ranges: &[Range<T>],
14679 type_id: TypeId,
14680 auto_scroll: bool,
14681 cx: &mut Context<Self>,
14682 ) {
14683 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14684 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14685 });
14686 self.folds_did_change(cx);
14687 }
14688
14689 fn remove_folds_with<T: ToOffset + Clone>(
14690 &mut self,
14691 ranges: &[Range<T>],
14692 auto_scroll: bool,
14693 cx: &mut Context<Self>,
14694 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14695 ) {
14696 if ranges.is_empty() {
14697 return;
14698 }
14699
14700 let mut buffers_affected = HashSet::default();
14701 let multi_buffer = self.buffer().read(cx);
14702 for range in ranges {
14703 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14704 buffers_affected.insert(buffer.read(cx).remote_id());
14705 };
14706 }
14707
14708 self.display_map.update(cx, update);
14709
14710 if auto_scroll {
14711 self.request_autoscroll(Autoscroll::fit(), cx);
14712 }
14713
14714 cx.notify();
14715 self.scrollbar_marker_state.dirty = true;
14716 self.active_indent_guides_state.dirty = true;
14717 }
14718
14719 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14720 self.display_map.read(cx).fold_placeholder.clone()
14721 }
14722
14723 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14724 self.buffer.update(cx, |buffer, cx| {
14725 buffer.set_all_diff_hunks_expanded(cx);
14726 });
14727 }
14728
14729 pub fn expand_all_diff_hunks(
14730 &mut self,
14731 _: &ExpandAllDiffHunks,
14732 _window: &mut Window,
14733 cx: &mut Context<Self>,
14734 ) {
14735 self.buffer.update(cx, |buffer, cx| {
14736 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14737 });
14738 }
14739
14740 pub fn toggle_selected_diff_hunks(
14741 &mut self,
14742 _: &ToggleSelectedDiffHunks,
14743 _window: &mut Window,
14744 cx: &mut Context<Self>,
14745 ) {
14746 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14747 self.toggle_diff_hunks_in_ranges(ranges, cx);
14748 }
14749
14750 pub fn diff_hunks_in_ranges<'a>(
14751 &'a self,
14752 ranges: &'a [Range<Anchor>],
14753 buffer: &'a MultiBufferSnapshot,
14754 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14755 ranges.iter().flat_map(move |range| {
14756 let end_excerpt_id = range.end.excerpt_id;
14757 let range = range.to_point(buffer);
14758 let mut peek_end = range.end;
14759 if range.end.row < buffer.max_row().0 {
14760 peek_end = Point::new(range.end.row + 1, 0);
14761 }
14762 buffer
14763 .diff_hunks_in_range(range.start..peek_end)
14764 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14765 })
14766 }
14767
14768 pub fn has_stageable_diff_hunks_in_ranges(
14769 &self,
14770 ranges: &[Range<Anchor>],
14771 snapshot: &MultiBufferSnapshot,
14772 ) -> bool {
14773 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14774 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14775 }
14776
14777 pub fn toggle_staged_selected_diff_hunks(
14778 &mut self,
14779 _: &::git::ToggleStaged,
14780 _: &mut Window,
14781 cx: &mut Context<Self>,
14782 ) {
14783 let snapshot = self.buffer.read(cx).snapshot(cx);
14784 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14785 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14786 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14787 }
14788
14789 pub fn stage_and_next(
14790 &mut self,
14791 _: &::git::StageAndNext,
14792 window: &mut Window,
14793 cx: &mut Context<Self>,
14794 ) {
14795 self.do_stage_or_unstage_and_next(true, window, cx);
14796 }
14797
14798 pub fn unstage_and_next(
14799 &mut self,
14800 _: &::git::UnstageAndNext,
14801 window: &mut Window,
14802 cx: &mut Context<Self>,
14803 ) {
14804 self.do_stage_or_unstage_and_next(false, window, cx);
14805 }
14806
14807 pub fn stage_or_unstage_diff_hunks(
14808 &mut self,
14809 stage: bool,
14810 ranges: Vec<Range<Anchor>>,
14811 cx: &mut Context<Self>,
14812 ) {
14813 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14814 cx.spawn(async move |this, cx| {
14815 task.await?;
14816 this.update(cx, |this, cx| {
14817 let snapshot = this.buffer.read(cx).snapshot(cx);
14818 let chunk_by = this
14819 .diff_hunks_in_ranges(&ranges, &snapshot)
14820 .chunk_by(|hunk| hunk.buffer_id);
14821 for (buffer_id, hunks) in &chunk_by {
14822 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14823 }
14824 })
14825 })
14826 .detach_and_log_err(cx);
14827 }
14828
14829 fn save_buffers_for_ranges_if_needed(
14830 &mut self,
14831 ranges: &[Range<Anchor>],
14832 cx: &mut Context<'_, Editor>,
14833 ) -> Task<Result<()>> {
14834 let multibuffer = self.buffer.read(cx);
14835 let snapshot = multibuffer.read(cx);
14836 let buffer_ids: HashSet<_> = ranges
14837 .iter()
14838 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14839 .collect();
14840 drop(snapshot);
14841
14842 let mut buffers = HashSet::default();
14843 for buffer_id in buffer_ids {
14844 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14845 let buffer = buffer_entity.read(cx);
14846 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14847 {
14848 buffers.insert(buffer_entity);
14849 }
14850 }
14851 }
14852
14853 if let Some(project) = &self.project {
14854 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14855 } else {
14856 Task::ready(Ok(()))
14857 }
14858 }
14859
14860 fn do_stage_or_unstage_and_next(
14861 &mut self,
14862 stage: bool,
14863 window: &mut Window,
14864 cx: &mut Context<Self>,
14865 ) {
14866 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14867
14868 if ranges.iter().any(|range| range.start != range.end) {
14869 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14870 return;
14871 }
14872
14873 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14874 let snapshot = self.snapshot(window, cx);
14875 let position = self.selections.newest::<Point>(cx).head();
14876 let mut row = snapshot
14877 .buffer_snapshot
14878 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14879 .find(|hunk| hunk.row_range.start.0 > position.row)
14880 .map(|hunk| hunk.row_range.start);
14881
14882 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14883 // Outside of the project diff editor, wrap around to the beginning.
14884 if !all_diff_hunks_expanded {
14885 row = row.or_else(|| {
14886 snapshot
14887 .buffer_snapshot
14888 .diff_hunks_in_range(Point::zero()..position)
14889 .find(|hunk| hunk.row_range.end.0 < position.row)
14890 .map(|hunk| hunk.row_range.start)
14891 });
14892 }
14893
14894 if let Some(row) = row {
14895 let destination = Point::new(row.0, 0);
14896 let autoscroll = Autoscroll::center();
14897
14898 self.unfold_ranges(&[destination..destination], false, false, cx);
14899 self.change_selections(Some(autoscroll), window, cx, |s| {
14900 s.select_ranges([destination..destination]);
14901 });
14902 }
14903 }
14904
14905 fn do_stage_or_unstage(
14906 &self,
14907 stage: bool,
14908 buffer_id: BufferId,
14909 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14910 cx: &mut App,
14911 ) -> Option<()> {
14912 let project = self.project.as_ref()?;
14913 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14914 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14915 let buffer_snapshot = buffer.read(cx).snapshot();
14916 let file_exists = buffer_snapshot
14917 .file()
14918 .is_some_and(|file| file.disk_state().exists());
14919 diff.update(cx, |diff, cx| {
14920 diff.stage_or_unstage_hunks(
14921 stage,
14922 &hunks
14923 .map(|hunk| buffer_diff::DiffHunk {
14924 buffer_range: hunk.buffer_range,
14925 diff_base_byte_range: hunk.diff_base_byte_range,
14926 secondary_status: hunk.secondary_status,
14927 range: Point::zero()..Point::zero(), // unused
14928 })
14929 .collect::<Vec<_>>(),
14930 &buffer_snapshot,
14931 file_exists,
14932 cx,
14933 )
14934 });
14935 None
14936 }
14937
14938 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14939 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14940 self.buffer
14941 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14942 }
14943
14944 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14945 self.buffer.update(cx, |buffer, cx| {
14946 let ranges = vec![Anchor::min()..Anchor::max()];
14947 if !buffer.all_diff_hunks_expanded()
14948 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14949 {
14950 buffer.collapse_diff_hunks(ranges, cx);
14951 true
14952 } else {
14953 false
14954 }
14955 })
14956 }
14957
14958 fn toggle_diff_hunks_in_ranges(
14959 &mut self,
14960 ranges: Vec<Range<Anchor>>,
14961 cx: &mut Context<'_, Editor>,
14962 ) {
14963 self.buffer.update(cx, |buffer, cx| {
14964 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14965 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14966 })
14967 }
14968
14969 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14970 self.buffer.update(cx, |buffer, cx| {
14971 let snapshot = buffer.snapshot(cx);
14972 let excerpt_id = range.end.excerpt_id;
14973 let point_range = range.to_point(&snapshot);
14974 let expand = !buffer.single_hunk_is_expanded(range, cx);
14975 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14976 })
14977 }
14978
14979 pub(crate) fn apply_all_diff_hunks(
14980 &mut self,
14981 _: &ApplyAllDiffHunks,
14982 window: &mut Window,
14983 cx: &mut Context<Self>,
14984 ) {
14985 let buffers = self.buffer.read(cx).all_buffers();
14986 for branch_buffer in buffers {
14987 branch_buffer.update(cx, |branch_buffer, cx| {
14988 branch_buffer.merge_into_base(Vec::new(), cx);
14989 });
14990 }
14991
14992 if let Some(project) = self.project.clone() {
14993 self.save(true, project, window, cx).detach_and_log_err(cx);
14994 }
14995 }
14996
14997 pub(crate) fn apply_selected_diff_hunks(
14998 &mut self,
14999 _: &ApplyDiffHunk,
15000 window: &mut Window,
15001 cx: &mut Context<Self>,
15002 ) {
15003 let snapshot = self.snapshot(window, cx);
15004 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15005 let mut ranges_by_buffer = HashMap::default();
15006 self.transact(window, cx, |editor, _window, cx| {
15007 for hunk in hunks {
15008 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15009 ranges_by_buffer
15010 .entry(buffer.clone())
15011 .or_insert_with(Vec::new)
15012 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15013 }
15014 }
15015
15016 for (buffer, ranges) in ranges_by_buffer {
15017 buffer.update(cx, |buffer, cx| {
15018 buffer.merge_into_base(ranges, cx);
15019 });
15020 }
15021 });
15022
15023 if let Some(project) = self.project.clone() {
15024 self.save(true, project, window, cx).detach_and_log_err(cx);
15025 }
15026 }
15027
15028 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15029 if hovered != self.gutter_hovered {
15030 self.gutter_hovered = hovered;
15031 cx.notify();
15032 }
15033 }
15034
15035 pub fn insert_blocks(
15036 &mut self,
15037 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15038 autoscroll: Option<Autoscroll>,
15039 cx: &mut Context<Self>,
15040 ) -> Vec<CustomBlockId> {
15041 let blocks = self
15042 .display_map
15043 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15044 if let Some(autoscroll) = autoscroll {
15045 self.request_autoscroll(autoscroll, cx);
15046 }
15047 cx.notify();
15048 blocks
15049 }
15050
15051 pub fn resize_blocks(
15052 &mut self,
15053 heights: HashMap<CustomBlockId, u32>,
15054 autoscroll: Option<Autoscroll>,
15055 cx: &mut Context<Self>,
15056 ) {
15057 self.display_map
15058 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15059 if let Some(autoscroll) = autoscroll {
15060 self.request_autoscroll(autoscroll, cx);
15061 }
15062 cx.notify();
15063 }
15064
15065 pub fn replace_blocks(
15066 &mut self,
15067 renderers: HashMap<CustomBlockId, RenderBlock>,
15068 autoscroll: Option<Autoscroll>,
15069 cx: &mut Context<Self>,
15070 ) {
15071 self.display_map
15072 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15073 if let Some(autoscroll) = autoscroll {
15074 self.request_autoscroll(autoscroll, cx);
15075 }
15076 cx.notify();
15077 }
15078
15079 pub fn remove_blocks(
15080 &mut self,
15081 block_ids: HashSet<CustomBlockId>,
15082 autoscroll: Option<Autoscroll>,
15083 cx: &mut Context<Self>,
15084 ) {
15085 self.display_map.update(cx, |display_map, cx| {
15086 display_map.remove_blocks(block_ids, cx)
15087 });
15088 if let Some(autoscroll) = autoscroll {
15089 self.request_autoscroll(autoscroll, cx);
15090 }
15091 cx.notify();
15092 }
15093
15094 pub fn row_for_block(
15095 &self,
15096 block_id: CustomBlockId,
15097 cx: &mut Context<Self>,
15098 ) -> Option<DisplayRow> {
15099 self.display_map
15100 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15101 }
15102
15103 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15104 self.focused_block = Some(focused_block);
15105 }
15106
15107 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15108 self.focused_block.take()
15109 }
15110
15111 pub fn insert_creases(
15112 &mut self,
15113 creases: impl IntoIterator<Item = Crease<Anchor>>,
15114 cx: &mut Context<Self>,
15115 ) -> Vec<CreaseId> {
15116 self.display_map
15117 .update(cx, |map, cx| map.insert_creases(creases, cx))
15118 }
15119
15120 pub fn remove_creases(
15121 &mut self,
15122 ids: impl IntoIterator<Item = CreaseId>,
15123 cx: &mut Context<Self>,
15124 ) {
15125 self.display_map
15126 .update(cx, |map, cx| map.remove_creases(ids, cx));
15127 }
15128
15129 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15130 self.display_map
15131 .update(cx, |map, cx| map.snapshot(cx))
15132 .longest_row()
15133 }
15134
15135 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15136 self.display_map
15137 .update(cx, |map, cx| map.snapshot(cx))
15138 .max_point()
15139 }
15140
15141 pub fn text(&self, cx: &App) -> String {
15142 self.buffer.read(cx).read(cx).text()
15143 }
15144
15145 pub fn is_empty(&self, cx: &App) -> bool {
15146 self.buffer.read(cx).read(cx).is_empty()
15147 }
15148
15149 pub fn text_option(&self, cx: &App) -> Option<String> {
15150 let text = self.text(cx);
15151 let text = text.trim();
15152
15153 if text.is_empty() {
15154 return None;
15155 }
15156
15157 Some(text.to_string())
15158 }
15159
15160 pub fn set_text(
15161 &mut self,
15162 text: impl Into<Arc<str>>,
15163 window: &mut Window,
15164 cx: &mut Context<Self>,
15165 ) {
15166 self.transact(window, cx, |this, _, cx| {
15167 this.buffer
15168 .read(cx)
15169 .as_singleton()
15170 .expect("you can only call set_text on editors for singleton buffers")
15171 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15172 });
15173 }
15174
15175 pub fn display_text(&self, cx: &mut App) -> String {
15176 self.display_map
15177 .update(cx, |map, cx| map.snapshot(cx))
15178 .text()
15179 }
15180
15181 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15182 let mut wrap_guides = smallvec::smallvec![];
15183
15184 if self.show_wrap_guides == Some(false) {
15185 return wrap_guides;
15186 }
15187
15188 let settings = self.buffer.read(cx).language_settings(cx);
15189 if settings.show_wrap_guides {
15190 match self.soft_wrap_mode(cx) {
15191 SoftWrap::Column(soft_wrap) => {
15192 wrap_guides.push((soft_wrap as usize, true));
15193 }
15194 SoftWrap::Bounded(soft_wrap) => {
15195 wrap_guides.push((soft_wrap as usize, true));
15196 }
15197 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15198 }
15199 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15200 }
15201
15202 wrap_guides
15203 }
15204
15205 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15206 let settings = self.buffer.read(cx).language_settings(cx);
15207 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15208 match mode {
15209 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15210 SoftWrap::None
15211 }
15212 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15213 language_settings::SoftWrap::PreferredLineLength => {
15214 SoftWrap::Column(settings.preferred_line_length)
15215 }
15216 language_settings::SoftWrap::Bounded => {
15217 SoftWrap::Bounded(settings.preferred_line_length)
15218 }
15219 }
15220 }
15221
15222 pub fn set_soft_wrap_mode(
15223 &mut self,
15224 mode: language_settings::SoftWrap,
15225
15226 cx: &mut Context<Self>,
15227 ) {
15228 self.soft_wrap_mode_override = Some(mode);
15229 cx.notify();
15230 }
15231
15232 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15233 self.hard_wrap = hard_wrap;
15234 cx.notify();
15235 }
15236
15237 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15238 self.text_style_refinement = Some(style);
15239 }
15240
15241 /// called by the Element so we know what style we were most recently rendered with.
15242 pub(crate) fn set_style(
15243 &mut self,
15244 style: EditorStyle,
15245 window: &mut Window,
15246 cx: &mut Context<Self>,
15247 ) {
15248 let rem_size = window.rem_size();
15249 self.display_map.update(cx, |map, cx| {
15250 map.set_font(
15251 style.text.font(),
15252 style.text.font_size.to_pixels(rem_size),
15253 cx,
15254 )
15255 });
15256 self.style = Some(style);
15257 }
15258
15259 pub fn style(&self) -> Option<&EditorStyle> {
15260 self.style.as_ref()
15261 }
15262
15263 // Called by the element. This method is not designed to be called outside of the editor
15264 // element's layout code because it does not notify when rewrapping is computed synchronously.
15265 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15266 self.display_map
15267 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15268 }
15269
15270 pub fn set_soft_wrap(&mut self) {
15271 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15272 }
15273
15274 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15275 if self.soft_wrap_mode_override.is_some() {
15276 self.soft_wrap_mode_override.take();
15277 } else {
15278 let soft_wrap = match self.soft_wrap_mode(cx) {
15279 SoftWrap::GitDiff => return,
15280 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15281 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15282 language_settings::SoftWrap::None
15283 }
15284 };
15285 self.soft_wrap_mode_override = Some(soft_wrap);
15286 }
15287 cx.notify();
15288 }
15289
15290 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15291 let Some(workspace) = self.workspace() else {
15292 return;
15293 };
15294 let fs = workspace.read(cx).app_state().fs.clone();
15295 let current_show = TabBarSettings::get_global(cx).show;
15296 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15297 setting.show = Some(!current_show);
15298 });
15299 }
15300
15301 pub fn toggle_indent_guides(
15302 &mut self,
15303 _: &ToggleIndentGuides,
15304 _: &mut Window,
15305 cx: &mut Context<Self>,
15306 ) {
15307 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15308 self.buffer
15309 .read(cx)
15310 .language_settings(cx)
15311 .indent_guides
15312 .enabled
15313 });
15314 self.show_indent_guides = Some(!currently_enabled);
15315 cx.notify();
15316 }
15317
15318 fn should_show_indent_guides(&self) -> Option<bool> {
15319 self.show_indent_guides
15320 }
15321
15322 pub fn toggle_line_numbers(
15323 &mut self,
15324 _: &ToggleLineNumbers,
15325 _: &mut Window,
15326 cx: &mut Context<Self>,
15327 ) {
15328 let mut editor_settings = EditorSettings::get_global(cx).clone();
15329 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15330 EditorSettings::override_global(editor_settings, cx);
15331 }
15332
15333 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15334 if let Some(show_line_numbers) = self.show_line_numbers {
15335 return show_line_numbers;
15336 }
15337 EditorSettings::get_global(cx).gutter.line_numbers
15338 }
15339
15340 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15341 self.use_relative_line_numbers
15342 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15343 }
15344
15345 pub fn toggle_relative_line_numbers(
15346 &mut self,
15347 _: &ToggleRelativeLineNumbers,
15348 _: &mut Window,
15349 cx: &mut Context<Self>,
15350 ) {
15351 let is_relative = self.should_use_relative_line_numbers(cx);
15352 self.set_relative_line_number(Some(!is_relative), cx)
15353 }
15354
15355 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15356 self.use_relative_line_numbers = is_relative;
15357 cx.notify();
15358 }
15359
15360 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15361 self.show_gutter = show_gutter;
15362 cx.notify();
15363 }
15364
15365 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15366 self.show_scrollbars = show_scrollbars;
15367 cx.notify();
15368 }
15369
15370 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15371 self.show_line_numbers = Some(show_line_numbers);
15372 cx.notify();
15373 }
15374
15375 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15376 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15377 cx.notify();
15378 }
15379
15380 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15381 self.show_code_actions = Some(show_code_actions);
15382 cx.notify();
15383 }
15384
15385 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15386 self.show_runnables = Some(show_runnables);
15387 cx.notify();
15388 }
15389
15390 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15391 self.show_breakpoints = Some(show_breakpoints);
15392 cx.notify();
15393 }
15394
15395 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15396 if self.display_map.read(cx).masked != masked {
15397 self.display_map.update(cx, |map, _| map.masked = masked);
15398 }
15399 cx.notify()
15400 }
15401
15402 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15403 self.show_wrap_guides = Some(show_wrap_guides);
15404 cx.notify();
15405 }
15406
15407 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15408 self.show_indent_guides = Some(show_indent_guides);
15409 cx.notify();
15410 }
15411
15412 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15413 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15414 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15415 if let Some(dir) = file.abs_path(cx).parent() {
15416 return Some(dir.to_owned());
15417 }
15418 }
15419
15420 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15421 return Some(project_path.path.to_path_buf());
15422 }
15423 }
15424
15425 None
15426 }
15427
15428 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15429 self.active_excerpt(cx)?
15430 .1
15431 .read(cx)
15432 .file()
15433 .and_then(|f| f.as_local())
15434 }
15435
15436 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15437 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15438 let buffer = buffer.read(cx);
15439 if let Some(project_path) = buffer.project_path(cx) {
15440 let project = self.project.as_ref()?.read(cx);
15441 project.absolute_path(&project_path, cx)
15442 } else {
15443 buffer
15444 .file()
15445 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15446 }
15447 })
15448 }
15449
15450 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15451 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15452 let project_path = buffer.read(cx).project_path(cx)?;
15453 let project = self.project.as_ref()?.read(cx);
15454 let entry = project.entry_for_path(&project_path, cx)?;
15455 let path = entry.path.to_path_buf();
15456 Some(path)
15457 })
15458 }
15459
15460 pub fn reveal_in_finder(
15461 &mut self,
15462 _: &RevealInFileManager,
15463 _window: &mut Window,
15464 cx: &mut Context<Self>,
15465 ) {
15466 if let Some(target) = self.target_file(cx) {
15467 cx.reveal_path(&target.abs_path(cx));
15468 }
15469 }
15470
15471 pub fn copy_path(
15472 &mut self,
15473 _: &zed_actions::workspace::CopyPath,
15474 _window: &mut Window,
15475 cx: &mut Context<Self>,
15476 ) {
15477 if let Some(path) = self.target_file_abs_path(cx) {
15478 if let Some(path) = path.to_str() {
15479 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15480 }
15481 }
15482 }
15483
15484 pub fn copy_relative_path(
15485 &mut self,
15486 _: &zed_actions::workspace::CopyRelativePath,
15487 _window: &mut Window,
15488 cx: &mut Context<Self>,
15489 ) {
15490 if let Some(path) = self.target_file_path(cx) {
15491 if let Some(path) = path.to_str() {
15492 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15493 }
15494 }
15495 }
15496
15497 pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15498 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15499 buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15500 } else {
15501 None
15502 }
15503 }
15504
15505 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15506 let _ = maybe!({
15507 let breakpoint_store = self.breakpoint_store.as_ref()?;
15508
15509 let Some((_, _, active_position)) =
15510 breakpoint_store.read(cx).active_position().cloned()
15511 else {
15512 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15513 return None;
15514 };
15515
15516 let snapshot = self
15517 .project
15518 .as_ref()?
15519 .read(cx)
15520 .buffer_for_id(active_position.buffer_id?, cx)?
15521 .read(cx)
15522 .snapshot();
15523
15524 for (id, ExcerptRange { context, .. }) in self
15525 .buffer
15526 .read(cx)
15527 .excerpts_for_buffer(active_position.buffer_id?, cx)
15528 {
15529 if context.start.cmp(&active_position, &snapshot).is_ge()
15530 || context.end.cmp(&active_position, &snapshot).is_lt()
15531 {
15532 continue;
15533 }
15534 let snapshot = self.buffer.read(cx).snapshot(cx);
15535 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15536
15537 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15538 self.go_to_line::<DebugCurrentRowHighlight>(
15539 multibuffer_anchor,
15540 Some(cx.theme().colors().editor_debugger_active_line_background),
15541 window,
15542 cx,
15543 );
15544
15545 cx.notify();
15546 }
15547
15548 Some(())
15549 });
15550 }
15551
15552 pub fn copy_file_name_without_extension(
15553 &mut self,
15554 _: &CopyFileNameWithoutExtension,
15555 _: &mut Window,
15556 cx: &mut Context<Self>,
15557 ) {
15558 if let Some(file) = self.target_file(cx) {
15559 if let Some(file_stem) = file.path().file_stem() {
15560 if let Some(name) = file_stem.to_str() {
15561 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15562 }
15563 }
15564 }
15565 }
15566
15567 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15568 if let Some(file) = self.target_file(cx) {
15569 if let Some(file_name) = file.path().file_name() {
15570 if let Some(name) = file_name.to_str() {
15571 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15572 }
15573 }
15574 }
15575 }
15576
15577 pub fn toggle_git_blame(
15578 &mut self,
15579 _: &::git::Blame,
15580 window: &mut Window,
15581 cx: &mut Context<Self>,
15582 ) {
15583 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15584
15585 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15586 self.start_git_blame(true, window, cx);
15587 }
15588
15589 cx.notify();
15590 }
15591
15592 pub fn toggle_git_blame_inline(
15593 &mut self,
15594 _: &ToggleGitBlameInline,
15595 window: &mut Window,
15596 cx: &mut Context<Self>,
15597 ) {
15598 self.toggle_git_blame_inline_internal(true, window, cx);
15599 cx.notify();
15600 }
15601
15602 pub fn git_blame_inline_enabled(&self) -> bool {
15603 self.git_blame_inline_enabled
15604 }
15605
15606 pub fn toggle_selection_menu(
15607 &mut self,
15608 _: &ToggleSelectionMenu,
15609 _: &mut Window,
15610 cx: &mut Context<Self>,
15611 ) {
15612 self.show_selection_menu = self
15613 .show_selection_menu
15614 .map(|show_selections_menu| !show_selections_menu)
15615 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15616
15617 cx.notify();
15618 }
15619
15620 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15621 self.show_selection_menu
15622 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15623 }
15624
15625 fn start_git_blame(
15626 &mut self,
15627 user_triggered: bool,
15628 window: &mut Window,
15629 cx: &mut Context<Self>,
15630 ) {
15631 if let Some(project) = self.project.as_ref() {
15632 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15633 return;
15634 };
15635
15636 if buffer.read(cx).file().is_none() {
15637 return;
15638 }
15639
15640 let focused = self.focus_handle(cx).contains_focused(window, cx);
15641
15642 let project = project.clone();
15643 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15644 self.blame_subscription =
15645 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15646 self.blame = Some(blame);
15647 }
15648 }
15649
15650 fn toggle_git_blame_inline_internal(
15651 &mut self,
15652 user_triggered: bool,
15653 window: &mut Window,
15654 cx: &mut Context<Self>,
15655 ) {
15656 if self.git_blame_inline_enabled {
15657 self.git_blame_inline_enabled = false;
15658 self.show_git_blame_inline = false;
15659 self.show_git_blame_inline_delay_task.take();
15660 } else {
15661 self.git_blame_inline_enabled = true;
15662 self.start_git_blame_inline(user_triggered, window, cx);
15663 }
15664
15665 cx.notify();
15666 }
15667
15668 fn start_git_blame_inline(
15669 &mut self,
15670 user_triggered: bool,
15671 window: &mut Window,
15672 cx: &mut Context<Self>,
15673 ) {
15674 self.start_git_blame(user_triggered, window, cx);
15675
15676 if ProjectSettings::get_global(cx)
15677 .git
15678 .inline_blame_delay()
15679 .is_some()
15680 {
15681 self.start_inline_blame_timer(window, cx);
15682 } else {
15683 self.show_git_blame_inline = true
15684 }
15685 }
15686
15687 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15688 self.blame.as_ref()
15689 }
15690
15691 pub fn show_git_blame_gutter(&self) -> bool {
15692 self.show_git_blame_gutter
15693 }
15694
15695 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15696 self.show_git_blame_gutter && self.has_blame_entries(cx)
15697 }
15698
15699 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15700 self.show_git_blame_inline
15701 && (self.focus_handle.is_focused(window)
15702 || self
15703 .git_blame_inline_tooltip
15704 .as_ref()
15705 .and_then(|t| t.upgrade())
15706 .is_some())
15707 && !self.newest_selection_head_on_empty_line(cx)
15708 && self.has_blame_entries(cx)
15709 }
15710
15711 fn has_blame_entries(&self, cx: &App) -> bool {
15712 self.blame()
15713 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15714 }
15715
15716 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15717 let cursor_anchor = self.selections.newest_anchor().head();
15718
15719 let snapshot = self.buffer.read(cx).snapshot(cx);
15720 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15721
15722 snapshot.line_len(buffer_row) == 0
15723 }
15724
15725 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15726 let buffer_and_selection = maybe!({
15727 let selection = self.selections.newest::<Point>(cx);
15728 let selection_range = selection.range();
15729
15730 let multi_buffer = self.buffer().read(cx);
15731 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15732 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15733
15734 let (buffer, range, _) = if selection.reversed {
15735 buffer_ranges.first()
15736 } else {
15737 buffer_ranges.last()
15738 }?;
15739
15740 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15741 ..text::ToPoint::to_point(&range.end, &buffer).row;
15742 Some((
15743 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15744 selection,
15745 ))
15746 });
15747
15748 let Some((buffer, selection)) = buffer_and_selection else {
15749 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15750 };
15751
15752 let Some(project) = self.project.as_ref() else {
15753 return Task::ready(Err(anyhow!("editor does not have project")));
15754 };
15755
15756 project.update(cx, |project, cx| {
15757 project.get_permalink_to_line(&buffer, selection, cx)
15758 })
15759 }
15760
15761 pub fn copy_permalink_to_line(
15762 &mut self,
15763 _: &CopyPermalinkToLine,
15764 window: &mut Window,
15765 cx: &mut Context<Self>,
15766 ) {
15767 let permalink_task = self.get_permalink_to_line(cx);
15768 let workspace = self.workspace();
15769
15770 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15771 Ok(permalink) => {
15772 cx.update(|_, cx| {
15773 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15774 })
15775 .ok();
15776 }
15777 Err(err) => {
15778 let message = format!("Failed to copy permalink: {err}");
15779
15780 Err::<(), anyhow::Error>(err).log_err();
15781
15782 if let Some(workspace) = workspace {
15783 workspace
15784 .update_in(cx, |workspace, _, cx| {
15785 struct CopyPermalinkToLine;
15786
15787 workspace.show_toast(
15788 Toast::new(
15789 NotificationId::unique::<CopyPermalinkToLine>(),
15790 message,
15791 ),
15792 cx,
15793 )
15794 })
15795 .ok();
15796 }
15797 }
15798 })
15799 .detach();
15800 }
15801
15802 pub fn copy_file_location(
15803 &mut self,
15804 _: &CopyFileLocation,
15805 _: &mut Window,
15806 cx: &mut Context<Self>,
15807 ) {
15808 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15809 if let Some(file) = self.target_file(cx) {
15810 if let Some(path) = file.path().to_str() {
15811 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15812 }
15813 }
15814 }
15815
15816 pub fn open_permalink_to_line(
15817 &mut self,
15818 _: &OpenPermalinkToLine,
15819 window: &mut Window,
15820 cx: &mut Context<Self>,
15821 ) {
15822 let permalink_task = self.get_permalink_to_line(cx);
15823 let workspace = self.workspace();
15824
15825 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15826 Ok(permalink) => {
15827 cx.update(|_, cx| {
15828 cx.open_url(permalink.as_ref());
15829 })
15830 .ok();
15831 }
15832 Err(err) => {
15833 let message = format!("Failed to open permalink: {err}");
15834
15835 Err::<(), anyhow::Error>(err).log_err();
15836
15837 if let Some(workspace) = workspace {
15838 workspace
15839 .update(cx, |workspace, cx| {
15840 struct OpenPermalinkToLine;
15841
15842 workspace.show_toast(
15843 Toast::new(
15844 NotificationId::unique::<OpenPermalinkToLine>(),
15845 message,
15846 ),
15847 cx,
15848 )
15849 })
15850 .ok();
15851 }
15852 }
15853 })
15854 .detach();
15855 }
15856
15857 pub fn insert_uuid_v4(
15858 &mut self,
15859 _: &InsertUuidV4,
15860 window: &mut Window,
15861 cx: &mut Context<Self>,
15862 ) {
15863 self.insert_uuid(UuidVersion::V4, window, cx);
15864 }
15865
15866 pub fn insert_uuid_v7(
15867 &mut self,
15868 _: &InsertUuidV7,
15869 window: &mut Window,
15870 cx: &mut Context<Self>,
15871 ) {
15872 self.insert_uuid(UuidVersion::V7, window, cx);
15873 }
15874
15875 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15876 self.transact(window, cx, |this, window, cx| {
15877 let edits = this
15878 .selections
15879 .all::<Point>(cx)
15880 .into_iter()
15881 .map(|selection| {
15882 let uuid = match version {
15883 UuidVersion::V4 => uuid::Uuid::new_v4(),
15884 UuidVersion::V7 => uuid::Uuid::now_v7(),
15885 };
15886
15887 (selection.range(), uuid.to_string())
15888 });
15889 this.edit(edits, cx);
15890 this.refresh_inline_completion(true, false, window, cx);
15891 });
15892 }
15893
15894 pub fn open_selections_in_multibuffer(
15895 &mut self,
15896 _: &OpenSelectionsInMultibuffer,
15897 window: &mut Window,
15898 cx: &mut Context<Self>,
15899 ) {
15900 let multibuffer = self.buffer.read(cx);
15901
15902 let Some(buffer) = multibuffer.as_singleton() else {
15903 return;
15904 };
15905
15906 let Some(workspace) = self.workspace() else {
15907 return;
15908 };
15909
15910 let locations = self
15911 .selections
15912 .disjoint_anchors()
15913 .iter()
15914 .map(|range| Location {
15915 buffer: buffer.clone(),
15916 range: range.start.text_anchor..range.end.text_anchor,
15917 })
15918 .collect::<Vec<_>>();
15919
15920 let title = multibuffer.title(cx).to_string();
15921
15922 cx.spawn_in(window, async move |_, cx| {
15923 workspace.update_in(cx, |workspace, window, cx| {
15924 Self::open_locations_in_multibuffer(
15925 workspace,
15926 locations,
15927 format!("Selections for '{title}'"),
15928 false,
15929 MultibufferSelectionMode::All,
15930 window,
15931 cx,
15932 );
15933 })
15934 })
15935 .detach();
15936 }
15937
15938 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15939 /// last highlight added will be used.
15940 ///
15941 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15942 pub fn highlight_rows<T: 'static>(
15943 &mut self,
15944 range: Range<Anchor>,
15945 color: Hsla,
15946 should_autoscroll: bool,
15947 cx: &mut Context<Self>,
15948 ) {
15949 let snapshot = self.buffer().read(cx).snapshot(cx);
15950 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15951 let ix = row_highlights.binary_search_by(|highlight| {
15952 Ordering::Equal
15953 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15954 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15955 });
15956
15957 if let Err(mut ix) = ix {
15958 let index = post_inc(&mut self.highlight_order);
15959
15960 // If this range intersects with the preceding highlight, then merge it with
15961 // the preceding highlight. Otherwise insert a new highlight.
15962 let mut merged = false;
15963 if ix > 0 {
15964 let prev_highlight = &mut row_highlights[ix - 1];
15965 if prev_highlight
15966 .range
15967 .end
15968 .cmp(&range.start, &snapshot)
15969 .is_ge()
15970 {
15971 ix -= 1;
15972 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15973 prev_highlight.range.end = range.end;
15974 }
15975 merged = true;
15976 prev_highlight.index = index;
15977 prev_highlight.color = color;
15978 prev_highlight.should_autoscroll = should_autoscroll;
15979 }
15980 }
15981
15982 if !merged {
15983 row_highlights.insert(
15984 ix,
15985 RowHighlight {
15986 range: range.clone(),
15987 index,
15988 color,
15989 should_autoscroll,
15990 },
15991 );
15992 }
15993
15994 // If any of the following highlights intersect with this one, merge them.
15995 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15996 let highlight = &row_highlights[ix];
15997 if next_highlight
15998 .range
15999 .start
16000 .cmp(&highlight.range.end, &snapshot)
16001 .is_le()
16002 {
16003 if next_highlight
16004 .range
16005 .end
16006 .cmp(&highlight.range.end, &snapshot)
16007 .is_gt()
16008 {
16009 row_highlights[ix].range.end = next_highlight.range.end;
16010 }
16011 row_highlights.remove(ix + 1);
16012 } else {
16013 break;
16014 }
16015 }
16016 }
16017 }
16018
16019 /// Remove any highlighted row ranges of the given type that intersect the
16020 /// given ranges.
16021 pub fn remove_highlighted_rows<T: 'static>(
16022 &mut self,
16023 ranges_to_remove: Vec<Range<Anchor>>,
16024 cx: &mut Context<Self>,
16025 ) {
16026 let snapshot = self.buffer().read(cx).snapshot(cx);
16027 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16028 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16029 row_highlights.retain(|highlight| {
16030 while let Some(range_to_remove) = ranges_to_remove.peek() {
16031 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16032 Ordering::Less | Ordering::Equal => {
16033 ranges_to_remove.next();
16034 }
16035 Ordering::Greater => {
16036 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16037 Ordering::Less | Ordering::Equal => {
16038 return false;
16039 }
16040 Ordering::Greater => break,
16041 }
16042 }
16043 }
16044 }
16045
16046 true
16047 })
16048 }
16049
16050 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16051 pub fn clear_row_highlights<T: 'static>(&mut self) {
16052 self.highlighted_rows.remove(&TypeId::of::<T>());
16053 }
16054
16055 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16056 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16057 self.highlighted_rows
16058 .get(&TypeId::of::<T>())
16059 .map_or(&[] as &[_], |vec| vec.as_slice())
16060 .iter()
16061 .map(|highlight| (highlight.range.clone(), highlight.color))
16062 }
16063
16064 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16065 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16066 /// Allows to ignore certain kinds of highlights.
16067 pub fn highlighted_display_rows(
16068 &self,
16069 window: &mut Window,
16070 cx: &mut App,
16071 ) -> BTreeMap<DisplayRow, LineHighlight> {
16072 let snapshot = self.snapshot(window, cx);
16073 let mut used_highlight_orders = HashMap::default();
16074 self.highlighted_rows
16075 .iter()
16076 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16077 .fold(
16078 BTreeMap::<DisplayRow, LineHighlight>::new(),
16079 |mut unique_rows, highlight| {
16080 let start = highlight.range.start.to_display_point(&snapshot);
16081 let end = highlight.range.end.to_display_point(&snapshot);
16082 let start_row = start.row().0;
16083 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16084 && end.column() == 0
16085 {
16086 end.row().0.saturating_sub(1)
16087 } else {
16088 end.row().0
16089 };
16090 for row in start_row..=end_row {
16091 let used_index =
16092 used_highlight_orders.entry(row).or_insert(highlight.index);
16093 if highlight.index >= *used_index {
16094 *used_index = highlight.index;
16095 unique_rows.insert(DisplayRow(row), highlight.color.into());
16096 }
16097 }
16098 unique_rows
16099 },
16100 )
16101 }
16102
16103 pub fn highlighted_display_row_for_autoscroll(
16104 &self,
16105 snapshot: &DisplaySnapshot,
16106 ) -> Option<DisplayRow> {
16107 self.highlighted_rows
16108 .values()
16109 .flat_map(|highlighted_rows| highlighted_rows.iter())
16110 .filter_map(|highlight| {
16111 if highlight.should_autoscroll {
16112 Some(highlight.range.start.to_display_point(snapshot).row())
16113 } else {
16114 None
16115 }
16116 })
16117 .min()
16118 }
16119
16120 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16121 self.highlight_background::<SearchWithinRange>(
16122 ranges,
16123 |colors| colors.editor_document_highlight_read_background,
16124 cx,
16125 )
16126 }
16127
16128 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16129 self.breadcrumb_header = Some(new_header);
16130 }
16131
16132 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16133 self.clear_background_highlights::<SearchWithinRange>(cx);
16134 }
16135
16136 pub fn highlight_background<T: 'static>(
16137 &mut self,
16138 ranges: &[Range<Anchor>],
16139 color_fetcher: fn(&ThemeColors) -> Hsla,
16140 cx: &mut Context<Self>,
16141 ) {
16142 self.background_highlights
16143 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16144 self.scrollbar_marker_state.dirty = true;
16145 cx.notify();
16146 }
16147
16148 pub fn clear_background_highlights<T: 'static>(
16149 &mut self,
16150 cx: &mut Context<Self>,
16151 ) -> Option<BackgroundHighlight> {
16152 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16153 if !text_highlights.1.is_empty() {
16154 self.scrollbar_marker_state.dirty = true;
16155 cx.notify();
16156 }
16157 Some(text_highlights)
16158 }
16159
16160 pub fn highlight_gutter<T: 'static>(
16161 &mut self,
16162 ranges: &[Range<Anchor>],
16163 color_fetcher: fn(&App) -> Hsla,
16164 cx: &mut Context<Self>,
16165 ) {
16166 self.gutter_highlights
16167 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16168 cx.notify();
16169 }
16170
16171 pub fn clear_gutter_highlights<T: 'static>(
16172 &mut self,
16173 cx: &mut Context<Self>,
16174 ) -> Option<GutterHighlight> {
16175 cx.notify();
16176 self.gutter_highlights.remove(&TypeId::of::<T>())
16177 }
16178
16179 #[cfg(feature = "test-support")]
16180 pub fn all_text_background_highlights(
16181 &self,
16182 window: &mut Window,
16183 cx: &mut Context<Self>,
16184 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16185 let snapshot = self.snapshot(window, cx);
16186 let buffer = &snapshot.buffer_snapshot;
16187 let start = buffer.anchor_before(0);
16188 let end = buffer.anchor_after(buffer.len());
16189 let theme = cx.theme().colors();
16190 self.background_highlights_in_range(start..end, &snapshot, theme)
16191 }
16192
16193 #[cfg(feature = "test-support")]
16194 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16195 let snapshot = self.buffer().read(cx).snapshot(cx);
16196
16197 let highlights = self
16198 .background_highlights
16199 .get(&TypeId::of::<items::BufferSearchHighlights>());
16200
16201 if let Some((_color, ranges)) = highlights {
16202 ranges
16203 .iter()
16204 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16205 .collect_vec()
16206 } else {
16207 vec![]
16208 }
16209 }
16210
16211 fn document_highlights_for_position<'a>(
16212 &'a self,
16213 position: Anchor,
16214 buffer: &'a MultiBufferSnapshot,
16215 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16216 let read_highlights = self
16217 .background_highlights
16218 .get(&TypeId::of::<DocumentHighlightRead>())
16219 .map(|h| &h.1);
16220 let write_highlights = self
16221 .background_highlights
16222 .get(&TypeId::of::<DocumentHighlightWrite>())
16223 .map(|h| &h.1);
16224 let left_position = position.bias_left(buffer);
16225 let right_position = position.bias_right(buffer);
16226 read_highlights
16227 .into_iter()
16228 .chain(write_highlights)
16229 .flat_map(move |ranges| {
16230 let start_ix = match ranges.binary_search_by(|probe| {
16231 let cmp = probe.end.cmp(&left_position, buffer);
16232 if cmp.is_ge() {
16233 Ordering::Greater
16234 } else {
16235 Ordering::Less
16236 }
16237 }) {
16238 Ok(i) | Err(i) => i,
16239 };
16240
16241 ranges[start_ix..]
16242 .iter()
16243 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16244 })
16245 }
16246
16247 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16248 self.background_highlights
16249 .get(&TypeId::of::<T>())
16250 .map_or(false, |(_, highlights)| !highlights.is_empty())
16251 }
16252
16253 pub fn background_highlights_in_range(
16254 &self,
16255 search_range: Range<Anchor>,
16256 display_snapshot: &DisplaySnapshot,
16257 theme: &ThemeColors,
16258 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16259 let mut results = Vec::new();
16260 for (color_fetcher, ranges) in self.background_highlights.values() {
16261 let color = color_fetcher(theme);
16262 let start_ix = match ranges.binary_search_by(|probe| {
16263 let cmp = probe
16264 .end
16265 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16266 if cmp.is_gt() {
16267 Ordering::Greater
16268 } else {
16269 Ordering::Less
16270 }
16271 }) {
16272 Ok(i) | Err(i) => i,
16273 };
16274 for range in &ranges[start_ix..] {
16275 if range
16276 .start
16277 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16278 .is_ge()
16279 {
16280 break;
16281 }
16282
16283 let start = range.start.to_display_point(display_snapshot);
16284 let end = range.end.to_display_point(display_snapshot);
16285 results.push((start..end, color))
16286 }
16287 }
16288 results
16289 }
16290
16291 pub fn background_highlight_row_ranges<T: 'static>(
16292 &self,
16293 search_range: Range<Anchor>,
16294 display_snapshot: &DisplaySnapshot,
16295 count: usize,
16296 ) -> Vec<RangeInclusive<DisplayPoint>> {
16297 let mut results = Vec::new();
16298 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16299 return vec![];
16300 };
16301
16302 let start_ix = match ranges.binary_search_by(|probe| {
16303 let cmp = probe
16304 .end
16305 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16306 if cmp.is_gt() {
16307 Ordering::Greater
16308 } else {
16309 Ordering::Less
16310 }
16311 }) {
16312 Ok(i) | Err(i) => i,
16313 };
16314 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16315 if let (Some(start_display), Some(end_display)) = (start, end) {
16316 results.push(
16317 start_display.to_display_point(display_snapshot)
16318 ..=end_display.to_display_point(display_snapshot),
16319 );
16320 }
16321 };
16322 let mut start_row: Option<Point> = None;
16323 let mut end_row: Option<Point> = None;
16324 if ranges.len() > count {
16325 return Vec::new();
16326 }
16327 for range in &ranges[start_ix..] {
16328 if range
16329 .start
16330 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16331 .is_ge()
16332 {
16333 break;
16334 }
16335 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16336 if let Some(current_row) = &end_row {
16337 if end.row == current_row.row {
16338 continue;
16339 }
16340 }
16341 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16342 if start_row.is_none() {
16343 assert_eq!(end_row, None);
16344 start_row = Some(start);
16345 end_row = Some(end);
16346 continue;
16347 }
16348 if let Some(current_end) = end_row.as_mut() {
16349 if start.row > current_end.row + 1 {
16350 push_region(start_row, end_row);
16351 start_row = Some(start);
16352 end_row = Some(end);
16353 } else {
16354 // Merge two hunks.
16355 *current_end = end;
16356 }
16357 } else {
16358 unreachable!();
16359 }
16360 }
16361 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16362 push_region(start_row, end_row);
16363 results
16364 }
16365
16366 pub fn gutter_highlights_in_range(
16367 &self,
16368 search_range: Range<Anchor>,
16369 display_snapshot: &DisplaySnapshot,
16370 cx: &App,
16371 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16372 let mut results = Vec::new();
16373 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16374 let color = color_fetcher(cx);
16375 let start_ix = match ranges.binary_search_by(|probe| {
16376 let cmp = probe
16377 .end
16378 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16379 if cmp.is_gt() {
16380 Ordering::Greater
16381 } else {
16382 Ordering::Less
16383 }
16384 }) {
16385 Ok(i) | Err(i) => i,
16386 };
16387 for range in &ranges[start_ix..] {
16388 if range
16389 .start
16390 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16391 .is_ge()
16392 {
16393 break;
16394 }
16395
16396 let start = range.start.to_display_point(display_snapshot);
16397 let end = range.end.to_display_point(display_snapshot);
16398 results.push((start..end, color))
16399 }
16400 }
16401 results
16402 }
16403
16404 /// Get the text ranges corresponding to the redaction query
16405 pub fn redacted_ranges(
16406 &self,
16407 search_range: Range<Anchor>,
16408 display_snapshot: &DisplaySnapshot,
16409 cx: &App,
16410 ) -> Vec<Range<DisplayPoint>> {
16411 display_snapshot
16412 .buffer_snapshot
16413 .redacted_ranges(search_range, |file| {
16414 if let Some(file) = file {
16415 file.is_private()
16416 && EditorSettings::get(
16417 Some(SettingsLocation {
16418 worktree_id: file.worktree_id(cx),
16419 path: file.path().as_ref(),
16420 }),
16421 cx,
16422 )
16423 .redact_private_values
16424 } else {
16425 false
16426 }
16427 })
16428 .map(|range| {
16429 range.start.to_display_point(display_snapshot)
16430 ..range.end.to_display_point(display_snapshot)
16431 })
16432 .collect()
16433 }
16434
16435 pub fn highlight_text<T: 'static>(
16436 &mut self,
16437 ranges: Vec<Range<Anchor>>,
16438 style: HighlightStyle,
16439 cx: &mut Context<Self>,
16440 ) {
16441 self.display_map.update(cx, |map, _| {
16442 map.highlight_text(TypeId::of::<T>(), ranges, style)
16443 });
16444 cx.notify();
16445 }
16446
16447 pub(crate) fn highlight_inlays<T: 'static>(
16448 &mut self,
16449 highlights: Vec<InlayHighlight>,
16450 style: HighlightStyle,
16451 cx: &mut Context<Self>,
16452 ) {
16453 self.display_map.update(cx, |map, _| {
16454 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16455 });
16456 cx.notify();
16457 }
16458
16459 pub fn text_highlights<'a, T: 'static>(
16460 &'a self,
16461 cx: &'a App,
16462 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16463 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16464 }
16465
16466 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16467 let cleared = self
16468 .display_map
16469 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16470 if cleared {
16471 cx.notify();
16472 }
16473 }
16474
16475 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16476 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16477 && self.focus_handle.is_focused(window)
16478 }
16479
16480 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16481 self.show_cursor_when_unfocused = is_enabled;
16482 cx.notify();
16483 }
16484
16485 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16486 cx.notify();
16487 }
16488
16489 fn on_buffer_event(
16490 &mut self,
16491 multibuffer: &Entity<MultiBuffer>,
16492 event: &multi_buffer::Event,
16493 window: &mut Window,
16494 cx: &mut Context<Self>,
16495 ) {
16496 match event {
16497 multi_buffer::Event::Edited {
16498 singleton_buffer_edited,
16499 edited_buffer: buffer_edited,
16500 } => {
16501 self.scrollbar_marker_state.dirty = true;
16502 self.active_indent_guides_state.dirty = true;
16503 self.refresh_active_diagnostics(cx);
16504 self.refresh_code_actions(window, cx);
16505 if self.has_active_inline_completion() {
16506 self.update_visible_inline_completion(window, cx);
16507 }
16508 if let Some(buffer) = buffer_edited {
16509 let buffer_id = buffer.read(cx).remote_id();
16510 if !self.registered_buffers.contains_key(&buffer_id) {
16511 if let Some(project) = self.project.as_ref() {
16512 project.update(cx, |project, cx| {
16513 self.registered_buffers.insert(
16514 buffer_id,
16515 project.register_buffer_with_language_servers(&buffer, cx),
16516 );
16517 })
16518 }
16519 }
16520 }
16521 cx.emit(EditorEvent::BufferEdited);
16522 cx.emit(SearchEvent::MatchesInvalidated);
16523 if *singleton_buffer_edited {
16524 if let Some(project) = &self.project {
16525 #[allow(clippy::mutable_key_type)]
16526 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16527 multibuffer
16528 .all_buffers()
16529 .into_iter()
16530 .filter_map(|buffer| {
16531 buffer.update(cx, |buffer, cx| {
16532 let language = buffer.language()?;
16533 let should_discard = project.update(cx, |project, cx| {
16534 project.is_local()
16535 && !project.has_language_servers_for(buffer, cx)
16536 });
16537 should_discard.not().then_some(language.clone())
16538 })
16539 })
16540 .collect::<HashSet<_>>()
16541 });
16542 if !languages_affected.is_empty() {
16543 self.refresh_inlay_hints(
16544 InlayHintRefreshReason::BufferEdited(languages_affected),
16545 cx,
16546 );
16547 }
16548 }
16549 }
16550
16551 let Some(project) = &self.project else { return };
16552 let (telemetry, is_via_ssh) = {
16553 let project = project.read(cx);
16554 let telemetry = project.client().telemetry().clone();
16555 let is_via_ssh = project.is_via_ssh();
16556 (telemetry, is_via_ssh)
16557 };
16558 refresh_linked_ranges(self, window, cx);
16559 telemetry.log_edit_event("editor", is_via_ssh);
16560 }
16561 multi_buffer::Event::ExcerptsAdded {
16562 buffer,
16563 predecessor,
16564 excerpts,
16565 } => {
16566 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16567 let buffer_id = buffer.read(cx).remote_id();
16568 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16569 if let Some(project) = &self.project {
16570 get_uncommitted_diff_for_buffer(
16571 project,
16572 [buffer.clone()],
16573 self.buffer.clone(),
16574 cx,
16575 )
16576 .detach();
16577 }
16578 }
16579 cx.emit(EditorEvent::ExcerptsAdded {
16580 buffer: buffer.clone(),
16581 predecessor: *predecessor,
16582 excerpts: excerpts.clone(),
16583 });
16584 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16585 }
16586 multi_buffer::Event::ExcerptsRemoved { ids } => {
16587 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16588 let buffer = self.buffer.read(cx);
16589 self.registered_buffers
16590 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16591 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16592 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16593 }
16594 multi_buffer::Event::ExcerptsEdited {
16595 excerpt_ids,
16596 buffer_ids,
16597 } => {
16598 self.display_map.update(cx, |map, cx| {
16599 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16600 });
16601 cx.emit(EditorEvent::ExcerptsEdited {
16602 ids: excerpt_ids.clone(),
16603 })
16604 }
16605 multi_buffer::Event::ExcerptsExpanded { ids } => {
16606 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16607 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16608 }
16609 multi_buffer::Event::Reparsed(buffer_id) => {
16610 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16611 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16612
16613 cx.emit(EditorEvent::Reparsed(*buffer_id));
16614 }
16615 multi_buffer::Event::DiffHunksToggled => {
16616 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16617 }
16618 multi_buffer::Event::LanguageChanged(buffer_id) => {
16619 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16620 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16621 cx.emit(EditorEvent::Reparsed(*buffer_id));
16622 cx.notify();
16623 }
16624 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16625 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16626 multi_buffer::Event::FileHandleChanged
16627 | multi_buffer::Event::Reloaded
16628 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16629 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16630 multi_buffer::Event::DiagnosticsUpdated => {
16631 self.refresh_active_diagnostics(cx);
16632 self.refresh_inline_diagnostics(true, window, cx);
16633 self.scrollbar_marker_state.dirty = true;
16634 cx.notify();
16635 }
16636 _ => {}
16637 };
16638 }
16639
16640 fn on_display_map_changed(
16641 &mut self,
16642 _: Entity<DisplayMap>,
16643 _: &mut Window,
16644 cx: &mut Context<Self>,
16645 ) {
16646 cx.notify();
16647 }
16648
16649 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16650 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16651 self.update_edit_prediction_settings(cx);
16652 self.refresh_inline_completion(true, false, window, cx);
16653 self.refresh_inlay_hints(
16654 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16655 self.selections.newest_anchor().head(),
16656 &self.buffer.read(cx).snapshot(cx),
16657 cx,
16658 )),
16659 cx,
16660 );
16661
16662 let old_cursor_shape = self.cursor_shape;
16663
16664 {
16665 let editor_settings = EditorSettings::get_global(cx);
16666 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16667 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16668 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16669 self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
16670
16671 if !self.hide_mouse_while_typing {
16672 self.mouse_cursor_hidden = false;
16673 }
16674 }
16675
16676 if old_cursor_shape != self.cursor_shape {
16677 cx.emit(EditorEvent::CursorShapeChanged);
16678 }
16679
16680 let project_settings = ProjectSettings::get_global(cx);
16681 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16682
16683 if self.mode == EditorMode::Full {
16684 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16685 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16686 if self.show_inline_diagnostics != show_inline_diagnostics {
16687 self.show_inline_diagnostics = show_inline_diagnostics;
16688 self.refresh_inline_diagnostics(false, window, cx);
16689 }
16690
16691 if self.git_blame_inline_enabled != inline_blame_enabled {
16692 self.toggle_git_blame_inline_internal(false, window, cx);
16693 }
16694 }
16695
16696 cx.notify();
16697 }
16698
16699 pub fn set_searchable(&mut self, searchable: bool) {
16700 self.searchable = searchable;
16701 }
16702
16703 pub fn searchable(&self) -> bool {
16704 self.searchable
16705 }
16706
16707 fn open_proposed_changes_editor(
16708 &mut self,
16709 _: &OpenProposedChangesEditor,
16710 window: &mut Window,
16711 cx: &mut Context<Self>,
16712 ) {
16713 let Some(workspace) = self.workspace() else {
16714 cx.propagate();
16715 return;
16716 };
16717
16718 let selections = self.selections.all::<usize>(cx);
16719 let multi_buffer = self.buffer.read(cx);
16720 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16721 let mut new_selections_by_buffer = HashMap::default();
16722 for selection in selections {
16723 for (buffer, range, _) in
16724 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16725 {
16726 let mut range = range.to_point(buffer);
16727 range.start.column = 0;
16728 range.end.column = buffer.line_len(range.end.row);
16729 new_selections_by_buffer
16730 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16731 .or_insert(Vec::new())
16732 .push(range)
16733 }
16734 }
16735
16736 let proposed_changes_buffers = new_selections_by_buffer
16737 .into_iter()
16738 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16739 .collect::<Vec<_>>();
16740 let proposed_changes_editor = cx.new(|cx| {
16741 ProposedChangesEditor::new(
16742 "Proposed changes",
16743 proposed_changes_buffers,
16744 self.project.clone(),
16745 window,
16746 cx,
16747 )
16748 });
16749
16750 window.defer(cx, move |window, cx| {
16751 workspace.update(cx, |workspace, cx| {
16752 workspace.active_pane().update(cx, |pane, cx| {
16753 pane.add_item(
16754 Box::new(proposed_changes_editor),
16755 true,
16756 true,
16757 None,
16758 window,
16759 cx,
16760 );
16761 });
16762 });
16763 });
16764 }
16765
16766 pub fn open_excerpts_in_split(
16767 &mut self,
16768 _: &OpenExcerptsSplit,
16769 window: &mut Window,
16770 cx: &mut Context<Self>,
16771 ) {
16772 self.open_excerpts_common(None, true, window, cx)
16773 }
16774
16775 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16776 self.open_excerpts_common(None, false, window, cx)
16777 }
16778
16779 fn open_excerpts_common(
16780 &mut self,
16781 jump_data: Option<JumpData>,
16782 split: bool,
16783 window: &mut Window,
16784 cx: &mut Context<Self>,
16785 ) {
16786 let Some(workspace) = self.workspace() else {
16787 cx.propagate();
16788 return;
16789 };
16790
16791 if self.buffer.read(cx).is_singleton() {
16792 cx.propagate();
16793 return;
16794 }
16795
16796 let mut new_selections_by_buffer = HashMap::default();
16797 match &jump_data {
16798 Some(JumpData::MultiBufferPoint {
16799 excerpt_id,
16800 position,
16801 anchor,
16802 line_offset_from_top,
16803 }) => {
16804 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16805 if let Some(buffer) = multi_buffer_snapshot
16806 .buffer_id_for_excerpt(*excerpt_id)
16807 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16808 {
16809 let buffer_snapshot = buffer.read(cx).snapshot();
16810 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16811 language::ToPoint::to_point(anchor, &buffer_snapshot)
16812 } else {
16813 buffer_snapshot.clip_point(*position, Bias::Left)
16814 };
16815 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16816 new_selections_by_buffer.insert(
16817 buffer,
16818 (
16819 vec![jump_to_offset..jump_to_offset],
16820 Some(*line_offset_from_top),
16821 ),
16822 );
16823 }
16824 }
16825 Some(JumpData::MultiBufferRow {
16826 row,
16827 line_offset_from_top,
16828 }) => {
16829 let point = MultiBufferPoint::new(row.0, 0);
16830 if let Some((buffer, buffer_point, _)) =
16831 self.buffer.read(cx).point_to_buffer_point(point, cx)
16832 {
16833 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16834 new_selections_by_buffer
16835 .entry(buffer)
16836 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16837 .0
16838 .push(buffer_offset..buffer_offset)
16839 }
16840 }
16841 None => {
16842 let selections = self.selections.all::<usize>(cx);
16843 let multi_buffer = self.buffer.read(cx);
16844 for selection in selections {
16845 for (snapshot, range, _, anchor) in multi_buffer
16846 .snapshot(cx)
16847 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16848 {
16849 if let Some(anchor) = anchor {
16850 // selection is in a deleted hunk
16851 let Some(buffer_id) = anchor.buffer_id else {
16852 continue;
16853 };
16854 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16855 continue;
16856 };
16857 let offset = text::ToOffset::to_offset(
16858 &anchor.text_anchor,
16859 &buffer_handle.read(cx).snapshot(),
16860 );
16861 let range = offset..offset;
16862 new_selections_by_buffer
16863 .entry(buffer_handle)
16864 .or_insert((Vec::new(), None))
16865 .0
16866 .push(range)
16867 } else {
16868 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16869 else {
16870 continue;
16871 };
16872 new_selections_by_buffer
16873 .entry(buffer_handle)
16874 .or_insert((Vec::new(), None))
16875 .0
16876 .push(range)
16877 }
16878 }
16879 }
16880 }
16881 }
16882
16883 if new_selections_by_buffer.is_empty() {
16884 return;
16885 }
16886
16887 // We defer the pane interaction because we ourselves are a workspace item
16888 // and activating a new item causes the pane to call a method on us reentrantly,
16889 // which panics if we're on the stack.
16890 window.defer(cx, move |window, cx| {
16891 workspace.update(cx, |workspace, cx| {
16892 let pane = if split {
16893 workspace.adjacent_pane(window, cx)
16894 } else {
16895 workspace.active_pane().clone()
16896 };
16897
16898 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16899 let editor = buffer
16900 .read(cx)
16901 .file()
16902 .is_none()
16903 .then(|| {
16904 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16905 // so `workspace.open_project_item` will never find them, always opening a new editor.
16906 // Instead, we try to activate the existing editor in the pane first.
16907 let (editor, pane_item_index) =
16908 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16909 let editor = item.downcast::<Editor>()?;
16910 let singleton_buffer =
16911 editor.read(cx).buffer().read(cx).as_singleton()?;
16912 if singleton_buffer == buffer {
16913 Some((editor, i))
16914 } else {
16915 None
16916 }
16917 })?;
16918 pane.update(cx, |pane, cx| {
16919 pane.activate_item(pane_item_index, true, true, window, cx)
16920 });
16921 Some(editor)
16922 })
16923 .flatten()
16924 .unwrap_or_else(|| {
16925 workspace.open_project_item::<Self>(
16926 pane.clone(),
16927 buffer,
16928 true,
16929 true,
16930 window,
16931 cx,
16932 )
16933 });
16934
16935 editor.update(cx, |editor, cx| {
16936 let autoscroll = match scroll_offset {
16937 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16938 None => Autoscroll::newest(),
16939 };
16940 let nav_history = editor.nav_history.take();
16941 editor.change_selections(Some(autoscroll), window, cx, |s| {
16942 s.select_ranges(ranges);
16943 });
16944 editor.nav_history = nav_history;
16945 });
16946 }
16947 })
16948 });
16949 }
16950
16951 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16952 let snapshot = self.buffer.read(cx).read(cx);
16953 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16954 Some(
16955 ranges
16956 .iter()
16957 .map(move |range| {
16958 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16959 })
16960 .collect(),
16961 )
16962 }
16963
16964 fn selection_replacement_ranges(
16965 &self,
16966 range: Range<OffsetUtf16>,
16967 cx: &mut App,
16968 ) -> Vec<Range<OffsetUtf16>> {
16969 let selections = self.selections.all::<OffsetUtf16>(cx);
16970 let newest_selection = selections
16971 .iter()
16972 .max_by_key(|selection| selection.id)
16973 .unwrap();
16974 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16975 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16976 let snapshot = self.buffer.read(cx).read(cx);
16977 selections
16978 .into_iter()
16979 .map(|mut selection| {
16980 selection.start.0 =
16981 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16982 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16983 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16984 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16985 })
16986 .collect()
16987 }
16988
16989 fn report_editor_event(
16990 &self,
16991 event_type: &'static str,
16992 file_extension: Option<String>,
16993 cx: &App,
16994 ) {
16995 if cfg!(any(test, feature = "test-support")) {
16996 return;
16997 }
16998
16999 let Some(project) = &self.project else { return };
17000
17001 // If None, we are in a file without an extension
17002 let file = self
17003 .buffer
17004 .read(cx)
17005 .as_singleton()
17006 .and_then(|b| b.read(cx).file());
17007 let file_extension = file_extension.or(file
17008 .as_ref()
17009 .and_then(|file| Path::new(file.file_name(cx)).extension())
17010 .and_then(|e| e.to_str())
17011 .map(|a| a.to_string()));
17012
17013 let vim_mode = cx
17014 .global::<SettingsStore>()
17015 .raw_user_settings()
17016 .get("vim_mode")
17017 == Some(&serde_json::Value::Bool(true));
17018
17019 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17020 let copilot_enabled = edit_predictions_provider
17021 == language::language_settings::EditPredictionProvider::Copilot;
17022 let copilot_enabled_for_language = self
17023 .buffer
17024 .read(cx)
17025 .language_settings(cx)
17026 .show_edit_predictions;
17027
17028 let project = project.read(cx);
17029 telemetry::event!(
17030 event_type,
17031 file_extension,
17032 vim_mode,
17033 copilot_enabled,
17034 copilot_enabled_for_language,
17035 edit_predictions_provider,
17036 is_via_ssh = project.is_via_ssh(),
17037 );
17038 }
17039
17040 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17041 /// with each line being an array of {text, highlight} objects.
17042 fn copy_highlight_json(
17043 &mut self,
17044 _: &CopyHighlightJson,
17045 window: &mut Window,
17046 cx: &mut Context<Self>,
17047 ) {
17048 #[derive(Serialize)]
17049 struct Chunk<'a> {
17050 text: String,
17051 highlight: Option<&'a str>,
17052 }
17053
17054 let snapshot = self.buffer.read(cx).snapshot(cx);
17055 let range = self
17056 .selected_text_range(false, window, cx)
17057 .and_then(|selection| {
17058 if selection.range.is_empty() {
17059 None
17060 } else {
17061 Some(selection.range)
17062 }
17063 })
17064 .unwrap_or_else(|| 0..snapshot.len());
17065
17066 let chunks = snapshot.chunks(range, true);
17067 let mut lines = Vec::new();
17068 let mut line: VecDeque<Chunk> = VecDeque::new();
17069
17070 let Some(style) = self.style.as_ref() else {
17071 return;
17072 };
17073
17074 for chunk in chunks {
17075 let highlight = chunk
17076 .syntax_highlight_id
17077 .and_then(|id| id.name(&style.syntax));
17078 let mut chunk_lines = chunk.text.split('\n').peekable();
17079 while let Some(text) = chunk_lines.next() {
17080 let mut merged_with_last_token = false;
17081 if let Some(last_token) = line.back_mut() {
17082 if last_token.highlight == highlight {
17083 last_token.text.push_str(text);
17084 merged_with_last_token = true;
17085 }
17086 }
17087
17088 if !merged_with_last_token {
17089 line.push_back(Chunk {
17090 text: text.into(),
17091 highlight,
17092 });
17093 }
17094
17095 if chunk_lines.peek().is_some() {
17096 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17097 line.pop_front();
17098 }
17099 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17100 line.pop_back();
17101 }
17102
17103 lines.push(mem::take(&mut line));
17104 }
17105 }
17106 }
17107
17108 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17109 return;
17110 };
17111 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17112 }
17113
17114 pub fn open_context_menu(
17115 &mut self,
17116 _: &OpenContextMenu,
17117 window: &mut Window,
17118 cx: &mut Context<Self>,
17119 ) {
17120 self.request_autoscroll(Autoscroll::newest(), cx);
17121 let position = self.selections.newest_display(cx).start;
17122 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17123 }
17124
17125 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17126 &self.inlay_hint_cache
17127 }
17128
17129 pub fn replay_insert_event(
17130 &mut self,
17131 text: &str,
17132 relative_utf16_range: Option<Range<isize>>,
17133 window: &mut Window,
17134 cx: &mut Context<Self>,
17135 ) {
17136 if !self.input_enabled {
17137 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17138 return;
17139 }
17140 if let Some(relative_utf16_range) = relative_utf16_range {
17141 let selections = self.selections.all::<OffsetUtf16>(cx);
17142 self.change_selections(None, window, cx, |s| {
17143 let new_ranges = selections.into_iter().map(|range| {
17144 let start = OffsetUtf16(
17145 range
17146 .head()
17147 .0
17148 .saturating_add_signed(relative_utf16_range.start),
17149 );
17150 let end = OffsetUtf16(
17151 range
17152 .head()
17153 .0
17154 .saturating_add_signed(relative_utf16_range.end),
17155 );
17156 start..end
17157 });
17158 s.select_ranges(new_ranges);
17159 });
17160 }
17161
17162 self.handle_input(text, window, cx);
17163 }
17164
17165 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17166 let Some(provider) = self.semantics_provider.as_ref() else {
17167 return false;
17168 };
17169
17170 let mut supports = false;
17171 self.buffer().update(cx, |this, cx| {
17172 this.for_each_buffer(|buffer| {
17173 supports |= provider.supports_inlay_hints(buffer, cx);
17174 });
17175 });
17176
17177 supports
17178 }
17179
17180 pub fn is_focused(&self, window: &Window) -> bool {
17181 self.focus_handle.is_focused(window)
17182 }
17183
17184 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17185 cx.emit(EditorEvent::Focused);
17186
17187 if let Some(descendant) = self
17188 .last_focused_descendant
17189 .take()
17190 .and_then(|descendant| descendant.upgrade())
17191 {
17192 window.focus(&descendant);
17193 } else {
17194 if let Some(blame) = self.blame.as_ref() {
17195 blame.update(cx, GitBlame::focus)
17196 }
17197
17198 self.blink_manager.update(cx, BlinkManager::enable);
17199 self.show_cursor_names(window, cx);
17200 self.buffer.update(cx, |buffer, cx| {
17201 buffer.finalize_last_transaction(cx);
17202 if self.leader_peer_id.is_none() {
17203 buffer.set_active_selections(
17204 &self.selections.disjoint_anchors(),
17205 self.selections.line_mode,
17206 self.cursor_shape,
17207 cx,
17208 );
17209 }
17210 });
17211 }
17212 }
17213
17214 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17215 cx.emit(EditorEvent::FocusedIn)
17216 }
17217
17218 fn handle_focus_out(
17219 &mut self,
17220 event: FocusOutEvent,
17221 _window: &mut Window,
17222 cx: &mut Context<Self>,
17223 ) {
17224 if event.blurred != self.focus_handle {
17225 self.last_focused_descendant = Some(event.blurred);
17226 }
17227 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17228 }
17229
17230 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17231 self.blink_manager.update(cx, BlinkManager::disable);
17232 self.buffer
17233 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17234
17235 if let Some(blame) = self.blame.as_ref() {
17236 blame.update(cx, GitBlame::blur)
17237 }
17238 if !self.hover_state.focused(window, cx) {
17239 hide_hover(self, cx);
17240 }
17241 if !self
17242 .context_menu
17243 .borrow()
17244 .as_ref()
17245 .is_some_and(|context_menu| context_menu.focused(window, cx))
17246 {
17247 self.hide_context_menu(window, cx);
17248 }
17249 self.discard_inline_completion(false, cx);
17250 cx.emit(EditorEvent::Blurred);
17251 cx.notify();
17252 }
17253
17254 pub fn register_action<A: Action>(
17255 &mut self,
17256 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17257 ) -> Subscription {
17258 let id = self.next_editor_action_id.post_inc();
17259 let listener = Arc::new(listener);
17260 self.editor_actions.borrow_mut().insert(
17261 id,
17262 Box::new(move |window, _| {
17263 let listener = listener.clone();
17264 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17265 let action = action.downcast_ref().unwrap();
17266 if phase == DispatchPhase::Bubble {
17267 listener(action, window, cx)
17268 }
17269 })
17270 }),
17271 );
17272
17273 let editor_actions = self.editor_actions.clone();
17274 Subscription::new(move || {
17275 editor_actions.borrow_mut().remove(&id);
17276 })
17277 }
17278
17279 pub fn file_header_size(&self) -> u32 {
17280 FILE_HEADER_HEIGHT
17281 }
17282
17283 pub fn restore(
17284 &mut self,
17285 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17286 window: &mut Window,
17287 cx: &mut Context<Self>,
17288 ) {
17289 let workspace = self.workspace();
17290 let project = self.project.as_ref();
17291 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17292 let mut tasks = Vec::new();
17293 for (buffer_id, changes) in revert_changes {
17294 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17295 buffer.update(cx, |buffer, cx| {
17296 buffer.edit(
17297 changes
17298 .into_iter()
17299 .map(|(range, text)| (range, text.to_string())),
17300 None,
17301 cx,
17302 );
17303 });
17304
17305 if let Some(project) =
17306 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17307 {
17308 project.update(cx, |project, cx| {
17309 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17310 })
17311 }
17312 }
17313 }
17314 tasks
17315 });
17316 cx.spawn_in(window, async move |_, cx| {
17317 for (buffer, task) in save_tasks {
17318 let result = task.await;
17319 if result.is_err() {
17320 let Some(path) = buffer
17321 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17322 .ok()
17323 else {
17324 continue;
17325 };
17326 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17327 let Some(task) = cx
17328 .update_window_entity(&workspace, |workspace, window, cx| {
17329 workspace
17330 .open_path_preview(path, None, false, false, false, window, cx)
17331 })
17332 .ok()
17333 else {
17334 continue;
17335 };
17336 task.await.log_err();
17337 }
17338 }
17339 }
17340 })
17341 .detach();
17342 self.change_selections(None, window, cx, |selections| selections.refresh());
17343 }
17344
17345 pub fn to_pixel_point(
17346 &self,
17347 source: multi_buffer::Anchor,
17348 editor_snapshot: &EditorSnapshot,
17349 window: &mut Window,
17350 ) -> Option<gpui::Point<Pixels>> {
17351 let source_point = source.to_display_point(editor_snapshot);
17352 self.display_to_pixel_point(source_point, editor_snapshot, window)
17353 }
17354
17355 pub fn display_to_pixel_point(
17356 &self,
17357 source: DisplayPoint,
17358 editor_snapshot: &EditorSnapshot,
17359 window: &mut Window,
17360 ) -> Option<gpui::Point<Pixels>> {
17361 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17362 let text_layout_details = self.text_layout_details(window);
17363 let scroll_top = text_layout_details
17364 .scroll_anchor
17365 .scroll_position(editor_snapshot)
17366 .y;
17367
17368 if source.row().as_f32() < scroll_top.floor() {
17369 return None;
17370 }
17371 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17372 let source_y = line_height * (source.row().as_f32() - scroll_top);
17373 Some(gpui::Point::new(source_x, source_y))
17374 }
17375
17376 pub fn has_visible_completions_menu(&self) -> bool {
17377 !self.edit_prediction_preview_is_active()
17378 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17379 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17380 })
17381 }
17382
17383 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17384 self.addons
17385 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17386 }
17387
17388 pub fn unregister_addon<T: Addon>(&mut self) {
17389 self.addons.remove(&std::any::TypeId::of::<T>());
17390 }
17391
17392 pub fn addon<T: Addon>(&self) -> Option<&T> {
17393 let type_id = std::any::TypeId::of::<T>();
17394 self.addons
17395 .get(&type_id)
17396 .and_then(|item| item.to_any().downcast_ref::<T>())
17397 }
17398
17399 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17400 let text_layout_details = self.text_layout_details(window);
17401 let style = &text_layout_details.editor_style;
17402 let font_id = window.text_system().resolve_font(&style.text.font());
17403 let font_size = style.text.font_size.to_pixels(window.rem_size());
17404 let line_height = style.text.line_height_in_pixels(window.rem_size());
17405 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17406
17407 gpui::Size::new(em_width, line_height)
17408 }
17409
17410 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17411 self.load_diff_task.clone()
17412 }
17413
17414 fn read_metadata_from_db(
17415 &mut self,
17416 item_id: u64,
17417 workspace_id: WorkspaceId,
17418 window: &mut Window,
17419 cx: &mut Context<Editor>,
17420 ) {
17421 if self.is_singleton(cx)
17422 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17423 {
17424 let buffer_snapshot = OnceCell::new();
17425
17426 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17427 if !selections.is_empty() {
17428 let snapshot =
17429 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17430 self.change_selections(None, window, cx, |s| {
17431 s.select_ranges(selections.into_iter().map(|(start, end)| {
17432 snapshot.clip_offset(start, Bias::Left)
17433 ..snapshot.clip_offset(end, Bias::Right)
17434 }));
17435 });
17436 }
17437 };
17438
17439 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17440 if !folds.is_empty() {
17441 let snapshot =
17442 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17443 self.fold_ranges(
17444 folds
17445 .into_iter()
17446 .map(|(start, end)| {
17447 snapshot.clip_offset(start, Bias::Left)
17448 ..snapshot.clip_offset(end, Bias::Right)
17449 })
17450 .collect(),
17451 false,
17452 window,
17453 cx,
17454 );
17455 }
17456 }
17457 }
17458
17459 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17460 }
17461}
17462
17463fn insert_extra_newline_brackets(
17464 buffer: &MultiBufferSnapshot,
17465 range: Range<usize>,
17466 language: &language::LanguageScope,
17467) -> bool {
17468 let leading_whitespace_len = buffer
17469 .reversed_chars_at(range.start)
17470 .take_while(|c| c.is_whitespace() && *c != '\n')
17471 .map(|c| c.len_utf8())
17472 .sum::<usize>();
17473 let trailing_whitespace_len = buffer
17474 .chars_at(range.end)
17475 .take_while(|c| c.is_whitespace() && *c != '\n')
17476 .map(|c| c.len_utf8())
17477 .sum::<usize>();
17478 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17479
17480 language.brackets().any(|(pair, enabled)| {
17481 let pair_start = pair.start.trim_end();
17482 let pair_end = pair.end.trim_start();
17483
17484 enabled
17485 && pair.newline
17486 && buffer.contains_str_at(range.end, pair_end)
17487 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17488 })
17489}
17490
17491fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17492 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17493 [(buffer, range, _)] => (*buffer, range.clone()),
17494 _ => return false,
17495 };
17496 let pair = {
17497 let mut result: Option<BracketMatch> = None;
17498
17499 for pair in buffer
17500 .all_bracket_ranges(range.clone())
17501 .filter(move |pair| {
17502 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17503 })
17504 {
17505 let len = pair.close_range.end - pair.open_range.start;
17506
17507 if let Some(existing) = &result {
17508 let existing_len = existing.close_range.end - existing.open_range.start;
17509 if len > existing_len {
17510 continue;
17511 }
17512 }
17513
17514 result = Some(pair);
17515 }
17516
17517 result
17518 };
17519 let Some(pair) = pair else {
17520 return false;
17521 };
17522 pair.newline_only
17523 && buffer
17524 .chars_for_range(pair.open_range.end..range.start)
17525 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17526 .all(|c| c.is_whitespace() && c != '\n')
17527}
17528
17529fn get_uncommitted_diff_for_buffer(
17530 project: &Entity<Project>,
17531 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17532 buffer: Entity<MultiBuffer>,
17533 cx: &mut App,
17534) -> Task<()> {
17535 let mut tasks = Vec::new();
17536 project.update(cx, |project, cx| {
17537 for buffer in buffers {
17538 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17539 }
17540 });
17541 cx.spawn(async move |cx| {
17542 let diffs = future::join_all(tasks).await;
17543 buffer
17544 .update(cx, |buffer, cx| {
17545 for diff in diffs.into_iter().flatten() {
17546 buffer.add_diff(diff, cx);
17547 }
17548 })
17549 .ok();
17550 })
17551}
17552
17553fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17554 let tab_size = tab_size.get() as usize;
17555 let mut width = offset;
17556
17557 for ch in text.chars() {
17558 width += if ch == '\t' {
17559 tab_size - (width % tab_size)
17560 } else {
17561 1
17562 };
17563 }
17564
17565 width - offset
17566}
17567
17568#[cfg(test)]
17569mod tests {
17570 use super::*;
17571
17572 #[test]
17573 fn test_string_size_with_expanded_tabs() {
17574 let nz = |val| NonZeroU32::new(val).unwrap();
17575 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17576 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17577 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17578 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17579 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17580 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17581 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17582 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17583 }
17584}
17585
17586/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17587struct WordBreakingTokenizer<'a> {
17588 input: &'a str,
17589}
17590
17591impl<'a> WordBreakingTokenizer<'a> {
17592 fn new(input: &'a str) -> Self {
17593 Self { input }
17594 }
17595}
17596
17597fn is_char_ideographic(ch: char) -> bool {
17598 use unicode_script::Script::*;
17599 use unicode_script::UnicodeScript;
17600 matches!(ch.script(), Han | Tangut | Yi)
17601}
17602
17603fn is_grapheme_ideographic(text: &str) -> bool {
17604 text.chars().any(is_char_ideographic)
17605}
17606
17607fn is_grapheme_whitespace(text: &str) -> bool {
17608 text.chars().any(|x| x.is_whitespace())
17609}
17610
17611fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17612 text.chars().next().map_or(false, |ch| {
17613 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17614 })
17615}
17616
17617#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17618enum WordBreakToken<'a> {
17619 Word { token: &'a str, grapheme_len: usize },
17620 InlineWhitespace { token: &'a str, grapheme_len: usize },
17621 Newline,
17622}
17623
17624impl<'a> Iterator for WordBreakingTokenizer<'a> {
17625 /// Yields a span, the count of graphemes in the token, and whether it was
17626 /// whitespace. Note that it also breaks at word boundaries.
17627 type Item = WordBreakToken<'a>;
17628
17629 fn next(&mut self) -> Option<Self::Item> {
17630 use unicode_segmentation::UnicodeSegmentation;
17631 if self.input.is_empty() {
17632 return None;
17633 }
17634
17635 let mut iter = self.input.graphemes(true).peekable();
17636 let mut offset = 0;
17637 let mut grapheme_len = 0;
17638 if let Some(first_grapheme) = iter.next() {
17639 let is_newline = first_grapheme == "\n";
17640 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17641 offset += first_grapheme.len();
17642 grapheme_len += 1;
17643 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17644 if let Some(grapheme) = iter.peek().copied() {
17645 if should_stay_with_preceding_ideograph(grapheme) {
17646 offset += grapheme.len();
17647 grapheme_len += 1;
17648 }
17649 }
17650 } else {
17651 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17652 let mut next_word_bound = words.peek().copied();
17653 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17654 next_word_bound = words.next();
17655 }
17656 while let Some(grapheme) = iter.peek().copied() {
17657 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17658 break;
17659 };
17660 if is_grapheme_whitespace(grapheme) != is_whitespace
17661 || (grapheme == "\n") != is_newline
17662 {
17663 break;
17664 };
17665 offset += grapheme.len();
17666 grapheme_len += 1;
17667 iter.next();
17668 }
17669 }
17670 let token = &self.input[..offset];
17671 self.input = &self.input[offset..];
17672 if token == "\n" {
17673 Some(WordBreakToken::Newline)
17674 } else if is_whitespace {
17675 Some(WordBreakToken::InlineWhitespace {
17676 token,
17677 grapheme_len,
17678 })
17679 } else {
17680 Some(WordBreakToken::Word {
17681 token,
17682 grapheme_len,
17683 })
17684 }
17685 } else {
17686 None
17687 }
17688 }
17689}
17690
17691#[test]
17692fn test_word_breaking_tokenizer() {
17693 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17694 ("", &[]),
17695 (" ", &[whitespace(" ", 2)]),
17696 ("Ʒ", &[word("Ʒ", 1)]),
17697 ("Ǽ", &[word("Ǽ", 1)]),
17698 ("⋑", &[word("⋑", 1)]),
17699 ("⋑⋑", &[word("⋑⋑", 2)]),
17700 (
17701 "原理,进而",
17702 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17703 ),
17704 (
17705 "hello world",
17706 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17707 ),
17708 (
17709 "hello, world",
17710 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17711 ),
17712 (
17713 " hello world",
17714 &[
17715 whitespace(" ", 2),
17716 word("hello", 5),
17717 whitespace(" ", 1),
17718 word("world", 5),
17719 ],
17720 ),
17721 (
17722 "这是什么 \n 钢笔",
17723 &[
17724 word("这", 1),
17725 word("是", 1),
17726 word("什", 1),
17727 word("么", 1),
17728 whitespace(" ", 1),
17729 newline(),
17730 whitespace(" ", 1),
17731 word("钢", 1),
17732 word("笔", 1),
17733 ],
17734 ),
17735 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17736 ];
17737
17738 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17739 WordBreakToken::Word {
17740 token,
17741 grapheme_len,
17742 }
17743 }
17744
17745 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17746 WordBreakToken::InlineWhitespace {
17747 token,
17748 grapheme_len,
17749 }
17750 }
17751
17752 fn newline() -> WordBreakToken<'static> {
17753 WordBreakToken::Newline
17754 }
17755
17756 for (input, result) in tests {
17757 assert_eq!(
17758 WordBreakingTokenizer::new(input)
17759 .collect::<Vec<_>>()
17760 .as_slice(),
17761 *result,
17762 );
17763 }
17764}
17765
17766fn wrap_with_prefix(
17767 line_prefix: String,
17768 unwrapped_text: String,
17769 wrap_column: usize,
17770 tab_size: NonZeroU32,
17771 preserve_existing_whitespace: bool,
17772) -> String {
17773 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17774 let mut wrapped_text = String::new();
17775 let mut current_line = line_prefix.clone();
17776
17777 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17778 let mut current_line_len = line_prefix_len;
17779 let mut in_whitespace = false;
17780 for token in tokenizer {
17781 let have_preceding_whitespace = in_whitespace;
17782 match token {
17783 WordBreakToken::Word {
17784 token,
17785 grapheme_len,
17786 } => {
17787 in_whitespace = false;
17788 if current_line_len + grapheme_len > wrap_column
17789 && current_line_len != line_prefix_len
17790 {
17791 wrapped_text.push_str(current_line.trim_end());
17792 wrapped_text.push('\n');
17793 current_line.truncate(line_prefix.len());
17794 current_line_len = line_prefix_len;
17795 }
17796 current_line.push_str(token);
17797 current_line_len += grapheme_len;
17798 }
17799 WordBreakToken::InlineWhitespace {
17800 mut token,
17801 mut grapheme_len,
17802 } => {
17803 in_whitespace = true;
17804 if have_preceding_whitespace && !preserve_existing_whitespace {
17805 continue;
17806 }
17807 if !preserve_existing_whitespace {
17808 token = " ";
17809 grapheme_len = 1;
17810 }
17811 if current_line_len + grapheme_len > wrap_column {
17812 wrapped_text.push_str(current_line.trim_end());
17813 wrapped_text.push('\n');
17814 current_line.truncate(line_prefix.len());
17815 current_line_len = line_prefix_len;
17816 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17817 current_line.push_str(token);
17818 current_line_len += grapheme_len;
17819 }
17820 }
17821 WordBreakToken::Newline => {
17822 in_whitespace = true;
17823 if preserve_existing_whitespace {
17824 wrapped_text.push_str(current_line.trim_end());
17825 wrapped_text.push('\n');
17826 current_line.truncate(line_prefix.len());
17827 current_line_len = line_prefix_len;
17828 } else if have_preceding_whitespace {
17829 continue;
17830 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17831 {
17832 wrapped_text.push_str(current_line.trim_end());
17833 wrapped_text.push('\n');
17834 current_line.truncate(line_prefix.len());
17835 current_line_len = line_prefix_len;
17836 } else if current_line_len != line_prefix_len {
17837 current_line.push(' ');
17838 current_line_len += 1;
17839 }
17840 }
17841 }
17842 }
17843
17844 if !current_line.is_empty() {
17845 wrapped_text.push_str(¤t_line);
17846 }
17847 wrapped_text
17848}
17849
17850#[test]
17851fn test_wrap_with_prefix() {
17852 assert_eq!(
17853 wrap_with_prefix(
17854 "# ".to_string(),
17855 "abcdefg".to_string(),
17856 4,
17857 NonZeroU32::new(4).unwrap(),
17858 false,
17859 ),
17860 "# abcdefg"
17861 );
17862 assert_eq!(
17863 wrap_with_prefix(
17864 "".to_string(),
17865 "\thello world".to_string(),
17866 8,
17867 NonZeroU32::new(4).unwrap(),
17868 false,
17869 ),
17870 "hello\nworld"
17871 );
17872 assert_eq!(
17873 wrap_with_prefix(
17874 "// ".to_string(),
17875 "xx \nyy zz aa bb cc".to_string(),
17876 12,
17877 NonZeroU32::new(4).unwrap(),
17878 false,
17879 ),
17880 "// xx yy zz\n// aa bb cc"
17881 );
17882 assert_eq!(
17883 wrap_with_prefix(
17884 String::new(),
17885 "这是什么 \n 钢笔".to_string(),
17886 3,
17887 NonZeroU32::new(4).unwrap(),
17888 false,
17889 ),
17890 "这是什\n么 钢\n笔"
17891 );
17892}
17893
17894pub trait CollaborationHub {
17895 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17896 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17897 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17898}
17899
17900impl CollaborationHub for Entity<Project> {
17901 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17902 self.read(cx).collaborators()
17903 }
17904
17905 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17906 self.read(cx).user_store().read(cx).participant_indices()
17907 }
17908
17909 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17910 let this = self.read(cx);
17911 let user_ids = this.collaborators().values().map(|c| c.user_id);
17912 this.user_store().read_with(cx, |user_store, cx| {
17913 user_store.participant_names(user_ids, cx)
17914 })
17915 }
17916}
17917
17918pub trait SemanticsProvider {
17919 fn hover(
17920 &self,
17921 buffer: &Entity<Buffer>,
17922 position: text::Anchor,
17923 cx: &mut App,
17924 ) -> Option<Task<Vec<project::Hover>>>;
17925
17926 fn inlay_hints(
17927 &self,
17928 buffer_handle: Entity<Buffer>,
17929 range: Range<text::Anchor>,
17930 cx: &mut App,
17931 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17932
17933 fn resolve_inlay_hint(
17934 &self,
17935 hint: InlayHint,
17936 buffer_handle: Entity<Buffer>,
17937 server_id: LanguageServerId,
17938 cx: &mut App,
17939 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17940
17941 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17942
17943 fn document_highlights(
17944 &self,
17945 buffer: &Entity<Buffer>,
17946 position: text::Anchor,
17947 cx: &mut App,
17948 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17949
17950 fn definitions(
17951 &self,
17952 buffer: &Entity<Buffer>,
17953 position: text::Anchor,
17954 kind: GotoDefinitionKind,
17955 cx: &mut App,
17956 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17957
17958 fn range_for_rename(
17959 &self,
17960 buffer: &Entity<Buffer>,
17961 position: text::Anchor,
17962 cx: &mut App,
17963 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17964
17965 fn perform_rename(
17966 &self,
17967 buffer: &Entity<Buffer>,
17968 position: text::Anchor,
17969 new_name: String,
17970 cx: &mut App,
17971 ) -> Option<Task<Result<ProjectTransaction>>>;
17972}
17973
17974pub trait CompletionProvider {
17975 fn completions(
17976 &self,
17977 excerpt_id: ExcerptId,
17978 buffer: &Entity<Buffer>,
17979 buffer_position: text::Anchor,
17980 trigger: CompletionContext,
17981 window: &mut Window,
17982 cx: &mut Context<Editor>,
17983 ) -> Task<Result<Option<Vec<Completion>>>>;
17984
17985 fn resolve_completions(
17986 &self,
17987 buffer: Entity<Buffer>,
17988 completion_indices: Vec<usize>,
17989 completions: Rc<RefCell<Box<[Completion]>>>,
17990 cx: &mut Context<Editor>,
17991 ) -> Task<Result<bool>>;
17992
17993 fn apply_additional_edits_for_completion(
17994 &self,
17995 _buffer: Entity<Buffer>,
17996 _completions: Rc<RefCell<Box<[Completion]>>>,
17997 _completion_index: usize,
17998 _push_to_history: bool,
17999 _cx: &mut Context<Editor>,
18000 ) -> Task<Result<Option<language::Transaction>>> {
18001 Task::ready(Ok(None))
18002 }
18003
18004 fn is_completion_trigger(
18005 &self,
18006 buffer: &Entity<Buffer>,
18007 position: language::Anchor,
18008 text: &str,
18009 trigger_in_words: bool,
18010 cx: &mut Context<Editor>,
18011 ) -> bool;
18012
18013 fn sort_completions(&self) -> bool {
18014 true
18015 }
18016
18017 fn filter_completions(&self) -> bool {
18018 true
18019 }
18020}
18021
18022pub trait CodeActionProvider {
18023 fn id(&self) -> Arc<str>;
18024
18025 fn code_actions(
18026 &self,
18027 buffer: &Entity<Buffer>,
18028 range: Range<text::Anchor>,
18029 window: &mut Window,
18030 cx: &mut App,
18031 ) -> Task<Result<Vec<CodeAction>>>;
18032
18033 fn apply_code_action(
18034 &self,
18035 buffer_handle: Entity<Buffer>,
18036 action: CodeAction,
18037 excerpt_id: ExcerptId,
18038 push_to_history: bool,
18039 window: &mut Window,
18040 cx: &mut App,
18041 ) -> Task<Result<ProjectTransaction>>;
18042}
18043
18044impl CodeActionProvider for Entity<Project> {
18045 fn id(&self) -> Arc<str> {
18046 "project".into()
18047 }
18048
18049 fn code_actions(
18050 &self,
18051 buffer: &Entity<Buffer>,
18052 range: Range<text::Anchor>,
18053 _window: &mut Window,
18054 cx: &mut App,
18055 ) -> Task<Result<Vec<CodeAction>>> {
18056 self.update(cx, |project, cx| {
18057 let code_lens = project.code_lens(buffer, range.clone(), cx);
18058 let code_actions = project.code_actions(buffer, range, None, cx);
18059 cx.background_spawn(async move {
18060 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18061 Ok(code_lens
18062 .context("code lens fetch")?
18063 .into_iter()
18064 .chain(code_actions.context("code action fetch")?)
18065 .collect())
18066 })
18067 })
18068 }
18069
18070 fn apply_code_action(
18071 &self,
18072 buffer_handle: Entity<Buffer>,
18073 action: CodeAction,
18074 _excerpt_id: ExcerptId,
18075 push_to_history: bool,
18076 _window: &mut Window,
18077 cx: &mut App,
18078 ) -> Task<Result<ProjectTransaction>> {
18079 self.update(cx, |project, cx| {
18080 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18081 })
18082 }
18083}
18084
18085fn snippet_completions(
18086 project: &Project,
18087 buffer: &Entity<Buffer>,
18088 buffer_position: text::Anchor,
18089 cx: &mut App,
18090) -> Task<Result<Vec<Completion>>> {
18091 let language = buffer.read(cx).language_at(buffer_position);
18092 let language_name = language.as_ref().map(|language| language.lsp_id());
18093 let snippet_store = project.snippets().read(cx);
18094 let snippets = snippet_store.snippets_for(language_name, cx);
18095
18096 if snippets.is_empty() {
18097 return Task::ready(Ok(vec![]));
18098 }
18099 let snapshot = buffer.read(cx).text_snapshot();
18100 let chars: String = snapshot
18101 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18102 .collect();
18103
18104 let scope = language.map(|language| language.default_scope());
18105 let executor = cx.background_executor().clone();
18106
18107 cx.background_spawn(async move {
18108 let classifier = CharClassifier::new(scope).for_completion(true);
18109 let mut last_word = chars
18110 .chars()
18111 .take_while(|c| classifier.is_word(*c))
18112 .collect::<String>();
18113 last_word = last_word.chars().rev().collect();
18114
18115 if last_word.is_empty() {
18116 return Ok(vec![]);
18117 }
18118
18119 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18120 let to_lsp = |point: &text::Anchor| {
18121 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18122 point_to_lsp(end)
18123 };
18124 let lsp_end = to_lsp(&buffer_position);
18125
18126 let candidates = snippets
18127 .iter()
18128 .enumerate()
18129 .flat_map(|(ix, snippet)| {
18130 snippet
18131 .prefix
18132 .iter()
18133 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18134 })
18135 .collect::<Vec<StringMatchCandidate>>();
18136
18137 let mut matches = fuzzy::match_strings(
18138 &candidates,
18139 &last_word,
18140 last_word.chars().any(|c| c.is_uppercase()),
18141 100,
18142 &Default::default(),
18143 executor,
18144 )
18145 .await;
18146
18147 // Remove all candidates where the query's start does not match the start of any word in the candidate
18148 if let Some(query_start) = last_word.chars().next() {
18149 matches.retain(|string_match| {
18150 split_words(&string_match.string).any(|word| {
18151 // Check that the first codepoint of the word as lowercase matches the first
18152 // codepoint of the query as lowercase
18153 word.chars()
18154 .flat_map(|codepoint| codepoint.to_lowercase())
18155 .zip(query_start.to_lowercase())
18156 .all(|(word_cp, query_cp)| word_cp == query_cp)
18157 })
18158 });
18159 }
18160
18161 let matched_strings = matches
18162 .into_iter()
18163 .map(|m| m.string)
18164 .collect::<HashSet<_>>();
18165
18166 let result: Vec<Completion> = snippets
18167 .into_iter()
18168 .filter_map(|snippet| {
18169 let matching_prefix = snippet
18170 .prefix
18171 .iter()
18172 .find(|prefix| matched_strings.contains(*prefix))?;
18173 let start = as_offset - last_word.len();
18174 let start = snapshot.anchor_before(start);
18175 let range = start..buffer_position;
18176 let lsp_start = to_lsp(&start);
18177 let lsp_range = lsp::Range {
18178 start: lsp_start,
18179 end: lsp_end,
18180 };
18181 Some(Completion {
18182 old_range: range,
18183 new_text: snippet.body.clone(),
18184 source: CompletionSource::Lsp {
18185 server_id: LanguageServerId(usize::MAX),
18186 resolved: true,
18187 lsp_completion: Box::new(lsp::CompletionItem {
18188 label: snippet.prefix.first().unwrap().clone(),
18189 kind: Some(CompletionItemKind::SNIPPET),
18190 label_details: snippet.description.as_ref().map(|description| {
18191 lsp::CompletionItemLabelDetails {
18192 detail: Some(description.clone()),
18193 description: None,
18194 }
18195 }),
18196 insert_text_format: Some(InsertTextFormat::SNIPPET),
18197 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18198 lsp::InsertReplaceEdit {
18199 new_text: snippet.body.clone(),
18200 insert: lsp_range,
18201 replace: lsp_range,
18202 },
18203 )),
18204 filter_text: Some(snippet.body.clone()),
18205 sort_text: Some(char::MAX.to_string()),
18206 ..lsp::CompletionItem::default()
18207 }),
18208 lsp_defaults: None,
18209 },
18210 label: CodeLabel {
18211 text: matching_prefix.clone(),
18212 runs: Vec::new(),
18213 filter_range: 0..matching_prefix.len(),
18214 },
18215 icon_path: None,
18216 documentation: snippet
18217 .description
18218 .clone()
18219 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18220 confirm: None,
18221 })
18222 })
18223 .collect();
18224
18225 Ok(result)
18226 })
18227}
18228
18229impl CompletionProvider for Entity<Project> {
18230 fn completions(
18231 &self,
18232 _excerpt_id: ExcerptId,
18233 buffer: &Entity<Buffer>,
18234 buffer_position: text::Anchor,
18235 options: CompletionContext,
18236 _window: &mut Window,
18237 cx: &mut Context<Editor>,
18238 ) -> Task<Result<Option<Vec<Completion>>>> {
18239 self.update(cx, |project, cx| {
18240 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18241 let project_completions = project.completions(buffer, buffer_position, options, cx);
18242 cx.background_spawn(async move {
18243 let snippets_completions = snippets.await?;
18244 match project_completions.await? {
18245 Some(mut completions) => {
18246 completions.extend(snippets_completions);
18247 Ok(Some(completions))
18248 }
18249 None => {
18250 if snippets_completions.is_empty() {
18251 Ok(None)
18252 } else {
18253 Ok(Some(snippets_completions))
18254 }
18255 }
18256 }
18257 })
18258 })
18259 }
18260
18261 fn resolve_completions(
18262 &self,
18263 buffer: Entity<Buffer>,
18264 completion_indices: Vec<usize>,
18265 completions: Rc<RefCell<Box<[Completion]>>>,
18266 cx: &mut Context<Editor>,
18267 ) -> Task<Result<bool>> {
18268 self.update(cx, |project, cx| {
18269 project.lsp_store().update(cx, |lsp_store, cx| {
18270 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18271 })
18272 })
18273 }
18274
18275 fn apply_additional_edits_for_completion(
18276 &self,
18277 buffer: Entity<Buffer>,
18278 completions: Rc<RefCell<Box<[Completion]>>>,
18279 completion_index: usize,
18280 push_to_history: bool,
18281 cx: &mut Context<Editor>,
18282 ) -> Task<Result<Option<language::Transaction>>> {
18283 self.update(cx, |project, cx| {
18284 project.lsp_store().update(cx, |lsp_store, cx| {
18285 lsp_store.apply_additional_edits_for_completion(
18286 buffer,
18287 completions,
18288 completion_index,
18289 push_to_history,
18290 cx,
18291 )
18292 })
18293 })
18294 }
18295
18296 fn is_completion_trigger(
18297 &self,
18298 buffer: &Entity<Buffer>,
18299 position: language::Anchor,
18300 text: &str,
18301 trigger_in_words: bool,
18302 cx: &mut Context<Editor>,
18303 ) -> bool {
18304 let mut chars = text.chars();
18305 let char = if let Some(char) = chars.next() {
18306 char
18307 } else {
18308 return false;
18309 };
18310 if chars.next().is_some() {
18311 return false;
18312 }
18313
18314 let buffer = buffer.read(cx);
18315 let snapshot = buffer.snapshot();
18316 if !snapshot.settings_at(position, cx).show_completions_on_input {
18317 return false;
18318 }
18319 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18320 if trigger_in_words && classifier.is_word(char) {
18321 return true;
18322 }
18323
18324 buffer.completion_triggers().contains(text)
18325 }
18326}
18327
18328impl SemanticsProvider for Entity<Project> {
18329 fn hover(
18330 &self,
18331 buffer: &Entity<Buffer>,
18332 position: text::Anchor,
18333 cx: &mut App,
18334 ) -> Option<Task<Vec<project::Hover>>> {
18335 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18336 }
18337
18338 fn document_highlights(
18339 &self,
18340 buffer: &Entity<Buffer>,
18341 position: text::Anchor,
18342 cx: &mut App,
18343 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18344 Some(self.update(cx, |project, cx| {
18345 project.document_highlights(buffer, position, cx)
18346 }))
18347 }
18348
18349 fn definitions(
18350 &self,
18351 buffer: &Entity<Buffer>,
18352 position: text::Anchor,
18353 kind: GotoDefinitionKind,
18354 cx: &mut App,
18355 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18356 Some(self.update(cx, |project, cx| match kind {
18357 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18358 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18359 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18360 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18361 }))
18362 }
18363
18364 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18365 // TODO: make this work for remote projects
18366 self.update(cx, |this, cx| {
18367 buffer.update(cx, |buffer, cx| {
18368 this.any_language_server_supports_inlay_hints(buffer, cx)
18369 })
18370 })
18371 }
18372
18373 fn inlay_hints(
18374 &self,
18375 buffer_handle: Entity<Buffer>,
18376 range: Range<text::Anchor>,
18377 cx: &mut App,
18378 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18379 Some(self.update(cx, |project, cx| {
18380 project.inlay_hints(buffer_handle, range, cx)
18381 }))
18382 }
18383
18384 fn resolve_inlay_hint(
18385 &self,
18386 hint: InlayHint,
18387 buffer_handle: Entity<Buffer>,
18388 server_id: LanguageServerId,
18389 cx: &mut App,
18390 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18391 Some(self.update(cx, |project, cx| {
18392 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18393 }))
18394 }
18395
18396 fn range_for_rename(
18397 &self,
18398 buffer: &Entity<Buffer>,
18399 position: text::Anchor,
18400 cx: &mut App,
18401 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18402 Some(self.update(cx, |project, cx| {
18403 let buffer = buffer.clone();
18404 let task = project.prepare_rename(buffer.clone(), position, cx);
18405 cx.spawn(async move |_, cx| {
18406 Ok(match task.await? {
18407 PrepareRenameResponse::Success(range) => Some(range),
18408 PrepareRenameResponse::InvalidPosition => None,
18409 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18410 // Fallback on using TreeSitter info to determine identifier range
18411 buffer.update(cx, |buffer, _| {
18412 let snapshot = buffer.snapshot();
18413 let (range, kind) = snapshot.surrounding_word(position);
18414 if kind != Some(CharKind::Word) {
18415 return None;
18416 }
18417 Some(
18418 snapshot.anchor_before(range.start)
18419 ..snapshot.anchor_after(range.end),
18420 )
18421 })?
18422 }
18423 })
18424 })
18425 }))
18426 }
18427
18428 fn perform_rename(
18429 &self,
18430 buffer: &Entity<Buffer>,
18431 position: text::Anchor,
18432 new_name: String,
18433 cx: &mut App,
18434 ) -> Option<Task<Result<ProjectTransaction>>> {
18435 Some(self.update(cx, |project, cx| {
18436 project.perform_rename(buffer.clone(), position, new_name, cx)
18437 }))
18438 }
18439}
18440
18441fn inlay_hint_settings(
18442 location: Anchor,
18443 snapshot: &MultiBufferSnapshot,
18444 cx: &mut Context<Editor>,
18445) -> InlayHintSettings {
18446 let file = snapshot.file_at(location);
18447 let language = snapshot.language_at(location).map(|l| l.name());
18448 language_settings(language, file, cx).inlay_hints
18449}
18450
18451fn consume_contiguous_rows(
18452 contiguous_row_selections: &mut Vec<Selection<Point>>,
18453 selection: &Selection<Point>,
18454 display_map: &DisplaySnapshot,
18455 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18456) -> (MultiBufferRow, MultiBufferRow) {
18457 contiguous_row_selections.push(selection.clone());
18458 let start_row = MultiBufferRow(selection.start.row);
18459 let mut end_row = ending_row(selection, display_map);
18460
18461 while let Some(next_selection) = selections.peek() {
18462 if next_selection.start.row <= end_row.0 {
18463 end_row = ending_row(next_selection, display_map);
18464 contiguous_row_selections.push(selections.next().unwrap().clone());
18465 } else {
18466 break;
18467 }
18468 }
18469 (start_row, end_row)
18470}
18471
18472fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18473 if next_selection.end.column > 0 || next_selection.is_empty() {
18474 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18475 } else {
18476 MultiBufferRow(next_selection.end.row)
18477 }
18478}
18479
18480impl EditorSnapshot {
18481 pub fn remote_selections_in_range<'a>(
18482 &'a self,
18483 range: &'a Range<Anchor>,
18484 collaboration_hub: &dyn CollaborationHub,
18485 cx: &'a App,
18486 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18487 let participant_names = collaboration_hub.user_names(cx);
18488 let participant_indices = collaboration_hub.user_participant_indices(cx);
18489 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18490 let collaborators_by_replica_id = collaborators_by_peer_id
18491 .iter()
18492 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18493 .collect::<HashMap<_, _>>();
18494 self.buffer_snapshot
18495 .selections_in_range(range, false)
18496 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18497 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18498 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18499 let user_name = participant_names.get(&collaborator.user_id).cloned();
18500 Some(RemoteSelection {
18501 replica_id,
18502 selection,
18503 cursor_shape,
18504 line_mode,
18505 participant_index,
18506 peer_id: collaborator.peer_id,
18507 user_name,
18508 })
18509 })
18510 }
18511
18512 pub fn hunks_for_ranges(
18513 &self,
18514 ranges: impl IntoIterator<Item = Range<Point>>,
18515 ) -> Vec<MultiBufferDiffHunk> {
18516 let mut hunks = Vec::new();
18517 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18518 HashMap::default();
18519 for query_range in ranges {
18520 let query_rows =
18521 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18522 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18523 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18524 ) {
18525 // Include deleted hunks that are adjacent to the query range, because
18526 // otherwise they would be missed.
18527 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18528 if hunk.status().is_deleted() {
18529 intersects_range |= hunk.row_range.start == query_rows.end;
18530 intersects_range |= hunk.row_range.end == query_rows.start;
18531 }
18532 if intersects_range {
18533 if !processed_buffer_rows
18534 .entry(hunk.buffer_id)
18535 .or_default()
18536 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18537 {
18538 continue;
18539 }
18540 hunks.push(hunk);
18541 }
18542 }
18543 }
18544
18545 hunks
18546 }
18547
18548 fn display_diff_hunks_for_rows<'a>(
18549 &'a self,
18550 display_rows: Range<DisplayRow>,
18551 folded_buffers: &'a HashSet<BufferId>,
18552 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18553 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18554 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18555
18556 self.buffer_snapshot
18557 .diff_hunks_in_range(buffer_start..buffer_end)
18558 .filter_map(|hunk| {
18559 if folded_buffers.contains(&hunk.buffer_id) {
18560 return None;
18561 }
18562
18563 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18564 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18565
18566 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18567 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18568
18569 let display_hunk = if hunk_display_start.column() != 0 {
18570 DisplayDiffHunk::Folded {
18571 display_row: hunk_display_start.row(),
18572 }
18573 } else {
18574 let mut end_row = hunk_display_end.row();
18575 if hunk_display_end.column() > 0 {
18576 end_row.0 += 1;
18577 }
18578 let is_created_file = hunk.is_created_file();
18579 DisplayDiffHunk::Unfolded {
18580 status: hunk.status(),
18581 diff_base_byte_range: hunk.diff_base_byte_range,
18582 display_row_range: hunk_display_start.row()..end_row,
18583 multi_buffer_range: Anchor::range_in_buffer(
18584 hunk.excerpt_id,
18585 hunk.buffer_id,
18586 hunk.buffer_range,
18587 ),
18588 is_created_file,
18589 }
18590 };
18591
18592 Some(display_hunk)
18593 })
18594 }
18595
18596 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18597 self.display_snapshot.buffer_snapshot.language_at(position)
18598 }
18599
18600 pub fn is_focused(&self) -> bool {
18601 self.is_focused
18602 }
18603
18604 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18605 self.placeholder_text.as_ref()
18606 }
18607
18608 pub fn scroll_position(&self) -> gpui::Point<f32> {
18609 self.scroll_anchor.scroll_position(&self.display_snapshot)
18610 }
18611
18612 fn gutter_dimensions(
18613 &self,
18614 font_id: FontId,
18615 font_size: Pixels,
18616 max_line_number_width: Pixels,
18617 cx: &App,
18618 ) -> Option<GutterDimensions> {
18619 if !self.show_gutter {
18620 return None;
18621 }
18622
18623 let descent = cx.text_system().descent(font_id, font_size);
18624 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18625 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18626
18627 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18628 matches!(
18629 ProjectSettings::get_global(cx).git.git_gutter,
18630 Some(GitGutterSetting::TrackedFiles)
18631 )
18632 });
18633 let gutter_settings = EditorSettings::get_global(cx).gutter;
18634 let show_line_numbers = self
18635 .show_line_numbers
18636 .unwrap_or(gutter_settings.line_numbers);
18637 let line_gutter_width = if show_line_numbers {
18638 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18639 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18640 max_line_number_width.max(min_width_for_number_on_gutter)
18641 } else {
18642 0.0.into()
18643 };
18644
18645 let show_code_actions = self
18646 .show_code_actions
18647 .unwrap_or(gutter_settings.code_actions);
18648
18649 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18650 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18651
18652 let git_blame_entries_width =
18653 self.git_blame_gutter_max_author_length
18654 .map(|max_author_length| {
18655 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18656
18657 /// The number of characters to dedicate to gaps and margins.
18658 const SPACING_WIDTH: usize = 4;
18659
18660 let max_char_count = max_author_length
18661 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18662 + ::git::SHORT_SHA_LENGTH
18663 + MAX_RELATIVE_TIMESTAMP.len()
18664 + SPACING_WIDTH;
18665
18666 em_advance * max_char_count
18667 });
18668
18669 let is_singleton = self.buffer_snapshot.is_singleton();
18670
18671 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18672 left_padding += if !is_singleton {
18673 em_width * 4.0
18674 } else if show_code_actions || show_runnables || show_breakpoints {
18675 em_width * 3.0
18676 } else if show_git_gutter && show_line_numbers {
18677 em_width * 2.0
18678 } else if show_git_gutter || show_line_numbers {
18679 em_width
18680 } else {
18681 px(0.)
18682 };
18683
18684 let shows_folds = is_singleton && gutter_settings.folds;
18685
18686 let right_padding = if shows_folds && show_line_numbers {
18687 em_width * 4.0
18688 } else if shows_folds || (!is_singleton && show_line_numbers) {
18689 em_width * 3.0
18690 } else if show_line_numbers {
18691 em_width
18692 } else {
18693 px(0.)
18694 };
18695
18696 Some(GutterDimensions {
18697 left_padding,
18698 right_padding,
18699 width: line_gutter_width + left_padding + right_padding,
18700 margin: -descent,
18701 git_blame_entries_width,
18702 })
18703 }
18704
18705 pub fn render_crease_toggle(
18706 &self,
18707 buffer_row: MultiBufferRow,
18708 row_contains_cursor: bool,
18709 editor: Entity<Editor>,
18710 window: &mut Window,
18711 cx: &mut App,
18712 ) -> Option<AnyElement> {
18713 let folded = self.is_line_folded(buffer_row);
18714 let mut is_foldable = false;
18715
18716 if let Some(crease) = self
18717 .crease_snapshot
18718 .query_row(buffer_row, &self.buffer_snapshot)
18719 {
18720 is_foldable = true;
18721 match crease {
18722 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18723 if let Some(render_toggle) = render_toggle {
18724 let toggle_callback =
18725 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18726 if folded {
18727 editor.update(cx, |editor, cx| {
18728 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18729 });
18730 } else {
18731 editor.update(cx, |editor, cx| {
18732 editor.unfold_at(
18733 &crate::UnfoldAt { buffer_row },
18734 window,
18735 cx,
18736 )
18737 });
18738 }
18739 });
18740 return Some((render_toggle)(
18741 buffer_row,
18742 folded,
18743 toggle_callback,
18744 window,
18745 cx,
18746 ));
18747 }
18748 }
18749 }
18750 }
18751
18752 is_foldable |= self.starts_indent(buffer_row);
18753
18754 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18755 Some(
18756 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18757 .toggle_state(folded)
18758 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18759 if folded {
18760 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18761 } else {
18762 this.fold_at(&FoldAt { buffer_row }, window, cx);
18763 }
18764 }))
18765 .into_any_element(),
18766 )
18767 } else {
18768 None
18769 }
18770 }
18771
18772 pub fn render_crease_trailer(
18773 &self,
18774 buffer_row: MultiBufferRow,
18775 window: &mut Window,
18776 cx: &mut App,
18777 ) -> Option<AnyElement> {
18778 let folded = self.is_line_folded(buffer_row);
18779 if let Crease::Inline { render_trailer, .. } = self
18780 .crease_snapshot
18781 .query_row(buffer_row, &self.buffer_snapshot)?
18782 {
18783 let render_trailer = render_trailer.as_ref()?;
18784 Some(render_trailer(buffer_row, folded, window, cx))
18785 } else {
18786 None
18787 }
18788 }
18789}
18790
18791impl Deref for EditorSnapshot {
18792 type Target = DisplaySnapshot;
18793
18794 fn deref(&self) -> &Self::Target {
18795 &self.display_snapshot
18796 }
18797}
18798
18799#[derive(Clone, Debug, PartialEq, Eq)]
18800pub enum EditorEvent {
18801 InputIgnored {
18802 text: Arc<str>,
18803 },
18804 InputHandled {
18805 utf16_range_to_replace: Option<Range<isize>>,
18806 text: Arc<str>,
18807 },
18808 ExcerptsAdded {
18809 buffer: Entity<Buffer>,
18810 predecessor: ExcerptId,
18811 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18812 },
18813 ExcerptsRemoved {
18814 ids: Vec<ExcerptId>,
18815 },
18816 BufferFoldToggled {
18817 ids: Vec<ExcerptId>,
18818 folded: bool,
18819 },
18820 ExcerptsEdited {
18821 ids: Vec<ExcerptId>,
18822 },
18823 ExcerptsExpanded {
18824 ids: Vec<ExcerptId>,
18825 },
18826 BufferEdited,
18827 Edited {
18828 transaction_id: clock::Lamport,
18829 },
18830 Reparsed(BufferId),
18831 Focused,
18832 FocusedIn,
18833 Blurred,
18834 DirtyChanged,
18835 Saved,
18836 TitleChanged,
18837 DiffBaseChanged,
18838 SelectionsChanged {
18839 local: bool,
18840 },
18841 ScrollPositionChanged {
18842 local: bool,
18843 autoscroll: bool,
18844 },
18845 Closed,
18846 TransactionUndone {
18847 transaction_id: clock::Lamport,
18848 },
18849 TransactionBegun {
18850 transaction_id: clock::Lamport,
18851 },
18852 Reloaded,
18853 CursorShapeChanged,
18854 PushedToNavHistory {
18855 anchor: Anchor,
18856 is_deactivate: bool,
18857 },
18858}
18859
18860impl EventEmitter<EditorEvent> for Editor {}
18861
18862impl Focusable for Editor {
18863 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18864 self.focus_handle.clone()
18865 }
18866}
18867
18868impl Render for Editor {
18869 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18870 let settings = ThemeSettings::get_global(cx);
18871
18872 let mut text_style = match self.mode {
18873 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18874 color: cx.theme().colors().editor_foreground,
18875 font_family: settings.ui_font.family.clone(),
18876 font_features: settings.ui_font.features.clone(),
18877 font_fallbacks: settings.ui_font.fallbacks.clone(),
18878 font_size: rems(0.875).into(),
18879 font_weight: settings.ui_font.weight,
18880 line_height: relative(settings.buffer_line_height.value()),
18881 ..Default::default()
18882 },
18883 EditorMode::Full => TextStyle {
18884 color: cx.theme().colors().editor_foreground,
18885 font_family: settings.buffer_font.family.clone(),
18886 font_features: settings.buffer_font.features.clone(),
18887 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18888 font_size: settings.buffer_font_size(cx).into(),
18889 font_weight: settings.buffer_font.weight,
18890 line_height: relative(settings.buffer_line_height.value()),
18891 ..Default::default()
18892 },
18893 };
18894 if let Some(text_style_refinement) = &self.text_style_refinement {
18895 text_style.refine(text_style_refinement)
18896 }
18897
18898 let background = match self.mode {
18899 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18900 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18901 EditorMode::Full => cx.theme().colors().editor_background,
18902 };
18903
18904 EditorElement::new(
18905 &cx.entity(),
18906 EditorStyle {
18907 background,
18908 local_player: cx.theme().players().local(),
18909 text: text_style,
18910 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18911 syntax: cx.theme().syntax().clone(),
18912 status: cx.theme().status().clone(),
18913 inlay_hints_style: make_inlay_hints_style(cx),
18914 inline_completion_styles: make_suggestion_styles(cx),
18915 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18916 },
18917 )
18918 }
18919}
18920
18921impl EntityInputHandler for Editor {
18922 fn text_for_range(
18923 &mut self,
18924 range_utf16: Range<usize>,
18925 adjusted_range: &mut Option<Range<usize>>,
18926 _: &mut Window,
18927 cx: &mut Context<Self>,
18928 ) -> Option<String> {
18929 let snapshot = self.buffer.read(cx).read(cx);
18930 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18931 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18932 if (start.0..end.0) != range_utf16 {
18933 adjusted_range.replace(start.0..end.0);
18934 }
18935 Some(snapshot.text_for_range(start..end).collect())
18936 }
18937
18938 fn selected_text_range(
18939 &mut self,
18940 ignore_disabled_input: bool,
18941 _: &mut Window,
18942 cx: &mut Context<Self>,
18943 ) -> Option<UTF16Selection> {
18944 // Prevent the IME menu from appearing when holding down an alphabetic key
18945 // while input is disabled.
18946 if !ignore_disabled_input && !self.input_enabled {
18947 return None;
18948 }
18949
18950 let selection = self.selections.newest::<OffsetUtf16>(cx);
18951 let range = selection.range();
18952
18953 Some(UTF16Selection {
18954 range: range.start.0..range.end.0,
18955 reversed: selection.reversed,
18956 })
18957 }
18958
18959 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18960 let snapshot = self.buffer.read(cx).read(cx);
18961 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18962 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18963 }
18964
18965 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18966 self.clear_highlights::<InputComposition>(cx);
18967 self.ime_transaction.take();
18968 }
18969
18970 fn replace_text_in_range(
18971 &mut self,
18972 range_utf16: Option<Range<usize>>,
18973 text: &str,
18974 window: &mut Window,
18975 cx: &mut Context<Self>,
18976 ) {
18977 if !self.input_enabled {
18978 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18979 return;
18980 }
18981
18982 self.transact(window, cx, |this, window, cx| {
18983 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18984 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18985 Some(this.selection_replacement_ranges(range_utf16, cx))
18986 } else {
18987 this.marked_text_ranges(cx)
18988 };
18989
18990 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18991 let newest_selection_id = this.selections.newest_anchor().id;
18992 this.selections
18993 .all::<OffsetUtf16>(cx)
18994 .iter()
18995 .zip(ranges_to_replace.iter())
18996 .find_map(|(selection, range)| {
18997 if selection.id == newest_selection_id {
18998 Some(
18999 (range.start.0 as isize - selection.head().0 as isize)
19000 ..(range.end.0 as isize - selection.head().0 as isize),
19001 )
19002 } else {
19003 None
19004 }
19005 })
19006 });
19007
19008 cx.emit(EditorEvent::InputHandled {
19009 utf16_range_to_replace: range_to_replace,
19010 text: text.into(),
19011 });
19012
19013 if let Some(new_selected_ranges) = new_selected_ranges {
19014 this.change_selections(None, window, cx, |selections| {
19015 selections.select_ranges(new_selected_ranges)
19016 });
19017 this.backspace(&Default::default(), window, cx);
19018 }
19019
19020 this.handle_input(text, window, cx);
19021 });
19022
19023 if let Some(transaction) = self.ime_transaction {
19024 self.buffer.update(cx, |buffer, cx| {
19025 buffer.group_until_transaction(transaction, cx);
19026 });
19027 }
19028
19029 self.unmark_text(window, cx);
19030 }
19031
19032 fn replace_and_mark_text_in_range(
19033 &mut self,
19034 range_utf16: Option<Range<usize>>,
19035 text: &str,
19036 new_selected_range_utf16: Option<Range<usize>>,
19037 window: &mut Window,
19038 cx: &mut Context<Self>,
19039 ) {
19040 if !self.input_enabled {
19041 return;
19042 }
19043
19044 let transaction = self.transact(window, cx, |this, window, cx| {
19045 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19046 let snapshot = this.buffer.read(cx).read(cx);
19047 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19048 for marked_range in &mut marked_ranges {
19049 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19050 marked_range.start.0 += relative_range_utf16.start;
19051 marked_range.start =
19052 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19053 marked_range.end =
19054 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19055 }
19056 }
19057 Some(marked_ranges)
19058 } else if let Some(range_utf16) = range_utf16 {
19059 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19060 Some(this.selection_replacement_ranges(range_utf16, cx))
19061 } else {
19062 None
19063 };
19064
19065 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19066 let newest_selection_id = this.selections.newest_anchor().id;
19067 this.selections
19068 .all::<OffsetUtf16>(cx)
19069 .iter()
19070 .zip(ranges_to_replace.iter())
19071 .find_map(|(selection, range)| {
19072 if selection.id == newest_selection_id {
19073 Some(
19074 (range.start.0 as isize - selection.head().0 as isize)
19075 ..(range.end.0 as isize - selection.head().0 as isize),
19076 )
19077 } else {
19078 None
19079 }
19080 })
19081 });
19082
19083 cx.emit(EditorEvent::InputHandled {
19084 utf16_range_to_replace: range_to_replace,
19085 text: text.into(),
19086 });
19087
19088 if let Some(ranges) = ranges_to_replace {
19089 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19090 }
19091
19092 let marked_ranges = {
19093 let snapshot = this.buffer.read(cx).read(cx);
19094 this.selections
19095 .disjoint_anchors()
19096 .iter()
19097 .map(|selection| {
19098 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19099 })
19100 .collect::<Vec<_>>()
19101 };
19102
19103 if text.is_empty() {
19104 this.unmark_text(window, cx);
19105 } else {
19106 this.highlight_text::<InputComposition>(
19107 marked_ranges.clone(),
19108 HighlightStyle {
19109 underline: Some(UnderlineStyle {
19110 thickness: px(1.),
19111 color: None,
19112 wavy: false,
19113 }),
19114 ..Default::default()
19115 },
19116 cx,
19117 );
19118 }
19119
19120 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19121 let use_autoclose = this.use_autoclose;
19122 let use_auto_surround = this.use_auto_surround;
19123 this.set_use_autoclose(false);
19124 this.set_use_auto_surround(false);
19125 this.handle_input(text, window, cx);
19126 this.set_use_autoclose(use_autoclose);
19127 this.set_use_auto_surround(use_auto_surround);
19128
19129 if let Some(new_selected_range) = new_selected_range_utf16 {
19130 let snapshot = this.buffer.read(cx).read(cx);
19131 let new_selected_ranges = marked_ranges
19132 .into_iter()
19133 .map(|marked_range| {
19134 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19135 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19136 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19137 snapshot.clip_offset_utf16(new_start, Bias::Left)
19138 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19139 })
19140 .collect::<Vec<_>>();
19141
19142 drop(snapshot);
19143 this.change_selections(None, window, cx, |selections| {
19144 selections.select_ranges(new_selected_ranges)
19145 });
19146 }
19147 });
19148
19149 self.ime_transaction = self.ime_transaction.or(transaction);
19150 if let Some(transaction) = self.ime_transaction {
19151 self.buffer.update(cx, |buffer, cx| {
19152 buffer.group_until_transaction(transaction, cx);
19153 });
19154 }
19155
19156 if self.text_highlights::<InputComposition>(cx).is_none() {
19157 self.ime_transaction.take();
19158 }
19159 }
19160
19161 fn bounds_for_range(
19162 &mut self,
19163 range_utf16: Range<usize>,
19164 element_bounds: gpui::Bounds<Pixels>,
19165 window: &mut Window,
19166 cx: &mut Context<Self>,
19167 ) -> Option<gpui::Bounds<Pixels>> {
19168 let text_layout_details = self.text_layout_details(window);
19169 let gpui::Size {
19170 width: em_width,
19171 height: line_height,
19172 } = self.character_size(window);
19173
19174 let snapshot = self.snapshot(window, cx);
19175 let scroll_position = snapshot.scroll_position();
19176 let scroll_left = scroll_position.x * em_width;
19177
19178 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19179 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19180 + self.gutter_dimensions.width
19181 + self.gutter_dimensions.margin;
19182 let y = line_height * (start.row().as_f32() - scroll_position.y);
19183
19184 Some(Bounds {
19185 origin: element_bounds.origin + point(x, y),
19186 size: size(em_width, line_height),
19187 })
19188 }
19189
19190 fn character_index_for_point(
19191 &mut self,
19192 point: gpui::Point<Pixels>,
19193 _window: &mut Window,
19194 _cx: &mut Context<Self>,
19195 ) -> Option<usize> {
19196 let position_map = self.last_position_map.as_ref()?;
19197 if !position_map.text_hitbox.contains(&point) {
19198 return None;
19199 }
19200 let display_point = position_map.point_for_position(point).previous_valid;
19201 let anchor = position_map
19202 .snapshot
19203 .display_point_to_anchor(display_point, Bias::Left);
19204 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19205 Some(utf16_offset.0)
19206 }
19207}
19208
19209trait SelectionExt {
19210 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19211 fn spanned_rows(
19212 &self,
19213 include_end_if_at_line_start: bool,
19214 map: &DisplaySnapshot,
19215 ) -> Range<MultiBufferRow>;
19216}
19217
19218impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19219 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19220 let start = self
19221 .start
19222 .to_point(&map.buffer_snapshot)
19223 .to_display_point(map);
19224 let end = self
19225 .end
19226 .to_point(&map.buffer_snapshot)
19227 .to_display_point(map);
19228 if self.reversed {
19229 end..start
19230 } else {
19231 start..end
19232 }
19233 }
19234
19235 fn spanned_rows(
19236 &self,
19237 include_end_if_at_line_start: bool,
19238 map: &DisplaySnapshot,
19239 ) -> Range<MultiBufferRow> {
19240 let start = self.start.to_point(&map.buffer_snapshot);
19241 let mut end = self.end.to_point(&map.buffer_snapshot);
19242 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19243 end.row -= 1;
19244 }
19245
19246 let buffer_start = map.prev_line_boundary(start).0;
19247 let buffer_end = map.next_line_boundary(end).0;
19248 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19249 }
19250}
19251
19252impl<T: InvalidationRegion> InvalidationStack<T> {
19253 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19254 where
19255 S: Clone + ToOffset,
19256 {
19257 while let Some(region) = self.last() {
19258 let all_selections_inside_invalidation_ranges =
19259 if selections.len() == region.ranges().len() {
19260 selections
19261 .iter()
19262 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19263 .all(|(selection, invalidation_range)| {
19264 let head = selection.head().to_offset(buffer);
19265 invalidation_range.start <= head && invalidation_range.end >= head
19266 })
19267 } else {
19268 false
19269 };
19270
19271 if all_selections_inside_invalidation_ranges {
19272 break;
19273 } else {
19274 self.pop();
19275 }
19276 }
19277 }
19278}
19279
19280impl<T> Default for InvalidationStack<T> {
19281 fn default() -> Self {
19282 Self(Default::default())
19283 }
19284}
19285
19286impl<T> Deref for InvalidationStack<T> {
19287 type Target = Vec<T>;
19288
19289 fn deref(&self) -> &Self::Target {
19290 &self.0
19291 }
19292}
19293
19294impl<T> DerefMut for InvalidationStack<T> {
19295 fn deref_mut(&mut self) -> &mut Self::Target {
19296 &mut self.0
19297 }
19298}
19299
19300impl InvalidationRegion for SnippetState {
19301 fn ranges(&self) -> &[Range<Anchor>] {
19302 &self.ranges[self.active_index]
19303 }
19304}
19305
19306pub fn diagnostic_block_renderer(
19307 diagnostic: Diagnostic,
19308 max_message_rows: Option<u8>,
19309 allow_closing: bool,
19310) -> RenderBlock {
19311 let (text_without_backticks, code_ranges) =
19312 highlight_diagnostic_message(&diagnostic, max_message_rows);
19313
19314 Arc::new(move |cx: &mut BlockContext| {
19315 let group_id: SharedString = cx.block_id.to_string().into();
19316
19317 let mut text_style = cx.window.text_style().clone();
19318 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19319 let theme_settings = ThemeSettings::get_global(cx);
19320 text_style.font_family = theme_settings.buffer_font.family.clone();
19321 text_style.font_style = theme_settings.buffer_font.style;
19322 text_style.font_features = theme_settings.buffer_font.features.clone();
19323 text_style.font_weight = theme_settings.buffer_font.weight;
19324
19325 let multi_line_diagnostic = diagnostic.message.contains('\n');
19326
19327 let buttons = |diagnostic: &Diagnostic| {
19328 if multi_line_diagnostic {
19329 v_flex()
19330 } else {
19331 h_flex()
19332 }
19333 .when(allow_closing, |div| {
19334 div.children(diagnostic.is_primary.then(|| {
19335 IconButton::new("close-block", IconName::XCircle)
19336 .icon_color(Color::Muted)
19337 .size(ButtonSize::Compact)
19338 .style(ButtonStyle::Transparent)
19339 .visible_on_hover(group_id.clone())
19340 .on_click(move |_click, window, cx| {
19341 window.dispatch_action(Box::new(Cancel), cx)
19342 })
19343 .tooltip(|window, cx| {
19344 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19345 })
19346 }))
19347 })
19348 .child(
19349 IconButton::new("copy-block", IconName::Copy)
19350 .icon_color(Color::Muted)
19351 .size(ButtonSize::Compact)
19352 .style(ButtonStyle::Transparent)
19353 .visible_on_hover(group_id.clone())
19354 .on_click({
19355 let message = diagnostic.message.clone();
19356 move |_click, _, cx| {
19357 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19358 }
19359 })
19360 .tooltip(Tooltip::text("Copy diagnostic message")),
19361 )
19362 };
19363
19364 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19365 AvailableSpace::min_size(),
19366 cx.window,
19367 cx.app,
19368 );
19369
19370 h_flex()
19371 .id(cx.block_id)
19372 .group(group_id.clone())
19373 .relative()
19374 .size_full()
19375 .block_mouse_down()
19376 .pl(cx.gutter_dimensions.width)
19377 .w(cx.max_width - cx.gutter_dimensions.full_width())
19378 .child(
19379 div()
19380 .flex()
19381 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19382 .flex_shrink(),
19383 )
19384 .child(buttons(&diagnostic))
19385 .child(div().flex().flex_shrink_0().child(
19386 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19387 &text_style,
19388 code_ranges.iter().map(|range| {
19389 (
19390 range.clone(),
19391 HighlightStyle {
19392 font_weight: Some(FontWeight::BOLD),
19393 ..Default::default()
19394 },
19395 )
19396 }),
19397 ),
19398 ))
19399 .into_any_element()
19400 })
19401}
19402
19403fn inline_completion_edit_text(
19404 current_snapshot: &BufferSnapshot,
19405 edits: &[(Range<Anchor>, String)],
19406 edit_preview: &EditPreview,
19407 include_deletions: bool,
19408 cx: &App,
19409) -> HighlightedText {
19410 let edits = edits
19411 .iter()
19412 .map(|(anchor, text)| {
19413 (
19414 anchor.start.text_anchor..anchor.end.text_anchor,
19415 text.clone(),
19416 )
19417 })
19418 .collect::<Vec<_>>();
19419
19420 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19421}
19422
19423pub fn highlight_diagnostic_message(
19424 diagnostic: &Diagnostic,
19425 mut max_message_rows: Option<u8>,
19426) -> (SharedString, Vec<Range<usize>>) {
19427 let mut text_without_backticks = String::new();
19428 let mut code_ranges = Vec::new();
19429
19430 if let Some(source) = &diagnostic.source {
19431 text_without_backticks.push_str(source);
19432 code_ranges.push(0..source.len());
19433 text_without_backticks.push_str(": ");
19434 }
19435
19436 let mut prev_offset = 0;
19437 let mut in_code_block = false;
19438 let has_row_limit = max_message_rows.is_some();
19439 let mut newline_indices = diagnostic
19440 .message
19441 .match_indices('\n')
19442 .filter(|_| has_row_limit)
19443 .map(|(ix, _)| ix)
19444 .fuse()
19445 .peekable();
19446
19447 for (quote_ix, _) in diagnostic
19448 .message
19449 .match_indices('`')
19450 .chain([(diagnostic.message.len(), "")])
19451 {
19452 let mut first_newline_ix = None;
19453 let mut last_newline_ix = None;
19454 while let Some(newline_ix) = newline_indices.peek() {
19455 if *newline_ix < quote_ix {
19456 if first_newline_ix.is_none() {
19457 first_newline_ix = Some(*newline_ix);
19458 }
19459 last_newline_ix = Some(*newline_ix);
19460
19461 if let Some(rows_left) = &mut max_message_rows {
19462 if *rows_left == 0 {
19463 break;
19464 } else {
19465 *rows_left -= 1;
19466 }
19467 }
19468 let _ = newline_indices.next();
19469 } else {
19470 break;
19471 }
19472 }
19473 let prev_len = text_without_backticks.len();
19474 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19475 text_without_backticks.push_str(new_text);
19476 if in_code_block {
19477 code_ranges.push(prev_len..text_without_backticks.len());
19478 }
19479 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19480 in_code_block = !in_code_block;
19481 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19482 text_without_backticks.push_str("...");
19483 break;
19484 }
19485 }
19486
19487 (text_without_backticks.into(), code_ranges)
19488}
19489
19490fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19491 match severity {
19492 DiagnosticSeverity::ERROR => colors.error,
19493 DiagnosticSeverity::WARNING => colors.warning,
19494 DiagnosticSeverity::INFORMATION => colors.info,
19495 DiagnosticSeverity::HINT => colors.info,
19496 _ => colors.ignored,
19497 }
19498}
19499
19500pub fn styled_runs_for_code_label<'a>(
19501 label: &'a CodeLabel,
19502 syntax_theme: &'a theme::SyntaxTheme,
19503) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19504 let fade_out = HighlightStyle {
19505 fade_out: Some(0.35),
19506 ..Default::default()
19507 };
19508
19509 let mut prev_end = label.filter_range.end;
19510 label
19511 .runs
19512 .iter()
19513 .enumerate()
19514 .flat_map(move |(ix, (range, highlight_id))| {
19515 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19516 style
19517 } else {
19518 return Default::default();
19519 };
19520 let mut muted_style = style;
19521 muted_style.highlight(fade_out);
19522
19523 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19524 if range.start >= label.filter_range.end {
19525 if range.start > prev_end {
19526 runs.push((prev_end..range.start, fade_out));
19527 }
19528 runs.push((range.clone(), muted_style));
19529 } else if range.end <= label.filter_range.end {
19530 runs.push((range.clone(), style));
19531 } else {
19532 runs.push((range.start..label.filter_range.end, style));
19533 runs.push((label.filter_range.end..range.end, muted_style));
19534 }
19535 prev_end = cmp::max(prev_end, range.end);
19536
19537 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19538 runs.push((prev_end..label.text.len(), fade_out));
19539 }
19540
19541 runs
19542 })
19543}
19544
19545pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19546 let mut prev_index = 0;
19547 let mut prev_codepoint: Option<char> = None;
19548 text.char_indices()
19549 .chain([(text.len(), '\0')])
19550 .filter_map(move |(index, codepoint)| {
19551 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19552 let is_boundary = index == text.len()
19553 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19554 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19555 if is_boundary {
19556 let chunk = &text[prev_index..index];
19557 prev_index = index;
19558 Some(chunk)
19559 } else {
19560 None
19561 }
19562 })
19563}
19564
19565pub trait RangeToAnchorExt: Sized {
19566 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19567
19568 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19569 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19570 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19571 }
19572}
19573
19574impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19575 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19576 let start_offset = self.start.to_offset(snapshot);
19577 let end_offset = self.end.to_offset(snapshot);
19578 if start_offset == end_offset {
19579 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19580 } else {
19581 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19582 }
19583 }
19584}
19585
19586pub trait RowExt {
19587 fn as_f32(&self) -> f32;
19588
19589 fn next_row(&self) -> Self;
19590
19591 fn previous_row(&self) -> Self;
19592
19593 fn minus(&self, other: Self) -> u32;
19594}
19595
19596impl RowExt for DisplayRow {
19597 fn as_f32(&self) -> f32 {
19598 self.0 as f32
19599 }
19600
19601 fn next_row(&self) -> Self {
19602 Self(self.0 + 1)
19603 }
19604
19605 fn previous_row(&self) -> Self {
19606 Self(self.0.saturating_sub(1))
19607 }
19608
19609 fn minus(&self, other: Self) -> u32 {
19610 self.0 - other.0
19611 }
19612}
19613
19614impl RowExt for MultiBufferRow {
19615 fn as_f32(&self) -> f32 {
19616 self.0 as f32
19617 }
19618
19619 fn next_row(&self) -> Self {
19620 Self(self.0 + 1)
19621 }
19622
19623 fn previous_row(&self) -> Self {
19624 Self(self.0.saturating_sub(1))
19625 }
19626
19627 fn minus(&self, other: Self) -> u32 {
19628 self.0 - other.0
19629 }
19630}
19631
19632trait RowRangeExt {
19633 type Row;
19634
19635 fn len(&self) -> usize;
19636
19637 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19638}
19639
19640impl RowRangeExt for Range<MultiBufferRow> {
19641 type Row = MultiBufferRow;
19642
19643 fn len(&self) -> usize {
19644 (self.end.0 - self.start.0) as usize
19645 }
19646
19647 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19648 (self.start.0..self.end.0).map(MultiBufferRow)
19649 }
19650}
19651
19652impl RowRangeExt for Range<DisplayRow> {
19653 type Row = DisplayRow;
19654
19655 fn len(&self) -> usize {
19656 (self.end.0 - self.start.0) as usize
19657 }
19658
19659 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19660 (self.start.0..self.end.0).map(DisplayRow)
19661 }
19662}
19663
19664/// If select range has more than one line, we
19665/// just point the cursor to range.start.
19666fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19667 if range.start.row == range.end.row {
19668 range
19669 } else {
19670 range.start..range.start
19671 }
19672}
19673pub struct KillRing(ClipboardItem);
19674impl Global for KillRing {}
19675
19676const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19677
19678struct BreakpointPromptEditor {
19679 pub(crate) prompt: Entity<Editor>,
19680 editor: WeakEntity<Editor>,
19681 breakpoint_anchor: Anchor,
19682 breakpoint: Breakpoint,
19683 block_ids: HashSet<CustomBlockId>,
19684 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19685 _subscriptions: Vec<Subscription>,
19686}
19687
19688impl BreakpointPromptEditor {
19689 const MAX_LINES: u8 = 4;
19690
19691 fn new(
19692 editor: WeakEntity<Editor>,
19693 breakpoint_anchor: Anchor,
19694 breakpoint: Breakpoint,
19695 window: &mut Window,
19696 cx: &mut Context<Self>,
19697 ) -> Self {
19698 let buffer = cx.new(|cx| {
19699 Buffer::local(
19700 breakpoint
19701 .kind
19702 .log_message()
19703 .map(|msg| msg.to_string())
19704 .unwrap_or_default(),
19705 cx,
19706 )
19707 });
19708 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19709
19710 let prompt = cx.new(|cx| {
19711 let mut prompt = Editor::new(
19712 EditorMode::AutoHeight {
19713 max_lines: Self::MAX_LINES as usize,
19714 },
19715 buffer,
19716 None,
19717 window,
19718 cx,
19719 );
19720 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19721 prompt.set_show_cursor_when_unfocused(false, cx);
19722 prompt.set_placeholder_text(
19723 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19724 cx,
19725 );
19726
19727 prompt
19728 });
19729
19730 Self {
19731 prompt,
19732 editor,
19733 breakpoint_anchor,
19734 breakpoint,
19735 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19736 block_ids: Default::default(),
19737 _subscriptions: vec![],
19738 }
19739 }
19740
19741 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19742 self.block_ids.extend(block_ids)
19743 }
19744
19745 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19746 if let Some(editor) = self.editor.upgrade() {
19747 let log_message = self
19748 .prompt
19749 .read(cx)
19750 .buffer
19751 .read(cx)
19752 .as_singleton()
19753 .expect("A multi buffer in breakpoint prompt isn't possible")
19754 .read(cx)
19755 .as_rope()
19756 .to_string();
19757
19758 editor.update(cx, |editor, cx| {
19759 editor.edit_breakpoint_at_anchor(
19760 self.breakpoint_anchor,
19761 self.breakpoint.clone(),
19762 BreakpointEditAction::EditLogMessage(log_message.into()),
19763 cx,
19764 );
19765
19766 editor.remove_blocks(self.block_ids.clone(), None, cx);
19767 cx.focus_self(window);
19768 });
19769 }
19770 }
19771
19772 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19773 self.editor
19774 .update(cx, |editor, cx| {
19775 editor.remove_blocks(self.block_ids.clone(), None, cx);
19776 window.focus(&editor.focus_handle);
19777 })
19778 .log_err();
19779 }
19780
19781 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19782 let settings = ThemeSettings::get_global(cx);
19783 let text_style = TextStyle {
19784 color: if self.prompt.read(cx).read_only(cx) {
19785 cx.theme().colors().text_disabled
19786 } else {
19787 cx.theme().colors().text
19788 },
19789 font_family: settings.buffer_font.family.clone(),
19790 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19791 font_size: settings.buffer_font_size(cx).into(),
19792 font_weight: settings.buffer_font.weight,
19793 line_height: relative(settings.buffer_line_height.value()),
19794 ..Default::default()
19795 };
19796 EditorElement::new(
19797 &self.prompt,
19798 EditorStyle {
19799 background: cx.theme().colors().editor_background,
19800 local_player: cx.theme().players().local(),
19801 text: text_style,
19802 ..Default::default()
19803 },
19804 )
19805 }
19806}
19807
19808impl Render for BreakpointPromptEditor {
19809 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19810 let gutter_dimensions = *self.gutter_dimensions.lock();
19811 h_flex()
19812 .key_context("Editor")
19813 .bg(cx.theme().colors().editor_background)
19814 .border_y_1()
19815 .border_color(cx.theme().status().info_border)
19816 .size_full()
19817 .py(window.line_height() / 2.5)
19818 .on_action(cx.listener(Self::confirm))
19819 .on_action(cx.listener(Self::cancel))
19820 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19821 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19822 }
19823}
19824
19825impl Focusable for BreakpointPromptEditor {
19826 fn focus_handle(&self, cx: &App) -> FocusHandle {
19827 self.prompt.focus_handle(cx)
19828 }
19829}
19830
19831fn all_edits_insertions_or_deletions(
19832 edits: &Vec<(Range<Anchor>, String)>,
19833 snapshot: &MultiBufferSnapshot,
19834) -> bool {
19835 let mut all_insertions = true;
19836 let mut all_deletions = true;
19837
19838 for (range, new_text) in edits.iter() {
19839 let range_is_empty = range.to_offset(&snapshot).is_empty();
19840 let text_is_empty = new_text.is_empty();
19841
19842 if range_is_empty != text_is_empty {
19843 if range_is_empty {
19844 all_deletions = false;
19845 } else {
19846 all_insertions = false;
19847 }
19848 } else {
19849 return false;
19850 }
19851
19852 if !all_insertions && !all_deletions {
19853 return false;
19854 }
19855 }
19856 all_insertions || all_deletions
19857}
19858
19859struct MissingEditPredictionKeybindingTooltip;
19860
19861impl Render for MissingEditPredictionKeybindingTooltip {
19862 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19863 ui::tooltip_container(window, cx, |container, _, cx| {
19864 container
19865 .flex_shrink_0()
19866 .max_w_80()
19867 .min_h(rems_from_px(124.))
19868 .justify_between()
19869 .child(
19870 v_flex()
19871 .flex_1()
19872 .text_ui_sm(cx)
19873 .child(Label::new("Conflict with Accept Keybinding"))
19874 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19875 )
19876 .child(
19877 h_flex()
19878 .pb_1()
19879 .gap_1()
19880 .items_end()
19881 .w_full()
19882 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19883 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19884 }))
19885 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19886 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19887 })),
19888 )
19889 })
19890 }
19891}
19892
19893#[derive(Debug, Clone, Copy, PartialEq)]
19894pub struct LineHighlight {
19895 pub background: Background,
19896 pub border: Option<gpui::Hsla>,
19897}
19898
19899impl From<Hsla> for LineHighlight {
19900 fn from(hsla: Hsla) -> Self {
19901 Self {
19902 background: hsla.into(),
19903 border: None,
19904 }
19905 }
19906}
19907
19908impl From<Background> for LineHighlight {
19909 fn from(background: Background) -> Self {
19910 Self {
19911 background,
19912 border: None,
19913 }
19914 }
19915}