1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
84 ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
85 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
86 HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
87 PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
88 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
89 WeakEntity, WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
103 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
104 TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109use persistence::DB;
110pub use proposed_changes_editor::{
111 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
112};
113use similar::{ChangeTag, TextDiff};
114use std::iter::Peekable;
115use task::{ResolvedTask, TaskTemplate, TaskVariables};
116
117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
118pub use lsp::CompletionContext;
119use lsp::{
120 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
121 LanguageServerId, LanguageServerName,
122};
123
124use language::BufferSnapshot;
125use movement::TextLayoutDetails;
126pub use multi_buffer::{
127 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
128 ToOffset, ToPoint,
129};
130use multi_buffer::{
131 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
132 ToOffsetUtf16,
133};
134use project::{
135 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
136 project_settings::{GitGutterSetting, ProjectSettings},
137 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
138 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
139};
140use rand::prelude::*;
141use rpc::{proto::*, ErrorExt};
142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
143use selections_collection::{
144 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
145};
146use serde::{Deserialize, Serialize};
147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
148use smallvec::SmallVec;
149use snippet::Snippet;
150use std::{
151 any::TypeId,
152 borrow::Cow,
153 cell::RefCell,
154 cmp::{self, Ordering, Reverse},
155 mem,
156 num::NonZeroU32,
157 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
158 path::{Path, PathBuf},
159 rc::Rc,
160 sync::Arc,
161 time::{Duration, Instant},
162};
163pub use sum_tree::Bias;
164use sum_tree::TreeMap;
165use text::{BufferId, OffsetUtf16, Rope};
166use theme::{
167 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
168 ThemeColors, ThemeSettings,
169};
170use ui::{
171 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
172 Tooltip,
173};
174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
175use workspace::{
176 item::{ItemHandle, PreviewTabsSettings},
177 ItemId, RestoreOnStartupBehavior,
178};
179use workspace::{
180 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
181 WorkspaceSettings,
182};
183use workspace::{
184 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
185};
186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
187
188use crate::hover_links::{find_url, find_url_from_range};
189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
190
191pub const FILE_HEADER_HEIGHT: u32 = 2;
192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
196const MAX_LINE_LEN: usize = 1024;
197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
200#[doc(hidden)]
201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
202
203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
205
206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
208
209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
210 alt: true,
211 shift: true,
212 control: false,
213 platform: false,
214 function: false,
215};
216
217pub fn render_parsed_markdown(
218 element_id: impl Into<ElementId>,
219 parsed: &language::ParsedMarkdown,
220 editor_style: &EditorStyle,
221 workspace: Option<WeakEntity<Workspace>>,
222 cx: &mut App,
223) -> InteractiveText {
224 let code_span_background_color = cx
225 .theme()
226 .colors()
227 .editor_document_highlight_read_background;
228
229 let highlights = gpui::combine_highlights(
230 parsed.highlights.iter().filter_map(|(range, highlight)| {
231 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
232 Some((range.clone(), highlight))
233 }),
234 parsed
235 .regions
236 .iter()
237 .zip(&parsed.region_ranges)
238 .filter_map(|(region, range)| {
239 if region.code {
240 Some((
241 range.clone(),
242 HighlightStyle {
243 background_color: Some(code_span_background_color),
244 ..Default::default()
245 },
246 ))
247 } else {
248 None
249 }
250 }),
251 );
252
253 let mut links = Vec::new();
254 let mut link_ranges = Vec::new();
255 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
256 if let Some(link) = region.link.clone() {
257 links.push(link);
258 link_ranges.push(range.clone());
259 }
260 }
261
262 InteractiveText::new(
263 element_id,
264 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
265 )
266 .on_click(
267 link_ranges,
268 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
269 markdown::Link::Web { url } => cx.open_url(url),
270 markdown::Link::Path { path } => {
271 if let Some(workspace) = &workspace {
272 _ = workspace.update(cx, |workspace, cx| {
273 workspace
274 .open_abs_path(path.clone(), false, window, cx)
275 .detach();
276 });
277 }
278 }
279 },
280 )
281}
282
283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub enum InlayId {
285 InlineCompletion(usize),
286 Hint(usize),
287}
288
289impl InlayId {
290 fn id(&self) -> usize {
291 match self {
292 Self::InlineCompletion(id) => *id,
293 Self::Hint(id) => *id,
294 }
295 }
296}
297
298enum DocumentHighlightRead {}
299enum DocumentHighlightWrite {}
300enum InputComposition {}
301enum SelectedTextHighlight {}
302
303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
304pub enum Navigated {
305 Yes,
306 No,
307}
308
309impl Navigated {
310 pub fn from_bool(yes: bool) -> Navigated {
311 if yes {
312 Navigated::Yes
313 } else {
314 Navigated::No
315 }
316 }
317}
318
319pub fn init_settings(cx: &mut App) {
320 EditorSettings::register(cx);
321}
322
323pub fn init(cx: &mut App) {
324 init_settings(cx);
325
326 workspace::register_project_item::<Editor>(cx);
327 workspace::FollowableViewRegistry::register::<Editor>(cx);
328 workspace::register_serializable_item::<Editor>(cx);
329
330 cx.observe_new(
331 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
332 workspace.register_action(Editor::new_file);
333 workspace.register_action(Editor::new_file_vertical);
334 workspace.register_action(Editor::new_file_horizontal);
335 workspace.register_action(Editor::cancel_language_server_work);
336 },
337 )
338 .detach();
339
340 cx.on_action(move |_: &workspace::NewFile, cx| {
341 let app_state = workspace::AppState::global(cx);
342 if let Some(app_state) = app_state.upgrade() {
343 workspace::open_new(
344 Default::default(),
345 app_state,
346 cx,
347 |workspace, window, cx| {
348 Editor::new_file(workspace, &Default::default(), window, cx)
349 },
350 )
351 .detach();
352 }
353 });
354 cx.on_action(move |_: &workspace::NewWindow, cx| {
355 let app_state = workspace::AppState::global(cx);
356 if let Some(app_state) = app_state.upgrade() {
357 workspace::open_new(
358 Default::default(),
359 app_state,
360 cx,
361 |workspace, window, cx| {
362 cx.activate(true);
363 Editor::new_file(workspace, &Default::default(), window, cx)
364 },
365 )
366 .detach();
367 }
368 });
369}
370
371pub struct SearchWithinRange;
372
373trait InvalidationRegion {
374 fn ranges(&self) -> &[Range<Anchor>];
375}
376
377#[derive(Clone, Debug, PartialEq)]
378pub enum SelectPhase {
379 Begin {
380 position: DisplayPoint,
381 add: bool,
382 click_count: usize,
383 },
384 BeginColumnar {
385 position: DisplayPoint,
386 reset: bool,
387 goal_column: u32,
388 },
389 Extend {
390 position: DisplayPoint,
391 click_count: usize,
392 },
393 Update {
394 position: DisplayPoint,
395 goal_column: u32,
396 scroll_delta: gpui::Point<f32>,
397 },
398 End,
399}
400
401#[derive(Clone, Debug)]
402pub enum SelectMode {
403 Character,
404 Word(Range<Anchor>),
405 Line(Range<Anchor>),
406 All,
407}
408
409#[derive(Copy, Clone, PartialEq, Eq, Debug)]
410pub enum EditorMode {
411 SingleLine { auto_width: bool },
412 AutoHeight { max_lines: usize },
413 Full,
414}
415
416#[derive(Copy, Clone, Debug)]
417pub enum SoftWrap {
418 /// Prefer not to wrap at all.
419 ///
420 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
421 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
422 GitDiff,
423 /// Prefer a single line generally, unless an overly long line is encountered.
424 None,
425 /// Soft wrap lines that exceed the editor width.
426 EditorWidth,
427 /// Soft wrap lines at the preferred line length.
428 Column(u32),
429 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
430 Bounded(u32),
431}
432
433#[derive(Clone)]
434pub struct EditorStyle {
435 pub background: Hsla,
436 pub local_player: PlayerColor,
437 pub text: TextStyle,
438 pub scrollbar_width: Pixels,
439 pub syntax: Arc<SyntaxTheme>,
440 pub status: StatusColors,
441 pub inlay_hints_style: HighlightStyle,
442 pub inline_completion_styles: InlineCompletionStyles,
443 pub unnecessary_code_fade: f32,
444}
445
446impl Default for EditorStyle {
447 fn default() -> Self {
448 Self {
449 background: Hsla::default(),
450 local_player: PlayerColor::default(),
451 text: TextStyle::default(),
452 scrollbar_width: Pixels::default(),
453 syntax: Default::default(),
454 // HACK: Status colors don't have a real default.
455 // We should look into removing the status colors from the editor
456 // style and retrieve them directly from the theme.
457 status: StatusColors::dark(),
458 inlay_hints_style: HighlightStyle::default(),
459 inline_completion_styles: InlineCompletionStyles {
460 insertion: HighlightStyle::default(),
461 whitespace: HighlightStyle::default(),
462 },
463 unnecessary_code_fade: Default::default(),
464 }
465 }
466}
467
468pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
469 let show_background = language_settings::language_settings(None, None, cx)
470 .inlay_hints
471 .show_background;
472
473 HighlightStyle {
474 color: Some(cx.theme().status().hint),
475 background_color: show_background.then(|| cx.theme().status().hint_background),
476 ..HighlightStyle::default()
477 }
478}
479
480pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
481 InlineCompletionStyles {
482 insertion: HighlightStyle {
483 color: Some(cx.theme().status().predictive),
484 ..HighlightStyle::default()
485 },
486 whitespace: HighlightStyle {
487 background_color: Some(cx.theme().status().created_background),
488 ..HighlightStyle::default()
489 },
490 }
491}
492
493type CompletionId = usize;
494
495pub(crate) enum EditDisplayMode {
496 TabAccept,
497 DiffPopover,
498 Inline,
499}
500
501enum InlineCompletion {
502 Edit {
503 edits: Vec<(Range<Anchor>, String)>,
504 edit_preview: Option<EditPreview>,
505 display_mode: EditDisplayMode,
506 snapshot: BufferSnapshot,
507 },
508 Move {
509 target: Anchor,
510 snapshot: BufferSnapshot,
511 },
512}
513
514struct InlineCompletionState {
515 inlay_ids: Vec<InlayId>,
516 completion: InlineCompletion,
517 completion_id: Option<SharedString>,
518 invalidation_range: Range<Anchor>,
519}
520
521enum EditPredictionSettings {
522 Disabled,
523 Enabled {
524 show_in_menu: bool,
525 preview_requires_modifier: bool,
526 },
527}
528
529enum InlineCompletionHighlight {}
530
531pub enum MenuInlineCompletionsPolicy {
532 Never,
533 ByProvider,
534}
535
536pub enum EditPredictionPreview {
537 /// Modifier is not pressed
538 Inactive,
539 /// Modifier pressed
540 Active {
541 previous_scroll_position: Option<ScrollAnchor>,
542 },
543}
544
545#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
546struct EditorActionId(usize);
547
548impl EditorActionId {
549 pub fn post_inc(&mut self) -> Self {
550 let answer = self.0;
551
552 *self = Self(answer + 1);
553
554 Self(answer)
555 }
556}
557
558// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
559// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
560
561type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
562type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
563
564#[derive(Default)]
565struct ScrollbarMarkerState {
566 scrollbar_size: Size<Pixels>,
567 dirty: bool,
568 markers: Arc<[PaintQuad]>,
569 pending_refresh: Option<Task<Result<()>>>,
570}
571
572impl ScrollbarMarkerState {
573 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
574 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
575 }
576}
577
578#[derive(Clone, Debug)]
579struct RunnableTasks {
580 templates: Vec<(TaskSourceKind, TaskTemplate)>,
581 offset: MultiBufferOffset,
582 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
583 column: u32,
584 // Values of all named captures, including those starting with '_'
585 extra_variables: HashMap<String, String>,
586 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
587 context_range: Range<BufferOffset>,
588}
589
590impl RunnableTasks {
591 fn resolve<'a>(
592 &'a self,
593 cx: &'a task::TaskContext,
594 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
595 self.templates.iter().filter_map(|(kind, template)| {
596 template
597 .resolve_task(&kind.to_id_base(), cx)
598 .map(|task| (kind.clone(), task))
599 })
600 }
601}
602
603#[derive(Clone)]
604struct ResolvedTasks {
605 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
606 position: Anchor,
607}
608#[derive(Copy, Clone, Debug)]
609struct MultiBufferOffset(usize);
610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
611struct BufferOffset(usize);
612
613// Addons allow storing per-editor state in other crates (e.g. Vim)
614pub trait Addon: 'static {
615 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
616
617 fn render_buffer_header_controls(
618 &self,
619 _: &ExcerptInfo,
620 _: &Window,
621 _: &App,
622 ) -> Option<AnyElement> {
623 None
624 }
625
626 fn to_any(&self) -> &dyn std::any::Any;
627}
628
629#[derive(Debug, Copy, Clone, PartialEq, Eq)]
630pub enum IsVimMode {
631 Yes,
632 No,
633}
634
635/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
636///
637/// See the [module level documentation](self) for more information.
638pub struct Editor {
639 focus_handle: FocusHandle,
640 last_focused_descendant: Option<WeakFocusHandle>,
641 /// The text buffer being edited
642 buffer: Entity<MultiBuffer>,
643 /// Map of how text in the buffer should be displayed.
644 /// Handles soft wraps, folds, fake inlay text insertions, etc.
645 pub display_map: Entity<DisplayMap>,
646 pub selections: SelectionsCollection,
647 pub scroll_manager: ScrollManager,
648 /// When inline assist editors are linked, they all render cursors because
649 /// typing enters text into each of them, even the ones that aren't focused.
650 pub(crate) show_cursor_when_unfocused: bool,
651 columnar_selection_tail: Option<Anchor>,
652 add_selections_state: Option<AddSelectionsState>,
653 select_next_state: Option<SelectNextState>,
654 select_prev_state: Option<SelectNextState>,
655 selection_history: SelectionHistory,
656 autoclose_regions: Vec<AutocloseRegion>,
657 snippet_stack: InvalidationStack<SnippetState>,
658 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
659 ime_transaction: Option<TransactionId>,
660 active_diagnostics: Option<ActiveDiagnosticGroup>,
661 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
662
663 // TODO: make this a access method
664 pub project: Option<Entity<Project>>,
665 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
666 completion_provider: Option<Box<dyn CompletionProvider>>,
667 collaboration_hub: Option<Box<dyn CollaborationHub>>,
668 blink_manager: Entity<BlinkManager>,
669 show_cursor_names: bool,
670 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
671 pub show_local_selections: bool,
672 mode: EditorMode,
673 show_breadcrumbs: bool,
674 show_gutter: bool,
675 show_scrollbars: bool,
676 show_line_numbers: Option<bool>,
677 use_relative_line_numbers: Option<bool>,
678 show_git_diff_gutter: Option<bool>,
679 show_code_actions: Option<bool>,
680 show_runnables: Option<bool>,
681 show_wrap_guides: Option<bool>,
682 show_indent_guides: Option<bool>,
683 placeholder_text: Option<Arc<str>>,
684 highlight_order: usize,
685 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
686 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
687 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
688 scrollbar_marker_state: ScrollbarMarkerState,
689 active_indent_guides_state: ActiveIndentGuidesState,
690 nav_history: Option<ItemNavHistory>,
691 context_menu: RefCell<Option<CodeContextMenu>>,
692 mouse_context_menu: Option<MouseContextMenu>,
693 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
694 signature_help_state: SignatureHelpState,
695 auto_signature_help: Option<bool>,
696 find_all_references_task_sources: Vec<Anchor>,
697 next_completion_id: CompletionId,
698 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
699 code_actions_task: Option<Task<Result<()>>>,
700 selection_highlight_task: Option<Task<()>>,
701 document_highlights_task: Option<Task<()>>,
702 linked_editing_range_task: Option<Task<Option<()>>>,
703 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
704 pending_rename: Option<RenameState>,
705 searchable: bool,
706 cursor_shape: CursorShape,
707 current_line_highlight: Option<CurrentLineHighlight>,
708 collapse_matches: bool,
709 autoindent_mode: Option<AutoindentMode>,
710 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
711 input_enabled: bool,
712 use_modal_editing: bool,
713 read_only: bool,
714 leader_peer_id: Option<PeerId>,
715 remote_id: Option<ViewId>,
716 hover_state: HoverState,
717 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
718 gutter_hovered: bool,
719 hovered_link_state: Option<HoveredLinkState>,
720 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
721 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
722 active_inline_completion: Option<InlineCompletionState>,
723 /// Used to prevent flickering as the user types while the menu is open
724 stale_inline_completion_in_menu: Option<InlineCompletionState>,
725 edit_prediction_settings: EditPredictionSettings,
726 inline_completions_hidden_for_vim_mode: bool,
727 show_inline_completions_override: Option<bool>,
728 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
729 edit_prediction_preview: EditPredictionPreview,
730 edit_prediction_cursor_on_leading_whitespace: bool,
731 edit_prediction_requires_modifier_in_leading_space: bool,
732 inlay_hint_cache: InlayHintCache,
733 next_inlay_id: usize,
734 _subscriptions: Vec<Subscription>,
735 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
736 gutter_dimensions: GutterDimensions,
737 style: Option<EditorStyle>,
738 text_style_refinement: Option<TextStyleRefinement>,
739 next_editor_action_id: EditorActionId,
740 editor_actions:
741 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
742 use_autoclose: bool,
743 use_auto_surround: bool,
744 auto_replace_emoji_shortcode: bool,
745 show_git_blame_gutter: bool,
746 show_git_blame_inline: bool,
747 show_git_blame_inline_delay_task: Option<Task<()>>,
748 distinguish_unstaged_diff_hunks: bool,
749 git_blame_inline_enabled: bool,
750 serialize_dirty_buffers: bool,
751 show_selection_menu: Option<bool>,
752 blame: Option<Entity<GitBlame>>,
753 blame_subscription: Option<Subscription>,
754 custom_context_menu: Option<
755 Box<
756 dyn 'static
757 + Fn(
758 &mut Self,
759 DisplayPoint,
760 &mut Window,
761 &mut Context<Self>,
762 ) -> Option<Entity<ui::ContextMenu>>,
763 >,
764 >,
765 last_bounds: Option<Bounds<Pixels>>,
766 last_position_map: Option<Rc<PositionMap>>,
767 expect_bounds_change: Option<Bounds<Pixels>>,
768 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
769 tasks_update_task: Option<Task<()>>,
770 in_project_search: bool,
771 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
772 breadcrumb_header: Option<String>,
773 focused_block: Option<FocusedBlock>,
774 next_scroll_position: NextScrollCursorCenterTopBottom,
775 addons: HashMap<TypeId, Box<dyn Addon>>,
776 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
777 load_diff_task: Option<Shared<Task<()>>>,
778 selection_mark_mode: bool,
779 toggle_fold_multiple_buffers: Task<()>,
780 _scroll_cursor_center_top_bottom_task: Task<()>,
781 serialize_selections: Task<()>,
782}
783
784#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
785enum NextScrollCursorCenterTopBottom {
786 #[default]
787 Center,
788 Top,
789 Bottom,
790}
791
792impl NextScrollCursorCenterTopBottom {
793 fn next(&self) -> Self {
794 match self {
795 Self::Center => Self::Top,
796 Self::Top => Self::Bottom,
797 Self::Bottom => Self::Center,
798 }
799 }
800}
801
802#[derive(Clone)]
803pub struct EditorSnapshot {
804 pub mode: EditorMode,
805 show_gutter: bool,
806 show_line_numbers: Option<bool>,
807 show_git_diff_gutter: Option<bool>,
808 show_code_actions: Option<bool>,
809 show_runnables: Option<bool>,
810 git_blame_gutter_max_author_length: Option<usize>,
811 pub display_snapshot: DisplaySnapshot,
812 pub placeholder_text: Option<Arc<str>>,
813 is_focused: bool,
814 scroll_anchor: ScrollAnchor,
815 ongoing_scroll: OngoingScroll,
816 current_line_highlight: CurrentLineHighlight,
817 gutter_hovered: bool,
818}
819
820const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
821
822#[derive(Default, Debug, Clone, Copy)]
823pub struct GutterDimensions {
824 pub left_padding: Pixels,
825 pub right_padding: Pixels,
826 pub width: Pixels,
827 pub margin: Pixels,
828 pub git_blame_entries_width: Option<Pixels>,
829}
830
831impl GutterDimensions {
832 /// The full width of the space taken up by the gutter.
833 pub fn full_width(&self) -> Pixels {
834 self.margin + self.width
835 }
836
837 /// The width of the space reserved for the fold indicators,
838 /// use alongside 'justify_end' and `gutter_width` to
839 /// right align content with the line numbers
840 pub fn fold_area_width(&self) -> Pixels {
841 self.margin + self.right_padding
842 }
843}
844
845#[derive(Debug)]
846pub struct RemoteSelection {
847 pub replica_id: ReplicaId,
848 pub selection: Selection<Anchor>,
849 pub cursor_shape: CursorShape,
850 pub peer_id: PeerId,
851 pub line_mode: bool,
852 pub participant_index: Option<ParticipantIndex>,
853 pub user_name: Option<SharedString>,
854}
855
856#[derive(Clone, Debug)]
857struct SelectionHistoryEntry {
858 selections: Arc<[Selection<Anchor>]>,
859 select_next_state: Option<SelectNextState>,
860 select_prev_state: Option<SelectNextState>,
861 add_selections_state: Option<AddSelectionsState>,
862}
863
864enum SelectionHistoryMode {
865 Normal,
866 Undoing,
867 Redoing,
868}
869
870#[derive(Clone, PartialEq, Eq, Hash)]
871struct HoveredCursor {
872 replica_id: u16,
873 selection_id: usize,
874}
875
876impl Default for SelectionHistoryMode {
877 fn default() -> Self {
878 Self::Normal
879 }
880}
881
882#[derive(Default)]
883struct SelectionHistory {
884 #[allow(clippy::type_complexity)]
885 selections_by_transaction:
886 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
887 mode: SelectionHistoryMode,
888 undo_stack: VecDeque<SelectionHistoryEntry>,
889 redo_stack: VecDeque<SelectionHistoryEntry>,
890}
891
892impl SelectionHistory {
893 fn insert_transaction(
894 &mut self,
895 transaction_id: TransactionId,
896 selections: Arc<[Selection<Anchor>]>,
897 ) {
898 self.selections_by_transaction
899 .insert(transaction_id, (selections, None));
900 }
901
902 #[allow(clippy::type_complexity)]
903 fn transaction(
904 &self,
905 transaction_id: TransactionId,
906 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
907 self.selections_by_transaction.get(&transaction_id)
908 }
909
910 #[allow(clippy::type_complexity)]
911 fn transaction_mut(
912 &mut self,
913 transaction_id: TransactionId,
914 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
915 self.selections_by_transaction.get_mut(&transaction_id)
916 }
917
918 fn push(&mut self, entry: SelectionHistoryEntry) {
919 if !entry.selections.is_empty() {
920 match self.mode {
921 SelectionHistoryMode::Normal => {
922 self.push_undo(entry);
923 self.redo_stack.clear();
924 }
925 SelectionHistoryMode::Undoing => self.push_redo(entry),
926 SelectionHistoryMode::Redoing => self.push_undo(entry),
927 }
928 }
929 }
930
931 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
932 if self
933 .undo_stack
934 .back()
935 .map_or(true, |e| e.selections != entry.selections)
936 {
937 self.undo_stack.push_back(entry);
938 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
939 self.undo_stack.pop_front();
940 }
941 }
942 }
943
944 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
945 if self
946 .redo_stack
947 .back()
948 .map_or(true, |e| e.selections != entry.selections)
949 {
950 self.redo_stack.push_back(entry);
951 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
952 self.redo_stack.pop_front();
953 }
954 }
955 }
956}
957
958struct RowHighlight {
959 index: usize,
960 range: Range<Anchor>,
961 color: Hsla,
962 should_autoscroll: bool,
963}
964
965#[derive(Clone, Debug)]
966struct AddSelectionsState {
967 above: bool,
968 stack: Vec<usize>,
969}
970
971#[derive(Clone)]
972struct SelectNextState {
973 query: AhoCorasick,
974 wordwise: bool,
975 done: bool,
976}
977
978impl std::fmt::Debug for SelectNextState {
979 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
980 f.debug_struct(std::any::type_name::<Self>())
981 .field("wordwise", &self.wordwise)
982 .field("done", &self.done)
983 .finish()
984 }
985}
986
987#[derive(Debug)]
988struct AutocloseRegion {
989 selection_id: usize,
990 range: Range<Anchor>,
991 pair: BracketPair,
992}
993
994#[derive(Debug)]
995struct SnippetState {
996 ranges: Vec<Vec<Range<Anchor>>>,
997 active_index: usize,
998 choices: Vec<Option<Vec<String>>>,
999}
1000
1001#[doc(hidden)]
1002pub struct RenameState {
1003 pub range: Range<Anchor>,
1004 pub old_name: Arc<str>,
1005 pub editor: Entity<Editor>,
1006 block_id: CustomBlockId,
1007}
1008
1009struct InvalidationStack<T>(Vec<T>);
1010
1011struct RegisteredInlineCompletionProvider {
1012 provider: Arc<dyn InlineCompletionProviderHandle>,
1013 _subscription: Subscription,
1014}
1015
1016#[derive(Debug)]
1017struct ActiveDiagnosticGroup {
1018 primary_range: Range<Anchor>,
1019 primary_message: String,
1020 group_id: usize,
1021 blocks: HashMap<CustomBlockId, Diagnostic>,
1022 is_valid: bool,
1023}
1024
1025#[derive(Serialize, Deserialize, Clone, Debug)]
1026pub struct ClipboardSelection {
1027 pub len: usize,
1028 pub is_entire_line: bool,
1029 pub first_line_indent: u32,
1030}
1031
1032#[derive(Debug)]
1033pub(crate) struct NavigationData {
1034 cursor_anchor: Anchor,
1035 cursor_position: Point,
1036 scroll_anchor: ScrollAnchor,
1037 scroll_top_row: u32,
1038}
1039
1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1041pub enum GotoDefinitionKind {
1042 Symbol,
1043 Declaration,
1044 Type,
1045 Implementation,
1046}
1047
1048#[derive(Debug, Clone)]
1049enum InlayHintRefreshReason {
1050 Toggle(bool),
1051 SettingsChange(InlayHintSettings),
1052 NewLinesShown,
1053 BufferEdited(HashSet<Arc<Language>>),
1054 RefreshRequested,
1055 ExcerptsRemoved(Vec<ExcerptId>),
1056}
1057
1058impl InlayHintRefreshReason {
1059 fn description(&self) -> &'static str {
1060 match self {
1061 Self::Toggle(_) => "toggle",
1062 Self::SettingsChange(_) => "settings change",
1063 Self::NewLinesShown => "new lines shown",
1064 Self::BufferEdited(_) => "buffer edited",
1065 Self::RefreshRequested => "refresh requested",
1066 Self::ExcerptsRemoved(_) => "excerpts removed",
1067 }
1068 }
1069}
1070
1071pub enum FormatTarget {
1072 Buffers,
1073 Ranges(Vec<Range<MultiBufferPoint>>),
1074}
1075
1076pub(crate) struct FocusedBlock {
1077 id: BlockId,
1078 focus_handle: WeakFocusHandle,
1079}
1080
1081#[derive(Clone)]
1082enum JumpData {
1083 MultiBufferRow {
1084 row: MultiBufferRow,
1085 line_offset_from_top: u32,
1086 },
1087 MultiBufferPoint {
1088 excerpt_id: ExcerptId,
1089 position: Point,
1090 anchor: text::Anchor,
1091 line_offset_from_top: u32,
1092 },
1093}
1094
1095pub enum MultibufferSelectionMode {
1096 First,
1097 All,
1098}
1099
1100impl Editor {
1101 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1102 let buffer = cx.new(|cx| Buffer::local("", cx));
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(
1105 EditorMode::SingleLine { auto_width: false },
1106 buffer,
1107 None,
1108 false,
1109 window,
1110 cx,
1111 )
1112 }
1113
1114 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1115 let buffer = cx.new(|cx| Buffer::local("", cx));
1116 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1117 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1118 }
1119
1120 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1121 let buffer = cx.new(|cx| Buffer::local("", cx));
1122 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1123 Self::new(
1124 EditorMode::SingleLine { auto_width: true },
1125 buffer,
1126 None,
1127 false,
1128 window,
1129 cx,
1130 )
1131 }
1132
1133 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1134 let buffer = cx.new(|cx| Buffer::local("", cx));
1135 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1136 Self::new(
1137 EditorMode::AutoHeight { max_lines },
1138 buffer,
1139 None,
1140 false,
1141 window,
1142 cx,
1143 )
1144 }
1145
1146 pub fn for_buffer(
1147 buffer: Entity<Buffer>,
1148 project: Option<Entity<Project>>,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1153 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1154 }
1155
1156 pub fn for_multibuffer(
1157 buffer: Entity<MultiBuffer>,
1158 project: Option<Entity<Project>>,
1159 show_excerpt_controls: bool,
1160 window: &mut Window,
1161 cx: &mut Context<Self>,
1162 ) -> Self {
1163 Self::new(
1164 EditorMode::Full,
1165 buffer,
1166 project,
1167 show_excerpt_controls,
1168 window,
1169 cx,
1170 )
1171 }
1172
1173 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1174 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1175 let mut clone = Self::new(
1176 self.mode,
1177 self.buffer.clone(),
1178 self.project.clone(),
1179 show_excerpt_controls,
1180 window,
1181 cx,
1182 );
1183 self.display_map.update(cx, |display_map, cx| {
1184 let snapshot = display_map.snapshot(cx);
1185 clone.display_map.update(cx, |display_map, cx| {
1186 display_map.set_state(&snapshot, cx);
1187 });
1188 });
1189 clone.selections.clone_state(&self.selections);
1190 clone.scroll_manager.clone_state(&self.scroll_manager);
1191 clone.searchable = self.searchable;
1192 clone
1193 }
1194
1195 pub fn new(
1196 mode: EditorMode,
1197 buffer: Entity<MultiBuffer>,
1198 project: Option<Entity<Project>>,
1199 show_excerpt_controls: bool,
1200 window: &mut Window,
1201 cx: &mut Context<Self>,
1202 ) -> Self {
1203 let style = window.text_style();
1204 let font_size = style.font_size.to_pixels(window.rem_size());
1205 let editor = cx.entity().downgrade();
1206 let fold_placeholder = FoldPlaceholder {
1207 constrain_width: true,
1208 render: Arc::new(move |fold_id, fold_range, _, cx| {
1209 let editor = editor.clone();
1210 div()
1211 .id(fold_id)
1212 .bg(cx.theme().colors().ghost_element_background)
1213 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1214 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1215 .rounded_sm()
1216 .size_full()
1217 .cursor_pointer()
1218 .child("⋯")
1219 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1220 .on_click(move |_, _window, cx| {
1221 editor
1222 .update(cx, |editor, cx| {
1223 editor.unfold_ranges(
1224 &[fold_range.start..fold_range.end],
1225 true,
1226 false,
1227 cx,
1228 );
1229 cx.stop_propagation();
1230 })
1231 .ok();
1232 })
1233 .into_any()
1234 }),
1235 merge_adjacent: true,
1236 ..Default::default()
1237 };
1238 let display_map = cx.new(|cx| {
1239 DisplayMap::new(
1240 buffer.clone(),
1241 style.font(),
1242 font_size,
1243 None,
1244 show_excerpt_controls,
1245 FILE_HEADER_HEIGHT,
1246 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1247 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1248 fold_placeholder,
1249 cx,
1250 )
1251 });
1252
1253 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1254
1255 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1256
1257 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1258 .then(|| language_settings::SoftWrap::None);
1259
1260 let mut project_subscriptions = Vec::new();
1261 if mode == EditorMode::Full {
1262 if let Some(project) = project.as_ref() {
1263 if buffer.read(cx).is_singleton() {
1264 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1265 cx.emit(EditorEvent::TitleChanged);
1266 }));
1267 }
1268 project_subscriptions.push(cx.subscribe_in(
1269 project,
1270 window,
1271 |editor, _, event, window, cx| {
1272 if let project::Event::RefreshInlayHints = event {
1273 editor
1274 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1275 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1276 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1277 let focus_handle = editor.focus_handle(cx);
1278 if focus_handle.is_focused(window) {
1279 let snapshot = buffer.read(cx).snapshot();
1280 for (range, snippet) in snippet_edits {
1281 let editor_range =
1282 language::range_from_lsp(*range).to_offset(&snapshot);
1283 editor
1284 .insert_snippet(
1285 &[editor_range],
1286 snippet.clone(),
1287 window,
1288 cx,
1289 )
1290 .ok();
1291 }
1292 }
1293 }
1294 }
1295 },
1296 ));
1297 if let Some(task_inventory) = project
1298 .read(cx)
1299 .task_store()
1300 .read(cx)
1301 .task_inventory()
1302 .cloned()
1303 {
1304 project_subscriptions.push(cx.observe_in(
1305 &task_inventory,
1306 window,
1307 |editor, _, window, cx| {
1308 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1309 },
1310 ));
1311 }
1312 }
1313 }
1314
1315 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1316
1317 let inlay_hint_settings =
1318 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1319 let focus_handle = cx.focus_handle();
1320 cx.on_focus(&focus_handle, window, Self::handle_focus)
1321 .detach();
1322 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1323 .detach();
1324 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1325 .detach();
1326 cx.on_blur(&focus_handle, window, Self::handle_blur)
1327 .detach();
1328
1329 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1330 Some(false)
1331 } else {
1332 None
1333 };
1334
1335 let mut code_action_providers = Vec::new();
1336 let mut load_uncommitted_diff = None;
1337 if let Some(project) = project.clone() {
1338 load_uncommitted_diff = Some(
1339 get_uncommitted_diff_for_buffer(
1340 &project,
1341 buffer.read(cx).all_buffers(),
1342 buffer.clone(),
1343 cx,
1344 )
1345 .shared(),
1346 );
1347 code_action_providers.push(Rc::new(project) as Rc<_>);
1348 }
1349
1350 let mut this = Self {
1351 focus_handle,
1352 show_cursor_when_unfocused: false,
1353 last_focused_descendant: None,
1354 buffer: buffer.clone(),
1355 display_map: display_map.clone(),
1356 selections,
1357 scroll_manager: ScrollManager::new(cx),
1358 columnar_selection_tail: None,
1359 add_selections_state: None,
1360 select_next_state: None,
1361 select_prev_state: None,
1362 selection_history: Default::default(),
1363 autoclose_regions: Default::default(),
1364 snippet_stack: Default::default(),
1365 select_larger_syntax_node_stack: Vec::new(),
1366 ime_transaction: Default::default(),
1367 active_diagnostics: None,
1368 soft_wrap_mode_override,
1369 completion_provider: project.clone().map(|project| Box::new(project) as _),
1370 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1371 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1372 project,
1373 blink_manager: blink_manager.clone(),
1374 show_local_selections: true,
1375 show_scrollbars: true,
1376 mode,
1377 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1378 show_gutter: mode == EditorMode::Full,
1379 show_line_numbers: None,
1380 use_relative_line_numbers: None,
1381 show_git_diff_gutter: None,
1382 show_code_actions: None,
1383 show_runnables: None,
1384 show_wrap_guides: None,
1385 show_indent_guides,
1386 placeholder_text: None,
1387 highlight_order: 0,
1388 highlighted_rows: HashMap::default(),
1389 background_highlights: Default::default(),
1390 gutter_highlights: TreeMap::default(),
1391 scrollbar_marker_state: ScrollbarMarkerState::default(),
1392 active_indent_guides_state: ActiveIndentGuidesState::default(),
1393 nav_history: None,
1394 context_menu: RefCell::new(None),
1395 mouse_context_menu: None,
1396 completion_tasks: Default::default(),
1397 signature_help_state: SignatureHelpState::default(),
1398 auto_signature_help: None,
1399 find_all_references_task_sources: Vec::new(),
1400 next_completion_id: 0,
1401 next_inlay_id: 0,
1402 code_action_providers,
1403 available_code_actions: Default::default(),
1404 code_actions_task: Default::default(),
1405 selection_highlight_task: Default::default(),
1406 document_highlights_task: Default::default(),
1407 linked_editing_range_task: Default::default(),
1408 pending_rename: Default::default(),
1409 searchable: true,
1410 cursor_shape: EditorSettings::get_global(cx)
1411 .cursor_shape
1412 .unwrap_or_default(),
1413 current_line_highlight: None,
1414 autoindent_mode: Some(AutoindentMode::EachLine),
1415 collapse_matches: false,
1416 workspace: None,
1417 input_enabled: true,
1418 use_modal_editing: mode == EditorMode::Full,
1419 read_only: false,
1420 use_autoclose: true,
1421 use_auto_surround: true,
1422 auto_replace_emoji_shortcode: false,
1423 leader_peer_id: None,
1424 remote_id: None,
1425 hover_state: Default::default(),
1426 pending_mouse_down: None,
1427 hovered_link_state: Default::default(),
1428 edit_prediction_provider: None,
1429 active_inline_completion: None,
1430 stale_inline_completion_in_menu: None,
1431 edit_prediction_preview: EditPredictionPreview::Inactive,
1432 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1433
1434 gutter_hovered: false,
1435 pixel_position_of_newest_cursor: None,
1436 last_bounds: None,
1437 last_position_map: None,
1438 expect_bounds_change: None,
1439 gutter_dimensions: GutterDimensions::default(),
1440 style: None,
1441 show_cursor_names: false,
1442 hovered_cursors: Default::default(),
1443 next_editor_action_id: EditorActionId::default(),
1444 editor_actions: Rc::default(),
1445 inline_completions_hidden_for_vim_mode: false,
1446 show_inline_completions_override: None,
1447 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1448 edit_prediction_settings: EditPredictionSettings::Disabled,
1449 edit_prediction_cursor_on_leading_whitespace: false,
1450 edit_prediction_requires_modifier_in_leading_space: true,
1451 custom_context_menu: None,
1452 show_git_blame_gutter: false,
1453 show_git_blame_inline: false,
1454 distinguish_unstaged_diff_hunks: false,
1455 show_selection_menu: None,
1456 show_git_blame_inline_delay_task: None,
1457 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1458 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1459 .session
1460 .restore_unsaved_buffers,
1461 blame: None,
1462 blame_subscription: None,
1463 tasks: Default::default(),
1464 _subscriptions: vec![
1465 cx.observe(&buffer, Self::on_buffer_changed),
1466 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1467 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1468 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1469 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1470 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1471 cx.observe_window_activation(window, |editor, window, cx| {
1472 let active = window.is_window_active();
1473 editor.blink_manager.update(cx, |blink_manager, cx| {
1474 if active {
1475 blink_manager.enable(cx);
1476 } else {
1477 blink_manager.disable(cx);
1478 }
1479 });
1480 }),
1481 ],
1482 tasks_update_task: None,
1483 linked_edit_ranges: Default::default(),
1484 in_project_search: false,
1485 previous_search_ranges: None,
1486 breadcrumb_header: None,
1487 focused_block: None,
1488 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1489 addons: HashMap::default(),
1490 registered_buffers: HashMap::default(),
1491 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1492 selection_mark_mode: false,
1493 toggle_fold_multiple_buffers: Task::ready(()),
1494 serialize_selections: Task::ready(()),
1495 text_style_refinement: None,
1496 load_diff_task: load_uncommitted_diff,
1497 };
1498 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1499 this._subscriptions.extend(project_subscriptions);
1500
1501 this.end_selection(window, cx);
1502 this.scroll_manager.show_scrollbar(window, cx);
1503
1504 if mode == EditorMode::Full {
1505 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1506 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1507
1508 if this.git_blame_inline_enabled {
1509 this.git_blame_inline_enabled = true;
1510 this.start_git_blame_inline(false, window, cx);
1511 }
1512
1513 if let Some(buffer) = buffer.read(cx).as_singleton() {
1514 if let Some(project) = this.project.as_ref() {
1515 let handle = project.update(cx, |project, cx| {
1516 project.register_buffer_with_language_servers(&buffer, cx)
1517 });
1518 this.registered_buffers
1519 .insert(buffer.read(cx).remote_id(), handle);
1520 }
1521 }
1522 }
1523
1524 this.report_editor_event("Editor Opened", None, cx);
1525 this
1526 }
1527
1528 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1529 self.mouse_context_menu
1530 .as_ref()
1531 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1532 }
1533
1534 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1535 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1536 }
1537
1538 fn key_context_internal(
1539 &self,
1540 has_active_edit_prediction: bool,
1541 window: &Window,
1542 cx: &App,
1543 ) -> KeyContext {
1544 let mut key_context = KeyContext::new_with_defaults();
1545 key_context.add("Editor");
1546 let mode = match self.mode {
1547 EditorMode::SingleLine { .. } => "single_line",
1548 EditorMode::AutoHeight { .. } => "auto_height",
1549 EditorMode::Full => "full",
1550 };
1551
1552 if EditorSettings::jupyter_enabled(cx) {
1553 key_context.add("jupyter");
1554 }
1555
1556 key_context.set("mode", mode);
1557 if self.pending_rename.is_some() {
1558 key_context.add("renaming");
1559 }
1560
1561 match self.context_menu.borrow().as_ref() {
1562 Some(CodeContextMenu::Completions(_)) => {
1563 key_context.add("menu");
1564 key_context.add("showing_completions");
1565 }
1566 Some(CodeContextMenu::CodeActions(_)) => {
1567 key_context.add("menu");
1568 key_context.add("showing_code_actions")
1569 }
1570 None => {}
1571 }
1572
1573 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1574 if !self.focus_handle(cx).contains_focused(window, cx)
1575 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1576 {
1577 for addon in self.addons.values() {
1578 addon.extend_key_context(&mut key_context, cx)
1579 }
1580 }
1581
1582 if let Some(extension) = self
1583 .buffer
1584 .read(cx)
1585 .as_singleton()
1586 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1587 {
1588 key_context.set("extension", extension.to_string());
1589 }
1590
1591 if has_active_edit_prediction {
1592 if self.edit_prediction_in_conflict() {
1593 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1594 } else {
1595 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1596 key_context.add("copilot_suggestion");
1597 }
1598 }
1599
1600 if self.selection_mark_mode {
1601 key_context.add("selection_mode");
1602 }
1603
1604 key_context
1605 }
1606
1607 pub fn edit_prediction_in_conflict(&self) -> bool {
1608 if !self.show_edit_predictions_in_menu() {
1609 return false;
1610 }
1611
1612 let showing_completions = self
1613 .context_menu
1614 .borrow()
1615 .as_ref()
1616 .map_or(false, |context| {
1617 matches!(context, CodeContextMenu::Completions(_))
1618 });
1619
1620 showing_completions
1621 || self.edit_prediction_requires_modifier()
1622 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1623 // bindings to insert tab characters.
1624 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1625 }
1626
1627 pub fn accept_edit_prediction_keybind(
1628 &self,
1629 window: &Window,
1630 cx: &App,
1631 ) -> AcceptEditPredictionBinding {
1632 let key_context = self.key_context_internal(true, window, cx);
1633 let in_conflict = self.edit_prediction_in_conflict();
1634
1635 AcceptEditPredictionBinding(
1636 window
1637 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1638 .into_iter()
1639 .filter(|binding| {
1640 !in_conflict
1641 || binding
1642 .keystrokes()
1643 .first()
1644 .map_or(false, |keystroke| keystroke.modifiers.modified())
1645 })
1646 .rev()
1647 .min_by_key(|binding| {
1648 binding
1649 .keystrokes()
1650 .first()
1651 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1652 }),
1653 )
1654 }
1655
1656 pub fn new_file(
1657 workspace: &mut Workspace,
1658 _: &workspace::NewFile,
1659 window: &mut Window,
1660 cx: &mut Context<Workspace>,
1661 ) {
1662 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1663 "Failed to create buffer",
1664 window,
1665 cx,
1666 |e, _, _| match e.error_code() {
1667 ErrorCode::RemoteUpgradeRequired => Some(format!(
1668 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1669 e.error_tag("required").unwrap_or("the latest version")
1670 )),
1671 _ => None,
1672 },
1673 );
1674 }
1675
1676 pub fn new_in_workspace(
1677 workspace: &mut Workspace,
1678 window: &mut Window,
1679 cx: &mut Context<Workspace>,
1680 ) -> Task<Result<Entity<Editor>>> {
1681 let project = workspace.project().clone();
1682 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1683
1684 cx.spawn_in(window, |workspace, mut cx| async move {
1685 let buffer = create.await?;
1686 workspace.update_in(&mut cx, |workspace, window, cx| {
1687 let editor =
1688 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1689 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1690 editor
1691 })
1692 })
1693 }
1694
1695 fn new_file_vertical(
1696 workspace: &mut Workspace,
1697 _: &workspace::NewFileSplitVertical,
1698 window: &mut Window,
1699 cx: &mut Context<Workspace>,
1700 ) {
1701 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1702 }
1703
1704 fn new_file_horizontal(
1705 workspace: &mut Workspace,
1706 _: &workspace::NewFileSplitHorizontal,
1707 window: &mut Window,
1708 cx: &mut Context<Workspace>,
1709 ) {
1710 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1711 }
1712
1713 fn new_file_in_direction(
1714 workspace: &mut Workspace,
1715 direction: SplitDirection,
1716 window: &mut Window,
1717 cx: &mut Context<Workspace>,
1718 ) {
1719 let project = workspace.project().clone();
1720 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1721
1722 cx.spawn_in(window, |workspace, mut cx| async move {
1723 let buffer = create.await?;
1724 workspace.update_in(&mut cx, move |workspace, window, cx| {
1725 workspace.split_item(
1726 direction,
1727 Box::new(
1728 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1729 ),
1730 window,
1731 cx,
1732 )
1733 })?;
1734 anyhow::Ok(())
1735 })
1736 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1737 match e.error_code() {
1738 ErrorCode::RemoteUpgradeRequired => Some(format!(
1739 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1740 e.error_tag("required").unwrap_or("the latest version")
1741 )),
1742 _ => None,
1743 }
1744 });
1745 }
1746
1747 pub fn leader_peer_id(&self) -> Option<PeerId> {
1748 self.leader_peer_id
1749 }
1750
1751 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1752 &self.buffer
1753 }
1754
1755 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1756 self.workspace.as_ref()?.0.upgrade()
1757 }
1758
1759 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1760 self.buffer().read(cx).title(cx)
1761 }
1762
1763 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1764 let git_blame_gutter_max_author_length = self
1765 .render_git_blame_gutter(cx)
1766 .then(|| {
1767 if let Some(blame) = self.blame.as_ref() {
1768 let max_author_length =
1769 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1770 Some(max_author_length)
1771 } else {
1772 None
1773 }
1774 })
1775 .flatten();
1776
1777 EditorSnapshot {
1778 mode: self.mode,
1779 show_gutter: self.show_gutter,
1780 show_line_numbers: self.show_line_numbers,
1781 show_git_diff_gutter: self.show_git_diff_gutter,
1782 show_code_actions: self.show_code_actions,
1783 show_runnables: self.show_runnables,
1784 git_blame_gutter_max_author_length,
1785 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1786 scroll_anchor: self.scroll_manager.anchor(),
1787 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1788 placeholder_text: self.placeholder_text.clone(),
1789 is_focused: self.focus_handle.is_focused(window),
1790 current_line_highlight: self
1791 .current_line_highlight
1792 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1793 gutter_hovered: self.gutter_hovered,
1794 }
1795 }
1796
1797 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1798 self.buffer.read(cx).language_at(point, cx)
1799 }
1800
1801 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1802 self.buffer.read(cx).read(cx).file_at(point).cloned()
1803 }
1804
1805 pub fn active_excerpt(
1806 &self,
1807 cx: &App,
1808 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1809 self.buffer
1810 .read(cx)
1811 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1812 }
1813
1814 pub fn mode(&self) -> EditorMode {
1815 self.mode
1816 }
1817
1818 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1819 self.collaboration_hub.as_deref()
1820 }
1821
1822 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1823 self.collaboration_hub = Some(hub);
1824 }
1825
1826 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1827 self.in_project_search = in_project_search;
1828 }
1829
1830 pub fn set_custom_context_menu(
1831 &mut self,
1832 f: impl 'static
1833 + Fn(
1834 &mut Self,
1835 DisplayPoint,
1836 &mut Window,
1837 &mut Context<Self>,
1838 ) -> Option<Entity<ui::ContextMenu>>,
1839 ) {
1840 self.custom_context_menu = Some(Box::new(f))
1841 }
1842
1843 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1844 self.completion_provider = provider;
1845 }
1846
1847 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1848 self.semantics_provider.clone()
1849 }
1850
1851 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1852 self.semantics_provider = provider;
1853 }
1854
1855 pub fn set_edit_prediction_provider<T>(
1856 &mut self,
1857 provider: Option<Entity<T>>,
1858 window: &mut Window,
1859 cx: &mut Context<Self>,
1860 ) where
1861 T: EditPredictionProvider,
1862 {
1863 self.edit_prediction_provider =
1864 provider.map(|provider| RegisteredInlineCompletionProvider {
1865 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1866 if this.focus_handle.is_focused(window) {
1867 this.update_visible_inline_completion(window, cx);
1868 }
1869 }),
1870 provider: Arc::new(provider),
1871 });
1872 self.refresh_inline_completion(false, false, window, cx);
1873 }
1874
1875 pub fn placeholder_text(&self) -> Option<&str> {
1876 self.placeholder_text.as_deref()
1877 }
1878
1879 pub fn set_placeholder_text(
1880 &mut self,
1881 placeholder_text: impl Into<Arc<str>>,
1882 cx: &mut Context<Self>,
1883 ) {
1884 let placeholder_text = Some(placeholder_text.into());
1885 if self.placeholder_text != placeholder_text {
1886 self.placeholder_text = placeholder_text;
1887 cx.notify();
1888 }
1889 }
1890
1891 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1892 self.cursor_shape = cursor_shape;
1893
1894 // Disrupt blink for immediate user feedback that the cursor shape has changed
1895 self.blink_manager.update(cx, BlinkManager::show_cursor);
1896
1897 cx.notify();
1898 }
1899
1900 pub fn set_current_line_highlight(
1901 &mut self,
1902 current_line_highlight: Option<CurrentLineHighlight>,
1903 ) {
1904 self.current_line_highlight = current_line_highlight;
1905 }
1906
1907 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1908 self.collapse_matches = collapse_matches;
1909 }
1910
1911 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1912 let buffers = self.buffer.read(cx).all_buffers();
1913 let Some(project) = self.project.as_ref() else {
1914 return;
1915 };
1916 project.update(cx, |project, cx| {
1917 for buffer in buffers {
1918 self.registered_buffers
1919 .entry(buffer.read(cx).remote_id())
1920 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1921 }
1922 })
1923 }
1924
1925 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1926 if self.collapse_matches {
1927 return range.start..range.start;
1928 }
1929 range.clone()
1930 }
1931
1932 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1933 if self.display_map.read(cx).clip_at_line_ends != clip {
1934 self.display_map
1935 .update(cx, |map, _| map.clip_at_line_ends = clip);
1936 }
1937 }
1938
1939 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1940 self.input_enabled = input_enabled;
1941 }
1942
1943 pub fn set_inline_completions_hidden_for_vim_mode(
1944 &mut self,
1945 hidden: bool,
1946 window: &mut Window,
1947 cx: &mut Context<Self>,
1948 ) {
1949 if hidden != self.inline_completions_hidden_for_vim_mode {
1950 self.inline_completions_hidden_for_vim_mode = hidden;
1951 if hidden {
1952 self.update_visible_inline_completion(window, cx);
1953 } else {
1954 self.refresh_inline_completion(true, false, window, cx);
1955 }
1956 }
1957 }
1958
1959 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1960 self.menu_inline_completions_policy = value;
1961 }
1962
1963 pub fn set_autoindent(&mut self, autoindent: bool) {
1964 if autoindent {
1965 self.autoindent_mode = Some(AutoindentMode::EachLine);
1966 } else {
1967 self.autoindent_mode = None;
1968 }
1969 }
1970
1971 pub fn read_only(&self, cx: &App) -> bool {
1972 self.read_only || self.buffer.read(cx).read_only()
1973 }
1974
1975 pub fn set_read_only(&mut self, read_only: bool) {
1976 self.read_only = read_only;
1977 }
1978
1979 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1980 self.use_autoclose = autoclose;
1981 }
1982
1983 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1984 self.use_auto_surround = auto_surround;
1985 }
1986
1987 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1988 self.auto_replace_emoji_shortcode = auto_replace;
1989 }
1990
1991 pub fn toggle_inline_completions(
1992 &mut self,
1993 _: &ToggleEditPrediction,
1994 window: &mut Window,
1995 cx: &mut Context<Self>,
1996 ) {
1997 if self.show_inline_completions_override.is_some() {
1998 self.set_show_edit_predictions(None, window, cx);
1999 } else {
2000 let show_edit_predictions = !self.edit_predictions_enabled();
2001 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2002 }
2003 }
2004
2005 pub fn set_show_edit_predictions(
2006 &mut self,
2007 show_edit_predictions: Option<bool>,
2008 window: &mut Window,
2009 cx: &mut Context<Self>,
2010 ) {
2011 self.show_inline_completions_override = show_edit_predictions;
2012 self.refresh_inline_completion(false, true, window, cx);
2013 }
2014
2015 fn inline_completions_disabled_in_scope(
2016 &self,
2017 buffer: &Entity<Buffer>,
2018 buffer_position: language::Anchor,
2019 cx: &App,
2020 ) -> bool {
2021 let snapshot = buffer.read(cx).snapshot();
2022 let settings = snapshot.settings_at(buffer_position, cx);
2023
2024 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2025 return false;
2026 };
2027
2028 scope.override_name().map_or(false, |scope_name| {
2029 settings
2030 .edit_predictions_disabled_in
2031 .iter()
2032 .any(|s| s == scope_name)
2033 })
2034 }
2035
2036 pub fn set_use_modal_editing(&mut self, to: bool) {
2037 self.use_modal_editing = to;
2038 }
2039
2040 pub fn use_modal_editing(&self) -> bool {
2041 self.use_modal_editing
2042 }
2043
2044 fn selections_did_change(
2045 &mut self,
2046 local: bool,
2047 old_cursor_position: &Anchor,
2048 show_completions: bool,
2049 window: &mut Window,
2050 cx: &mut Context<Self>,
2051 ) {
2052 window.invalidate_character_coordinates();
2053
2054 // Copy selections to primary selection buffer
2055 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2056 if local {
2057 let selections = self.selections.all::<usize>(cx);
2058 let buffer_handle = self.buffer.read(cx).read(cx);
2059
2060 let mut text = String::new();
2061 for (index, selection) in selections.iter().enumerate() {
2062 let text_for_selection = buffer_handle
2063 .text_for_range(selection.start..selection.end)
2064 .collect::<String>();
2065
2066 text.push_str(&text_for_selection);
2067 if index != selections.len() - 1 {
2068 text.push('\n');
2069 }
2070 }
2071
2072 if !text.is_empty() {
2073 cx.write_to_primary(ClipboardItem::new_string(text));
2074 }
2075 }
2076
2077 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2078 self.buffer.update(cx, |buffer, cx| {
2079 buffer.set_active_selections(
2080 &self.selections.disjoint_anchors(),
2081 self.selections.line_mode,
2082 self.cursor_shape,
2083 cx,
2084 )
2085 });
2086 }
2087 let display_map = self
2088 .display_map
2089 .update(cx, |display_map, cx| display_map.snapshot(cx));
2090 let buffer = &display_map.buffer_snapshot;
2091 self.add_selections_state = None;
2092 self.select_next_state = None;
2093 self.select_prev_state = None;
2094 self.select_larger_syntax_node_stack.clear();
2095 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2096 self.snippet_stack
2097 .invalidate(&self.selections.disjoint_anchors(), buffer);
2098 self.take_rename(false, window, cx);
2099
2100 let new_cursor_position = self.selections.newest_anchor().head();
2101
2102 self.push_to_nav_history(
2103 *old_cursor_position,
2104 Some(new_cursor_position.to_point(buffer)),
2105 cx,
2106 );
2107
2108 if local {
2109 let new_cursor_position = self.selections.newest_anchor().head();
2110 let mut context_menu = self.context_menu.borrow_mut();
2111 let completion_menu = match context_menu.as_ref() {
2112 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2113 _ => {
2114 *context_menu = None;
2115 None
2116 }
2117 };
2118 if let Some(buffer_id) = new_cursor_position.buffer_id {
2119 if !self.registered_buffers.contains_key(&buffer_id) {
2120 if let Some(project) = self.project.as_ref() {
2121 project.update(cx, |project, cx| {
2122 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2123 return;
2124 };
2125 self.registered_buffers.insert(
2126 buffer_id,
2127 project.register_buffer_with_language_servers(&buffer, cx),
2128 );
2129 })
2130 }
2131 }
2132 }
2133
2134 if let Some(completion_menu) = completion_menu {
2135 let cursor_position = new_cursor_position.to_offset(buffer);
2136 let (word_range, kind) =
2137 buffer.surrounding_word(completion_menu.initial_position, true);
2138 if kind == Some(CharKind::Word)
2139 && word_range.to_inclusive().contains(&cursor_position)
2140 {
2141 let mut completion_menu = completion_menu.clone();
2142 drop(context_menu);
2143
2144 let query = Self::completion_query(buffer, cursor_position);
2145 cx.spawn(move |this, mut cx| async move {
2146 completion_menu
2147 .filter(query.as_deref(), cx.background_executor().clone())
2148 .await;
2149
2150 this.update(&mut cx, |this, cx| {
2151 let mut context_menu = this.context_menu.borrow_mut();
2152 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2153 else {
2154 return;
2155 };
2156
2157 if menu.id > completion_menu.id {
2158 return;
2159 }
2160
2161 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2162 drop(context_menu);
2163 cx.notify();
2164 })
2165 })
2166 .detach();
2167
2168 if show_completions {
2169 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2170 }
2171 } else {
2172 drop(context_menu);
2173 self.hide_context_menu(window, cx);
2174 }
2175 } else {
2176 drop(context_menu);
2177 }
2178
2179 hide_hover(self, cx);
2180
2181 if old_cursor_position.to_display_point(&display_map).row()
2182 != new_cursor_position.to_display_point(&display_map).row()
2183 {
2184 self.available_code_actions.take();
2185 }
2186 self.refresh_code_actions(window, cx);
2187 self.refresh_document_highlights(cx);
2188 self.refresh_selected_text_highlights(window, cx);
2189 refresh_matching_bracket_highlights(self, window, cx);
2190 self.update_visible_inline_completion(window, cx);
2191 self.edit_prediction_requires_modifier_in_leading_space = true;
2192 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2193 if self.git_blame_inline_enabled {
2194 self.start_inline_blame_timer(window, cx);
2195 }
2196 }
2197
2198 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2199 cx.emit(EditorEvent::SelectionsChanged { local });
2200
2201 let selections = &self.selections.disjoint;
2202 if selections.len() == 1 {
2203 cx.emit(SearchEvent::ActiveMatchChanged)
2204 }
2205 if local
2206 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2207 {
2208 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2209 let background_executor = cx.background_executor().clone();
2210 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2211 let snapshot = self.buffer().read(cx).snapshot(cx);
2212 let selections = selections.clone();
2213 self.serialize_selections = cx.background_spawn(async move {
2214 background_executor.timer(Duration::from_millis(100)).await;
2215 let selections = selections
2216 .iter()
2217 .map(|selection| {
2218 (
2219 selection.start.to_offset(&snapshot),
2220 selection.end.to_offset(&snapshot),
2221 )
2222 })
2223 .collect();
2224 DB.save_editor_selections(editor_id, workspace_id, selections)
2225 .await
2226 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2227 .log_err();
2228 });
2229 }
2230 }
2231
2232 cx.notify();
2233 }
2234
2235 pub fn change_selections<R>(
2236 &mut self,
2237 autoscroll: Option<Autoscroll>,
2238 window: &mut Window,
2239 cx: &mut Context<Self>,
2240 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2241 ) -> R {
2242 self.change_selections_inner(autoscroll, true, window, cx, change)
2243 }
2244
2245 fn change_selections_inner<R>(
2246 &mut self,
2247 autoscroll: Option<Autoscroll>,
2248 request_completions: bool,
2249 window: &mut Window,
2250 cx: &mut Context<Self>,
2251 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2252 ) -> R {
2253 let old_cursor_position = self.selections.newest_anchor().head();
2254 self.push_to_selection_history();
2255
2256 let (changed, result) = self.selections.change_with(cx, change);
2257
2258 if changed {
2259 if let Some(autoscroll) = autoscroll {
2260 self.request_autoscroll(autoscroll, cx);
2261 }
2262 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2263
2264 if self.should_open_signature_help_automatically(
2265 &old_cursor_position,
2266 self.signature_help_state.backspace_pressed(),
2267 cx,
2268 ) {
2269 self.show_signature_help(&ShowSignatureHelp, window, cx);
2270 }
2271 self.signature_help_state.set_backspace_pressed(false);
2272 }
2273
2274 result
2275 }
2276
2277 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2278 where
2279 I: IntoIterator<Item = (Range<S>, T)>,
2280 S: ToOffset,
2281 T: Into<Arc<str>>,
2282 {
2283 if self.read_only(cx) {
2284 return;
2285 }
2286
2287 self.buffer
2288 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2289 }
2290
2291 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2292 where
2293 I: IntoIterator<Item = (Range<S>, T)>,
2294 S: ToOffset,
2295 T: Into<Arc<str>>,
2296 {
2297 if self.read_only(cx) {
2298 return;
2299 }
2300
2301 self.buffer.update(cx, |buffer, cx| {
2302 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2303 });
2304 }
2305
2306 pub fn edit_with_block_indent<I, S, T>(
2307 &mut self,
2308 edits: I,
2309 original_indent_columns: Vec<u32>,
2310 cx: &mut Context<Self>,
2311 ) where
2312 I: IntoIterator<Item = (Range<S>, T)>,
2313 S: ToOffset,
2314 T: Into<Arc<str>>,
2315 {
2316 if self.read_only(cx) {
2317 return;
2318 }
2319
2320 self.buffer.update(cx, |buffer, cx| {
2321 buffer.edit(
2322 edits,
2323 Some(AutoindentMode::Block {
2324 original_indent_columns,
2325 }),
2326 cx,
2327 )
2328 });
2329 }
2330
2331 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2332 self.hide_context_menu(window, cx);
2333
2334 match phase {
2335 SelectPhase::Begin {
2336 position,
2337 add,
2338 click_count,
2339 } => self.begin_selection(position, add, click_count, window, cx),
2340 SelectPhase::BeginColumnar {
2341 position,
2342 goal_column,
2343 reset,
2344 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2345 SelectPhase::Extend {
2346 position,
2347 click_count,
2348 } => self.extend_selection(position, click_count, window, cx),
2349 SelectPhase::Update {
2350 position,
2351 goal_column,
2352 scroll_delta,
2353 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2354 SelectPhase::End => self.end_selection(window, cx),
2355 }
2356 }
2357
2358 fn extend_selection(
2359 &mut self,
2360 position: DisplayPoint,
2361 click_count: usize,
2362 window: &mut Window,
2363 cx: &mut Context<Self>,
2364 ) {
2365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2366 let tail = self.selections.newest::<usize>(cx).tail();
2367 self.begin_selection(position, false, click_count, window, cx);
2368
2369 let position = position.to_offset(&display_map, Bias::Left);
2370 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2371
2372 let mut pending_selection = self
2373 .selections
2374 .pending_anchor()
2375 .expect("extend_selection not called with pending selection");
2376 if position >= tail {
2377 pending_selection.start = tail_anchor;
2378 } else {
2379 pending_selection.end = tail_anchor;
2380 pending_selection.reversed = true;
2381 }
2382
2383 let mut pending_mode = self.selections.pending_mode().unwrap();
2384 match &mut pending_mode {
2385 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2386 _ => {}
2387 }
2388
2389 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2390 s.set_pending(pending_selection, pending_mode)
2391 });
2392 }
2393
2394 fn begin_selection(
2395 &mut self,
2396 position: DisplayPoint,
2397 add: bool,
2398 click_count: usize,
2399 window: &mut Window,
2400 cx: &mut Context<Self>,
2401 ) {
2402 if !self.focus_handle.is_focused(window) {
2403 self.last_focused_descendant = None;
2404 window.focus(&self.focus_handle);
2405 }
2406
2407 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2408 let buffer = &display_map.buffer_snapshot;
2409 let newest_selection = self.selections.newest_anchor().clone();
2410 let position = display_map.clip_point(position, Bias::Left);
2411
2412 let start;
2413 let end;
2414 let mode;
2415 let mut auto_scroll;
2416 match click_count {
2417 1 => {
2418 start = buffer.anchor_before(position.to_point(&display_map));
2419 end = start;
2420 mode = SelectMode::Character;
2421 auto_scroll = true;
2422 }
2423 2 => {
2424 let range = movement::surrounding_word(&display_map, position);
2425 start = buffer.anchor_before(range.start.to_point(&display_map));
2426 end = buffer.anchor_before(range.end.to_point(&display_map));
2427 mode = SelectMode::Word(start..end);
2428 auto_scroll = true;
2429 }
2430 3 => {
2431 let position = display_map
2432 .clip_point(position, Bias::Left)
2433 .to_point(&display_map);
2434 let line_start = display_map.prev_line_boundary(position).0;
2435 let next_line_start = buffer.clip_point(
2436 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2437 Bias::Left,
2438 );
2439 start = buffer.anchor_before(line_start);
2440 end = buffer.anchor_before(next_line_start);
2441 mode = SelectMode::Line(start..end);
2442 auto_scroll = true;
2443 }
2444 _ => {
2445 start = buffer.anchor_before(0);
2446 end = buffer.anchor_before(buffer.len());
2447 mode = SelectMode::All;
2448 auto_scroll = false;
2449 }
2450 }
2451 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2452
2453 let point_to_delete: Option<usize> = {
2454 let selected_points: Vec<Selection<Point>> =
2455 self.selections.disjoint_in_range(start..end, cx);
2456
2457 if !add || click_count > 1 {
2458 None
2459 } else if !selected_points.is_empty() {
2460 Some(selected_points[0].id)
2461 } else {
2462 let clicked_point_already_selected =
2463 self.selections.disjoint.iter().find(|selection| {
2464 selection.start.to_point(buffer) == start.to_point(buffer)
2465 || selection.end.to_point(buffer) == end.to_point(buffer)
2466 });
2467
2468 clicked_point_already_selected.map(|selection| selection.id)
2469 }
2470 };
2471
2472 let selections_count = self.selections.count();
2473
2474 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2475 if let Some(point_to_delete) = point_to_delete {
2476 s.delete(point_to_delete);
2477
2478 if selections_count == 1 {
2479 s.set_pending_anchor_range(start..end, mode);
2480 }
2481 } else {
2482 if !add {
2483 s.clear_disjoint();
2484 } else if click_count > 1 {
2485 s.delete(newest_selection.id)
2486 }
2487
2488 s.set_pending_anchor_range(start..end, mode);
2489 }
2490 });
2491 }
2492
2493 fn begin_columnar_selection(
2494 &mut self,
2495 position: DisplayPoint,
2496 goal_column: u32,
2497 reset: bool,
2498 window: &mut Window,
2499 cx: &mut Context<Self>,
2500 ) {
2501 if !self.focus_handle.is_focused(window) {
2502 self.last_focused_descendant = None;
2503 window.focus(&self.focus_handle);
2504 }
2505
2506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2507
2508 if reset {
2509 let pointer_position = display_map
2510 .buffer_snapshot
2511 .anchor_before(position.to_point(&display_map));
2512
2513 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2514 s.clear_disjoint();
2515 s.set_pending_anchor_range(
2516 pointer_position..pointer_position,
2517 SelectMode::Character,
2518 );
2519 });
2520 }
2521
2522 let tail = self.selections.newest::<Point>(cx).tail();
2523 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2524
2525 if !reset {
2526 self.select_columns(
2527 tail.to_display_point(&display_map),
2528 position,
2529 goal_column,
2530 &display_map,
2531 window,
2532 cx,
2533 );
2534 }
2535 }
2536
2537 fn update_selection(
2538 &mut self,
2539 position: DisplayPoint,
2540 goal_column: u32,
2541 scroll_delta: gpui::Point<f32>,
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
2547 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2548 let tail = tail.to_display_point(&display_map);
2549 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2550 } else if let Some(mut pending) = self.selections.pending_anchor() {
2551 let buffer = self.buffer.read(cx).snapshot(cx);
2552 let head;
2553 let tail;
2554 let mode = self.selections.pending_mode().unwrap();
2555 match &mode {
2556 SelectMode::Character => {
2557 head = position.to_point(&display_map);
2558 tail = pending.tail().to_point(&buffer);
2559 }
2560 SelectMode::Word(original_range) => {
2561 let original_display_range = original_range.start.to_display_point(&display_map)
2562 ..original_range.end.to_display_point(&display_map);
2563 let original_buffer_range = original_display_range.start.to_point(&display_map)
2564 ..original_display_range.end.to_point(&display_map);
2565 if movement::is_inside_word(&display_map, position)
2566 || original_display_range.contains(&position)
2567 {
2568 let word_range = movement::surrounding_word(&display_map, position);
2569 if word_range.start < original_display_range.start {
2570 head = word_range.start.to_point(&display_map);
2571 } else {
2572 head = word_range.end.to_point(&display_map);
2573 }
2574 } else {
2575 head = position.to_point(&display_map);
2576 }
2577
2578 if head <= original_buffer_range.start {
2579 tail = original_buffer_range.end;
2580 } else {
2581 tail = original_buffer_range.start;
2582 }
2583 }
2584 SelectMode::Line(original_range) => {
2585 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2586
2587 let position = display_map
2588 .clip_point(position, Bias::Left)
2589 .to_point(&display_map);
2590 let line_start = display_map.prev_line_boundary(position).0;
2591 let next_line_start = buffer.clip_point(
2592 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2593 Bias::Left,
2594 );
2595
2596 if line_start < original_range.start {
2597 head = line_start
2598 } else {
2599 head = next_line_start
2600 }
2601
2602 if head <= original_range.start {
2603 tail = original_range.end;
2604 } else {
2605 tail = original_range.start;
2606 }
2607 }
2608 SelectMode::All => {
2609 return;
2610 }
2611 };
2612
2613 if head < tail {
2614 pending.start = buffer.anchor_before(head);
2615 pending.end = buffer.anchor_before(tail);
2616 pending.reversed = true;
2617 } else {
2618 pending.start = buffer.anchor_before(tail);
2619 pending.end = buffer.anchor_before(head);
2620 pending.reversed = false;
2621 }
2622
2623 self.change_selections(None, window, cx, |s| {
2624 s.set_pending(pending, mode);
2625 });
2626 } else {
2627 log::error!("update_selection dispatched with no pending selection");
2628 return;
2629 }
2630
2631 self.apply_scroll_delta(scroll_delta, window, cx);
2632 cx.notify();
2633 }
2634
2635 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2636 self.columnar_selection_tail.take();
2637 if self.selections.pending_anchor().is_some() {
2638 let selections = self.selections.all::<usize>(cx);
2639 self.change_selections(None, window, cx, |s| {
2640 s.select(selections);
2641 s.clear_pending();
2642 });
2643 }
2644 }
2645
2646 fn select_columns(
2647 &mut self,
2648 tail: DisplayPoint,
2649 head: DisplayPoint,
2650 goal_column: u32,
2651 display_map: &DisplaySnapshot,
2652 window: &mut Window,
2653 cx: &mut Context<Self>,
2654 ) {
2655 let start_row = cmp::min(tail.row(), head.row());
2656 let end_row = cmp::max(tail.row(), head.row());
2657 let start_column = cmp::min(tail.column(), goal_column);
2658 let end_column = cmp::max(tail.column(), goal_column);
2659 let reversed = start_column < tail.column();
2660
2661 let selection_ranges = (start_row.0..=end_row.0)
2662 .map(DisplayRow)
2663 .filter_map(|row| {
2664 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2665 let start = display_map
2666 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2667 .to_point(display_map);
2668 let end = display_map
2669 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2670 .to_point(display_map);
2671 if reversed {
2672 Some(end..start)
2673 } else {
2674 Some(start..end)
2675 }
2676 } else {
2677 None
2678 }
2679 })
2680 .collect::<Vec<_>>();
2681
2682 self.change_selections(None, window, cx, |s| {
2683 s.select_ranges(selection_ranges);
2684 });
2685 cx.notify();
2686 }
2687
2688 pub fn has_pending_nonempty_selection(&self) -> bool {
2689 let pending_nonempty_selection = match self.selections.pending_anchor() {
2690 Some(Selection { start, end, .. }) => start != end,
2691 None => false,
2692 };
2693
2694 pending_nonempty_selection
2695 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2696 }
2697
2698 pub fn has_pending_selection(&self) -> bool {
2699 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2700 }
2701
2702 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2703 self.selection_mark_mode = false;
2704
2705 if self.clear_expanded_diff_hunks(cx) {
2706 cx.notify();
2707 return;
2708 }
2709 if self.dismiss_menus_and_popups(true, window, cx) {
2710 return;
2711 }
2712
2713 if self.mode == EditorMode::Full
2714 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2715 {
2716 return;
2717 }
2718
2719 cx.propagate();
2720 }
2721
2722 pub fn dismiss_menus_and_popups(
2723 &mut self,
2724 is_user_requested: bool,
2725 window: &mut Window,
2726 cx: &mut Context<Self>,
2727 ) -> bool {
2728 if self.take_rename(false, window, cx).is_some() {
2729 return true;
2730 }
2731
2732 if hide_hover(self, cx) {
2733 return true;
2734 }
2735
2736 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2737 return true;
2738 }
2739
2740 if self.hide_context_menu(window, cx).is_some() {
2741 return true;
2742 }
2743
2744 if self.mouse_context_menu.take().is_some() {
2745 return true;
2746 }
2747
2748 if is_user_requested && self.discard_inline_completion(true, cx) {
2749 return true;
2750 }
2751
2752 if self.snippet_stack.pop().is_some() {
2753 return true;
2754 }
2755
2756 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2757 self.dismiss_diagnostics(cx);
2758 return true;
2759 }
2760
2761 false
2762 }
2763
2764 fn linked_editing_ranges_for(
2765 &self,
2766 selection: Range<text::Anchor>,
2767 cx: &App,
2768 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2769 if self.linked_edit_ranges.is_empty() {
2770 return None;
2771 }
2772 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2773 selection.end.buffer_id.and_then(|end_buffer_id| {
2774 if selection.start.buffer_id != Some(end_buffer_id) {
2775 return None;
2776 }
2777 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2778 let snapshot = buffer.read(cx).snapshot();
2779 self.linked_edit_ranges
2780 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2781 .map(|ranges| (ranges, snapshot, buffer))
2782 })?;
2783 use text::ToOffset as TO;
2784 // find offset from the start of current range to current cursor position
2785 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2786
2787 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2788 let start_difference = start_offset - start_byte_offset;
2789 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2790 let end_difference = end_offset - start_byte_offset;
2791 // Current range has associated linked ranges.
2792 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2793 for range in linked_ranges.iter() {
2794 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2795 let end_offset = start_offset + end_difference;
2796 let start_offset = start_offset + start_difference;
2797 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2798 continue;
2799 }
2800 if self.selections.disjoint_anchor_ranges().any(|s| {
2801 if s.start.buffer_id != selection.start.buffer_id
2802 || s.end.buffer_id != selection.end.buffer_id
2803 {
2804 return false;
2805 }
2806 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2807 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2808 }) {
2809 continue;
2810 }
2811 let start = buffer_snapshot.anchor_after(start_offset);
2812 let end = buffer_snapshot.anchor_after(end_offset);
2813 linked_edits
2814 .entry(buffer.clone())
2815 .or_default()
2816 .push(start..end);
2817 }
2818 Some(linked_edits)
2819 }
2820
2821 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2822 let text: Arc<str> = text.into();
2823
2824 if self.read_only(cx) {
2825 return;
2826 }
2827
2828 let selections = self.selections.all_adjusted(cx);
2829 let mut bracket_inserted = false;
2830 let mut edits = Vec::new();
2831 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2832 let mut new_selections = Vec::with_capacity(selections.len());
2833 let mut new_autoclose_regions = Vec::new();
2834 let snapshot = self.buffer.read(cx).read(cx);
2835
2836 for (selection, autoclose_region) in
2837 self.selections_with_autoclose_regions(selections, &snapshot)
2838 {
2839 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2840 // Determine if the inserted text matches the opening or closing
2841 // bracket of any of this language's bracket pairs.
2842 let mut bracket_pair = None;
2843 let mut is_bracket_pair_start = false;
2844 let mut is_bracket_pair_end = false;
2845 if !text.is_empty() {
2846 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2847 // and they are removing the character that triggered IME popup.
2848 for (pair, enabled) in scope.brackets() {
2849 if !pair.close && !pair.surround {
2850 continue;
2851 }
2852
2853 if enabled && pair.start.ends_with(text.as_ref()) {
2854 let prefix_len = pair.start.len() - text.len();
2855 let preceding_text_matches_prefix = prefix_len == 0
2856 || (selection.start.column >= (prefix_len as u32)
2857 && snapshot.contains_str_at(
2858 Point::new(
2859 selection.start.row,
2860 selection.start.column - (prefix_len as u32),
2861 ),
2862 &pair.start[..prefix_len],
2863 ));
2864 if preceding_text_matches_prefix {
2865 bracket_pair = Some(pair.clone());
2866 is_bracket_pair_start = true;
2867 break;
2868 }
2869 }
2870 if pair.end.as_str() == text.as_ref() {
2871 bracket_pair = Some(pair.clone());
2872 is_bracket_pair_end = true;
2873 break;
2874 }
2875 }
2876 }
2877
2878 if let Some(bracket_pair) = bracket_pair {
2879 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2880 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2881 let auto_surround =
2882 self.use_auto_surround && snapshot_settings.use_auto_surround;
2883 if selection.is_empty() {
2884 if is_bracket_pair_start {
2885 // If the inserted text is a suffix of an opening bracket and the
2886 // selection is preceded by the rest of the opening bracket, then
2887 // insert the closing bracket.
2888 let following_text_allows_autoclose = snapshot
2889 .chars_at(selection.start)
2890 .next()
2891 .map_or(true, |c| scope.should_autoclose_before(c));
2892
2893 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2894 && bracket_pair.start.len() == 1
2895 {
2896 let target = bracket_pair.start.chars().next().unwrap();
2897 let current_line_count = snapshot
2898 .reversed_chars_at(selection.start)
2899 .take_while(|&c| c != '\n')
2900 .filter(|&c| c == target)
2901 .count();
2902 current_line_count % 2 == 1
2903 } else {
2904 false
2905 };
2906
2907 if autoclose
2908 && bracket_pair.close
2909 && following_text_allows_autoclose
2910 && !is_closing_quote
2911 {
2912 let anchor = snapshot.anchor_before(selection.end);
2913 new_selections.push((selection.map(|_| anchor), text.len()));
2914 new_autoclose_regions.push((
2915 anchor,
2916 text.len(),
2917 selection.id,
2918 bracket_pair.clone(),
2919 ));
2920 edits.push((
2921 selection.range(),
2922 format!("{}{}", text, bracket_pair.end).into(),
2923 ));
2924 bracket_inserted = true;
2925 continue;
2926 }
2927 }
2928
2929 if let Some(region) = autoclose_region {
2930 // If the selection is followed by an auto-inserted closing bracket,
2931 // then don't insert that closing bracket again; just move the selection
2932 // past the closing bracket.
2933 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2934 && text.as_ref() == region.pair.end.as_str();
2935 if should_skip {
2936 let anchor = snapshot.anchor_after(selection.end);
2937 new_selections
2938 .push((selection.map(|_| anchor), region.pair.end.len()));
2939 continue;
2940 }
2941 }
2942
2943 let always_treat_brackets_as_autoclosed = snapshot
2944 .settings_at(selection.start, cx)
2945 .always_treat_brackets_as_autoclosed;
2946 if always_treat_brackets_as_autoclosed
2947 && is_bracket_pair_end
2948 && snapshot.contains_str_at(selection.end, text.as_ref())
2949 {
2950 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2951 // and the inserted text is a closing bracket and the selection is followed
2952 // by the closing bracket then move the selection past the closing bracket.
2953 let anchor = snapshot.anchor_after(selection.end);
2954 new_selections.push((selection.map(|_| anchor), text.len()));
2955 continue;
2956 }
2957 }
2958 // If an opening bracket is 1 character long and is typed while
2959 // text is selected, then surround that text with the bracket pair.
2960 else if auto_surround
2961 && bracket_pair.surround
2962 && is_bracket_pair_start
2963 && bracket_pair.start.chars().count() == 1
2964 {
2965 edits.push((selection.start..selection.start, text.clone()));
2966 edits.push((
2967 selection.end..selection.end,
2968 bracket_pair.end.as_str().into(),
2969 ));
2970 bracket_inserted = true;
2971 new_selections.push((
2972 Selection {
2973 id: selection.id,
2974 start: snapshot.anchor_after(selection.start),
2975 end: snapshot.anchor_before(selection.end),
2976 reversed: selection.reversed,
2977 goal: selection.goal,
2978 },
2979 0,
2980 ));
2981 continue;
2982 }
2983 }
2984 }
2985
2986 if self.auto_replace_emoji_shortcode
2987 && selection.is_empty()
2988 && text.as_ref().ends_with(':')
2989 {
2990 if let Some(possible_emoji_short_code) =
2991 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2992 {
2993 if !possible_emoji_short_code.is_empty() {
2994 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2995 let emoji_shortcode_start = Point::new(
2996 selection.start.row,
2997 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2998 );
2999
3000 // Remove shortcode from buffer
3001 edits.push((
3002 emoji_shortcode_start..selection.start,
3003 "".to_string().into(),
3004 ));
3005 new_selections.push((
3006 Selection {
3007 id: selection.id,
3008 start: snapshot.anchor_after(emoji_shortcode_start),
3009 end: snapshot.anchor_before(selection.start),
3010 reversed: selection.reversed,
3011 goal: selection.goal,
3012 },
3013 0,
3014 ));
3015
3016 // Insert emoji
3017 let selection_start_anchor = snapshot.anchor_after(selection.start);
3018 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3019 edits.push((selection.start..selection.end, emoji.to_string().into()));
3020
3021 continue;
3022 }
3023 }
3024 }
3025 }
3026
3027 // If not handling any auto-close operation, then just replace the selected
3028 // text with the given input and move the selection to the end of the
3029 // newly inserted text.
3030 let anchor = snapshot.anchor_after(selection.end);
3031 if !self.linked_edit_ranges.is_empty() {
3032 let start_anchor = snapshot.anchor_before(selection.start);
3033
3034 let is_word_char = text.chars().next().map_or(true, |char| {
3035 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3036 classifier.is_word(char)
3037 });
3038
3039 if is_word_char {
3040 if let Some(ranges) = self
3041 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3042 {
3043 for (buffer, edits) in ranges {
3044 linked_edits
3045 .entry(buffer.clone())
3046 .or_default()
3047 .extend(edits.into_iter().map(|range| (range, text.clone())));
3048 }
3049 }
3050 }
3051 }
3052
3053 new_selections.push((selection.map(|_| anchor), 0));
3054 edits.push((selection.start..selection.end, text.clone()));
3055 }
3056
3057 drop(snapshot);
3058
3059 self.transact(window, cx, |this, window, cx| {
3060 this.buffer.update(cx, |buffer, cx| {
3061 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3062 });
3063 for (buffer, edits) in linked_edits {
3064 buffer.update(cx, |buffer, cx| {
3065 let snapshot = buffer.snapshot();
3066 let edits = edits
3067 .into_iter()
3068 .map(|(range, text)| {
3069 use text::ToPoint as TP;
3070 let end_point = TP::to_point(&range.end, &snapshot);
3071 let start_point = TP::to_point(&range.start, &snapshot);
3072 (start_point..end_point, text)
3073 })
3074 .sorted_by_key(|(range, _)| range.start)
3075 .collect::<Vec<_>>();
3076 buffer.edit(edits, None, cx);
3077 })
3078 }
3079 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3080 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3081 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3082 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3083 .zip(new_selection_deltas)
3084 .map(|(selection, delta)| Selection {
3085 id: selection.id,
3086 start: selection.start + delta,
3087 end: selection.end + delta,
3088 reversed: selection.reversed,
3089 goal: SelectionGoal::None,
3090 })
3091 .collect::<Vec<_>>();
3092
3093 let mut i = 0;
3094 for (position, delta, selection_id, pair) in new_autoclose_regions {
3095 let position = position.to_offset(&map.buffer_snapshot) + delta;
3096 let start = map.buffer_snapshot.anchor_before(position);
3097 let end = map.buffer_snapshot.anchor_after(position);
3098 while let Some(existing_state) = this.autoclose_regions.get(i) {
3099 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3100 Ordering::Less => i += 1,
3101 Ordering::Greater => break,
3102 Ordering::Equal => {
3103 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3104 Ordering::Less => i += 1,
3105 Ordering::Equal => break,
3106 Ordering::Greater => break,
3107 }
3108 }
3109 }
3110 }
3111 this.autoclose_regions.insert(
3112 i,
3113 AutocloseRegion {
3114 selection_id,
3115 range: start..end,
3116 pair,
3117 },
3118 );
3119 }
3120
3121 let had_active_inline_completion = this.has_active_inline_completion();
3122 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3123 s.select(new_selections)
3124 });
3125
3126 if !bracket_inserted {
3127 if let Some(on_type_format_task) =
3128 this.trigger_on_type_formatting(text.to_string(), window, cx)
3129 {
3130 on_type_format_task.detach_and_log_err(cx);
3131 }
3132 }
3133
3134 let editor_settings = EditorSettings::get_global(cx);
3135 if bracket_inserted
3136 && (editor_settings.auto_signature_help
3137 || editor_settings.show_signature_help_after_edits)
3138 {
3139 this.show_signature_help(&ShowSignatureHelp, window, cx);
3140 }
3141
3142 let trigger_in_words =
3143 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3144 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3145 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3146 this.refresh_inline_completion(true, false, window, cx);
3147 });
3148 }
3149
3150 fn find_possible_emoji_shortcode_at_position(
3151 snapshot: &MultiBufferSnapshot,
3152 position: Point,
3153 ) -> Option<String> {
3154 let mut chars = Vec::new();
3155 let mut found_colon = false;
3156 for char in snapshot.reversed_chars_at(position).take(100) {
3157 // Found a possible emoji shortcode in the middle of the buffer
3158 if found_colon {
3159 if char.is_whitespace() {
3160 chars.reverse();
3161 return Some(chars.iter().collect());
3162 }
3163 // If the previous character is not a whitespace, we are in the middle of a word
3164 // and we only want to complete the shortcode if the word is made up of other emojis
3165 let mut containing_word = String::new();
3166 for ch in snapshot
3167 .reversed_chars_at(position)
3168 .skip(chars.len() + 1)
3169 .take(100)
3170 {
3171 if ch.is_whitespace() {
3172 break;
3173 }
3174 containing_word.push(ch);
3175 }
3176 let containing_word = containing_word.chars().rev().collect::<String>();
3177 if util::word_consists_of_emojis(containing_word.as_str()) {
3178 chars.reverse();
3179 return Some(chars.iter().collect());
3180 }
3181 }
3182
3183 if char.is_whitespace() || !char.is_ascii() {
3184 return None;
3185 }
3186 if char == ':' {
3187 found_colon = true;
3188 } else {
3189 chars.push(char);
3190 }
3191 }
3192 // Found a possible emoji shortcode at the beginning of the buffer
3193 chars.reverse();
3194 Some(chars.iter().collect())
3195 }
3196
3197 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3198 self.transact(window, cx, |this, window, cx| {
3199 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3200 let selections = this.selections.all::<usize>(cx);
3201 let multi_buffer = this.buffer.read(cx);
3202 let buffer = multi_buffer.snapshot(cx);
3203 selections
3204 .iter()
3205 .map(|selection| {
3206 let start_point = selection.start.to_point(&buffer);
3207 let mut indent =
3208 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3209 indent.len = cmp::min(indent.len, start_point.column);
3210 let start = selection.start;
3211 let end = selection.end;
3212 let selection_is_empty = start == end;
3213 let language_scope = buffer.language_scope_at(start);
3214 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3215 &language_scope
3216 {
3217 let leading_whitespace_len = buffer
3218 .reversed_chars_at(start)
3219 .take_while(|c| c.is_whitespace() && *c != '\n')
3220 .map(|c| c.len_utf8())
3221 .sum::<usize>();
3222
3223 let trailing_whitespace_len = buffer
3224 .chars_at(end)
3225 .take_while(|c| c.is_whitespace() && *c != '\n')
3226 .map(|c| c.len_utf8())
3227 .sum::<usize>();
3228
3229 let insert_extra_newline =
3230 language.brackets().any(|(pair, enabled)| {
3231 let pair_start = pair.start.trim_end();
3232 let pair_end = pair.end.trim_start();
3233
3234 enabled
3235 && pair.newline
3236 && buffer.contains_str_at(
3237 end + trailing_whitespace_len,
3238 pair_end,
3239 )
3240 && buffer.contains_str_at(
3241 (start - leading_whitespace_len)
3242 .saturating_sub(pair_start.len()),
3243 pair_start,
3244 )
3245 });
3246
3247 // Comment extension on newline is allowed only for cursor selections
3248 let comment_delimiter = maybe!({
3249 if !selection_is_empty {
3250 return None;
3251 }
3252
3253 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3254 return None;
3255 }
3256
3257 let delimiters = language.line_comment_prefixes();
3258 let max_len_of_delimiter =
3259 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3260 let (snapshot, range) =
3261 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3262
3263 let mut index_of_first_non_whitespace = 0;
3264 let comment_candidate = snapshot
3265 .chars_for_range(range)
3266 .skip_while(|c| {
3267 let should_skip = c.is_whitespace();
3268 if should_skip {
3269 index_of_first_non_whitespace += 1;
3270 }
3271 should_skip
3272 })
3273 .take(max_len_of_delimiter)
3274 .collect::<String>();
3275 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3276 comment_candidate.starts_with(comment_prefix.as_ref())
3277 })?;
3278 let cursor_is_placed_after_comment_marker =
3279 index_of_first_non_whitespace + comment_prefix.len()
3280 <= start_point.column as usize;
3281 if cursor_is_placed_after_comment_marker {
3282 Some(comment_prefix.clone())
3283 } else {
3284 None
3285 }
3286 });
3287 (comment_delimiter, insert_extra_newline)
3288 } else {
3289 (None, false)
3290 };
3291
3292 let capacity_for_delimiter = comment_delimiter
3293 .as_deref()
3294 .map(str::len)
3295 .unwrap_or_default();
3296 let mut new_text =
3297 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3298 new_text.push('\n');
3299 new_text.extend(indent.chars());
3300 if let Some(delimiter) = &comment_delimiter {
3301 new_text.push_str(delimiter);
3302 }
3303 if insert_extra_newline {
3304 new_text = new_text.repeat(2);
3305 }
3306
3307 let anchor = buffer.anchor_after(end);
3308 let new_selection = selection.map(|_| anchor);
3309 (
3310 (start..end, new_text),
3311 (insert_extra_newline, new_selection),
3312 )
3313 })
3314 .unzip()
3315 };
3316
3317 this.edit_with_autoindent(edits, cx);
3318 let buffer = this.buffer.read(cx).snapshot(cx);
3319 let new_selections = selection_fixup_info
3320 .into_iter()
3321 .map(|(extra_newline_inserted, new_selection)| {
3322 let mut cursor = new_selection.end.to_point(&buffer);
3323 if extra_newline_inserted {
3324 cursor.row -= 1;
3325 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3326 }
3327 new_selection.map(|_| cursor)
3328 })
3329 .collect();
3330
3331 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3332 s.select(new_selections)
3333 });
3334 this.refresh_inline_completion(true, false, window, cx);
3335 });
3336 }
3337
3338 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3339 let buffer = self.buffer.read(cx);
3340 let snapshot = buffer.snapshot(cx);
3341
3342 let mut edits = Vec::new();
3343 let mut rows = Vec::new();
3344
3345 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3346 let cursor = selection.head();
3347 let row = cursor.row;
3348
3349 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3350
3351 let newline = "\n".to_string();
3352 edits.push((start_of_line..start_of_line, newline));
3353
3354 rows.push(row + rows_inserted as u32);
3355 }
3356
3357 self.transact(window, cx, |editor, window, cx| {
3358 editor.edit(edits, cx);
3359
3360 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3361 let mut index = 0;
3362 s.move_cursors_with(|map, _, _| {
3363 let row = rows[index];
3364 index += 1;
3365
3366 let point = Point::new(row, 0);
3367 let boundary = map.next_line_boundary(point).1;
3368 let clipped = map.clip_point(boundary, Bias::Left);
3369
3370 (clipped, SelectionGoal::None)
3371 });
3372 });
3373
3374 let mut indent_edits = Vec::new();
3375 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3376 for row in rows {
3377 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3378 for (row, indent) in indents {
3379 if indent.len == 0 {
3380 continue;
3381 }
3382
3383 let text = match indent.kind {
3384 IndentKind::Space => " ".repeat(indent.len as usize),
3385 IndentKind::Tab => "\t".repeat(indent.len as usize),
3386 };
3387 let point = Point::new(row.0, 0);
3388 indent_edits.push((point..point, text));
3389 }
3390 }
3391 editor.edit(indent_edits, cx);
3392 });
3393 }
3394
3395 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3396 let buffer = self.buffer.read(cx);
3397 let snapshot = buffer.snapshot(cx);
3398
3399 let mut edits = Vec::new();
3400 let mut rows = Vec::new();
3401 let mut rows_inserted = 0;
3402
3403 for selection in self.selections.all_adjusted(cx) {
3404 let cursor = selection.head();
3405 let row = cursor.row;
3406
3407 let point = Point::new(row + 1, 0);
3408 let start_of_line = snapshot.clip_point(point, Bias::Left);
3409
3410 let newline = "\n".to_string();
3411 edits.push((start_of_line..start_of_line, newline));
3412
3413 rows_inserted += 1;
3414 rows.push(row + rows_inserted);
3415 }
3416
3417 self.transact(window, cx, |editor, window, cx| {
3418 editor.edit(edits, cx);
3419
3420 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3421 let mut index = 0;
3422 s.move_cursors_with(|map, _, _| {
3423 let row = rows[index];
3424 index += 1;
3425
3426 let point = Point::new(row, 0);
3427 let boundary = map.next_line_boundary(point).1;
3428 let clipped = map.clip_point(boundary, Bias::Left);
3429
3430 (clipped, SelectionGoal::None)
3431 });
3432 });
3433
3434 let mut indent_edits = Vec::new();
3435 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3436 for row in rows {
3437 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3438 for (row, indent) in indents {
3439 if indent.len == 0 {
3440 continue;
3441 }
3442
3443 let text = match indent.kind {
3444 IndentKind::Space => " ".repeat(indent.len as usize),
3445 IndentKind::Tab => "\t".repeat(indent.len as usize),
3446 };
3447 let point = Point::new(row.0, 0);
3448 indent_edits.push((point..point, text));
3449 }
3450 }
3451 editor.edit(indent_edits, cx);
3452 });
3453 }
3454
3455 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3456 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3457 original_indent_columns: Vec::new(),
3458 });
3459 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3460 }
3461
3462 fn insert_with_autoindent_mode(
3463 &mut self,
3464 text: &str,
3465 autoindent_mode: Option<AutoindentMode>,
3466 window: &mut Window,
3467 cx: &mut Context<Self>,
3468 ) {
3469 if self.read_only(cx) {
3470 return;
3471 }
3472
3473 let text: Arc<str> = text.into();
3474 self.transact(window, cx, |this, window, cx| {
3475 let old_selections = this.selections.all_adjusted(cx);
3476 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3477 let anchors = {
3478 let snapshot = buffer.read(cx);
3479 old_selections
3480 .iter()
3481 .map(|s| {
3482 let anchor = snapshot.anchor_after(s.head());
3483 s.map(|_| anchor)
3484 })
3485 .collect::<Vec<_>>()
3486 };
3487 buffer.edit(
3488 old_selections
3489 .iter()
3490 .map(|s| (s.start..s.end, text.clone())),
3491 autoindent_mode,
3492 cx,
3493 );
3494 anchors
3495 });
3496
3497 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3498 s.select_anchors(selection_anchors);
3499 });
3500
3501 cx.notify();
3502 });
3503 }
3504
3505 fn trigger_completion_on_input(
3506 &mut self,
3507 text: &str,
3508 trigger_in_words: bool,
3509 window: &mut Window,
3510 cx: &mut Context<Self>,
3511 ) {
3512 if self.is_completion_trigger(text, trigger_in_words, cx) {
3513 self.show_completions(
3514 &ShowCompletions {
3515 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3516 },
3517 window,
3518 cx,
3519 );
3520 } else {
3521 self.hide_context_menu(window, cx);
3522 }
3523 }
3524
3525 fn is_completion_trigger(
3526 &self,
3527 text: &str,
3528 trigger_in_words: bool,
3529 cx: &mut Context<Self>,
3530 ) -> bool {
3531 let position = self.selections.newest_anchor().head();
3532 let multibuffer = self.buffer.read(cx);
3533 let Some(buffer) = position
3534 .buffer_id
3535 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3536 else {
3537 return false;
3538 };
3539
3540 if let Some(completion_provider) = &self.completion_provider {
3541 completion_provider.is_completion_trigger(
3542 &buffer,
3543 position.text_anchor,
3544 text,
3545 trigger_in_words,
3546 cx,
3547 )
3548 } else {
3549 false
3550 }
3551 }
3552
3553 /// If any empty selections is touching the start of its innermost containing autoclose
3554 /// region, expand it to select the brackets.
3555 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3556 let selections = self.selections.all::<usize>(cx);
3557 let buffer = self.buffer.read(cx).read(cx);
3558 let new_selections = self
3559 .selections_with_autoclose_regions(selections, &buffer)
3560 .map(|(mut selection, region)| {
3561 if !selection.is_empty() {
3562 return selection;
3563 }
3564
3565 if let Some(region) = region {
3566 let mut range = region.range.to_offset(&buffer);
3567 if selection.start == range.start && range.start >= region.pair.start.len() {
3568 range.start -= region.pair.start.len();
3569 if buffer.contains_str_at(range.start, ®ion.pair.start)
3570 && buffer.contains_str_at(range.end, ®ion.pair.end)
3571 {
3572 range.end += region.pair.end.len();
3573 selection.start = range.start;
3574 selection.end = range.end;
3575
3576 return selection;
3577 }
3578 }
3579 }
3580
3581 let always_treat_brackets_as_autoclosed = buffer
3582 .settings_at(selection.start, cx)
3583 .always_treat_brackets_as_autoclosed;
3584
3585 if !always_treat_brackets_as_autoclosed {
3586 return selection;
3587 }
3588
3589 if let Some(scope) = buffer.language_scope_at(selection.start) {
3590 for (pair, enabled) in scope.brackets() {
3591 if !enabled || !pair.close {
3592 continue;
3593 }
3594
3595 if buffer.contains_str_at(selection.start, &pair.end) {
3596 let pair_start_len = pair.start.len();
3597 if buffer.contains_str_at(
3598 selection.start.saturating_sub(pair_start_len),
3599 &pair.start,
3600 ) {
3601 selection.start -= pair_start_len;
3602 selection.end += pair.end.len();
3603
3604 return selection;
3605 }
3606 }
3607 }
3608 }
3609
3610 selection
3611 })
3612 .collect();
3613
3614 drop(buffer);
3615 self.change_selections(None, window, cx, |selections| {
3616 selections.select(new_selections)
3617 });
3618 }
3619
3620 /// Iterate the given selections, and for each one, find the smallest surrounding
3621 /// autoclose region. This uses the ordering of the selections and the autoclose
3622 /// regions to avoid repeated comparisons.
3623 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3624 &'a self,
3625 selections: impl IntoIterator<Item = Selection<D>>,
3626 buffer: &'a MultiBufferSnapshot,
3627 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3628 let mut i = 0;
3629 let mut regions = self.autoclose_regions.as_slice();
3630 selections.into_iter().map(move |selection| {
3631 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3632
3633 let mut enclosing = None;
3634 while let Some(pair_state) = regions.get(i) {
3635 if pair_state.range.end.to_offset(buffer) < range.start {
3636 regions = ®ions[i + 1..];
3637 i = 0;
3638 } else if pair_state.range.start.to_offset(buffer) > range.end {
3639 break;
3640 } else {
3641 if pair_state.selection_id == selection.id {
3642 enclosing = Some(pair_state);
3643 }
3644 i += 1;
3645 }
3646 }
3647
3648 (selection, enclosing)
3649 })
3650 }
3651
3652 /// Remove any autoclose regions that no longer contain their selection.
3653 fn invalidate_autoclose_regions(
3654 &mut self,
3655 mut selections: &[Selection<Anchor>],
3656 buffer: &MultiBufferSnapshot,
3657 ) {
3658 self.autoclose_regions.retain(|state| {
3659 let mut i = 0;
3660 while let Some(selection) = selections.get(i) {
3661 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3662 selections = &selections[1..];
3663 continue;
3664 }
3665 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3666 break;
3667 }
3668 if selection.id == state.selection_id {
3669 return true;
3670 } else {
3671 i += 1;
3672 }
3673 }
3674 false
3675 });
3676 }
3677
3678 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3679 let offset = position.to_offset(buffer);
3680 let (word_range, kind) = buffer.surrounding_word(offset, true);
3681 if offset > word_range.start && kind == Some(CharKind::Word) {
3682 Some(
3683 buffer
3684 .text_for_range(word_range.start..offset)
3685 .collect::<String>(),
3686 )
3687 } else {
3688 None
3689 }
3690 }
3691
3692 pub fn toggle_inlay_hints(
3693 &mut self,
3694 _: &ToggleInlayHints,
3695 _: &mut Window,
3696 cx: &mut Context<Self>,
3697 ) {
3698 self.refresh_inlay_hints(
3699 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3700 cx,
3701 );
3702 }
3703
3704 pub fn inlay_hints_enabled(&self) -> bool {
3705 self.inlay_hint_cache.enabled
3706 }
3707
3708 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3709 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3710 return;
3711 }
3712
3713 let reason_description = reason.description();
3714 let ignore_debounce = matches!(
3715 reason,
3716 InlayHintRefreshReason::SettingsChange(_)
3717 | InlayHintRefreshReason::Toggle(_)
3718 | InlayHintRefreshReason::ExcerptsRemoved(_)
3719 );
3720 let (invalidate_cache, required_languages) = match reason {
3721 InlayHintRefreshReason::Toggle(enabled) => {
3722 self.inlay_hint_cache.enabled = enabled;
3723 if enabled {
3724 (InvalidationStrategy::RefreshRequested, None)
3725 } else {
3726 self.inlay_hint_cache.clear();
3727 self.splice_inlays(
3728 &self
3729 .visible_inlay_hints(cx)
3730 .iter()
3731 .map(|inlay| inlay.id)
3732 .collect::<Vec<InlayId>>(),
3733 Vec::new(),
3734 cx,
3735 );
3736 return;
3737 }
3738 }
3739 InlayHintRefreshReason::SettingsChange(new_settings) => {
3740 match self.inlay_hint_cache.update_settings(
3741 &self.buffer,
3742 new_settings,
3743 self.visible_inlay_hints(cx),
3744 cx,
3745 ) {
3746 ControlFlow::Break(Some(InlaySplice {
3747 to_remove,
3748 to_insert,
3749 })) => {
3750 self.splice_inlays(&to_remove, to_insert, cx);
3751 return;
3752 }
3753 ControlFlow::Break(None) => return,
3754 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3755 }
3756 }
3757 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3758 if let Some(InlaySplice {
3759 to_remove,
3760 to_insert,
3761 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3762 {
3763 self.splice_inlays(&to_remove, to_insert, cx);
3764 }
3765 return;
3766 }
3767 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3768 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3769 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3770 }
3771 InlayHintRefreshReason::RefreshRequested => {
3772 (InvalidationStrategy::RefreshRequested, None)
3773 }
3774 };
3775
3776 if let Some(InlaySplice {
3777 to_remove,
3778 to_insert,
3779 }) = self.inlay_hint_cache.spawn_hint_refresh(
3780 reason_description,
3781 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3782 invalidate_cache,
3783 ignore_debounce,
3784 cx,
3785 ) {
3786 self.splice_inlays(&to_remove, to_insert, cx);
3787 }
3788 }
3789
3790 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3791 self.display_map
3792 .read(cx)
3793 .current_inlays()
3794 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3795 .cloned()
3796 .collect()
3797 }
3798
3799 pub fn excerpts_for_inlay_hints_query(
3800 &self,
3801 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3802 cx: &mut Context<Editor>,
3803 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3804 let Some(project) = self.project.as_ref() else {
3805 return HashMap::default();
3806 };
3807 let project = project.read(cx);
3808 let multi_buffer = self.buffer().read(cx);
3809 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3810 let multi_buffer_visible_start = self
3811 .scroll_manager
3812 .anchor()
3813 .anchor
3814 .to_point(&multi_buffer_snapshot);
3815 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3816 multi_buffer_visible_start
3817 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3818 Bias::Left,
3819 );
3820 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3821 multi_buffer_snapshot
3822 .range_to_buffer_ranges(multi_buffer_visible_range)
3823 .into_iter()
3824 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3825 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3826 let buffer_file = project::File::from_dyn(buffer.file())?;
3827 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3828 let worktree_entry = buffer_worktree
3829 .read(cx)
3830 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3831 if worktree_entry.is_ignored {
3832 return None;
3833 }
3834
3835 let language = buffer.language()?;
3836 if let Some(restrict_to_languages) = restrict_to_languages {
3837 if !restrict_to_languages.contains(language) {
3838 return None;
3839 }
3840 }
3841 Some((
3842 excerpt_id,
3843 (
3844 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3845 buffer.version().clone(),
3846 excerpt_visible_range,
3847 ),
3848 ))
3849 })
3850 .collect()
3851 }
3852
3853 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3854 TextLayoutDetails {
3855 text_system: window.text_system().clone(),
3856 editor_style: self.style.clone().unwrap(),
3857 rem_size: window.rem_size(),
3858 scroll_anchor: self.scroll_manager.anchor(),
3859 visible_rows: self.visible_line_count(),
3860 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3861 }
3862 }
3863
3864 pub fn splice_inlays(
3865 &self,
3866 to_remove: &[InlayId],
3867 to_insert: Vec<Inlay>,
3868 cx: &mut Context<Self>,
3869 ) {
3870 self.display_map.update(cx, |display_map, cx| {
3871 display_map.splice_inlays(to_remove, to_insert, cx)
3872 });
3873 cx.notify();
3874 }
3875
3876 fn trigger_on_type_formatting(
3877 &self,
3878 input: String,
3879 window: &mut Window,
3880 cx: &mut Context<Self>,
3881 ) -> Option<Task<Result<()>>> {
3882 if input.len() != 1 {
3883 return None;
3884 }
3885
3886 let project = self.project.as_ref()?;
3887 let position = self.selections.newest_anchor().head();
3888 let (buffer, buffer_position) = self
3889 .buffer
3890 .read(cx)
3891 .text_anchor_for_position(position, cx)?;
3892
3893 let settings = language_settings::language_settings(
3894 buffer
3895 .read(cx)
3896 .language_at(buffer_position)
3897 .map(|l| l.name()),
3898 buffer.read(cx).file(),
3899 cx,
3900 );
3901 if !settings.use_on_type_format {
3902 return None;
3903 }
3904
3905 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3906 // hence we do LSP request & edit on host side only — add formats to host's history.
3907 let push_to_lsp_host_history = true;
3908 // If this is not the host, append its history with new edits.
3909 let push_to_client_history = project.read(cx).is_via_collab();
3910
3911 let on_type_formatting = project.update(cx, |project, cx| {
3912 project.on_type_format(
3913 buffer.clone(),
3914 buffer_position,
3915 input,
3916 push_to_lsp_host_history,
3917 cx,
3918 )
3919 });
3920 Some(cx.spawn_in(window, |editor, mut cx| async move {
3921 if let Some(transaction) = on_type_formatting.await? {
3922 if push_to_client_history {
3923 buffer
3924 .update(&mut cx, |buffer, _| {
3925 buffer.push_transaction(transaction, Instant::now());
3926 })
3927 .ok();
3928 }
3929 editor.update(&mut cx, |editor, cx| {
3930 editor.refresh_document_highlights(cx);
3931 })?;
3932 }
3933 Ok(())
3934 }))
3935 }
3936
3937 pub fn show_completions(
3938 &mut self,
3939 options: &ShowCompletions,
3940 window: &mut Window,
3941 cx: &mut Context<Self>,
3942 ) {
3943 if self.pending_rename.is_some() {
3944 return;
3945 }
3946
3947 let Some(provider) = self.completion_provider.as_ref() else {
3948 return;
3949 };
3950
3951 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3952 return;
3953 }
3954
3955 let position = self.selections.newest_anchor().head();
3956 if position.diff_base_anchor.is_some() {
3957 return;
3958 }
3959 let (buffer, buffer_position) =
3960 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3961 output
3962 } else {
3963 return;
3964 };
3965 let show_completion_documentation = buffer
3966 .read(cx)
3967 .snapshot()
3968 .settings_at(buffer_position, cx)
3969 .show_completion_documentation;
3970
3971 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3972
3973 let trigger_kind = match &options.trigger {
3974 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3975 CompletionTriggerKind::TRIGGER_CHARACTER
3976 }
3977 _ => CompletionTriggerKind::INVOKED,
3978 };
3979 let completion_context = CompletionContext {
3980 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3981 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3982 Some(String::from(trigger))
3983 } else {
3984 None
3985 }
3986 }),
3987 trigger_kind,
3988 };
3989 let completions =
3990 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3991 let sort_completions = provider.sort_completions();
3992
3993 let id = post_inc(&mut self.next_completion_id);
3994 let task = cx.spawn_in(window, |editor, mut cx| {
3995 async move {
3996 editor.update(&mut cx, |this, _| {
3997 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3998 })?;
3999 let completions = completions.await.log_err();
4000 let menu = if let Some(completions) = completions {
4001 let mut menu = CompletionsMenu::new(
4002 id,
4003 sort_completions,
4004 show_completion_documentation,
4005 position,
4006 buffer.clone(),
4007 completions.into(),
4008 );
4009
4010 menu.filter(query.as_deref(), cx.background_executor().clone())
4011 .await;
4012
4013 menu.visible().then_some(menu)
4014 } else {
4015 None
4016 };
4017
4018 editor.update_in(&mut cx, |editor, window, cx| {
4019 match editor.context_menu.borrow().as_ref() {
4020 None => {}
4021 Some(CodeContextMenu::Completions(prev_menu)) => {
4022 if prev_menu.id > id {
4023 return;
4024 }
4025 }
4026 _ => return,
4027 }
4028
4029 if editor.focus_handle.is_focused(window) && menu.is_some() {
4030 let mut menu = menu.unwrap();
4031 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4032
4033 *editor.context_menu.borrow_mut() =
4034 Some(CodeContextMenu::Completions(menu));
4035
4036 if editor.show_edit_predictions_in_menu() {
4037 editor.update_visible_inline_completion(window, cx);
4038 } else {
4039 editor.discard_inline_completion(false, cx);
4040 }
4041
4042 cx.notify();
4043 } else if editor.completion_tasks.len() <= 1 {
4044 // If there are no more completion tasks and the last menu was
4045 // empty, we should hide it.
4046 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4047 // If it was already hidden and we don't show inline
4048 // completions in the menu, we should also show the
4049 // inline-completion when available.
4050 if was_hidden && editor.show_edit_predictions_in_menu() {
4051 editor.update_visible_inline_completion(window, cx);
4052 }
4053 }
4054 })?;
4055
4056 Ok::<_, anyhow::Error>(())
4057 }
4058 .log_err()
4059 });
4060
4061 self.completion_tasks.push((id, task));
4062 }
4063
4064 pub fn confirm_completion(
4065 &mut self,
4066 action: &ConfirmCompletion,
4067 window: &mut Window,
4068 cx: &mut Context<Self>,
4069 ) -> Option<Task<Result<()>>> {
4070 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4071 }
4072
4073 pub fn compose_completion(
4074 &mut self,
4075 action: &ComposeCompletion,
4076 window: &mut Window,
4077 cx: &mut Context<Self>,
4078 ) -> Option<Task<Result<()>>> {
4079 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4080 }
4081
4082 fn do_completion(
4083 &mut self,
4084 item_ix: Option<usize>,
4085 intent: CompletionIntent,
4086 window: &mut Window,
4087 cx: &mut Context<Editor>,
4088 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4089 use language::ToOffset as _;
4090
4091 let completions_menu =
4092 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4093 menu
4094 } else {
4095 return None;
4096 };
4097
4098 let entries = completions_menu.entries.borrow();
4099 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4100 if self.show_edit_predictions_in_menu() {
4101 self.discard_inline_completion(true, cx);
4102 }
4103 let candidate_id = mat.candidate_id;
4104 drop(entries);
4105
4106 let buffer_handle = completions_menu.buffer;
4107 let completion = completions_menu
4108 .completions
4109 .borrow()
4110 .get(candidate_id)?
4111 .clone();
4112 cx.stop_propagation();
4113
4114 let snippet;
4115 let text;
4116
4117 if completion.is_snippet() {
4118 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4119 text = snippet.as_ref().unwrap().text.clone();
4120 } else {
4121 snippet = None;
4122 text = completion.new_text.clone();
4123 };
4124 let selections = self.selections.all::<usize>(cx);
4125 let buffer = buffer_handle.read(cx);
4126 let old_range = completion.old_range.to_offset(buffer);
4127 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4128
4129 let newest_selection = self.selections.newest_anchor();
4130 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4131 return None;
4132 }
4133
4134 let lookbehind = newest_selection
4135 .start
4136 .text_anchor
4137 .to_offset(buffer)
4138 .saturating_sub(old_range.start);
4139 let lookahead = old_range
4140 .end
4141 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4142 let mut common_prefix_len = old_text
4143 .bytes()
4144 .zip(text.bytes())
4145 .take_while(|(a, b)| a == b)
4146 .count();
4147
4148 let snapshot = self.buffer.read(cx).snapshot(cx);
4149 let mut range_to_replace: Option<Range<isize>> = None;
4150 let mut ranges = Vec::new();
4151 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4152 for selection in &selections {
4153 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4154 let start = selection.start.saturating_sub(lookbehind);
4155 let end = selection.end + lookahead;
4156 if selection.id == newest_selection.id {
4157 range_to_replace = Some(
4158 ((start + common_prefix_len) as isize - selection.start as isize)
4159 ..(end as isize - selection.start as isize),
4160 );
4161 }
4162 ranges.push(start + common_prefix_len..end);
4163 } else {
4164 common_prefix_len = 0;
4165 ranges.clear();
4166 ranges.extend(selections.iter().map(|s| {
4167 if s.id == newest_selection.id {
4168 range_to_replace = Some(
4169 old_range.start.to_offset_utf16(&snapshot).0 as isize
4170 - selection.start as isize
4171 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4172 - selection.start as isize,
4173 );
4174 old_range.clone()
4175 } else {
4176 s.start..s.end
4177 }
4178 }));
4179 break;
4180 }
4181 if !self.linked_edit_ranges.is_empty() {
4182 let start_anchor = snapshot.anchor_before(selection.head());
4183 let end_anchor = snapshot.anchor_after(selection.tail());
4184 if let Some(ranges) = self
4185 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4186 {
4187 for (buffer, edits) in ranges {
4188 linked_edits.entry(buffer.clone()).or_default().extend(
4189 edits
4190 .into_iter()
4191 .map(|range| (range, text[common_prefix_len..].to_owned())),
4192 );
4193 }
4194 }
4195 }
4196 }
4197 let text = &text[common_prefix_len..];
4198
4199 cx.emit(EditorEvent::InputHandled {
4200 utf16_range_to_replace: range_to_replace,
4201 text: text.into(),
4202 });
4203
4204 self.transact(window, cx, |this, window, cx| {
4205 if let Some(mut snippet) = snippet {
4206 snippet.text = text.to_string();
4207 for tabstop in snippet
4208 .tabstops
4209 .iter_mut()
4210 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4211 {
4212 tabstop.start -= common_prefix_len as isize;
4213 tabstop.end -= common_prefix_len as isize;
4214 }
4215
4216 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4217 } else {
4218 this.buffer.update(cx, |buffer, cx| {
4219 buffer.edit(
4220 ranges.iter().map(|range| (range.clone(), text)),
4221 this.autoindent_mode.clone(),
4222 cx,
4223 );
4224 });
4225 }
4226 for (buffer, edits) in linked_edits {
4227 buffer.update(cx, |buffer, cx| {
4228 let snapshot = buffer.snapshot();
4229 let edits = edits
4230 .into_iter()
4231 .map(|(range, text)| {
4232 use text::ToPoint as TP;
4233 let end_point = TP::to_point(&range.end, &snapshot);
4234 let start_point = TP::to_point(&range.start, &snapshot);
4235 (start_point..end_point, text)
4236 })
4237 .sorted_by_key(|(range, _)| range.start)
4238 .collect::<Vec<_>>();
4239 buffer.edit(edits, None, cx);
4240 })
4241 }
4242
4243 this.refresh_inline_completion(true, false, window, cx);
4244 });
4245
4246 let show_new_completions_on_confirm = completion
4247 .confirm
4248 .as_ref()
4249 .map_or(false, |confirm| confirm(intent, window, cx));
4250 if show_new_completions_on_confirm {
4251 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4252 }
4253
4254 let provider = self.completion_provider.as_ref()?;
4255 drop(completion);
4256 let apply_edits = provider.apply_additional_edits_for_completion(
4257 buffer_handle,
4258 completions_menu.completions.clone(),
4259 candidate_id,
4260 true,
4261 cx,
4262 );
4263
4264 let editor_settings = EditorSettings::get_global(cx);
4265 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4266 // After the code completion is finished, users often want to know what signatures are needed.
4267 // so we should automatically call signature_help
4268 self.show_signature_help(&ShowSignatureHelp, window, cx);
4269 }
4270
4271 Some(cx.foreground_executor().spawn(async move {
4272 apply_edits.await?;
4273 Ok(())
4274 }))
4275 }
4276
4277 pub fn toggle_code_actions(
4278 &mut self,
4279 action: &ToggleCodeActions,
4280 window: &mut Window,
4281 cx: &mut Context<Self>,
4282 ) {
4283 let mut context_menu = self.context_menu.borrow_mut();
4284 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4285 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4286 // Toggle if we're selecting the same one
4287 *context_menu = None;
4288 cx.notify();
4289 return;
4290 } else {
4291 // Otherwise, clear it and start a new one
4292 *context_menu = None;
4293 cx.notify();
4294 }
4295 }
4296 drop(context_menu);
4297 let snapshot = self.snapshot(window, cx);
4298 let deployed_from_indicator = action.deployed_from_indicator;
4299 let mut task = self.code_actions_task.take();
4300 let action = action.clone();
4301 cx.spawn_in(window, |editor, mut cx| async move {
4302 while let Some(prev_task) = task {
4303 prev_task.await.log_err();
4304 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4305 }
4306
4307 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4308 if editor.focus_handle.is_focused(window) {
4309 let multibuffer_point = action
4310 .deployed_from_indicator
4311 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4312 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4313 let (buffer, buffer_row) = snapshot
4314 .buffer_snapshot
4315 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4316 .and_then(|(buffer_snapshot, range)| {
4317 editor
4318 .buffer
4319 .read(cx)
4320 .buffer(buffer_snapshot.remote_id())
4321 .map(|buffer| (buffer, range.start.row))
4322 })?;
4323 let (_, code_actions) = editor
4324 .available_code_actions
4325 .clone()
4326 .and_then(|(location, code_actions)| {
4327 let snapshot = location.buffer.read(cx).snapshot();
4328 let point_range = location.range.to_point(&snapshot);
4329 let point_range = point_range.start.row..=point_range.end.row;
4330 if point_range.contains(&buffer_row) {
4331 Some((location, code_actions))
4332 } else {
4333 None
4334 }
4335 })
4336 .unzip();
4337 let buffer_id = buffer.read(cx).remote_id();
4338 let tasks = editor
4339 .tasks
4340 .get(&(buffer_id, buffer_row))
4341 .map(|t| Arc::new(t.to_owned()));
4342 if tasks.is_none() && code_actions.is_none() {
4343 return None;
4344 }
4345
4346 editor.completion_tasks.clear();
4347 editor.discard_inline_completion(false, cx);
4348 let task_context =
4349 tasks
4350 .as_ref()
4351 .zip(editor.project.clone())
4352 .map(|(tasks, project)| {
4353 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4354 });
4355
4356 Some(cx.spawn_in(window, |editor, mut cx| async move {
4357 let task_context = match task_context {
4358 Some(task_context) => task_context.await,
4359 None => None,
4360 };
4361 let resolved_tasks =
4362 tasks.zip(task_context).map(|(tasks, task_context)| {
4363 Rc::new(ResolvedTasks {
4364 templates: tasks.resolve(&task_context).collect(),
4365 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4366 multibuffer_point.row,
4367 tasks.column,
4368 )),
4369 })
4370 });
4371 let spawn_straight_away = resolved_tasks
4372 .as_ref()
4373 .map_or(false, |tasks| tasks.templates.len() == 1)
4374 && code_actions
4375 .as_ref()
4376 .map_or(true, |actions| actions.is_empty());
4377 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4378 *editor.context_menu.borrow_mut() =
4379 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4380 buffer,
4381 actions: CodeActionContents {
4382 tasks: resolved_tasks,
4383 actions: code_actions,
4384 },
4385 selected_item: Default::default(),
4386 scroll_handle: UniformListScrollHandle::default(),
4387 deployed_from_indicator,
4388 }));
4389 if spawn_straight_away {
4390 if let Some(task) = editor.confirm_code_action(
4391 &ConfirmCodeAction { item_ix: Some(0) },
4392 window,
4393 cx,
4394 ) {
4395 cx.notify();
4396 return task;
4397 }
4398 }
4399 cx.notify();
4400 Task::ready(Ok(()))
4401 }) {
4402 task.await
4403 } else {
4404 Ok(())
4405 }
4406 }))
4407 } else {
4408 Some(Task::ready(Ok(())))
4409 }
4410 })?;
4411 if let Some(task) = spawned_test_task {
4412 task.await?;
4413 }
4414
4415 Ok::<_, anyhow::Error>(())
4416 })
4417 .detach_and_log_err(cx);
4418 }
4419
4420 pub fn confirm_code_action(
4421 &mut self,
4422 action: &ConfirmCodeAction,
4423 window: &mut Window,
4424 cx: &mut Context<Self>,
4425 ) -> Option<Task<Result<()>>> {
4426 let actions_menu =
4427 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4428 menu
4429 } else {
4430 return None;
4431 };
4432 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4433 let action = actions_menu.actions.get(action_ix)?;
4434 let title = action.label();
4435 let buffer = actions_menu.buffer;
4436 let workspace = self.workspace()?;
4437
4438 match action {
4439 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4440 workspace.update(cx, |workspace, cx| {
4441 workspace::tasks::schedule_resolved_task(
4442 workspace,
4443 task_source_kind,
4444 resolved_task,
4445 false,
4446 cx,
4447 );
4448
4449 Some(Task::ready(Ok(())))
4450 })
4451 }
4452 CodeActionsItem::CodeAction {
4453 excerpt_id,
4454 action,
4455 provider,
4456 } => {
4457 let apply_code_action =
4458 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4459 let workspace = workspace.downgrade();
4460 Some(cx.spawn_in(window, |editor, cx| async move {
4461 let project_transaction = apply_code_action.await?;
4462 Self::open_project_transaction(
4463 &editor,
4464 workspace,
4465 project_transaction,
4466 title,
4467 cx,
4468 )
4469 .await
4470 }))
4471 }
4472 }
4473 }
4474
4475 pub async fn open_project_transaction(
4476 this: &WeakEntity<Editor>,
4477 workspace: WeakEntity<Workspace>,
4478 transaction: ProjectTransaction,
4479 title: String,
4480 mut cx: AsyncWindowContext,
4481 ) -> Result<()> {
4482 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4483 cx.update(|_, cx| {
4484 entries.sort_unstable_by_key(|(buffer, _)| {
4485 buffer.read(cx).file().map(|f| f.path().clone())
4486 });
4487 })?;
4488
4489 // If the project transaction's edits are all contained within this editor, then
4490 // avoid opening a new editor to display them.
4491
4492 if let Some((buffer, transaction)) = entries.first() {
4493 if entries.len() == 1 {
4494 let excerpt = this.update(&mut cx, |editor, cx| {
4495 editor
4496 .buffer()
4497 .read(cx)
4498 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4499 })?;
4500 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4501 if excerpted_buffer == *buffer {
4502 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4503 let excerpt_range = excerpt_range.to_offset(buffer);
4504 buffer
4505 .edited_ranges_for_transaction::<usize>(transaction)
4506 .all(|range| {
4507 excerpt_range.start <= range.start
4508 && excerpt_range.end >= range.end
4509 })
4510 })?;
4511
4512 if all_edits_within_excerpt {
4513 return Ok(());
4514 }
4515 }
4516 }
4517 }
4518 } else {
4519 return Ok(());
4520 }
4521
4522 let mut ranges_to_highlight = Vec::new();
4523 let excerpt_buffer = cx.new(|cx| {
4524 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4525 for (buffer_handle, transaction) in &entries {
4526 let buffer = buffer_handle.read(cx);
4527 ranges_to_highlight.extend(
4528 multibuffer.push_excerpts_with_context_lines(
4529 buffer_handle.clone(),
4530 buffer
4531 .edited_ranges_for_transaction::<usize>(transaction)
4532 .collect(),
4533 DEFAULT_MULTIBUFFER_CONTEXT,
4534 cx,
4535 ),
4536 );
4537 }
4538 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4539 multibuffer
4540 })?;
4541
4542 workspace.update_in(&mut cx, |workspace, window, cx| {
4543 let project = workspace.project().clone();
4544 let editor = cx
4545 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4546 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4547 editor.update(cx, |editor, cx| {
4548 editor.highlight_background::<Self>(
4549 &ranges_to_highlight,
4550 |theme| theme.editor_highlighted_line_background,
4551 cx,
4552 );
4553 });
4554 })?;
4555
4556 Ok(())
4557 }
4558
4559 pub fn clear_code_action_providers(&mut self) {
4560 self.code_action_providers.clear();
4561 self.available_code_actions.take();
4562 }
4563
4564 pub fn add_code_action_provider(
4565 &mut self,
4566 provider: Rc<dyn CodeActionProvider>,
4567 window: &mut Window,
4568 cx: &mut Context<Self>,
4569 ) {
4570 if self
4571 .code_action_providers
4572 .iter()
4573 .any(|existing_provider| existing_provider.id() == provider.id())
4574 {
4575 return;
4576 }
4577
4578 self.code_action_providers.push(provider);
4579 self.refresh_code_actions(window, cx);
4580 }
4581
4582 pub fn remove_code_action_provider(
4583 &mut self,
4584 id: Arc<str>,
4585 window: &mut Window,
4586 cx: &mut Context<Self>,
4587 ) {
4588 self.code_action_providers
4589 .retain(|provider| provider.id() != id);
4590 self.refresh_code_actions(window, cx);
4591 }
4592
4593 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4594 let buffer = self.buffer.read(cx);
4595 let newest_selection = self.selections.newest_anchor().clone();
4596 if newest_selection.head().diff_base_anchor.is_some() {
4597 return None;
4598 }
4599 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4600 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4601 if start_buffer != end_buffer {
4602 return None;
4603 }
4604
4605 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4606 cx.background_executor()
4607 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4608 .await;
4609
4610 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4611 let providers = this.code_action_providers.clone();
4612 let tasks = this
4613 .code_action_providers
4614 .iter()
4615 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4616 .collect::<Vec<_>>();
4617 (providers, tasks)
4618 })?;
4619
4620 let mut actions = Vec::new();
4621 for (provider, provider_actions) in
4622 providers.into_iter().zip(future::join_all(tasks).await)
4623 {
4624 if let Some(provider_actions) = provider_actions.log_err() {
4625 actions.extend(provider_actions.into_iter().map(|action| {
4626 AvailableCodeAction {
4627 excerpt_id: newest_selection.start.excerpt_id,
4628 action,
4629 provider: provider.clone(),
4630 }
4631 }));
4632 }
4633 }
4634
4635 this.update(&mut cx, |this, cx| {
4636 this.available_code_actions = if actions.is_empty() {
4637 None
4638 } else {
4639 Some((
4640 Location {
4641 buffer: start_buffer,
4642 range: start..end,
4643 },
4644 actions.into(),
4645 ))
4646 };
4647 cx.notify();
4648 })
4649 }));
4650 None
4651 }
4652
4653 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4654 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4655 self.show_git_blame_inline = false;
4656
4657 self.show_git_blame_inline_delay_task =
4658 Some(cx.spawn_in(window, |this, mut cx| async move {
4659 cx.background_executor().timer(delay).await;
4660
4661 this.update(&mut cx, |this, cx| {
4662 this.show_git_blame_inline = true;
4663 cx.notify();
4664 })
4665 .log_err();
4666 }));
4667 }
4668 }
4669
4670 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4671 if self.pending_rename.is_some() {
4672 return None;
4673 }
4674
4675 let provider = self.semantics_provider.clone()?;
4676 let buffer = self.buffer.read(cx);
4677 let newest_selection = self.selections.newest_anchor().clone();
4678 let cursor_position = newest_selection.head();
4679 let (cursor_buffer, cursor_buffer_position) =
4680 buffer.text_anchor_for_position(cursor_position, cx)?;
4681 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4682 if cursor_buffer != tail_buffer {
4683 return None;
4684 }
4685 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4686 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4687 cx.background_executor()
4688 .timer(Duration::from_millis(debounce))
4689 .await;
4690
4691 let highlights = if let Some(highlights) = cx
4692 .update(|cx| {
4693 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4694 })
4695 .ok()
4696 .flatten()
4697 {
4698 highlights.await.log_err()
4699 } else {
4700 None
4701 };
4702
4703 if let Some(highlights) = highlights {
4704 this.update(&mut cx, |this, cx| {
4705 if this.pending_rename.is_some() {
4706 return;
4707 }
4708
4709 let buffer_id = cursor_position.buffer_id;
4710 let buffer = this.buffer.read(cx);
4711 if !buffer
4712 .text_anchor_for_position(cursor_position, cx)
4713 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4714 {
4715 return;
4716 }
4717
4718 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4719 let mut write_ranges = Vec::new();
4720 let mut read_ranges = Vec::new();
4721 for highlight in highlights {
4722 for (excerpt_id, excerpt_range) in
4723 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4724 {
4725 let start = highlight
4726 .range
4727 .start
4728 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4729 let end = highlight
4730 .range
4731 .end
4732 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4733 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4734 continue;
4735 }
4736
4737 let range = Anchor {
4738 buffer_id,
4739 excerpt_id,
4740 text_anchor: start,
4741 diff_base_anchor: None,
4742 }..Anchor {
4743 buffer_id,
4744 excerpt_id,
4745 text_anchor: end,
4746 diff_base_anchor: None,
4747 };
4748 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4749 write_ranges.push(range);
4750 } else {
4751 read_ranges.push(range);
4752 }
4753 }
4754 }
4755
4756 this.highlight_background::<DocumentHighlightRead>(
4757 &read_ranges,
4758 |theme| theme.editor_document_highlight_read_background,
4759 cx,
4760 );
4761 this.highlight_background::<DocumentHighlightWrite>(
4762 &write_ranges,
4763 |theme| theme.editor_document_highlight_write_background,
4764 cx,
4765 );
4766 cx.notify();
4767 })
4768 .log_err();
4769 }
4770 }));
4771 None
4772 }
4773
4774 pub fn refresh_selected_text_highlights(
4775 &mut self,
4776 window: &mut Window,
4777 cx: &mut Context<Editor>,
4778 ) {
4779 self.selection_highlight_task.take();
4780 if !EditorSettings::get_global(cx).selection_highlight {
4781 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4782 return;
4783 }
4784 if self.selections.count() != 1 || self.selections.line_mode {
4785 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4786 return;
4787 }
4788 let selection = self.selections.newest::<Point>(cx);
4789 if selection.is_empty() || selection.start.row != selection.end.row {
4790 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4791 return;
4792 }
4793 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4794 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4795 cx.background_executor()
4796 .timer(Duration::from_millis(debounce))
4797 .await;
4798 let Some(matches_task) = editor
4799 .read_with(&mut cx, |editor, cx| {
4800 let buffer = editor.buffer().read(cx).snapshot(cx);
4801 cx.background_spawn(async move {
4802 let mut ranges = Vec::new();
4803 let buffer_ranges =
4804 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
4805 let query = buffer.text_for_range(selection.range()).collect::<String>();
4806 for range in buffer_ranges {
4807 for (search_buffer, search_range, excerpt_id) in
4808 buffer.range_to_buffer_ranges(range)
4809 {
4810 ranges.extend(
4811 project::search::SearchQuery::text(
4812 query.clone(),
4813 false,
4814 false,
4815 false,
4816 Default::default(),
4817 Default::default(),
4818 None,
4819 )
4820 .unwrap()
4821 .search(search_buffer, Some(search_range.clone()))
4822 .await
4823 .into_iter()
4824 .map(|match_range| {
4825 let start = search_buffer
4826 .anchor_after(search_range.start + match_range.start);
4827 let end = search_buffer
4828 .anchor_before(search_range.start + match_range.end);
4829 Anchor::range_in_buffer(
4830 excerpt_id,
4831 search_buffer.remote_id(),
4832 start..end,
4833 )
4834 }),
4835 );
4836 }
4837 }
4838 ranges
4839 })
4840 })
4841 .log_err()
4842 else {
4843 return;
4844 };
4845 let matches = matches_task.await;
4846 editor
4847 .update_in(&mut cx, |editor, _, cx| {
4848 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4849 if !matches.is_empty() {
4850 editor.highlight_background::<SelectedTextHighlight>(
4851 &matches,
4852 |theme| theme.editor_document_highlight_bracket_background,
4853 cx,
4854 )
4855 }
4856 })
4857 .log_err();
4858 }));
4859 }
4860
4861 pub fn refresh_inline_completion(
4862 &mut self,
4863 debounce: bool,
4864 user_requested: bool,
4865 window: &mut Window,
4866 cx: &mut Context<Self>,
4867 ) -> Option<()> {
4868 let provider = self.edit_prediction_provider()?;
4869 let cursor = self.selections.newest_anchor().head();
4870 let (buffer, cursor_buffer_position) =
4871 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4872
4873 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4874 self.discard_inline_completion(false, cx);
4875 return None;
4876 }
4877
4878 if !user_requested
4879 && (!self.should_show_edit_predictions()
4880 || !self.is_focused(window)
4881 || buffer.read(cx).is_empty())
4882 {
4883 self.discard_inline_completion(false, cx);
4884 return None;
4885 }
4886
4887 self.update_visible_inline_completion(window, cx);
4888 provider.refresh(
4889 self.project.clone(),
4890 buffer,
4891 cursor_buffer_position,
4892 debounce,
4893 cx,
4894 );
4895 Some(())
4896 }
4897
4898 fn show_edit_predictions_in_menu(&self) -> bool {
4899 match self.edit_prediction_settings {
4900 EditPredictionSettings::Disabled => false,
4901 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4902 }
4903 }
4904
4905 pub fn edit_predictions_enabled(&self) -> bool {
4906 match self.edit_prediction_settings {
4907 EditPredictionSettings::Disabled => false,
4908 EditPredictionSettings::Enabled { .. } => true,
4909 }
4910 }
4911
4912 fn edit_prediction_requires_modifier(&self) -> bool {
4913 match self.edit_prediction_settings {
4914 EditPredictionSettings::Disabled => false,
4915 EditPredictionSettings::Enabled {
4916 preview_requires_modifier,
4917 ..
4918 } => preview_requires_modifier,
4919 }
4920 }
4921
4922 fn edit_prediction_settings_at_position(
4923 &self,
4924 buffer: &Entity<Buffer>,
4925 buffer_position: language::Anchor,
4926 cx: &App,
4927 ) -> EditPredictionSettings {
4928 if self.mode != EditorMode::Full
4929 || !self.show_inline_completions_override.unwrap_or(true)
4930 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4931 {
4932 return EditPredictionSettings::Disabled;
4933 }
4934
4935 let buffer = buffer.read(cx);
4936
4937 let file = buffer.file();
4938
4939 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4940 return EditPredictionSettings::Disabled;
4941 };
4942
4943 let by_provider = matches!(
4944 self.menu_inline_completions_policy,
4945 MenuInlineCompletionsPolicy::ByProvider
4946 );
4947
4948 let show_in_menu = by_provider
4949 && self
4950 .edit_prediction_provider
4951 .as_ref()
4952 .map_or(false, |provider| {
4953 provider.provider.show_completions_in_menu()
4954 });
4955
4956 let preview_requires_modifier =
4957 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4958
4959 EditPredictionSettings::Enabled {
4960 show_in_menu,
4961 preview_requires_modifier,
4962 }
4963 }
4964
4965 fn should_show_edit_predictions(&self) -> bool {
4966 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4967 }
4968
4969 pub fn edit_prediction_preview_is_active(&self) -> bool {
4970 matches!(
4971 self.edit_prediction_preview,
4972 EditPredictionPreview::Active { .. }
4973 )
4974 }
4975
4976 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4977 let cursor = self.selections.newest_anchor().head();
4978 if let Some((buffer, cursor_position)) =
4979 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4980 {
4981 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4982 } else {
4983 false
4984 }
4985 }
4986
4987 fn inline_completions_enabled_in_buffer(
4988 &self,
4989 buffer: &Entity<Buffer>,
4990 buffer_position: language::Anchor,
4991 cx: &App,
4992 ) -> bool {
4993 maybe!({
4994 let provider = self.edit_prediction_provider()?;
4995 if !provider.is_enabled(&buffer, buffer_position, cx) {
4996 return Some(false);
4997 }
4998 let buffer = buffer.read(cx);
4999 let Some(file) = buffer.file() else {
5000 return Some(true);
5001 };
5002 let settings = all_language_settings(Some(file), cx);
5003 Some(settings.inline_completions_enabled_for_path(file.path()))
5004 })
5005 .unwrap_or(false)
5006 }
5007
5008 fn cycle_inline_completion(
5009 &mut self,
5010 direction: Direction,
5011 window: &mut Window,
5012 cx: &mut Context<Self>,
5013 ) -> Option<()> {
5014 let provider = self.edit_prediction_provider()?;
5015 let cursor = self.selections.newest_anchor().head();
5016 let (buffer, cursor_buffer_position) =
5017 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5018 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5019 return None;
5020 }
5021
5022 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5023 self.update_visible_inline_completion(window, cx);
5024
5025 Some(())
5026 }
5027
5028 pub fn show_inline_completion(
5029 &mut self,
5030 _: &ShowEditPrediction,
5031 window: &mut Window,
5032 cx: &mut Context<Self>,
5033 ) {
5034 if !self.has_active_inline_completion() {
5035 self.refresh_inline_completion(false, true, window, cx);
5036 return;
5037 }
5038
5039 self.update_visible_inline_completion(window, cx);
5040 }
5041
5042 pub fn display_cursor_names(
5043 &mut self,
5044 _: &DisplayCursorNames,
5045 window: &mut Window,
5046 cx: &mut Context<Self>,
5047 ) {
5048 self.show_cursor_names(window, cx);
5049 }
5050
5051 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5052 self.show_cursor_names = true;
5053 cx.notify();
5054 cx.spawn_in(window, |this, mut cx| async move {
5055 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5056 this.update(&mut cx, |this, cx| {
5057 this.show_cursor_names = false;
5058 cx.notify()
5059 })
5060 .ok()
5061 })
5062 .detach();
5063 }
5064
5065 pub fn next_edit_prediction(
5066 &mut self,
5067 _: &NextEditPrediction,
5068 window: &mut Window,
5069 cx: &mut Context<Self>,
5070 ) {
5071 if self.has_active_inline_completion() {
5072 self.cycle_inline_completion(Direction::Next, window, cx);
5073 } else {
5074 let is_copilot_disabled = self
5075 .refresh_inline_completion(false, true, window, cx)
5076 .is_none();
5077 if is_copilot_disabled {
5078 cx.propagate();
5079 }
5080 }
5081 }
5082
5083 pub fn previous_edit_prediction(
5084 &mut self,
5085 _: &PreviousEditPrediction,
5086 window: &mut Window,
5087 cx: &mut Context<Self>,
5088 ) {
5089 if self.has_active_inline_completion() {
5090 self.cycle_inline_completion(Direction::Prev, window, cx);
5091 } else {
5092 let is_copilot_disabled = self
5093 .refresh_inline_completion(false, true, window, cx)
5094 .is_none();
5095 if is_copilot_disabled {
5096 cx.propagate();
5097 }
5098 }
5099 }
5100
5101 pub fn accept_edit_prediction(
5102 &mut self,
5103 _: &AcceptEditPrediction,
5104 window: &mut Window,
5105 cx: &mut Context<Self>,
5106 ) {
5107 if self.show_edit_predictions_in_menu() {
5108 self.hide_context_menu(window, cx);
5109 }
5110
5111 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5112 return;
5113 };
5114
5115 self.report_inline_completion_event(
5116 active_inline_completion.completion_id.clone(),
5117 true,
5118 cx,
5119 );
5120
5121 match &active_inline_completion.completion {
5122 InlineCompletion::Move { target, .. } => {
5123 let target = *target;
5124
5125 if let Some(position_map) = &self.last_position_map {
5126 if position_map
5127 .visible_row_range
5128 .contains(&target.to_display_point(&position_map.snapshot).row())
5129 || !self.edit_prediction_requires_modifier()
5130 {
5131 self.unfold_ranges(&[target..target], true, false, cx);
5132 // Note that this is also done in vim's handler of the Tab action.
5133 self.change_selections(
5134 Some(Autoscroll::newest()),
5135 window,
5136 cx,
5137 |selections| {
5138 selections.select_anchor_ranges([target..target]);
5139 },
5140 );
5141 self.clear_row_highlights::<EditPredictionPreview>();
5142
5143 self.edit_prediction_preview = EditPredictionPreview::Active {
5144 previous_scroll_position: None,
5145 };
5146 } else {
5147 self.edit_prediction_preview = EditPredictionPreview::Active {
5148 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5149 };
5150 self.highlight_rows::<EditPredictionPreview>(
5151 target..target,
5152 cx.theme().colors().editor_highlighted_line_background,
5153 true,
5154 cx,
5155 );
5156 self.request_autoscroll(Autoscroll::fit(), cx);
5157 }
5158 }
5159 }
5160 InlineCompletion::Edit { edits, .. } => {
5161 if let Some(provider) = self.edit_prediction_provider() {
5162 provider.accept(cx);
5163 }
5164
5165 let snapshot = self.buffer.read(cx).snapshot(cx);
5166 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5167
5168 self.buffer.update(cx, |buffer, cx| {
5169 buffer.edit(edits.iter().cloned(), None, cx)
5170 });
5171
5172 self.change_selections(None, window, cx, |s| {
5173 s.select_anchor_ranges([last_edit_end..last_edit_end])
5174 });
5175
5176 self.update_visible_inline_completion(window, cx);
5177 if self.active_inline_completion.is_none() {
5178 self.refresh_inline_completion(true, true, window, cx);
5179 }
5180
5181 cx.notify();
5182 }
5183 }
5184
5185 self.edit_prediction_requires_modifier_in_leading_space = false;
5186 }
5187
5188 pub fn accept_partial_inline_completion(
5189 &mut self,
5190 _: &AcceptPartialEditPrediction,
5191 window: &mut Window,
5192 cx: &mut Context<Self>,
5193 ) {
5194 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5195 return;
5196 };
5197 if self.selections.count() != 1 {
5198 return;
5199 }
5200
5201 self.report_inline_completion_event(
5202 active_inline_completion.completion_id.clone(),
5203 true,
5204 cx,
5205 );
5206
5207 match &active_inline_completion.completion {
5208 InlineCompletion::Move { target, .. } => {
5209 let target = *target;
5210 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5211 selections.select_anchor_ranges([target..target]);
5212 });
5213 }
5214 InlineCompletion::Edit { edits, .. } => {
5215 // Find an insertion that starts at the cursor position.
5216 let snapshot = self.buffer.read(cx).snapshot(cx);
5217 let cursor_offset = self.selections.newest::<usize>(cx).head();
5218 let insertion = edits.iter().find_map(|(range, text)| {
5219 let range = range.to_offset(&snapshot);
5220 if range.is_empty() && range.start == cursor_offset {
5221 Some(text)
5222 } else {
5223 None
5224 }
5225 });
5226
5227 if let Some(text) = insertion {
5228 let mut partial_completion = text
5229 .chars()
5230 .by_ref()
5231 .take_while(|c| c.is_alphabetic())
5232 .collect::<String>();
5233 if partial_completion.is_empty() {
5234 partial_completion = text
5235 .chars()
5236 .by_ref()
5237 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5238 .collect::<String>();
5239 }
5240
5241 cx.emit(EditorEvent::InputHandled {
5242 utf16_range_to_replace: None,
5243 text: partial_completion.clone().into(),
5244 });
5245
5246 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5247
5248 self.refresh_inline_completion(true, true, window, cx);
5249 cx.notify();
5250 } else {
5251 self.accept_edit_prediction(&Default::default(), window, cx);
5252 }
5253 }
5254 }
5255 }
5256
5257 fn discard_inline_completion(
5258 &mut self,
5259 should_report_inline_completion_event: bool,
5260 cx: &mut Context<Self>,
5261 ) -> bool {
5262 if should_report_inline_completion_event {
5263 let completion_id = self
5264 .active_inline_completion
5265 .as_ref()
5266 .and_then(|active_completion| active_completion.completion_id.clone());
5267
5268 self.report_inline_completion_event(completion_id, false, cx);
5269 }
5270
5271 if let Some(provider) = self.edit_prediction_provider() {
5272 provider.discard(cx);
5273 }
5274
5275 self.take_active_inline_completion(cx)
5276 }
5277
5278 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5279 let Some(provider) = self.edit_prediction_provider() else {
5280 return;
5281 };
5282
5283 let Some((_, buffer, _)) = self
5284 .buffer
5285 .read(cx)
5286 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5287 else {
5288 return;
5289 };
5290
5291 let extension = buffer
5292 .read(cx)
5293 .file()
5294 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5295
5296 let event_type = match accepted {
5297 true => "Edit Prediction Accepted",
5298 false => "Edit Prediction Discarded",
5299 };
5300 telemetry::event!(
5301 event_type,
5302 provider = provider.name(),
5303 prediction_id = id,
5304 suggestion_accepted = accepted,
5305 file_extension = extension,
5306 );
5307 }
5308
5309 pub fn has_active_inline_completion(&self) -> bool {
5310 self.active_inline_completion.is_some()
5311 }
5312
5313 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5314 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5315 return false;
5316 };
5317
5318 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5319 self.clear_highlights::<InlineCompletionHighlight>(cx);
5320 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5321 true
5322 }
5323
5324 /// Returns true when we're displaying the edit prediction popover below the cursor
5325 /// like we are not previewing and the LSP autocomplete menu is visible
5326 /// or we are in `when_holding_modifier` mode.
5327 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5328 if self.edit_prediction_preview_is_active()
5329 || !self.show_edit_predictions_in_menu()
5330 || !self.edit_predictions_enabled()
5331 {
5332 return false;
5333 }
5334
5335 if self.has_visible_completions_menu() {
5336 return true;
5337 }
5338
5339 has_completion && self.edit_prediction_requires_modifier()
5340 }
5341
5342 fn handle_modifiers_changed(
5343 &mut self,
5344 modifiers: Modifiers,
5345 position_map: &PositionMap,
5346 window: &mut Window,
5347 cx: &mut Context<Self>,
5348 ) {
5349 if self.show_edit_predictions_in_menu() {
5350 self.update_edit_prediction_preview(&modifiers, window, cx);
5351 }
5352
5353 self.update_selection_mode(&modifiers, position_map, window, cx);
5354
5355 let mouse_position = window.mouse_position();
5356 if !position_map.text_hitbox.is_hovered(window) {
5357 return;
5358 }
5359
5360 self.update_hovered_link(
5361 position_map.point_for_position(mouse_position),
5362 &position_map.snapshot,
5363 modifiers,
5364 window,
5365 cx,
5366 )
5367 }
5368
5369 fn update_selection_mode(
5370 &mut self,
5371 modifiers: &Modifiers,
5372 position_map: &PositionMap,
5373 window: &mut Window,
5374 cx: &mut Context<Self>,
5375 ) {
5376 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5377 return;
5378 }
5379
5380 let mouse_position = window.mouse_position();
5381 let point_for_position = position_map.point_for_position(mouse_position);
5382 let position = point_for_position.previous_valid;
5383
5384 self.select(
5385 SelectPhase::BeginColumnar {
5386 position,
5387 reset: false,
5388 goal_column: point_for_position.exact_unclipped.column(),
5389 },
5390 window,
5391 cx,
5392 );
5393 }
5394
5395 fn update_edit_prediction_preview(
5396 &mut self,
5397 modifiers: &Modifiers,
5398 window: &mut Window,
5399 cx: &mut Context<Self>,
5400 ) {
5401 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5402 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5403 return;
5404 };
5405
5406 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5407 if matches!(
5408 self.edit_prediction_preview,
5409 EditPredictionPreview::Inactive
5410 ) {
5411 self.edit_prediction_preview = EditPredictionPreview::Active {
5412 previous_scroll_position: None,
5413 };
5414
5415 self.update_visible_inline_completion(window, cx);
5416 cx.notify();
5417 }
5418 } else if let EditPredictionPreview::Active {
5419 previous_scroll_position,
5420 } = self.edit_prediction_preview
5421 {
5422 if let (Some(previous_scroll_position), Some(position_map)) =
5423 (previous_scroll_position, self.last_position_map.as_ref())
5424 {
5425 self.set_scroll_position(
5426 previous_scroll_position
5427 .scroll_position(&position_map.snapshot.display_snapshot),
5428 window,
5429 cx,
5430 );
5431 }
5432
5433 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5434 self.clear_row_highlights::<EditPredictionPreview>();
5435 self.update_visible_inline_completion(window, cx);
5436 cx.notify();
5437 }
5438 }
5439
5440 fn update_visible_inline_completion(
5441 &mut self,
5442 _window: &mut Window,
5443 cx: &mut Context<Self>,
5444 ) -> Option<()> {
5445 let selection = self.selections.newest_anchor();
5446 let cursor = selection.head();
5447 let multibuffer = self.buffer.read(cx).snapshot(cx);
5448 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5449 let excerpt_id = cursor.excerpt_id;
5450
5451 let show_in_menu = self.show_edit_predictions_in_menu();
5452 let completions_menu_has_precedence = !show_in_menu
5453 && (self.context_menu.borrow().is_some()
5454 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5455
5456 if completions_menu_has_precedence
5457 || !offset_selection.is_empty()
5458 || self
5459 .active_inline_completion
5460 .as_ref()
5461 .map_or(false, |completion| {
5462 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5463 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5464 !invalidation_range.contains(&offset_selection.head())
5465 })
5466 {
5467 self.discard_inline_completion(false, cx);
5468 return None;
5469 }
5470
5471 self.take_active_inline_completion(cx);
5472 let Some(provider) = self.edit_prediction_provider() else {
5473 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5474 return None;
5475 };
5476
5477 let (buffer, cursor_buffer_position) =
5478 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5479
5480 self.edit_prediction_settings =
5481 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5482
5483 self.edit_prediction_cursor_on_leading_whitespace =
5484 multibuffer.is_line_whitespace_upto(cursor);
5485
5486 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5487 let edits = inline_completion
5488 .edits
5489 .into_iter()
5490 .flat_map(|(range, new_text)| {
5491 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5492 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5493 Some((start..end, new_text))
5494 })
5495 .collect::<Vec<_>>();
5496 if edits.is_empty() {
5497 return None;
5498 }
5499
5500 let first_edit_start = edits.first().unwrap().0.start;
5501 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5502 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5503
5504 let last_edit_end = edits.last().unwrap().0.end;
5505 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5506 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5507
5508 let cursor_row = cursor.to_point(&multibuffer).row;
5509
5510 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5511
5512 let mut inlay_ids = Vec::new();
5513 let invalidation_row_range;
5514 let move_invalidation_row_range = if cursor_row < edit_start_row {
5515 Some(cursor_row..edit_end_row)
5516 } else if cursor_row > edit_end_row {
5517 Some(edit_start_row..cursor_row)
5518 } else {
5519 None
5520 };
5521 let is_move =
5522 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5523 let completion = if is_move {
5524 invalidation_row_range =
5525 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5526 let target = first_edit_start;
5527 InlineCompletion::Move { target, snapshot }
5528 } else {
5529 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5530 && !self.inline_completions_hidden_for_vim_mode;
5531
5532 if show_completions_in_buffer {
5533 if edits
5534 .iter()
5535 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5536 {
5537 let mut inlays = Vec::new();
5538 for (range, new_text) in &edits {
5539 let inlay = Inlay::inline_completion(
5540 post_inc(&mut self.next_inlay_id),
5541 range.start,
5542 new_text.as_str(),
5543 );
5544 inlay_ids.push(inlay.id);
5545 inlays.push(inlay);
5546 }
5547
5548 self.splice_inlays(&[], inlays, cx);
5549 } else {
5550 let background_color = cx.theme().status().deleted_background;
5551 self.highlight_text::<InlineCompletionHighlight>(
5552 edits.iter().map(|(range, _)| range.clone()).collect(),
5553 HighlightStyle {
5554 background_color: Some(background_color),
5555 ..Default::default()
5556 },
5557 cx,
5558 );
5559 }
5560 }
5561
5562 invalidation_row_range = edit_start_row..edit_end_row;
5563
5564 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5565 if provider.show_tab_accept_marker() {
5566 EditDisplayMode::TabAccept
5567 } else {
5568 EditDisplayMode::Inline
5569 }
5570 } else {
5571 EditDisplayMode::DiffPopover
5572 };
5573
5574 InlineCompletion::Edit {
5575 edits,
5576 edit_preview: inline_completion.edit_preview,
5577 display_mode,
5578 snapshot,
5579 }
5580 };
5581
5582 let invalidation_range = multibuffer
5583 .anchor_before(Point::new(invalidation_row_range.start, 0))
5584 ..multibuffer.anchor_after(Point::new(
5585 invalidation_row_range.end,
5586 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5587 ));
5588
5589 self.stale_inline_completion_in_menu = None;
5590 self.active_inline_completion = Some(InlineCompletionState {
5591 inlay_ids,
5592 completion,
5593 completion_id: inline_completion.id,
5594 invalidation_range,
5595 });
5596
5597 cx.notify();
5598
5599 Some(())
5600 }
5601
5602 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5603 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5604 }
5605
5606 fn render_code_actions_indicator(
5607 &self,
5608 _style: &EditorStyle,
5609 row: DisplayRow,
5610 is_active: bool,
5611 cx: &mut Context<Self>,
5612 ) -> Option<IconButton> {
5613 if self.available_code_actions.is_some() {
5614 Some(
5615 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5616 .shape(ui::IconButtonShape::Square)
5617 .icon_size(IconSize::XSmall)
5618 .icon_color(Color::Muted)
5619 .toggle_state(is_active)
5620 .tooltip({
5621 let focus_handle = self.focus_handle.clone();
5622 move |window, cx| {
5623 Tooltip::for_action_in(
5624 "Toggle Code Actions",
5625 &ToggleCodeActions {
5626 deployed_from_indicator: None,
5627 },
5628 &focus_handle,
5629 window,
5630 cx,
5631 )
5632 }
5633 })
5634 .on_click(cx.listener(move |editor, _e, window, cx| {
5635 window.focus(&editor.focus_handle(cx));
5636 editor.toggle_code_actions(
5637 &ToggleCodeActions {
5638 deployed_from_indicator: Some(row),
5639 },
5640 window,
5641 cx,
5642 );
5643 })),
5644 )
5645 } else {
5646 None
5647 }
5648 }
5649
5650 fn clear_tasks(&mut self) {
5651 self.tasks.clear()
5652 }
5653
5654 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5655 if self.tasks.insert(key, value).is_some() {
5656 // This case should hopefully be rare, but just in case...
5657 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5658 }
5659 }
5660
5661 fn build_tasks_context(
5662 project: &Entity<Project>,
5663 buffer: &Entity<Buffer>,
5664 buffer_row: u32,
5665 tasks: &Arc<RunnableTasks>,
5666 cx: &mut Context<Self>,
5667 ) -> Task<Option<task::TaskContext>> {
5668 let position = Point::new(buffer_row, tasks.column);
5669 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5670 let location = Location {
5671 buffer: buffer.clone(),
5672 range: range_start..range_start,
5673 };
5674 // Fill in the environmental variables from the tree-sitter captures
5675 let mut captured_task_variables = TaskVariables::default();
5676 for (capture_name, value) in tasks.extra_variables.clone() {
5677 captured_task_variables.insert(
5678 task::VariableName::Custom(capture_name.into()),
5679 value.clone(),
5680 );
5681 }
5682 project.update(cx, |project, cx| {
5683 project.task_store().update(cx, |task_store, cx| {
5684 task_store.task_context_for_location(captured_task_variables, location, cx)
5685 })
5686 })
5687 }
5688
5689 pub fn spawn_nearest_task(
5690 &mut self,
5691 action: &SpawnNearestTask,
5692 window: &mut Window,
5693 cx: &mut Context<Self>,
5694 ) {
5695 let Some((workspace, _)) = self.workspace.clone() else {
5696 return;
5697 };
5698 let Some(project) = self.project.clone() else {
5699 return;
5700 };
5701
5702 // Try to find a closest, enclosing node using tree-sitter that has a
5703 // task
5704 let Some((buffer, buffer_row, tasks)) = self
5705 .find_enclosing_node_task(cx)
5706 // Or find the task that's closest in row-distance.
5707 .or_else(|| self.find_closest_task(cx))
5708 else {
5709 return;
5710 };
5711
5712 let reveal_strategy = action.reveal;
5713 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5714 cx.spawn_in(window, |_, mut cx| async move {
5715 let context = task_context.await?;
5716 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5717
5718 let resolved = resolved_task.resolved.as_mut()?;
5719 resolved.reveal = reveal_strategy;
5720
5721 workspace
5722 .update(&mut cx, |workspace, cx| {
5723 workspace::tasks::schedule_resolved_task(
5724 workspace,
5725 task_source_kind,
5726 resolved_task,
5727 false,
5728 cx,
5729 );
5730 })
5731 .ok()
5732 })
5733 .detach();
5734 }
5735
5736 fn find_closest_task(
5737 &mut self,
5738 cx: &mut Context<Self>,
5739 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5740 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5741
5742 let ((buffer_id, row), tasks) = self
5743 .tasks
5744 .iter()
5745 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5746
5747 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5748 let tasks = Arc::new(tasks.to_owned());
5749 Some((buffer, *row, tasks))
5750 }
5751
5752 fn find_enclosing_node_task(
5753 &mut self,
5754 cx: &mut Context<Self>,
5755 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5756 let snapshot = self.buffer.read(cx).snapshot(cx);
5757 let offset = self.selections.newest::<usize>(cx).head();
5758 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5759 let buffer_id = excerpt.buffer().remote_id();
5760
5761 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5762 let mut cursor = layer.node().walk();
5763
5764 while cursor.goto_first_child_for_byte(offset).is_some() {
5765 if cursor.node().end_byte() == offset {
5766 cursor.goto_next_sibling();
5767 }
5768 }
5769
5770 // Ascend to the smallest ancestor that contains the range and has a task.
5771 loop {
5772 let node = cursor.node();
5773 let node_range = node.byte_range();
5774 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5775
5776 // Check if this node contains our offset
5777 if node_range.start <= offset && node_range.end >= offset {
5778 // If it contains offset, check for task
5779 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5780 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5781 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5782 }
5783 }
5784
5785 if !cursor.goto_parent() {
5786 break;
5787 }
5788 }
5789 None
5790 }
5791
5792 fn render_run_indicator(
5793 &self,
5794 _style: &EditorStyle,
5795 is_active: bool,
5796 row: DisplayRow,
5797 cx: &mut Context<Self>,
5798 ) -> IconButton {
5799 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5800 .shape(ui::IconButtonShape::Square)
5801 .icon_size(IconSize::XSmall)
5802 .icon_color(Color::Muted)
5803 .toggle_state(is_active)
5804 .on_click(cx.listener(move |editor, _e, window, cx| {
5805 window.focus(&editor.focus_handle(cx));
5806 editor.toggle_code_actions(
5807 &ToggleCodeActions {
5808 deployed_from_indicator: Some(row),
5809 },
5810 window,
5811 cx,
5812 );
5813 }))
5814 }
5815
5816 pub fn context_menu_visible(&self) -> bool {
5817 !self.edit_prediction_preview_is_active()
5818 && self
5819 .context_menu
5820 .borrow()
5821 .as_ref()
5822 .map_or(false, |menu| menu.visible())
5823 }
5824
5825 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5826 self.context_menu
5827 .borrow()
5828 .as_ref()
5829 .map(|menu| menu.origin())
5830 }
5831
5832 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5833 px(30.)
5834 }
5835
5836 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5837 if self.read_only(cx) {
5838 cx.theme().players().read_only()
5839 } else {
5840 self.style.as_ref().unwrap().local_player
5841 }
5842 }
5843
5844 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5845 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5846 let accept_keystroke = accept_binding.keystroke()?;
5847
5848 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5849
5850 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5851 Color::Accent
5852 } else {
5853 Color::Muted
5854 };
5855
5856 h_flex()
5857 .px_0p5()
5858 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5859 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5860 .text_size(TextSize::XSmall.rems(cx))
5861 .child(h_flex().children(ui::render_modifiers(
5862 &accept_keystroke.modifiers,
5863 PlatformStyle::platform(),
5864 Some(modifiers_color),
5865 Some(IconSize::XSmall.rems().into()),
5866 true,
5867 )))
5868 .when(is_platform_style_mac, |parent| {
5869 parent.child(accept_keystroke.key.clone())
5870 })
5871 .when(!is_platform_style_mac, |parent| {
5872 parent.child(
5873 Key::new(
5874 util::capitalize(&accept_keystroke.key),
5875 Some(Color::Default),
5876 )
5877 .size(Some(IconSize::XSmall.rems().into())),
5878 )
5879 })
5880 .into()
5881 }
5882
5883 fn render_edit_prediction_line_popover(
5884 &self,
5885 label: impl Into<SharedString>,
5886 icon: Option<IconName>,
5887 window: &mut Window,
5888 cx: &App,
5889 ) -> Option<Div> {
5890 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5891
5892 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5893
5894 let result = h_flex()
5895 .gap_1()
5896 .border_1()
5897 .rounded_lg()
5898 .shadow_sm()
5899 .bg(bg_color)
5900 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5901 .py_0p5()
5902 .pl_1()
5903 .pr(padding_right)
5904 .children(self.render_edit_prediction_accept_keybind(window, cx))
5905 .child(Label::new(label).size(LabelSize::Small))
5906 .when_some(icon, |element, icon| {
5907 element.child(
5908 div()
5909 .mt(px(1.5))
5910 .child(Icon::new(icon).size(IconSize::Small)),
5911 )
5912 });
5913
5914 Some(result)
5915 }
5916
5917 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5918 let accent_color = cx.theme().colors().text_accent;
5919 let editor_bg_color = cx.theme().colors().editor_background;
5920 editor_bg_color.blend(accent_color.opacity(0.1))
5921 }
5922
5923 fn render_edit_prediction_cursor_popover(
5924 &self,
5925 min_width: Pixels,
5926 max_width: Pixels,
5927 cursor_point: Point,
5928 style: &EditorStyle,
5929 accept_keystroke: Option<&gpui::Keystroke>,
5930 _window: &Window,
5931 cx: &mut Context<Editor>,
5932 ) -> Option<AnyElement> {
5933 let provider = self.edit_prediction_provider.as_ref()?;
5934
5935 if provider.provider.needs_terms_acceptance(cx) {
5936 return Some(
5937 h_flex()
5938 .min_w(min_width)
5939 .flex_1()
5940 .px_2()
5941 .py_1()
5942 .gap_3()
5943 .elevation_2(cx)
5944 .hover(|style| style.bg(cx.theme().colors().element_hover))
5945 .id("accept-terms")
5946 .cursor_pointer()
5947 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5948 .on_click(cx.listener(|this, _event, window, cx| {
5949 cx.stop_propagation();
5950 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5951 window.dispatch_action(
5952 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5953 cx,
5954 );
5955 }))
5956 .child(
5957 h_flex()
5958 .flex_1()
5959 .gap_2()
5960 .child(Icon::new(IconName::ZedPredict))
5961 .child(Label::new("Accept Terms of Service"))
5962 .child(div().w_full())
5963 .child(
5964 Icon::new(IconName::ArrowUpRight)
5965 .color(Color::Muted)
5966 .size(IconSize::Small),
5967 )
5968 .into_any_element(),
5969 )
5970 .into_any(),
5971 );
5972 }
5973
5974 let is_refreshing = provider.provider.is_refreshing(cx);
5975
5976 fn pending_completion_container() -> Div {
5977 h_flex()
5978 .h_full()
5979 .flex_1()
5980 .gap_2()
5981 .child(Icon::new(IconName::ZedPredict))
5982 }
5983
5984 let completion = match &self.active_inline_completion {
5985 Some(completion) => match &completion.completion {
5986 InlineCompletion::Move {
5987 target, snapshot, ..
5988 } if !self.has_visible_completions_menu() => {
5989 use text::ToPoint as _;
5990
5991 return Some(
5992 h_flex()
5993 .px_2()
5994 .py_1()
5995 .elevation_2(cx)
5996 .border_color(cx.theme().colors().border)
5997 .rounded_tl(px(0.))
5998 .gap_2()
5999 .child(
6000 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6001 Icon::new(IconName::ZedPredictDown)
6002 } else {
6003 Icon::new(IconName::ZedPredictUp)
6004 },
6005 )
6006 .child(Label::new("Hold").size(LabelSize::Small))
6007 .child(h_flex().children(ui::render_modifiers(
6008 &accept_keystroke?.modifiers,
6009 PlatformStyle::platform(),
6010 Some(Color::Default),
6011 Some(IconSize::Small.rems().into()),
6012 false,
6013 )))
6014 .into_any(),
6015 );
6016 }
6017 _ => self.render_edit_prediction_cursor_popover_preview(
6018 completion,
6019 cursor_point,
6020 style,
6021 cx,
6022 )?,
6023 },
6024
6025 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6026 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6027 stale_completion,
6028 cursor_point,
6029 style,
6030 cx,
6031 )?,
6032
6033 None => {
6034 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6035 }
6036 },
6037
6038 None => pending_completion_container().child(Label::new("No Prediction")),
6039 };
6040
6041 let completion = if is_refreshing {
6042 completion
6043 .with_animation(
6044 "loading-completion",
6045 Animation::new(Duration::from_secs(2))
6046 .repeat()
6047 .with_easing(pulsating_between(0.4, 0.8)),
6048 |label, delta| label.opacity(delta),
6049 )
6050 .into_any_element()
6051 } else {
6052 completion.into_any_element()
6053 };
6054
6055 let has_completion = self.active_inline_completion.is_some();
6056
6057 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6058 Some(
6059 h_flex()
6060 .min_w(min_width)
6061 .max_w(max_width)
6062 .flex_1()
6063 .elevation_2(cx)
6064 .border_color(cx.theme().colors().border)
6065 .child(
6066 div()
6067 .flex_1()
6068 .py_1()
6069 .px_2()
6070 .overflow_hidden()
6071 .child(completion),
6072 )
6073 .when_some(accept_keystroke, |el, accept_keystroke| {
6074 if !accept_keystroke.modifiers.modified() {
6075 return el;
6076 }
6077
6078 el.child(
6079 h_flex()
6080 .h_full()
6081 .border_l_1()
6082 .rounded_r_lg()
6083 .border_color(cx.theme().colors().border)
6084 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6085 .gap_1()
6086 .py_1()
6087 .px_2()
6088 .child(
6089 h_flex()
6090 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6091 .when(is_platform_style_mac, |parent| parent.gap_1())
6092 .child(h_flex().children(ui::render_modifiers(
6093 &accept_keystroke.modifiers,
6094 PlatformStyle::platform(),
6095 Some(if !has_completion {
6096 Color::Muted
6097 } else {
6098 Color::Default
6099 }),
6100 None,
6101 false,
6102 ))),
6103 )
6104 .child(Label::new("Preview").into_any_element())
6105 .opacity(if has_completion { 1.0 } else { 0.4 }),
6106 )
6107 })
6108 .into_any(),
6109 )
6110 }
6111
6112 fn render_edit_prediction_cursor_popover_preview(
6113 &self,
6114 completion: &InlineCompletionState,
6115 cursor_point: Point,
6116 style: &EditorStyle,
6117 cx: &mut Context<Editor>,
6118 ) -> Option<Div> {
6119 use text::ToPoint as _;
6120
6121 fn render_relative_row_jump(
6122 prefix: impl Into<String>,
6123 current_row: u32,
6124 target_row: u32,
6125 ) -> Div {
6126 let (row_diff, arrow) = if target_row < current_row {
6127 (current_row - target_row, IconName::ArrowUp)
6128 } else {
6129 (target_row - current_row, IconName::ArrowDown)
6130 };
6131
6132 h_flex()
6133 .child(
6134 Label::new(format!("{}{}", prefix.into(), row_diff))
6135 .color(Color::Muted)
6136 .size(LabelSize::Small),
6137 )
6138 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6139 }
6140
6141 match &completion.completion {
6142 InlineCompletion::Move {
6143 target, snapshot, ..
6144 } => Some(
6145 h_flex()
6146 .px_2()
6147 .gap_2()
6148 .flex_1()
6149 .child(
6150 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6151 Icon::new(IconName::ZedPredictDown)
6152 } else {
6153 Icon::new(IconName::ZedPredictUp)
6154 },
6155 )
6156 .child(Label::new("Jump to Edit")),
6157 ),
6158
6159 InlineCompletion::Edit {
6160 edits,
6161 edit_preview,
6162 snapshot,
6163 display_mode: _,
6164 } => {
6165 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6166
6167 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6168 &snapshot,
6169 &edits,
6170 edit_preview.as_ref()?,
6171 true,
6172 cx,
6173 )
6174 .first_line_preview();
6175
6176 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6177 .with_highlights(&style.text, highlighted_edits.highlights);
6178
6179 let preview = h_flex()
6180 .gap_1()
6181 .min_w_16()
6182 .child(styled_text)
6183 .when(has_more_lines, |parent| parent.child("…"));
6184
6185 let left = if first_edit_row != cursor_point.row {
6186 render_relative_row_jump("", cursor_point.row, first_edit_row)
6187 .into_any_element()
6188 } else {
6189 Icon::new(IconName::ZedPredict).into_any_element()
6190 };
6191
6192 Some(
6193 h_flex()
6194 .h_full()
6195 .flex_1()
6196 .gap_2()
6197 .pr_1()
6198 .overflow_x_hidden()
6199 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6200 .child(left)
6201 .child(preview),
6202 )
6203 }
6204 }
6205 }
6206
6207 fn render_context_menu(
6208 &self,
6209 style: &EditorStyle,
6210 max_height_in_lines: u32,
6211 y_flipped: bool,
6212 window: &mut Window,
6213 cx: &mut Context<Editor>,
6214 ) -> Option<AnyElement> {
6215 let menu = self.context_menu.borrow();
6216 let menu = menu.as_ref()?;
6217 if !menu.visible() {
6218 return None;
6219 };
6220 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6221 }
6222
6223 fn render_context_menu_aside(
6224 &mut self,
6225 max_size: Size<Pixels>,
6226 window: &mut Window,
6227 cx: &mut Context<Editor>,
6228 ) -> Option<AnyElement> {
6229 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6230 if menu.visible() {
6231 menu.render_aside(self, max_size, window, cx)
6232 } else {
6233 None
6234 }
6235 })
6236 }
6237
6238 fn hide_context_menu(
6239 &mut self,
6240 window: &mut Window,
6241 cx: &mut Context<Self>,
6242 ) -> Option<CodeContextMenu> {
6243 cx.notify();
6244 self.completion_tasks.clear();
6245 let context_menu = self.context_menu.borrow_mut().take();
6246 self.stale_inline_completion_in_menu.take();
6247 self.update_visible_inline_completion(window, cx);
6248 context_menu
6249 }
6250
6251 fn show_snippet_choices(
6252 &mut self,
6253 choices: &Vec<String>,
6254 selection: Range<Anchor>,
6255 cx: &mut Context<Self>,
6256 ) {
6257 if selection.start.buffer_id.is_none() {
6258 return;
6259 }
6260 let buffer_id = selection.start.buffer_id.unwrap();
6261 let buffer = self.buffer().read(cx).buffer(buffer_id);
6262 let id = post_inc(&mut self.next_completion_id);
6263
6264 if let Some(buffer) = buffer {
6265 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6266 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6267 ));
6268 }
6269 }
6270
6271 pub fn insert_snippet(
6272 &mut self,
6273 insertion_ranges: &[Range<usize>],
6274 snippet: Snippet,
6275 window: &mut Window,
6276 cx: &mut Context<Self>,
6277 ) -> Result<()> {
6278 struct Tabstop<T> {
6279 is_end_tabstop: bool,
6280 ranges: Vec<Range<T>>,
6281 choices: Option<Vec<String>>,
6282 }
6283
6284 let tabstops = self.buffer.update(cx, |buffer, cx| {
6285 let snippet_text: Arc<str> = snippet.text.clone().into();
6286 buffer.edit(
6287 insertion_ranges
6288 .iter()
6289 .cloned()
6290 .map(|range| (range, snippet_text.clone())),
6291 Some(AutoindentMode::EachLine),
6292 cx,
6293 );
6294
6295 let snapshot = &*buffer.read(cx);
6296 let snippet = &snippet;
6297 snippet
6298 .tabstops
6299 .iter()
6300 .map(|tabstop| {
6301 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6302 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6303 });
6304 let mut tabstop_ranges = tabstop
6305 .ranges
6306 .iter()
6307 .flat_map(|tabstop_range| {
6308 let mut delta = 0_isize;
6309 insertion_ranges.iter().map(move |insertion_range| {
6310 let insertion_start = insertion_range.start as isize + delta;
6311 delta +=
6312 snippet.text.len() as isize - insertion_range.len() as isize;
6313
6314 let start = ((insertion_start + tabstop_range.start) as usize)
6315 .min(snapshot.len());
6316 let end = ((insertion_start + tabstop_range.end) as usize)
6317 .min(snapshot.len());
6318 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6319 })
6320 })
6321 .collect::<Vec<_>>();
6322 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6323
6324 Tabstop {
6325 is_end_tabstop,
6326 ranges: tabstop_ranges,
6327 choices: tabstop.choices.clone(),
6328 }
6329 })
6330 .collect::<Vec<_>>()
6331 });
6332 if let Some(tabstop) = tabstops.first() {
6333 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6334 s.select_ranges(tabstop.ranges.iter().cloned());
6335 });
6336
6337 if let Some(choices) = &tabstop.choices {
6338 if let Some(selection) = tabstop.ranges.first() {
6339 self.show_snippet_choices(choices, selection.clone(), cx)
6340 }
6341 }
6342
6343 // If we're already at the last tabstop and it's at the end of the snippet,
6344 // we're done, we don't need to keep the state around.
6345 if !tabstop.is_end_tabstop {
6346 let choices = tabstops
6347 .iter()
6348 .map(|tabstop| tabstop.choices.clone())
6349 .collect();
6350
6351 let ranges = tabstops
6352 .into_iter()
6353 .map(|tabstop| tabstop.ranges)
6354 .collect::<Vec<_>>();
6355
6356 self.snippet_stack.push(SnippetState {
6357 active_index: 0,
6358 ranges,
6359 choices,
6360 });
6361 }
6362
6363 // Check whether the just-entered snippet ends with an auto-closable bracket.
6364 if self.autoclose_regions.is_empty() {
6365 let snapshot = self.buffer.read(cx).snapshot(cx);
6366 for selection in &mut self.selections.all::<Point>(cx) {
6367 let selection_head = selection.head();
6368 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6369 continue;
6370 };
6371
6372 let mut bracket_pair = None;
6373 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6374 let prev_chars = snapshot
6375 .reversed_chars_at(selection_head)
6376 .collect::<String>();
6377 for (pair, enabled) in scope.brackets() {
6378 if enabled
6379 && pair.close
6380 && prev_chars.starts_with(pair.start.as_str())
6381 && next_chars.starts_with(pair.end.as_str())
6382 {
6383 bracket_pair = Some(pair.clone());
6384 break;
6385 }
6386 }
6387 if let Some(pair) = bracket_pair {
6388 let start = snapshot.anchor_after(selection_head);
6389 let end = snapshot.anchor_after(selection_head);
6390 self.autoclose_regions.push(AutocloseRegion {
6391 selection_id: selection.id,
6392 range: start..end,
6393 pair,
6394 });
6395 }
6396 }
6397 }
6398 }
6399 Ok(())
6400 }
6401
6402 pub fn move_to_next_snippet_tabstop(
6403 &mut self,
6404 window: &mut Window,
6405 cx: &mut Context<Self>,
6406 ) -> bool {
6407 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6408 }
6409
6410 pub fn move_to_prev_snippet_tabstop(
6411 &mut self,
6412 window: &mut Window,
6413 cx: &mut Context<Self>,
6414 ) -> bool {
6415 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6416 }
6417
6418 pub fn move_to_snippet_tabstop(
6419 &mut self,
6420 bias: Bias,
6421 window: &mut Window,
6422 cx: &mut Context<Self>,
6423 ) -> bool {
6424 if let Some(mut snippet) = self.snippet_stack.pop() {
6425 match bias {
6426 Bias::Left => {
6427 if snippet.active_index > 0 {
6428 snippet.active_index -= 1;
6429 } else {
6430 self.snippet_stack.push(snippet);
6431 return false;
6432 }
6433 }
6434 Bias::Right => {
6435 if snippet.active_index + 1 < snippet.ranges.len() {
6436 snippet.active_index += 1;
6437 } else {
6438 self.snippet_stack.push(snippet);
6439 return false;
6440 }
6441 }
6442 }
6443 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6445 s.select_anchor_ranges(current_ranges.iter().cloned())
6446 });
6447
6448 if let Some(choices) = &snippet.choices[snippet.active_index] {
6449 if let Some(selection) = current_ranges.first() {
6450 self.show_snippet_choices(&choices, selection.clone(), cx);
6451 }
6452 }
6453
6454 // If snippet state is not at the last tabstop, push it back on the stack
6455 if snippet.active_index + 1 < snippet.ranges.len() {
6456 self.snippet_stack.push(snippet);
6457 }
6458 return true;
6459 }
6460 }
6461
6462 false
6463 }
6464
6465 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6466 self.transact(window, cx, |this, window, cx| {
6467 this.select_all(&SelectAll, window, cx);
6468 this.insert("", window, cx);
6469 });
6470 }
6471
6472 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6473 self.transact(window, cx, |this, window, cx| {
6474 this.select_autoclose_pair(window, cx);
6475 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6476 if !this.linked_edit_ranges.is_empty() {
6477 let selections = this.selections.all::<MultiBufferPoint>(cx);
6478 let snapshot = this.buffer.read(cx).snapshot(cx);
6479
6480 for selection in selections.iter() {
6481 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6482 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6483 if selection_start.buffer_id != selection_end.buffer_id {
6484 continue;
6485 }
6486 if let Some(ranges) =
6487 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6488 {
6489 for (buffer, entries) in ranges {
6490 linked_ranges.entry(buffer).or_default().extend(entries);
6491 }
6492 }
6493 }
6494 }
6495
6496 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6497 if !this.selections.line_mode {
6498 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6499 for selection in &mut selections {
6500 if selection.is_empty() {
6501 let old_head = selection.head();
6502 let mut new_head =
6503 movement::left(&display_map, old_head.to_display_point(&display_map))
6504 .to_point(&display_map);
6505 if let Some((buffer, line_buffer_range)) = display_map
6506 .buffer_snapshot
6507 .buffer_line_for_row(MultiBufferRow(old_head.row))
6508 {
6509 let indent_size =
6510 buffer.indent_size_for_line(line_buffer_range.start.row);
6511 let indent_len = match indent_size.kind {
6512 IndentKind::Space => {
6513 buffer.settings_at(line_buffer_range.start, cx).tab_size
6514 }
6515 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6516 };
6517 if old_head.column <= indent_size.len && old_head.column > 0 {
6518 let indent_len = indent_len.get();
6519 new_head = cmp::min(
6520 new_head,
6521 MultiBufferPoint::new(
6522 old_head.row,
6523 ((old_head.column - 1) / indent_len) * indent_len,
6524 ),
6525 );
6526 }
6527 }
6528
6529 selection.set_head(new_head, SelectionGoal::None);
6530 }
6531 }
6532 }
6533
6534 this.signature_help_state.set_backspace_pressed(true);
6535 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6536 s.select(selections)
6537 });
6538 this.insert("", window, cx);
6539 let empty_str: Arc<str> = Arc::from("");
6540 for (buffer, edits) in linked_ranges {
6541 let snapshot = buffer.read(cx).snapshot();
6542 use text::ToPoint as TP;
6543
6544 let edits = edits
6545 .into_iter()
6546 .map(|range| {
6547 let end_point = TP::to_point(&range.end, &snapshot);
6548 let mut start_point = TP::to_point(&range.start, &snapshot);
6549
6550 if end_point == start_point {
6551 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6552 .saturating_sub(1);
6553 start_point =
6554 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6555 };
6556
6557 (start_point..end_point, empty_str.clone())
6558 })
6559 .sorted_by_key(|(range, _)| range.start)
6560 .collect::<Vec<_>>();
6561 buffer.update(cx, |this, cx| {
6562 this.edit(edits, None, cx);
6563 })
6564 }
6565 this.refresh_inline_completion(true, false, window, cx);
6566 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6567 });
6568 }
6569
6570 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6571 self.transact(window, cx, |this, window, cx| {
6572 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6573 let line_mode = s.line_mode;
6574 s.move_with(|map, selection| {
6575 if selection.is_empty() && !line_mode {
6576 let cursor = movement::right(map, selection.head());
6577 selection.end = cursor;
6578 selection.reversed = true;
6579 selection.goal = SelectionGoal::None;
6580 }
6581 })
6582 });
6583 this.insert("", window, cx);
6584 this.refresh_inline_completion(true, false, window, cx);
6585 });
6586 }
6587
6588 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6589 if self.move_to_prev_snippet_tabstop(window, cx) {
6590 return;
6591 }
6592
6593 self.outdent(&Outdent, window, cx);
6594 }
6595
6596 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6597 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6598 return;
6599 }
6600
6601 let mut selections = self.selections.all_adjusted(cx);
6602 let buffer = self.buffer.read(cx);
6603 let snapshot = buffer.snapshot(cx);
6604 let rows_iter = selections.iter().map(|s| s.head().row);
6605 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6606
6607 let mut edits = Vec::new();
6608 let mut prev_edited_row = 0;
6609 let mut row_delta = 0;
6610 for selection in &mut selections {
6611 if selection.start.row != prev_edited_row {
6612 row_delta = 0;
6613 }
6614 prev_edited_row = selection.end.row;
6615
6616 // If the selection is non-empty, then increase the indentation of the selected lines.
6617 if !selection.is_empty() {
6618 row_delta =
6619 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6620 continue;
6621 }
6622
6623 // If the selection is empty and the cursor is in the leading whitespace before the
6624 // suggested indentation, then auto-indent the line.
6625 let cursor = selection.head();
6626 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6627 if let Some(suggested_indent) =
6628 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6629 {
6630 if cursor.column < suggested_indent.len
6631 && cursor.column <= current_indent.len
6632 && current_indent.len <= suggested_indent.len
6633 {
6634 selection.start = Point::new(cursor.row, suggested_indent.len);
6635 selection.end = selection.start;
6636 if row_delta == 0 {
6637 edits.extend(Buffer::edit_for_indent_size_adjustment(
6638 cursor.row,
6639 current_indent,
6640 suggested_indent,
6641 ));
6642 row_delta = suggested_indent.len - current_indent.len;
6643 }
6644 continue;
6645 }
6646 }
6647
6648 // Otherwise, insert a hard or soft tab.
6649 let settings = buffer.settings_at(cursor, cx);
6650 let tab_size = if settings.hard_tabs {
6651 IndentSize::tab()
6652 } else {
6653 let tab_size = settings.tab_size.get();
6654 let char_column = snapshot
6655 .text_for_range(Point::new(cursor.row, 0)..cursor)
6656 .flat_map(str::chars)
6657 .count()
6658 + row_delta as usize;
6659 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6660 IndentSize::spaces(chars_to_next_tab_stop)
6661 };
6662 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6663 selection.end = selection.start;
6664 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6665 row_delta += tab_size.len;
6666 }
6667
6668 self.transact(window, cx, |this, window, cx| {
6669 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6670 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6671 s.select(selections)
6672 });
6673 this.refresh_inline_completion(true, false, window, cx);
6674 });
6675 }
6676
6677 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6678 if self.read_only(cx) {
6679 return;
6680 }
6681 let mut selections = self.selections.all::<Point>(cx);
6682 let mut prev_edited_row = 0;
6683 let mut row_delta = 0;
6684 let mut edits = Vec::new();
6685 let buffer = self.buffer.read(cx);
6686 let snapshot = buffer.snapshot(cx);
6687 for selection in &mut selections {
6688 if selection.start.row != prev_edited_row {
6689 row_delta = 0;
6690 }
6691 prev_edited_row = selection.end.row;
6692
6693 row_delta =
6694 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6695 }
6696
6697 self.transact(window, cx, |this, window, cx| {
6698 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6700 s.select(selections)
6701 });
6702 });
6703 }
6704
6705 fn indent_selection(
6706 buffer: &MultiBuffer,
6707 snapshot: &MultiBufferSnapshot,
6708 selection: &mut Selection<Point>,
6709 edits: &mut Vec<(Range<Point>, String)>,
6710 delta_for_start_row: u32,
6711 cx: &App,
6712 ) -> u32 {
6713 let settings = buffer.settings_at(selection.start, cx);
6714 let tab_size = settings.tab_size.get();
6715 let indent_kind = if settings.hard_tabs {
6716 IndentKind::Tab
6717 } else {
6718 IndentKind::Space
6719 };
6720 let mut start_row = selection.start.row;
6721 let mut end_row = selection.end.row + 1;
6722
6723 // If a selection ends at the beginning of a line, don't indent
6724 // that last line.
6725 if selection.end.column == 0 && selection.end.row > selection.start.row {
6726 end_row -= 1;
6727 }
6728
6729 // Avoid re-indenting a row that has already been indented by a
6730 // previous selection, but still update this selection's column
6731 // to reflect that indentation.
6732 if delta_for_start_row > 0 {
6733 start_row += 1;
6734 selection.start.column += delta_for_start_row;
6735 if selection.end.row == selection.start.row {
6736 selection.end.column += delta_for_start_row;
6737 }
6738 }
6739
6740 let mut delta_for_end_row = 0;
6741 let has_multiple_rows = start_row + 1 != end_row;
6742 for row in start_row..end_row {
6743 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6744 let indent_delta = match (current_indent.kind, indent_kind) {
6745 (IndentKind::Space, IndentKind::Space) => {
6746 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6747 IndentSize::spaces(columns_to_next_tab_stop)
6748 }
6749 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6750 (_, IndentKind::Tab) => IndentSize::tab(),
6751 };
6752
6753 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6754 0
6755 } else {
6756 selection.start.column
6757 };
6758 let row_start = Point::new(row, start);
6759 edits.push((
6760 row_start..row_start,
6761 indent_delta.chars().collect::<String>(),
6762 ));
6763
6764 // Update this selection's endpoints to reflect the indentation.
6765 if row == selection.start.row {
6766 selection.start.column += indent_delta.len;
6767 }
6768 if row == selection.end.row {
6769 selection.end.column += indent_delta.len;
6770 delta_for_end_row = indent_delta.len;
6771 }
6772 }
6773
6774 if selection.start.row == selection.end.row {
6775 delta_for_start_row + delta_for_end_row
6776 } else {
6777 delta_for_end_row
6778 }
6779 }
6780
6781 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6782 if self.read_only(cx) {
6783 return;
6784 }
6785 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6786 let selections = self.selections.all::<Point>(cx);
6787 let mut deletion_ranges = Vec::new();
6788 let mut last_outdent = None;
6789 {
6790 let buffer = self.buffer.read(cx);
6791 let snapshot = buffer.snapshot(cx);
6792 for selection in &selections {
6793 let settings = buffer.settings_at(selection.start, cx);
6794 let tab_size = settings.tab_size.get();
6795 let mut rows = selection.spanned_rows(false, &display_map);
6796
6797 // Avoid re-outdenting a row that has already been outdented by a
6798 // previous selection.
6799 if let Some(last_row) = last_outdent {
6800 if last_row == rows.start {
6801 rows.start = rows.start.next_row();
6802 }
6803 }
6804 let has_multiple_rows = rows.len() > 1;
6805 for row in rows.iter_rows() {
6806 let indent_size = snapshot.indent_size_for_line(row);
6807 if indent_size.len > 0 {
6808 let deletion_len = match indent_size.kind {
6809 IndentKind::Space => {
6810 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6811 if columns_to_prev_tab_stop == 0 {
6812 tab_size
6813 } else {
6814 columns_to_prev_tab_stop
6815 }
6816 }
6817 IndentKind::Tab => 1,
6818 };
6819 let start = if has_multiple_rows
6820 || deletion_len > selection.start.column
6821 || indent_size.len < selection.start.column
6822 {
6823 0
6824 } else {
6825 selection.start.column - deletion_len
6826 };
6827 deletion_ranges.push(
6828 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6829 );
6830 last_outdent = Some(row);
6831 }
6832 }
6833 }
6834 }
6835
6836 self.transact(window, cx, |this, window, cx| {
6837 this.buffer.update(cx, |buffer, cx| {
6838 let empty_str: Arc<str> = Arc::default();
6839 buffer.edit(
6840 deletion_ranges
6841 .into_iter()
6842 .map(|range| (range, empty_str.clone())),
6843 None,
6844 cx,
6845 );
6846 });
6847 let selections = this.selections.all::<usize>(cx);
6848 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6849 s.select(selections)
6850 });
6851 });
6852 }
6853
6854 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6855 if self.read_only(cx) {
6856 return;
6857 }
6858 let selections = self
6859 .selections
6860 .all::<usize>(cx)
6861 .into_iter()
6862 .map(|s| s.range());
6863
6864 self.transact(window, cx, |this, window, cx| {
6865 this.buffer.update(cx, |buffer, cx| {
6866 buffer.autoindent_ranges(selections, cx);
6867 });
6868 let selections = this.selections.all::<usize>(cx);
6869 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6870 s.select(selections)
6871 });
6872 });
6873 }
6874
6875 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6876 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6877 let selections = self.selections.all::<Point>(cx);
6878
6879 let mut new_cursors = Vec::new();
6880 let mut edit_ranges = Vec::new();
6881 let mut selections = selections.iter().peekable();
6882 while let Some(selection) = selections.next() {
6883 let mut rows = selection.spanned_rows(false, &display_map);
6884 let goal_display_column = selection.head().to_display_point(&display_map).column();
6885
6886 // Accumulate contiguous regions of rows that we want to delete.
6887 while let Some(next_selection) = selections.peek() {
6888 let next_rows = next_selection.spanned_rows(false, &display_map);
6889 if next_rows.start <= rows.end {
6890 rows.end = next_rows.end;
6891 selections.next().unwrap();
6892 } else {
6893 break;
6894 }
6895 }
6896
6897 let buffer = &display_map.buffer_snapshot;
6898 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6899 let edit_end;
6900 let cursor_buffer_row;
6901 if buffer.max_point().row >= rows.end.0 {
6902 // If there's a line after the range, delete the \n from the end of the row range
6903 // and position the cursor on the next line.
6904 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6905 cursor_buffer_row = rows.end;
6906 } else {
6907 // If there isn't a line after the range, delete the \n from the line before the
6908 // start of the row range and position the cursor there.
6909 edit_start = edit_start.saturating_sub(1);
6910 edit_end = buffer.len();
6911 cursor_buffer_row = rows.start.previous_row();
6912 }
6913
6914 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6915 *cursor.column_mut() =
6916 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6917
6918 new_cursors.push((
6919 selection.id,
6920 buffer.anchor_after(cursor.to_point(&display_map)),
6921 ));
6922 edit_ranges.push(edit_start..edit_end);
6923 }
6924
6925 self.transact(window, cx, |this, window, cx| {
6926 let buffer = this.buffer.update(cx, |buffer, cx| {
6927 let empty_str: Arc<str> = Arc::default();
6928 buffer.edit(
6929 edit_ranges
6930 .into_iter()
6931 .map(|range| (range, empty_str.clone())),
6932 None,
6933 cx,
6934 );
6935 buffer.snapshot(cx)
6936 });
6937 let new_selections = new_cursors
6938 .into_iter()
6939 .map(|(id, cursor)| {
6940 let cursor = cursor.to_point(&buffer);
6941 Selection {
6942 id,
6943 start: cursor,
6944 end: cursor,
6945 reversed: false,
6946 goal: SelectionGoal::None,
6947 }
6948 })
6949 .collect();
6950
6951 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6952 s.select(new_selections);
6953 });
6954 });
6955 }
6956
6957 pub fn join_lines_impl(
6958 &mut self,
6959 insert_whitespace: bool,
6960 window: &mut Window,
6961 cx: &mut Context<Self>,
6962 ) {
6963 if self.read_only(cx) {
6964 return;
6965 }
6966 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6967 for selection in self.selections.all::<Point>(cx) {
6968 let start = MultiBufferRow(selection.start.row);
6969 // Treat single line selections as if they include the next line. Otherwise this action
6970 // would do nothing for single line selections individual cursors.
6971 let end = if selection.start.row == selection.end.row {
6972 MultiBufferRow(selection.start.row + 1)
6973 } else {
6974 MultiBufferRow(selection.end.row)
6975 };
6976
6977 if let Some(last_row_range) = row_ranges.last_mut() {
6978 if start <= last_row_range.end {
6979 last_row_range.end = end;
6980 continue;
6981 }
6982 }
6983 row_ranges.push(start..end);
6984 }
6985
6986 let snapshot = self.buffer.read(cx).snapshot(cx);
6987 let mut cursor_positions = Vec::new();
6988 for row_range in &row_ranges {
6989 let anchor = snapshot.anchor_before(Point::new(
6990 row_range.end.previous_row().0,
6991 snapshot.line_len(row_range.end.previous_row()),
6992 ));
6993 cursor_positions.push(anchor..anchor);
6994 }
6995
6996 self.transact(window, cx, |this, window, cx| {
6997 for row_range in row_ranges.into_iter().rev() {
6998 for row in row_range.iter_rows().rev() {
6999 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7000 let next_line_row = row.next_row();
7001 let indent = snapshot.indent_size_for_line(next_line_row);
7002 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7003
7004 let replace =
7005 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7006 " "
7007 } else {
7008 ""
7009 };
7010
7011 this.buffer.update(cx, |buffer, cx| {
7012 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7013 });
7014 }
7015 }
7016
7017 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7018 s.select_anchor_ranges(cursor_positions)
7019 });
7020 });
7021 }
7022
7023 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7024 self.join_lines_impl(true, window, cx);
7025 }
7026
7027 pub fn sort_lines_case_sensitive(
7028 &mut self,
7029 _: &SortLinesCaseSensitive,
7030 window: &mut Window,
7031 cx: &mut Context<Self>,
7032 ) {
7033 self.manipulate_lines(window, cx, |lines| lines.sort())
7034 }
7035
7036 pub fn sort_lines_case_insensitive(
7037 &mut self,
7038 _: &SortLinesCaseInsensitive,
7039 window: &mut Window,
7040 cx: &mut Context<Self>,
7041 ) {
7042 self.manipulate_lines(window, cx, |lines| {
7043 lines.sort_by_key(|line| line.to_lowercase())
7044 })
7045 }
7046
7047 pub fn unique_lines_case_insensitive(
7048 &mut self,
7049 _: &UniqueLinesCaseInsensitive,
7050 window: &mut Window,
7051 cx: &mut Context<Self>,
7052 ) {
7053 self.manipulate_lines(window, cx, |lines| {
7054 let mut seen = HashSet::default();
7055 lines.retain(|line| seen.insert(line.to_lowercase()));
7056 })
7057 }
7058
7059 pub fn unique_lines_case_sensitive(
7060 &mut self,
7061 _: &UniqueLinesCaseSensitive,
7062 window: &mut Window,
7063 cx: &mut Context<Self>,
7064 ) {
7065 self.manipulate_lines(window, cx, |lines| {
7066 let mut seen = HashSet::default();
7067 lines.retain(|line| seen.insert(*line));
7068 })
7069 }
7070
7071 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7072 let mut revert_changes = HashMap::default();
7073 let snapshot = self.snapshot(window, cx);
7074 for hunk in snapshot
7075 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7076 {
7077 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7078 }
7079 if !revert_changes.is_empty() {
7080 self.transact(window, cx, |editor, window, cx| {
7081 editor.revert(revert_changes, window, cx);
7082 });
7083 }
7084 }
7085
7086 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7087 let Some(project) = self.project.clone() else {
7088 return;
7089 };
7090 self.reload(project, window, cx)
7091 .detach_and_notify_err(window, cx);
7092 }
7093
7094 pub fn revert_selected_hunks(
7095 &mut self,
7096 _: &RevertSelectedHunks,
7097 window: &mut Window,
7098 cx: &mut Context<Self>,
7099 ) {
7100 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7101 self.discard_hunks_in_ranges(selections, window, cx);
7102 }
7103
7104 fn discard_hunks_in_ranges(
7105 &mut self,
7106 ranges: impl Iterator<Item = Range<Point>>,
7107 window: &mut Window,
7108 cx: &mut Context<Editor>,
7109 ) {
7110 let mut revert_changes = HashMap::default();
7111 let snapshot = self.snapshot(window, cx);
7112 for hunk in &snapshot.hunks_for_ranges(ranges) {
7113 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7114 }
7115 if !revert_changes.is_empty() {
7116 self.transact(window, cx, |editor, window, cx| {
7117 editor.revert(revert_changes, window, cx);
7118 });
7119 }
7120 }
7121
7122 pub fn open_active_item_in_terminal(
7123 &mut self,
7124 _: &OpenInTerminal,
7125 window: &mut Window,
7126 cx: &mut Context<Self>,
7127 ) {
7128 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7129 let project_path = buffer.read(cx).project_path(cx)?;
7130 let project = self.project.as_ref()?.read(cx);
7131 let entry = project.entry_for_path(&project_path, cx)?;
7132 let parent = match &entry.canonical_path {
7133 Some(canonical_path) => canonical_path.to_path_buf(),
7134 None => project.absolute_path(&project_path, cx)?,
7135 }
7136 .parent()?
7137 .to_path_buf();
7138 Some(parent)
7139 }) {
7140 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7141 }
7142 }
7143
7144 pub fn prepare_revert_change(
7145 &self,
7146 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7147 hunk: &MultiBufferDiffHunk,
7148 cx: &mut App,
7149 ) -> Option<()> {
7150 let buffer = self.buffer.read(cx);
7151 let diff = buffer.diff_for(hunk.buffer_id)?;
7152 let buffer = buffer.buffer(hunk.buffer_id)?;
7153 let buffer = buffer.read(cx);
7154 let original_text = diff
7155 .read(cx)
7156 .base_text()
7157 .as_ref()?
7158 .as_rope()
7159 .slice(hunk.diff_base_byte_range.clone());
7160 let buffer_snapshot = buffer.snapshot();
7161 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7162 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7163 probe
7164 .0
7165 .start
7166 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7167 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7168 }) {
7169 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7170 Some(())
7171 } else {
7172 None
7173 }
7174 }
7175
7176 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7177 self.manipulate_lines(window, cx, |lines| lines.reverse())
7178 }
7179
7180 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7181 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7182 }
7183
7184 fn manipulate_lines<Fn>(
7185 &mut self,
7186 window: &mut Window,
7187 cx: &mut Context<Self>,
7188 mut callback: Fn,
7189 ) where
7190 Fn: FnMut(&mut Vec<&str>),
7191 {
7192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7193 let buffer = self.buffer.read(cx).snapshot(cx);
7194
7195 let mut edits = Vec::new();
7196
7197 let selections = self.selections.all::<Point>(cx);
7198 let mut selections = selections.iter().peekable();
7199 let mut contiguous_row_selections = Vec::new();
7200 let mut new_selections = Vec::new();
7201 let mut added_lines = 0;
7202 let mut removed_lines = 0;
7203
7204 while let Some(selection) = selections.next() {
7205 let (start_row, end_row) = consume_contiguous_rows(
7206 &mut contiguous_row_selections,
7207 selection,
7208 &display_map,
7209 &mut selections,
7210 );
7211
7212 let start_point = Point::new(start_row.0, 0);
7213 let end_point = Point::new(
7214 end_row.previous_row().0,
7215 buffer.line_len(end_row.previous_row()),
7216 );
7217 let text = buffer
7218 .text_for_range(start_point..end_point)
7219 .collect::<String>();
7220
7221 let mut lines = text.split('\n').collect_vec();
7222
7223 let lines_before = lines.len();
7224 callback(&mut lines);
7225 let lines_after = lines.len();
7226
7227 edits.push((start_point..end_point, lines.join("\n")));
7228
7229 // Selections must change based on added and removed line count
7230 let start_row =
7231 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7232 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7233 new_selections.push(Selection {
7234 id: selection.id,
7235 start: start_row,
7236 end: end_row,
7237 goal: SelectionGoal::None,
7238 reversed: selection.reversed,
7239 });
7240
7241 if lines_after > lines_before {
7242 added_lines += lines_after - lines_before;
7243 } else if lines_before > lines_after {
7244 removed_lines += lines_before - lines_after;
7245 }
7246 }
7247
7248 self.transact(window, cx, |this, window, cx| {
7249 let buffer = this.buffer.update(cx, |buffer, cx| {
7250 buffer.edit(edits, None, cx);
7251 buffer.snapshot(cx)
7252 });
7253
7254 // Recalculate offsets on newly edited buffer
7255 let new_selections = new_selections
7256 .iter()
7257 .map(|s| {
7258 let start_point = Point::new(s.start.0, 0);
7259 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7260 Selection {
7261 id: s.id,
7262 start: buffer.point_to_offset(start_point),
7263 end: buffer.point_to_offset(end_point),
7264 goal: s.goal,
7265 reversed: s.reversed,
7266 }
7267 })
7268 .collect();
7269
7270 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7271 s.select(new_selections);
7272 });
7273
7274 this.request_autoscroll(Autoscroll::fit(), cx);
7275 });
7276 }
7277
7278 pub fn convert_to_upper_case(
7279 &mut self,
7280 _: &ConvertToUpperCase,
7281 window: &mut Window,
7282 cx: &mut Context<Self>,
7283 ) {
7284 self.manipulate_text(window, cx, |text| text.to_uppercase())
7285 }
7286
7287 pub fn convert_to_lower_case(
7288 &mut self,
7289 _: &ConvertToLowerCase,
7290 window: &mut Window,
7291 cx: &mut Context<Self>,
7292 ) {
7293 self.manipulate_text(window, cx, |text| text.to_lowercase())
7294 }
7295
7296 pub fn convert_to_title_case(
7297 &mut self,
7298 _: &ConvertToTitleCase,
7299 window: &mut Window,
7300 cx: &mut Context<Self>,
7301 ) {
7302 self.manipulate_text(window, cx, |text| {
7303 text.split('\n')
7304 .map(|line| line.to_case(Case::Title))
7305 .join("\n")
7306 })
7307 }
7308
7309 pub fn convert_to_snake_case(
7310 &mut self,
7311 _: &ConvertToSnakeCase,
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) {
7315 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7316 }
7317
7318 pub fn convert_to_kebab_case(
7319 &mut self,
7320 _: &ConvertToKebabCase,
7321 window: &mut Window,
7322 cx: &mut Context<Self>,
7323 ) {
7324 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7325 }
7326
7327 pub fn convert_to_upper_camel_case(
7328 &mut self,
7329 _: &ConvertToUpperCamelCase,
7330 window: &mut Window,
7331 cx: &mut Context<Self>,
7332 ) {
7333 self.manipulate_text(window, cx, |text| {
7334 text.split('\n')
7335 .map(|line| line.to_case(Case::UpperCamel))
7336 .join("\n")
7337 })
7338 }
7339
7340 pub fn convert_to_lower_camel_case(
7341 &mut self,
7342 _: &ConvertToLowerCamelCase,
7343 window: &mut Window,
7344 cx: &mut Context<Self>,
7345 ) {
7346 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7347 }
7348
7349 pub fn convert_to_opposite_case(
7350 &mut self,
7351 _: &ConvertToOppositeCase,
7352 window: &mut Window,
7353 cx: &mut Context<Self>,
7354 ) {
7355 self.manipulate_text(window, cx, |text| {
7356 text.chars()
7357 .fold(String::with_capacity(text.len()), |mut t, c| {
7358 if c.is_uppercase() {
7359 t.extend(c.to_lowercase());
7360 } else {
7361 t.extend(c.to_uppercase());
7362 }
7363 t
7364 })
7365 })
7366 }
7367
7368 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7369 where
7370 Fn: FnMut(&str) -> String,
7371 {
7372 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7373 let buffer = self.buffer.read(cx).snapshot(cx);
7374
7375 let mut new_selections = Vec::new();
7376 let mut edits = Vec::new();
7377 let mut selection_adjustment = 0i32;
7378
7379 for selection in self.selections.all::<usize>(cx) {
7380 let selection_is_empty = selection.is_empty();
7381
7382 let (start, end) = if selection_is_empty {
7383 let word_range = movement::surrounding_word(
7384 &display_map,
7385 selection.start.to_display_point(&display_map),
7386 );
7387 let start = word_range.start.to_offset(&display_map, Bias::Left);
7388 let end = word_range.end.to_offset(&display_map, Bias::Left);
7389 (start, end)
7390 } else {
7391 (selection.start, selection.end)
7392 };
7393
7394 let text = buffer.text_for_range(start..end).collect::<String>();
7395 let old_length = text.len() as i32;
7396 let text = callback(&text);
7397
7398 new_selections.push(Selection {
7399 start: (start as i32 - selection_adjustment) as usize,
7400 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7401 goal: SelectionGoal::None,
7402 ..selection
7403 });
7404
7405 selection_adjustment += old_length - text.len() as i32;
7406
7407 edits.push((start..end, text));
7408 }
7409
7410 self.transact(window, cx, |this, window, cx| {
7411 this.buffer.update(cx, |buffer, cx| {
7412 buffer.edit(edits, None, cx);
7413 });
7414
7415 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7416 s.select(new_selections);
7417 });
7418
7419 this.request_autoscroll(Autoscroll::fit(), cx);
7420 });
7421 }
7422
7423 pub fn duplicate(
7424 &mut self,
7425 upwards: bool,
7426 whole_lines: bool,
7427 window: &mut Window,
7428 cx: &mut Context<Self>,
7429 ) {
7430 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7431 let buffer = &display_map.buffer_snapshot;
7432 let selections = self.selections.all::<Point>(cx);
7433
7434 let mut edits = Vec::new();
7435 let mut selections_iter = selections.iter().peekable();
7436 while let Some(selection) = selections_iter.next() {
7437 let mut rows = selection.spanned_rows(false, &display_map);
7438 // duplicate line-wise
7439 if whole_lines || selection.start == selection.end {
7440 // Avoid duplicating the same lines twice.
7441 while let Some(next_selection) = selections_iter.peek() {
7442 let next_rows = next_selection.spanned_rows(false, &display_map);
7443 if next_rows.start < rows.end {
7444 rows.end = next_rows.end;
7445 selections_iter.next().unwrap();
7446 } else {
7447 break;
7448 }
7449 }
7450
7451 // Copy the text from the selected row region and splice it either at the start
7452 // or end of the region.
7453 let start = Point::new(rows.start.0, 0);
7454 let end = Point::new(
7455 rows.end.previous_row().0,
7456 buffer.line_len(rows.end.previous_row()),
7457 );
7458 let text = buffer
7459 .text_for_range(start..end)
7460 .chain(Some("\n"))
7461 .collect::<String>();
7462 let insert_location = if upwards {
7463 Point::new(rows.end.0, 0)
7464 } else {
7465 start
7466 };
7467 edits.push((insert_location..insert_location, text));
7468 } else {
7469 // duplicate character-wise
7470 let start = selection.start;
7471 let end = selection.end;
7472 let text = buffer.text_for_range(start..end).collect::<String>();
7473 edits.push((selection.end..selection.end, text));
7474 }
7475 }
7476
7477 self.transact(window, cx, |this, _, cx| {
7478 this.buffer.update(cx, |buffer, cx| {
7479 buffer.edit(edits, None, cx);
7480 });
7481
7482 this.request_autoscroll(Autoscroll::fit(), cx);
7483 });
7484 }
7485
7486 pub fn duplicate_line_up(
7487 &mut self,
7488 _: &DuplicateLineUp,
7489 window: &mut Window,
7490 cx: &mut Context<Self>,
7491 ) {
7492 self.duplicate(true, true, window, cx);
7493 }
7494
7495 pub fn duplicate_line_down(
7496 &mut self,
7497 _: &DuplicateLineDown,
7498 window: &mut Window,
7499 cx: &mut Context<Self>,
7500 ) {
7501 self.duplicate(false, true, window, cx);
7502 }
7503
7504 pub fn duplicate_selection(
7505 &mut self,
7506 _: &DuplicateSelection,
7507 window: &mut Window,
7508 cx: &mut Context<Self>,
7509 ) {
7510 self.duplicate(false, false, window, cx);
7511 }
7512
7513 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7514 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7515 let buffer = self.buffer.read(cx).snapshot(cx);
7516
7517 let mut edits = Vec::new();
7518 let mut unfold_ranges = Vec::new();
7519 let mut refold_creases = Vec::new();
7520
7521 let selections = self.selections.all::<Point>(cx);
7522 let mut selections = selections.iter().peekable();
7523 let mut contiguous_row_selections = Vec::new();
7524 let mut new_selections = Vec::new();
7525
7526 while let Some(selection) = selections.next() {
7527 // Find all the selections that span a contiguous row range
7528 let (start_row, end_row) = consume_contiguous_rows(
7529 &mut contiguous_row_selections,
7530 selection,
7531 &display_map,
7532 &mut selections,
7533 );
7534
7535 // Move the text spanned by the row range to be before the line preceding the row range
7536 if start_row.0 > 0 {
7537 let range_to_move = Point::new(
7538 start_row.previous_row().0,
7539 buffer.line_len(start_row.previous_row()),
7540 )
7541 ..Point::new(
7542 end_row.previous_row().0,
7543 buffer.line_len(end_row.previous_row()),
7544 );
7545 let insertion_point = display_map
7546 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7547 .0;
7548
7549 // Don't move lines across excerpts
7550 if buffer
7551 .excerpt_containing(insertion_point..range_to_move.end)
7552 .is_some()
7553 {
7554 let text = buffer
7555 .text_for_range(range_to_move.clone())
7556 .flat_map(|s| s.chars())
7557 .skip(1)
7558 .chain(['\n'])
7559 .collect::<String>();
7560
7561 edits.push((
7562 buffer.anchor_after(range_to_move.start)
7563 ..buffer.anchor_before(range_to_move.end),
7564 String::new(),
7565 ));
7566 let insertion_anchor = buffer.anchor_after(insertion_point);
7567 edits.push((insertion_anchor..insertion_anchor, text));
7568
7569 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7570
7571 // Move selections up
7572 new_selections.extend(contiguous_row_selections.drain(..).map(
7573 |mut selection| {
7574 selection.start.row -= row_delta;
7575 selection.end.row -= row_delta;
7576 selection
7577 },
7578 ));
7579
7580 // Move folds up
7581 unfold_ranges.push(range_to_move.clone());
7582 for fold in display_map.folds_in_range(
7583 buffer.anchor_before(range_to_move.start)
7584 ..buffer.anchor_after(range_to_move.end),
7585 ) {
7586 let mut start = fold.range.start.to_point(&buffer);
7587 let mut end = fold.range.end.to_point(&buffer);
7588 start.row -= row_delta;
7589 end.row -= row_delta;
7590 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7591 }
7592 }
7593 }
7594
7595 // If we didn't move line(s), preserve the existing selections
7596 new_selections.append(&mut contiguous_row_selections);
7597 }
7598
7599 self.transact(window, cx, |this, window, cx| {
7600 this.unfold_ranges(&unfold_ranges, true, true, cx);
7601 this.buffer.update(cx, |buffer, cx| {
7602 for (range, text) in edits {
7603 buffer.edit([(range, text)], None, cx);
7604 }
7605 });
7606 this.fold_creases(refold_creases, true, window, cx);
7607 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7608 s.select(new_selections);
7609 })
7610 });
7611 }
7612
7613 pub fn move_line_down(
7614 &mut self,
7615 _: &MoveLineDown,
7616 window: &mut Window,
7617 cx: &mut Context<Self>,
7618 ) {
7619 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7620 let buffer = self.buffer.read(cx).snapshot(cx);
7621
7622 let mut edits = Vec::new();
7623 let mut unfold_ranges = Vec::new();
7624 let mut refold_creases = Vec::new();
7625
7626 let selections = self.selections.all::<Point>(cx);
7627 let mut selections = selections.iter().peekable();
7628 let mut contiguous_row_selections = Vec::new();
7629 let mut new_selections = Vec::new();
7630
7631 while let Some(selection) = selections.next() {
7632 // Find all the selections that span a contiguous row range
7633 let (start_row, end_row) = consume_contiguous_rows(
7634 &mut contiguous_row_selections,
7635 selection,
7636 &display_map,
7637 &mut selections,
7638 );
7639
7640 // Move the text spanned by the row range to be after the last line of the row range
7641 if end_row.0 <= buffer.max_point().row {
7642 let range_to_move =
7643 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7644 let insertion_point = display_map
7645 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7646 .0;
7647
7648 // Don't move lines across excerpt boundaries
7649 if buffer
7650 .excerpt_containing(range_to_move.start..insertion_point)
7651 .is_some()
7652 {
7653 let mut text = String::from("\n");
7654 text.extend(buffer.text_for_range(range_to_move.clone()));
7655 text.pop(); // Drop trailing newline
7656 edits.push((
7657 buffer.anchor_after(range_to_move.start)
7658 ..buffer.anchor_before(range_to_move.end),
7659 String::new(),
7660 ));
7661 let insertion_anchor = buffer.anchor_after(insertion_point);
7662 edits.push((insertion_anchor..insertion_anchor, text));
7663
7664 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7665
7666 // Move selections down
7667 new_selections.extend(contiguous_row_selections.drain(..).map(
7668 |mut selection| {
7669 selection.start.row += row_delta;
7670 selection.end.row += row_delta;
7671 selection
7672 },
7673 ));
7674
7675 // Move folds down
7676 unfold_ranges.push(range_to_move.clone());
7677 for fold in display_map.folds_in_range(
7678 buffer.anchor_before(range_to_move.start)
7679 ..buffer.anchor_after(range_to_move.end),
7680 ) {
7681 let mut start = fold.range.start.to_point(&buffer);
7682 let mut end = fold.range.end.to_point(&buffer);
7683 start.row += row_delta;
7684 end.row += row_delta;
7685 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7686 }
7687 }
7688 }
7689
7690 // If we didn't move line(s), preserve the existing selections
7691 new_selections.append(&mut contiguous_row_selections);
7692 }
7693
7694 self.transact(window, cx, |this, window, cx| {
7695 this.unfold_ranges(&unfold_ranges, true, true, cx);
7696 this.buffer.update(cx, |buffer, cx| {
7697 for (range, text) in edits {
7698 buffer.edit([(range, text)], None, cx);
7699 }
7700 });
7701 this.fold_creases(refold_creases, true, window, cx);
7702 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7703 s.select(new_selections)
7704 });
7705 });
7706 }
7707
7708 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7709 let text_layout_details = &self.text_layout_details(window);
7710 self.transact(window, cx, |this, window, cx| {
7711 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7712 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7713 let line_mode = s.line_mode;
7714 s.move_with(|display_map, selection| {
7715 if !selection.is_empty() || line_mode {
7716 return;
7717 }
7718
7719 let mut head = selection.head();
7720 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7721 if head.column() == display_map.line_len(head.row()) {
7722 transpose_offset = display_map
7723 .buffer_snapshot
7724 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7725 }
7726
7727 if transpose_offset == 0 {
7728 return;
7729 }
7730
7731 *head.column_mut() += 1;
7732 head = display_map.clip_point(head, Bias::Right);
7733 let goal = SelectionGoal::HorizontalPosition(
7734 display_map
7735 .x_for_display_point(head, text_layout_details)
7736 .into(),
7737 );
7738 selection.collapse_to(head, goal);
7739
7740 let transpose_start = display_map
7741 .buffer_snapshot
7742 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7743 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7744 let transpose_end = display_map
7745 .buffer_snapshot
7746 .clip_offset(transpose_offset + 1, Bias::Right);
7747 if let Some(ch) =
7748 display_map.buffer_snapshot.chars_at(transpose_start).next()
7749 {
7750 edits.push((transpose_start..transpose_offset, String::new()));
7751 edits.push((transpose_end..transpose_end, ch.to_string()));
7752 }
7753 }
7754 });
7755 edits
7756 });
7757 this.buffer
7758 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7759 let selections = this.selections.all::<usize>(cx);
7760 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7761 s.select(selections);
7762 });
7763 });
7764 }
7765
7766 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7767 self.rewrap_impl(IsVimMode::No, cx)
7768 }
7769
7770 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7771 let buffer = self.buffer.read(cx).snapshot(cx);
7772 let selections = self.selections.all::<Point>(cx);
7773 let mut selections = selections.iter().peekable();
7774
7775 let mut edits = Vec::new();
7776 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7777
7778 while let Some(selection) = selections.next() {
7779 let mut start_row = selection.start.row;
7780 let mut end_row = selection.end.row;
7781
7782 // Skip selections that overlap with a range that has already been rewrapped.
7783 let selection_range = start_row..end_row;
7784 if rewrapped_row_ranges
7785 .iter()
7786 .any(|range| range.overlaps(&selection_range))
7787 {
7788 continue;
7789 }
7790
7791 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7792
7793 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7794 match language_scope.language_name().as_ref() {
7795 "Markdown" | "Plain Text" => {
7796 should_rewrap = true;
7797 }
7798 _ => {}
7799 }
7800 }
7801
7802 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7803
7804 // Since not all lines in the selection may be at the same indent
7805 // level, choose the indent size that is the most common between all
7806 // of the lines.
7807 //
7808 // If there is a tie, we use the deepest indent.
7809 let (indent_size, indent_end) = {
7810 let mut indent_size_occurrences = HashMap::default();
7811 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7812
7813 for row in start_row..=end_row {
7814 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7815 rows_by_indent_size.entry(indent).or_default().push(row);
7816 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7817 }
7818
7819 let indent_size = indent_size_occurrences
7820 .into_iter()
7821 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7822 .map(|(indent, _)| indent)
7823 .unwrap_or_default();
7824 let row = rows_by_indent_size[&indent_size][0];
7825 let indent_end = Point::new(row, indent_size.len);
7826
7827 (indent_size, indent_end)
7828 };
7829
7830 let mut line_prefix = indent_size.chars().collect::<String>();
7831
7832 if let Some(comment_prefix) =
7833 buffer
7834 .language_scope_at(selection.head())
7835 .and_then(|language| {
7836 language
7837 .line_comment_prefixes()
7838 .iter()
7839 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7840 .cloned()
7841 })
7842 {
7843 line_prefix.push_str(&comment_prefix);
7844 should_rewrap = true;
7845 }
7846
7847 if !should_rewrap {
7848 continue;
7849 }
7850
7851 if selection.is_empty() {
7852 'expand_upwards: while start_row > 0 {
7853 let prev_row = start_row - 1;
7854 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7855 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7856 {
7857 start_row = prev_row;
7858 } else {
7859 break 'expand_upwards;
7860 }
7861 }
7862
7863 'expand_downwards: while end_row < buffer.max_point().row {
7864 let next_row = end_row + 1;
7865 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7866 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7867 {
7868 end_row = next_row;
7869 } else {
7870 break 'expand_downwards;
7871 }
7872 }
7873 }
7874
7875 let start = Point::new(start_row, 0);
7876 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7877 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7878 let Some(lines_without_prefixes) = selection_text
7879 .lines()
7880 .map(|line| {
7881 line.strip_prefix(&line_prefix)
7882 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7883 .ok_or_else(|| {
7884 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7885 })
7886 })
7887 .collect::<Result<Vec<_>, _>>()
7888 .log_err()
7889 else {
7890 continue;
7891 };
7892
7893 let wrap_column = buffer
7894 .settings_at(Point::new(start_row, 0), cx)
7895 .preferred_line_length as usize;
7896 let wrapped_text = wrap_with_prefix(
7897 line_prefix,
7898 lines_without_prefixes.join(" "),
7899 wrap_column,
7900 tab_size,
7901 );
7902
7903 // TODO: should always use char-based diff while still supporting cursor behavior that
7904 // matches vim.
7905 let diff = match is_vim_mode {
7906 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7907 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7908 };
7909 let mut offset = start.to_offset(&buffer);
7910 let mut moved_since_edit = true;
7911
7912 for change in diff.iter_all_changes() {
7913 let value = change.value();
7914 match change.tag() {
7915 ChangeTag::Equal => {
7916 offset += value.len();
7917 moved_since_edit = true;
7918 }
7919 ChangeTag::Delete => {
7920 let start = buffer.anchor_after(offset);
7921 let end = buffer.anchor_before(offset + value.len());
7922
7923 if moved_since_edit {
7924 edits.push((start..end, String::new()));
7925 } else {
7926 edits.last_mut().unwrap().0.end = end;
7927 }
7928
7929 offset += value.len();
7930 moved_since_edit = false;
7931 }
7932 ChangeTag::Insert => {
7933 if moved_since_edit {
7934 let anchor = buffer.anchor_after(offset);
7935 edits.push((anchor..anchor, value.to_string()));
7936 } else {
7937 edits.last_mut().unwrap().1.push_str(value);
7938 }
7939
7940 moved_since_edit = false;
7941 }
7942 }
7943 }
7944
7945 rewrapped_row_ranges.push(start_row..=end_row);
7946 }
7947
7948 self.buffer
7949 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7950 }
7951
7952 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7953 let mut text = String::new();
7954 let buffer = self.buffer.read(cx).snapshot(cx);
7955 let mut selections = self.selections.all::<Point>(cx);
7956 let mut clipboard_selections = Vec::with_capacity(selections.len());
7957 {
7958 let max_point = buffer.max_point();
7959 let mut is_first = true;
7960 for selection in &mut selections {
7961 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7962 if is_entire_line {
7963 selection.start = Point::new(selection.start.row, 0);
7964 if !selection.is_empty() && selection.end.column == 0 {
7965 selection.end = cmp::min(max_point, selection.end);
7966 } else {
7967 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7968 }
7969 selection.goal = SelectionGoal::None;
7970 }
7971 if is_first {
7972 is_first = false;
7973 } else {
7974 text += "\n";
7975 }
7976 let mut len = 0;
7977 for chunk in buffer.text_for_range(selection.start..selection.end) {
7978 text.push_str(chunk);
7979 len += chunk.len();
7980 }
7981 clipboard_selections.push(ClipboardSelection {
7982 len,
7983 is_entire_line,
7984 first_line_indent: buffer
7985 .indent_size_for_line(MultiBufferRow(selection.start.row))
7986 .len,
7987 });
7988 }
7989 }
7990
7991 self.transact(window, cx, |this, window, cx| {
7992 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7993 s.select(selections);
7994 });
7995 this.insert("", window, cx);
7996 });
7997 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7998 }
7999
8000 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8001 let item = self.cut_common(window, cx);
8002 cx.write_to_clipboard(item);
8003 }
8004
8005 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8006 self.change_selections(None, window, cx, |s| {
8007 s.move_with(|snapshot, sel| {
8008 if sel.is_empty() {
8009 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8010 }
8011 });
8012 });
8013 let item = self.cut_common(window, cx);
8014 cx.set_global(KillRing(item))
8015 }
8016
8017 pub fn kill_ring_yank(
8018 &mut self,
8019 _: &KillRingYank,
8020 window: &mut Window,
8021 cx: &mut Context<Self>,
8022 ) {
8023 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8024 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8025 (kill_ring.text().to_string(), kill_ring.metadata_json())
8026 } else {
8027 return;
8028 }
8029 } else {
8030 return;
8031 };
8032 self.do_paste(&text, metadata, false, window, cx);
8033 }
8034
8035 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8036 let selections = self.selections.all::<Point>(cx);
8037 let buffer = self.buffer.read(cx).read(cx);
8038 let mut text = String::new();
8039
8040 let mut clipboard_selections = Vec::with_capacity(selections.len());
8041 {
8042 let max_point = buffer.max_point();
8043 let mut is_first = true;
8044 for selection in selections.iter() {
8045 let mut start = selection.start;
8046 let mut end = selection.end;
8047 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8048 if is_entire_line {
8049 start = Point::new(start.row, 0);
8050 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8051 }
8052 if is_first {
8053 is_first = false;
8054 } else {
8055 text += "\n";
8056 }
8057 let mut len = 0;
8058 for chunk in buffer.text_for_range(start..end) {
8059 text.push_str(chunk);
8060 len += chunk.len();
8061 }
8062 clipboard_selections.push(ClipboardSelection {
8063 len,
8064 is_entire_line,
8065 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8066 });
8067 }
8068 }
8069
8070 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8071 text,
8072 clipboard_selections,
8073 ));
8074 }
8075
8076 pub fn do_paste(
8077 &mut self,
8078 text: &String,
8079 clipboard_selections: Option<Vec<ClipboardSelection>>,
8080 handle_entire_lines: bool,
8081 window: &mut Window,
8082 cx: &mut Context<Self>,
8083 ) {
8084 if self.read_only(cx) {
8085 return;
8086 }
8087
8088 let clipboard_text = Cow::Borrowed(text);
8089
8090 self.transact(window, cx, |this, window, cx| {
8091 if let Some(mut clipboard_selections) = clipboard_selections {
8092 let old_selections = this.selections.all::<usize>(cx);
8093 let all_selections_were_entire_line =
8094 clipboard_selections.iter().all(|s| s.is_entire_line);
8095 let first_selection_indent_column =
8096 clipboard_selections.first().map(|s| s.first_line_indent);
8097 if clipboard_selections.len() != old_selections.len() {
8098 clipboard_selections.drain(..);
8099 }
8100 let cursor_offset = this.selections.last::<usize>(cx).head();
8101 let mut auto_indent_on_paste = true;
8102
8103 this.buffer.update(cx, |buffer, cx| {
8104 let snapshot = buffer.read(cx);
8105 auto_indent_on_paste =
8106 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8107
8108 let mut start_offset = 0;
8109 let mut edits = Vec::new();
8110 let mut original_indent_columns = Vec::new();
8111 for (ix, selection) in old_selections.iter().enumerate() {
8112 let to_insert;
8113 let entire_line;
8114 let original_indent_column;
8115 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8116 let end_offset = start_offset + clipboard_selection.len;
8117 to_insert = &clipboard_text[start_offset..end_offset];
8118 entire_line = clipboard_selection.is_entire_line;
8119 start_offset = end_offset + 1;
8120 original_indent_column = Some(clipboard_selection.first_line_indent);
8121 } else {
8122 to_insert = clipboard_text.as_str();
8123 entire_line = all_selections_were_entire_line;
8124 original_indent_column = first_selection_indent_column
8125 }
8126
8127 // If the corresponding selection was empty when this slice of the
8128 // clipboard text was written, then the entire line containing the
8129 // selection was copied. If this selection is also currently empty,
8130 // then paste the line before the current line of the buffer.
8131 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8132 let column = selection.start.to_point(&snapshot).column as usize;
8133 let line_start = selection.start - column;
8134 line_start..line_start
8135 } else {
8136 selection.range()
8137 };
8138
8139 edits.push((range, to_insert));
8140 original_indent_columns.extend(original_indent_column);
8141 }
8142 drop(snapshot);
8143
8144 buffer.edit(
8145 edits,
8146 if auto_indent_on_paste {
8147 Some(AutoindentMode::Block {
8148 original_indent_columns,
8149 })
8150 } else {
8151 None
8152 },
8153 cx,
8154 );
8155 });
8156
8157 let selections = this.selections.all::<usize>(cx);
8158 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8159 s.select(selections)
8160 });
8161 } else {
8162 this.insert(&clipboard_text, window, cx);
8163 }
8164 });
8165 }
8166
8167 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8168 if let Some(item) = cx.read_from_clipboard() {
8169 let entries = item.entries();
8170
8171 match entries.first() {
8172 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8173 // of all the pasted entries.
8174 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8175 .do_paste(
8176 clipboard_string.text(),
8177 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8178 true,
8179 window,
8180 cx,
8181 ),
8182 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8183 }
8184 }
8185 }
8186
8187 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8188 if self.read_only(cx) {
8189 return;
8190 }
8191
8192 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8193 if let Some((selections, _)) =
8194 self.selection_history.transaction(transaction_id).cloned()
8195 {
8196 self.change_selections(None, window, cx, |s| {
8197 s.select_anchors(selections.to_vec());
8198 });
8199 }
8200 self.request_autoscroll(Autoscroll::fit(), cx);
8201 self.unmark_text(window, cx);
8202 self.refresh_inline_completion(true, false, window, cx);
8203 cx.emit(EditorEvent::Edited { transaction_id });
8204 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8205 }
8206 }
8207
8208 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8209 if self.read_only(cx) {
8210 return;
8211 }
8212
8213 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8214 if let Some((_, Some(selections))) =
8215 self.selection_history.transaction(transaction_id).cloned()
8216 {
8217 self.change_selections(None, window, cx, |s| {
8218 s.select_anchors(selections.to_vec());
8219 });
8220 }
8221 self.request_autoscroll(Autoscroll::fit(), cx);
8222 self.unmark_text(window, cx);
8223 self.refresh_inline_completion(true, false, window, cx);
8224 cx.emit(EditorEvent::Edited { transaction_id });
8225 }
8226 }
8227
8228 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8229 self.buffer
8230 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8231 }
8232
8233 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8234 self.buffer
8235 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8236 }
8237
8238 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8239 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8240 let line_mode = s.line_mode;
8241 s.move_with(|map, selection| {
8242 let cursor = if selection.is_empty() && !line_mode {
8243 movement::left(map, selection.start)
8244 } else {
8245 selection.start
8246 };
8247 selection.collapse_to(cursor, SelectionGoal::None);
8248 });
8249 })
8250 }
8251
8252 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8253 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8254 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8255 })
8256 }
8257
8258 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8259 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8260 let line_mode = s.line_mode;
8261 s.move_with(|map, selection| {
8262 let cursor = if selection.is_empty() && !line_mode {
8263 movement::right(map, selection.end)
8264 } else {
8265 selection.end
8266 };
8267 selection.collapse_to(cursor, SelectionGoal::None)
8268 });
8269 })
8270 }
8271
8272 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8273 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8274 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8275 })
8276 }
8277
8278 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8279 if self.take_rename(true, window, cx).is_some() {
8280 return;
8281 }
8282
8283 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8284 cx.propagate();
8285 return;
8286 }
8287
8288 let text_layout_details = &self.text_layout_details(window);
8289 let selection_count = self.selections.count();
8290 let first_selection = self.selections.first_anchor();
8291
8292 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8293 let line_mode = s.line_mode;
8294 s.move_with(|map, selection| {
8295 if !selection.is_empty() && !line_mode {
8296 selection.goal = SelectionGoal::None;
8297 }
8298 let (cursor, goal) = movement::up(
8299 map,
8300 selection.start,
8301 selection.goal,
8302 false,
8303 text_layout_details,
8304 );
8305 selection.collapse_to(cursor, goal);
8306 });
8307 });
8308
8309 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8310 {
8311 cx.propagate();
8312 }
8313 }
8314
8315 pub fn move_up_by_lines(
8316 &mut self,
8317 action: &MoveUpByLines,
8318 window: &mut Window,
8319 cx: &mut Context<Self>,
8320 ) {
8321 if self.take_rename(true, window, cx).is_some() {
8322 return;
8323 }
8324
8325 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8326 cx.propagate();
8327 return;
8328 }
8329
8330 let text_layout_details = &self.text_layout_details(window);
8331
8332 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8333 let line_mode = s.line_mode;
8334 s.move_with(|map, selection| {
8335 if !selection.is_empty() && !line_mode {
8336 selection.goal = SelectionGoal::None;
8337 }
8338 let (cursor, goal) = movement::up_by_rows(
8339 map,
8340 selection.start,
8341 action.lines,
8342 selection.goal,
8343 false,
8344 text_layout_details,
8345 );
8346 selection.collapse_to(cursor, goal);
8347 });
8348 })
8349 }
8350
8351 pub fn move_down_by_lines(
8352 &mut self,
8353 action: &MoveDownByLines,
8354 window: &mut Window,
8355 cx: &mut Context<Self>,
8356 ) {
8357 if self.take_rename(true, window, cx).is_some() {
8358 return;
8359 }
8360
8361 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8362 cx.propagate();
8363 return;
8364 }
8365
8366 let text_layout_details = &self.text_layout_details(window);
8367
8368 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8369 let line_mode = s.line_mode;
8370 s.move_with(|map, selection| {
8371 if !selection.is_empty() && !line_mode {
8372 selection.goal = SelectionGoal::None;
8373 }
8374 let (cursor, goal) = movement::down_by_rows(
8375 map,
8376 selection.start,
8377 action.lines,
8378 selection.goal,
8379 false,
8380 text_layout_details,
8381 );
8382 selection.collapse_to(cursor, goal);
8383 });
8384 })
8385 }
8386
8387 pub fn select_down_by_lines(
8388 &mut self,
8389 action: &SelectDownByLines,
8390 window: &mut Window,
8391 cx: &mut Context<Self>,
8392 ) {
8393 let text_layout_details = &self.text_layout_details(window);
8394 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8395 s.move_heads_with(|map, head, goal| {
8396 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8397 })
8398 })
8399 }
8400
8401 pub fn select_up_by_lines(
8402 &mut self,
8403 action: &SelectUpByLines,
8404 window: &mut Window,
8405 cx: &mut Context<Self>,
8406 ) {
8407 let text_layout_details = &self.text_layout_details(window);
8408 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8409 s.move_heads_with(|map, head, goal| {
8410 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8411 })
8412 })
8413 }
8414
8415 pub fn select_page_up(
8416 &mut self,
8417 _: &SelectPageUp,
8418 window: &mut Window,
8419 cx: &mut Context<Self>,
8420 ) {
8421 let Some(row_count) = self.visible_row_count() else {
8422 return;
8423 };
8424
8425 let text_layout_details = &self.text_layout_details(window);
8426
8427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8428 s.move_heads_with(|map, head, goal| {
8429 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8430 })
8431 })
8432 }
8433
8434 pub fn move_page_up(
8435 &mut self,
8436 action: &MovePageUp,
8437 window: &mut Window,
8438 cx: &mut Context<Self>,
8439 ) {
8440 if self.take_rename(true, window, cx).is_some() {
8441 return;
8442 }
8443
8444 if self
8445 .context_menu
8446 .borrow_mut()
8447 .as_mut()
8448 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8449 .unwrap_or(false)
8450 {
8451 return;
8452 }
8453
8454 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8455 cx.propagate();
8456 return;
8457 }
8458
8459 let Some(row_count) = self.visible_row_count() else {
8460 return;
8461 };
8462
8463 let autoscroll = if action.center_cursor {
8464 Autoscroll::center()
8465 } else {
8466 Autoscroll::fit()
8467 };
8468
8469 let text_layout_details = &self.text_layout_details(window);
8470
8471 self.change_selections(Some(autoscroll), window, cx, |s| {
8472 let line_mode = s.line_mode;
8473 s.move_with(|map, selection| {
8474 if !selection.is_empty() && !line_mode {
8475 selection.goal = SelectionGoal::None;
8476 }
8477 let (cursor, goal) = movement::up_by_rows(
8478 map,
8479 selection.end,
8480 row_count,
8481 selection.goal,
8482 false,
8483 text_layout_details,
8484 );
8485 selection.collapse_to(cursor, goal);
8486 });
8487 });
8488 }
8489
8490 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8491 let text_layout_details = &self.text_layout_details(window);
8492 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8493 s.move_heads_with(|map, head, goal| {
8494 movement::up(map, head, goal, false, text_layout_details)
8495 })
8496 })
8497 }
8498
8499 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8500 self.take_rename(true, window, cx);
8501
8502 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8503 cx.propagate();
8504 return;
8505 }
8506
8507 let text_layout_details = &self.text_layout_details(window);
8508 let selection_count = self.selections.count();
8509 let first_selection = self.selections.first_anchor();
8510
8511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8512 let line_mode = s.line_mode;
8513 s.move_with(|map, selection| {
8514 if !selection.is_empty() && !line_mode {
8515 selection.goal = SelectionGoal::None;
8516 }
8517 let (cursor, goal) = movement::down(
8518 map,
8519 selection.end,
8520 selection.goal,
8521 false,
8522 text_layout_details,
8523 );
8524 selection.collapse_to(cursor, goal);
8525 });
8526 });
8527
8528 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8529 {
8530 cx.propagate();
8531 }
8532 }
8533
8534 pub fn select_page_down(
8535 &mut self,
8536 _: &SelectPageDown,
8537 window: &mut Window,
8538 cx: &mut Context<Self>,
8539 ) {
8540 let Some(row_count) = self.visible_row_count() else {
8541 return;
8542 };
8543
8544 let text_layout_details = &self.text_layout_details(window);
8545
8546 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8547 s.move_heads_with(|map, head, goal| {
8548 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8549 })
8550 })
8551 }
8552
8553 pub fn move_page_down(
8554 &mut self,
8555 action: &MovePageDown,
8556 window: &mut Window,
8557 cx: &mut Context<Self>,
8558 ) {
8559 if self.take_rename(true, window, cx).is_some() {
8560 return;
8561 }
8562
8563 if self
8564 .context_menu
8565 .borrow_mut()
8566 .as_mut()
8567 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8568 .unwrap_or(false)
8569 {
8570 return;
8571 }
8572
8573 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8574 cx.propagate();
8575 return;
8576 }
8577
8578 let Some(row_count) = self.visible_row_count() else {
8579 return;
8580 };
8581
8582 let autoscroll = if action.center_cursor {
8583 Autoscroll::center()
8584 } else {
8585 Autoscroll::fit()
8586 };
8587
8588 let text_layout_details = &self.text_layout_details(window);
8589 self.change_selections(Some(autoscroll), window, cx, |s| {
8590 let line_mode = s.line_mode;
8591 s.move_with(|map, selection| {
8592 if !selection.is_empty() && !line_mode {
8593 selection.goal = SelectionGoal::None;
8594 }
8595 let (cursor, goal) = movement::down_by_rows(
8596 map,
8597 selection.end,
8598 row_count,
8599 selection.goal,
8600 false,
8601 text_layout_details,
8602 );
8603 selection.collapse_to(cursor, goal);
8604 });
8605 });
8606 }
8607
8608 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8609 let text_layout_details = &self.text_layout_details(window);
8610 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8611 s.move_heads_with(|map, head, goal| {
8612 movement::down(map, head, goal, false, text_layout_details)
8613 })
8614 });
8615 }
8616
8617 pub fn context_menu_first(
8618 &mut self,
8619 _: &ContextMenuFirst,
8620 _window: &mut Window,
8621 cx: &mut Context<Self>,
8622 ) {
8623 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8624 context_menu.select_first(self.completion_provider.as_deref(), cx);
8625 }
8626 }
8627
8628 pub fn context_menu_prev(
8629 &mut self,
8630 _: &ContextMenuPrev,
8631 _window: &mut Window,
8632 cx: &mut Context<Self>,
8633 ) {
8634 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8635 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8636 }
8637 }
8638
8639 pub fn context_menu_next(
8640 &mut self,
8641 _: &ContextMenuNext,
8642 _window: &mut Window,
8643 cx: &mut Context<Self>,
8644 ) {
8645 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8646 context_menu.select_next(self.completion_provider.as_deref(), cx);
8647 }
8648 }
8649
8650 pub fn context_menu_last(
8651 &mut self,
8652 _: &ContextMenuLast,
8653 _window: &mut Window,
8654 cx: &mut Context<Self>,
8655 ) {
8656 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8657 context_menu.select_last(self.completion_provider.as_deref(), cx);
8658 }
8659 }
8660
8661 pub fn move_to_previous_word_start(
8662 &mut self,
8663 _: &MoveToPreviousWordStart,
8664 window: &mut Window,
8665 cx: &mut Context<Self>,
8666 ) {
8667 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8668 s.move_cursors_with(|map, head, _| {
8669 (
8670 movement::previous_word_start(map, head),
8671 SelectionGoal::None,
8672 )
8673 });
8674 })
8675 }
8676
8677 pub fn move_to_previous_subword_start(
8678 &mut self,
8679 _: &MoveToPreviousSubwordStart,
8680 window: &mut Window,
8681 cx: &mut Context<Self>,
8682 ) {
8683 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8684 s.move_cursors_with(|map, head, _| {
8685 (
8686 movement::previous_subword_start(map, head),
8687 SelectionGoal::None,
8688 )
8689 });
8690 })
8691 }
8692
8693 pub fn select_to_previous_word_start(
8694 &mut self,
8695 _: &SelectToPreviousWordStart,
8696 window: &mut Window,
8697 cx: &mut Context<Self>,
8698 ) {
8699 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8700 s.move_heads_with(|map, head, _| {
8701 (
8702 movement::previous_word_start(map, head),
8703 SelectionGoal::None,
8704 )
8705 });
8706 })
8707 }
8708
8709 pub fn select_to_previous_subword_start(
8710 &mut self,
8711 _: &SelectToPreviousSubwordStart,
8712 window: &mut Window,
8713 cx: &mut Context<Self>,
8714 ) {
8715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8716 s.move_heads_with(|map, head, _| {
8717 (
8718 movement::previous_subword_start(map, head),
8719 SelectionGoal::None,
8720 )
8721 });
8722 })
8723 }
8724
8725 pub fn delete_to_previous_word_start(
8726 &mut self,
8727 action: &DeleteToPreviousWordStart,
8728 window: &mut Window,
8729 cx: &mut Context<Self>,
8730 ) {
8731 self.transact(window, cx, |this, window, cx| {
8732 this.select_autoclose_pair(window, cx);
8733 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8734 let line_mode = s.line_mode;
8735 s.move_with(|map, selection| {
8736 if selection.is_empty() && !line_mode {
8737 let cursor = if action.ignore_newlines {
8738 movement::previous_word_start(map, selection.head())
8739 } else {
8740 movement::previous_word_start_or_newline(map, selection.head())
8741 };
8742 selection.set_head(cursor, SelectionGoal::None);
8743 }
8744 });
8745 });
8746 this.insert("", window, cx);
8747 });
8748 }
8749
8750 pub fn delete_to_previous_subword_start(
8751 &mut self,
8752 _: &DeleteToPreviousSubwordStart,
8753 window: &mut Window,
8754 cx: &mut Context<Self>,
8755 ) {
8756 self.transact(window, cx, |this, window, cx| {
8757 this.select_autoclose_pair(window, cx);
8758 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8759 let line_mode = s.line_mode;
8760 s.move_with(|map, selection| {
8761 if selection.is_empty() && !line_mode {
8762 let cursor = movement::previous_subword_start(map, selection.head());
8763 selection.set_head(cursor, SelectionGoal::None);
8764 }
8765 });
8766 });
8767 this.insert("", window, cx);
8768 });
8769 }
8770
8771 pub fn move_to_next_word_end(
8772 &mut self,
8773 _: &MoveToNextWordEnd,
8774 window: &mut Window,
8775 cx: &mut Context<Self>,
8776 ) {
8777 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8778 s.move_cursors_with(|map, head, _| {
8779 (movement::next_word_end(map, head), SelectionGoal::None)
8780 });
8781 })
8782 }
8783
8784 pub fn move_to_next_subword_end(
8785 &mut self,
8786 _: &MoveToNextSubwordEnd,
8787 window: &mut Window,
8788 cx: &mut Context<Self>,
8789 ) {
8790 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8791 s.move_cursors_with(|map, head, _| {
8792 (movement::next_subword_end(map, head), SelectionGoal::None)
8793 });
8794 })
8795 }
8796
8797 pub fn select_to_next_word_end(
8798 &mut self,
8799 _: &SelectToNextWordEnd,
8800 window: &mut Window,
8801 cx: &mut Context<Self>,
8802 ) {
8803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8804 s.move_heads_with(|map, head, _| {
8805 (movement::next_word_end(map, head), SelectionGoal::None)
8806 });
8807 })
8808 }
8809
8810 pub fn select_to_next_subword_end(
8811 &mut self,
8812 _: &SelectToNextSubwordEnd,
8813 window: &mut Window,
8814 cx: &mut Context<Self>,
8815 ) {
8816 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8817 s.move_heads_with(|map, head, _| {
8818 (movement::next_subword_end(map, head), SelectionGoal::None)
8819 });
8820 })
8821 }
8822
8823 pub fn delete_to_next_word_end(
8824 &mut self,
8825 action: &DeleteToNextWordEnd,
8826 window: &mut Window,
8827 cx: &mut Context<Self>,
8828 ) {
8829 self.transact(window, cx, |this, window, cx| {
8830 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8831 let line_mode = s.line_mode;
8832 s.move_with(|map, selection| {
8833 if selection.is_empty() && !line_mode {
8834 let cursor = if action.ignore_newlines {
8835 movement::next_word_end(map, selection.head())
8836 } else {
8837 movement::next_word_end_or_newline(map, selection.head())
8838 };
8839 selection.set_head(cursor, SelectionGoal::None);
8840 }
8841 });
8842 });
8843 this.insert("", window, cx);
8844 });
8845 }
8846
8847 pub fn delete_to_next_subword_end(
8848 &mut self,
8849 _: &DeleteToNextSubwordEnd,
8850 window: &mut Window,
8851 cx: &mut Context<Self>,
8852 ) {
8853 self.transact(window, cx, |this, window, cx| {
8854 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8855 s.move_with(|map, selection| {
8856 if selection.is_empty() {
8857 let cursor = movement::next_subword_end(map, selection.head());
8858 selection.set_head(cursor, SelectionGoal::None);
8859 }
8860 });
8861 });
8862 this.insert("", window, cx);
8863 });
8864 }
8865
8866 pub fn move_to_beginning_of_line(
8867 &mut self,
8868 action: &MoveToBeginningOfLine,
8869 window: &mut Window,
8870 cx: &mut Context<Self>,
8871 ) {
8872 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8873 s.move_cursors_with(|map, head, _| {
8874 (
8875 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8876 SelectionGoal::None,
8877 )
8878 });
8879 })
8880 }
8881
8882 pub fn select_to_beginning_of_line(
8883 &mut self,
8884 action: &SelectToBeginningOfLine,
8885 window: &mut Window,
8886 cx: &mut Context<Self>,
8887 ) {
8888 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8889 s.move_heads_with(|map, head, _| {
8890 (
8891 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8892 SelectionGoal::None,
8893 )
8894 });
8895 });
8896 }
8897
8898 pub fn delete_to_beginning_of_line(
8899 &mut self,
8900 _: &DeleteToBeginningOfLine,
8901 window: &mut Window,
8902 cx: &mut Context<Self>,
8903 ) {
8904 self.transact(window, cx, |this, window, cx| {
8905 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8906 s.move_with(|_, selection| {
8907 selection.reversed = true;
8908 });
8909 });
8910
8911 this.select_to_beginning_of_line(
8912 &SelectToBeginningOfLine {
8913 stop_at_soft_wraps: false,
8914 },
8915 window,
8916 cx,
8917 );
8918 this.backspace(&Backspace, window, cx);
8919 });
8920 }
8921
8922 pub fn move_to_end_of_line(
8923 &mut self,
8924 action: &MoveToEndOfLine,
8925 window: &mut Window,
8926 cx: &mut Context<Self>,
8927 ) {
8928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8929 s.move_cursors_with(|map, head, _| {
8930 (
8931 movement::line_end(map, head, action.stop_at_soft_wraps),
8932 SelectionGoal::None,
8933 )
8934 });
8935 })
8936 }
8937
8938 pub fn select_to_end_of_line(
8939 &mut self,
8940 action: &SelectToEndOfLine,
8941 window: &mut Window,
8942 cx: &mut Context<Self>,
8943 ) {
8944 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8945 s.move_heads_with(|map, head, _| {
8946 (
8947 movement::line_end(map, head, action.stop_at_soft_wraps),
8948 SelectionGoal::None,
8949 )
8950 });
8951 })
8952 }
8953
8954 pub fn delete_to_end_of_line(
8955 &mut self,
8956 _: &DeleteToEndOfLine,
8957 window: &mut Window,
8958 cx: &mut Context<Self>,
8959 ) {
8960 self.transact(window, cx, |this, window, cx| {
8961 this.select_to_end_of_line(
8962 &SelectToEndOfLine {
8963 stop_at_soft_wraps: false,
8964 },
8965 window,
8966 cx,
8967 );
8968 this.delete(&Delete, window, cx);
8969 });
8970 }
8971
8972 pub fn cut_to_end_of_line(
8973 &mut self,
8974 _: &CutToEndOfLine,
8975 window: &mut Window,
8976 cx: &mut Context<Self>,
8977 ) {
8978 self.transact(window, cx, |this, window, cx| {
8979 this.select_to_end_of_line(
8980 &SelectToEndOfLine {
8981 stop_at_soft_wraps: false,
8982 },
8983 window,
8984 cx,
8985 );
8986 this.cut(&Cut, window, cx);
8987 });
8988 }
8989
8990 pub fn move_to_start_of_paragraph(
8991 &mut self,
8992 _: &MoveToStartOfParagraph,
8993 window: &mut Window,
8994 cx: &mut Context<Self>,
8995 ) {
8996 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8997 cx.propagate();
8998 return;
8999 }
9000
9001 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9002 s.move_with(|map, selection| {
9003 selection.collapse_to(
9004 movement::start_of_paragraph(map, selection.head(), 1),
9005 SelectionGoal::None,
9006 )
9007 });
9008 })
9009 }
9010
9011 pub fn move_to_end_of_paragraph(
9012 &mut self,
9013 _: &MoveToEndOfParagraph,
9014 window: &mut Window,
9015 cx: &mut Context<Self>,
9016 ) {
9017 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9018 cx.propagate();
9019 return;
9020 }
9021
9022 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9023 s.move_with(|map, selection| {
9024 selection.collapse_to(
9025 movement::end_of_paragraph(map, selection.head(), 1),
9026 SelectionGoal::None,
9027 )
9028 });
9029 })
9030 }
9031
9032 pub fn select_to_start_of_paragraph(
9033 &mut self,
9034 _: &SelectToStartOfParagraph,
9035 window: &mut Window,
9036 cx: &mut Context<Self>,
9037 ) {
9038 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9039 cx.propagate();
9040 return;
9041 }
9042
9043 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9044 s.move_heads_with(|map, head, _| {
9045 (
9046 movement::start_of_paragraph(map, head, 1),
9047 SelectionGoal::None,
9048 )
9049 });
9050 })
9051 }
9052
9053 pub fn select_to_end_of_paragraph(
9054 &mut self,
9055 _: &SelectToEndOfParagraph,
9056 window: &mut Window,
9057 cx: &mut Context<Self>,
9058 ) {
9059 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9060 cx.propagate();
9061 return;
9062 }
9063
9064 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9065 s.move_heads_with(|map, head, _| {
9066 (
9067 movement::end_of_paragraph(map, head, 1),
9068 SelectionGoal::None,
9069 )
9070 });
9071 })
9072 }
9073
9074 pub fn move_to_beginning(
9075 &mut self,
9076 _: &MoveToBeginning,
9077 window: &mut Window,
9078 cx: &mut Context<Self>,
9079 ) {
9080 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9081 cx.propagate();
9082 return;
9083 }
9084
9085 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9086 s.select_ranges(vec![0..0]);
9087 });
9088 }
9089
9090 pub fn select_to_beginning(
9091 &mut self,
9092 _: &SelectToBeginning,
9093 window: &mut Window,
9094 cx: &mut Context<Self>,
9095 ) {
9096 let mut selection = self.selections.last::<Point>(cx);
9097 selection.set_head(Point::zero(), SelectionGoal::None);
9098
9099 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9100 s.select(vec![selection]);
9101 });
9102 }
9103
9104 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9105 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9106 cx.propagate();
9107 return;
9108 }
9109
9110 let cursor = self.buffer.read(cx).read(cx).len();
9111 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9112 s.select_ranges(vec![cursor..cursor])
9113 });
9114 }
9115
9116 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9117 self.nav_history = nav_history;
9118 }
9119
9120 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9121 self.nav_history.as_ref()
9122 }
9123
9124 fn push_to_nav_history(
9125 &mut self,
9126 cursor_anchor: Anchor,
9127 new_position: Option<Point>,
9128 cx: &mut Context<Self>,
9129 ) {
9130 if let Some(nav_history) = self.nav_history.as_mut() {
9131 let buffer = self.buffer.read(cx).read(cx);
9132 let cursor_position = cursor_anchor.to_point(&buffer);
9133 let scroll_state = self.scroll_manager.anchor();
9134 let scroll_top_row = scroll_state.top_row(&buffer);
9135 drop(buffer);
9136
9137 if let Some(new_position) = new_position {
9138 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9139 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9140 return;
9141 }
9142 }
9143
9144 nav_history.push(
9145 Some(NavigationData {
9146 cursor_anchor,
9147 cursor_position,
9148 scroll_anchor: scroll_state,
9149 scroll_top_row,
9150 }),
9151 cx,
9152 );
9153 }
9154 }
9155
9156 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9157 let buffer = self.buffer.read(cx).snapshot(cx);
9158 let mut selection = self.selections.first::<usize>(cx);
9159 selection.set_head(buffer.len(), SelectionGoal::None);
9160 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9161 s.select(vec![selection]);
9162 });
9163 }
9164
9165 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9166 let end = self.buffer.read(cx).read(cx).len();
9167 self.change_selections(None, window, cx, |s| {
9168 s.select_ranges(vec![0..end]);
9169 });
9170 }
9171
9172 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9174 let mut selections = self.selections.all::<Point>(cx);
9175 let max_point = display_map.buffer_snapshot.max_point();
9176 for selection in &mut selections {
9177 let rows = selection.spanned_rows(true, &display_map);
9178 selection.start = Point::new(rows.start.0, 0);
9179 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9180 selection.reversed = false;
9181 }
9182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9183 s.select(selections);
9184 });
9185 }
9186
9187 pub fn split_selection_into_lines(
9188 &mut self,
9189 _: &SplitSelectionIntoLines,
9190 window: &mut Window,
9191 cx: &mut Context<Self>,
9192 ) {
9193 let selections = self
9194 .selections
9195 .all::<Point>(cx)
9196 .into_iter()
9197 .map(|selection| selection.start..selection.end)
9198 .collect::<Vec<_>>();
9199 self.unfold_ranges(&selections, true, true, cx);
9200
9201 let mut new_selection_ranges = Vec::new();
9202 {
9203 let buffer = self.buffer.read(cx).read(cx);
9204 for selection in selections {
9205 for row in selection.start.row..selection.end.row {
9206 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9207 new_selection_ranges.push(cursor..cursor);
9208 }
9209
9210 let is_multiline_selection = selection.start.row != selection.end.row;
9211 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9212 // so this action feels more ergonomic when paired with other selection operations
9213 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9214 if !should_skip_last {
9215 new_selection_ranges.push(selection.end..selection.end);
9216 }
9217 }
9218 }
9219 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9220 s.select_ranges(new_selection_ranges);
9221 });
9222 }
9223
9224 pub fn add_selection_above(
9225 &mut self,
9226 _: &AddSelectionAbove,
9227 window: &mut Window,
9228 cx: &mut Context<Self>,
9229 ) {
9230 self.add_selection(true, window, cx);
9231 }
9232
9233 pub fn add_selection_below(
9234 &mut self,
9235 _: &AddSelectionBelow,
9236 window: &mut Window,
9237 cx: &mut Context<Self>,
9238 ) {
9239 self.add_selection(false, window, cx);
9240 }
9241
9242 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9243 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9244 let mut selections = self.selections.all::<Point>(cx);
9245 let text_layout_details = self.text_layout_details(window);
9246 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9247 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9248 let range = oldest_selection.display_range(&display_map).sorted();
9249
9250 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9251 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9252 let positions = start_x.min(end_x)..start_x.max(end_x);
9253
9254 selections.clear();
9255 let mut stack = Vec::new();
9256 for row in range.start.row().0..=range.end.row().0 {
9257 if let Some(selection) = self.selections.build_columnar_selection(
9258 &display_map,
9259 DisplayRow(row),
9260 &positions,
9261 oldest_selection.reversed,
9262 &text_layout_details,
9263 ) {
9264 stack.push(selection.id);
9265 selections.push(selection);
9266 }
9267 }
9268
9269 if above {
9270 stack.reverse();
9271 }
9272
9273 AddSelectionsState { above, stack }
9274 });
9275
9276 let last_added_selection = *state.stack.last().unwrap();
9277 let mut new_selections = Vec::new();
9278 if above == state.above {
9279 let end_row = if above {
9280 DisplayRow(0)
9281 } else {
9282 display_map.max_point().row()
9283 };
9284
9285 'outer: for selection in selections {
9286 if selection.id == last_added_selection {
9287 let range = selection.display_range(&display_map).sorted();
9288 debug_assert_eq!(range.start.row(), range.end.row());
9289 let mut row = range.start.row();
9290 let positions =
9291 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9292 px(start)..px(end)
9293 } else {
9294 let start_x =
9295 display_map.x_for_display_point(range.start, &text_layout_details);
9296 let end_x =
9297 display_map.x_for_display_point(range.end, &text_layout_details);
9298 start_x.min(end_x)..start_x.max(end_x)
9299 };
9300
9301 while row != end_row {
9302 if above {
9303 row.0 -= 1;
9304 } else {
9305 row.0 += 1;
9306 }
9307
9308 if let Some(new_selection) = self.selections.build_columnar_selection(
9309 &display_map,
9310 row,
9311 &positions,
9312 selection.reversed,
9313 &text_layout_details,
9314 ) {
9315 state.stack.push(new_selection.id);
9316 if above {
9317 new_selections.push(new_selection);
9318 new_selections.push(selection);
9319 } else {
9320 new_selections.push(selection);
9321 new_selections.push(new_selection);
9322 }
9323
9324 continue 'outer;
9325 }
9326 }
9327 }
9328
9329 new_selections.push(selection);
9330 }
9331 } else {
9332 new_selections = selections;
9333 new_selections.retain(|s| s.id != last_added_selection);
9334 state.stack.pop();
9335 }
9336
9337 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9338 s.select(new_selections);
9339 });
9340 if state.stack.len() > 1 {
9341 self.add_selections_state = Some(state);
9342 }
9343 }
9344
9345 pub fn select_next_match_internal(
9346 &mut self,
9347 display_map: &DisplaySnapshot,
9348 replace_newest: bool,
9349 autoscroll: Option<Autoscroll>,
9350 window: &mut Window,
9351 cx: &mut Context<Self>,
9352 ) -> Result<()> {
9353 fn select_next_match_ranges(
9354 this: &mut Editor,
9355 range: Range<usize>,
9356 replace_newest: bool,
9357 auto_scroll: Option<Autoscroll>,
9358 window: &mut Window,
9359 cx: &mut Context<Editor>,
9360 ) {
9361 this.unfold_ranges(&[range.clone()], false, true, cx);
9362 this.change_selections(auto_scroll, window, cx, |s| {
9363 if replace_newest {
9364 s.delete(s.newest_anchor().id);
9365 }
9366 s.insert_range(range.clone());
9367 });
9368 }
9369
9370 let buffer = &display_map.buffer_snapshot;
9371 let mut selections = self.selections.all::<usize>(cx);
9372 if let Some(mut select_next_state) = self.select_next_state.take() {
9373 let query = &select_next_state.query;
9374 if !select_next_state.done {
9375 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9376 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9377 let mut next_selected_range = None;
9378
9379 let bytes_after_last_selection =
9380 buffer.bytes_in_range(last_selection.end..buffer.len());
9381 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9382 let query_matches = query
9383 .stream_find_iter(bytes_after_last_selection)
9384 .map(|result| (last_selection.end, result))
9385 .chain(
9386 query
9387 .stream_find_iter(bytes_before_first_selection)
9388 .map(|result| (0, result)),
9389 );
9390
9391 for (start_offset, query_match) in query_matches {
9392 let query_match = query_match.unwrap(); // can only fail due to I/O
9393 let offset_range =
9394 start_offset + query_match.start()..start_offset + query_match.end();
9395 let display_range = offset_range.start.to_display_point(display_map)
9396 ..offset_range.end.to_display_point(display_map);
9397
9398 if !select_next_state.wordwise
9399 || (!movement::is_inside_word(display_map, display_range.start)
9400 && !movement::is_inside_word(display_map, display_range.end))
9401 {
9402 // TODO: This is n^2, because we might check all the selections
9403 if !selections
9404 .iter()
9405 .any(|selection| selection.range().overlaps(&offset_range))
9406 {
9407 next_selected_range = Some(offset_range);
9408 break;
9409 }
9410 }
9411 }
9412
9413 if let Some(next_selected_range) = next_selected_range {
9414 select_next_match_ranges(
9415 self,
9416 next_selected_range,
9417 replace_newest,
9418 autoscroll,
9419 window,
9420 cx,
9421 );
9422 } else {
9423 select_next_state.done = true;
9424 }
9425 }
9426
9427 self.select_next_state = Some(select_next_state);
9428 } else {
9429 let mut only_carets = true;
9430 let mut same_text_selected = true;
9431 let mut selected_text = None;
9432
9433 let mut selections_iter = selections.iter().peekable();
9434 while let Some(selection) = selections_iter.next() {
9435 if selection.start != selection.end {
9436 only_carets = false;
9437 }
9438
9439 if same_text_selected {
9440 if selected_text.is_none() {
9441 selected_text =
9442 Some(buffer.text_for_range(selection.range()).collect::<String>());
9443 }
9444
9445 if let Some(next_selection) = selections_iter.peek() {
9446 if next_selection.range().len() == selection.range().len() {
9447 let next_selected_text = buffer
9448 .text_for_range(next_selection.range())
9449 .collect::<String>();
9450 if Some(next_selected_text) != selected_text {
9451 same_text_selected = false;
9452 selected_text = None;
9453 }
9454 } else {
9455 same_text_selected = false;
9456 selected_text = None;
9457 }
9458 }
9459 }
9460 }
9461
9462 if only_carets {
9463 for selection in &mut selections {
9464 let word_range = movement::surrounding_word(
9465 display_map,
9466 selection.start.to_display_point(display_map),
9467 );
9468 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9469 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9470 selection.goal = SelectionGoal::None;
9471 selection.reversed = false;
9472 select_next_match_ranges(
9473 self,
9474 selection.start..selection.end,
9475 replace_newest,
9476 autoscroll,
9477 window,
9478 cx,
9479 );
9480 }
9481
9482 if selections.len() == 1 {
9483 let selection = selections
9484 .last()
9485 .expect("ensured that there's only one selection");
9486 let query = buffer
9487 .text_for_range(selection.start..selection.end)
9488 .collect::<String>();
9489 let is_empty = query.is_empty();
9490 let select_state = SelectNextState {
9491 query: AhoCorasick::new(&[query])?,
9492 wordwise: true,
9493 done: is_empty,
9494 };
9495 self.select_next_state = Some(select_state);
9496 } else {
9497 self.select_next_state = None;
9498 }
9499 } else if let Some(selected_text) = selected_text {
9500 self.select_next_state = Some(SelectNextState {
9501 query: AhoCorasick::new(&[selected_text])?,
9502 wordwise: false,
9503 done: false,
9504 });
9505 self.select_next_match_internal(
9506 display_map,
9507 replace_newest,
9508 autoscroll,
9509 window,
9510 cx,
9511 )?;
9512 }
9513 }
9514 Ok(())
9515 }
9516
9517 pub fn select_all_matches(
9518 &mut self,
9519 _action: &SelectAllMatches,
9520 window: &mut Window,
9521 cx: &mut Context<Self>,
9522 ) -> Result<()> {
9523 self.push_to_selection_history();
9524 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9525
9526 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9527 let Some(select_next_state) = self.select_next_state.as_mut() else {
9528 return Ok(());
9529 };
9530 if select_next_state.done {
9531 return Ok(());
9532 }
9533
9534 let mut new_selections = self.selections.all::<usize>(cx);
9535
9536 let buffer = &display_map.buffer_snapshot;
9537 let query_matches = select_next_state
9538 .query
9539 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9540
9541 for query_match in query_matches {
9542 let query_match = query_match.unwrap(); // can only fail due to I/O
9543 let offset_range = query_match.start()..query_match.end();
9544 let display_range = offset_range.start.to_display_point(&display_map)
9545 ..offset_range.end.to_display_point(&display_map);
9546
9547 if !select_next_state.wordwise
9548 || (!movement::is_inside_word(&display_map, display_range.start)
9549 && !movement::is_inside_word(&display_map, display_range.end))
9550 {
9551 self.selections.change_with(cx, |selections| {
9552 new_selections.push(Selection {
9553 id: selections.new_selection_id(),
9554 start: offset_range.start,
9555 end: offset_range.end,
9556 reversed: false,
9557 goal: SelectionGoal::None,
9558 });
9559 });
9560 }
9561 }
9562
9563 new_selections.sort_by_key(|selection| selection.start);
9564 let mut ix = 0;
9565 while ix + 1 < new_selections.len() {
9566 let current_selection = &new_selections[ix];
9567 let next_selection = &new_selections[ix + 1];
9568 if current_selection.range().overlaps(&next_selection.range()) {
9569 if current_selection.id < next_selection.id {
9570 new_selections.remove(ix + 1);
9571 } else {
9572 new_selections.remove(ix);
9573 }
9574 } else {
9575 ix += 1;
9576 }
9577 }
9578
9579 let reversed = self.selections.oldest::<usize>(cx).reversed;
9580
9581 for selection in new_selections.iter_mut() {
9582 selection.reversed = reversed;
9583 }
9584
9585 select_next_state.done = true;
9586 self.unfold_ranges(
9587 &new_selections
9588 .iter()
9589 .map(|selection| selection.range())
9590 .collect::<Vec<_>>(),
9591 false,
9592 false,
9593 cx,
9594 );
9595 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9596 selections.select(new_selections)
9597 });
9598
9599 Ok(())
9600 }
9601
9602 pub fn select_next(
9603 &mut self,
9604 action: &SelectNext,
9605 window: &mut Window,
9606 cx: &mut Context<Self>,
9607 ) -> Result<()> {
9608 self.push_to_selection_history();
9609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9610 self.select_next_match_internal(
9611 &display_map,
9612 action.replace_newest,
9613 Some(Autoscroll::newest()),
9614 window,
9615 cx,
9616 )?;
9617 Ok(())
9618 }
9619
9620 pub fn select_previous(
9621 &mut self,
9622 action: &SelectPrevious,
9623 window: &mut Window,
9624 cx: &mut Context<Self>,
9625 ) -> Result<()> {
9626 self.push_to_selection_history();
9627 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9628 let buffer = &display_map.buffer_snapshot;
9629 let mut selections = self.selections.all::<usize>(cx);
9630 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9631 let query = &select_prev_state.query;
9632 if !select_prev_state.done {
9633 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9634 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9635 let mut next_selected_range = None;
9636 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9637 let bytes_before_last_selection =
9638 buffer.reversed_bytes_in_range(0..last_selection.start);
9639 let bytes_after_first_selection =
9640 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9641 let query_matches = query
9642 .stream_find_iter(bytes_before_last_selection)
9643 .map(|result| (last_selection.start, result))
9644 .chain(
9645 query
9646 .stream_find_iter(bytes_after_first_selection)
9647 .map(|result| (buffer.len(), result)),
9648 );
9649 for (end_offset, query_match) in query_matches {
9650 let query_match = query_match.unwrap(); // can only fail due to I/O
9651 let offset_range =
9652 end_offset - query_match.end()..end_offset - query_match.start();
9653 let display_range = offset_range.start.to_display_point(&display_map)
9654 ..offset_range.end.to_display_point(&display_map);
9655
9656 if !select_prev_state.wordwise
9657 || (!movement::is_inside_word(&display_map, display_range.start)
9658 && !movement::is_inside_word(&display_map, display_range.end))
9659 {
9660 next_selected_range = Some(offset_range);
9661 break;
9662 }
9663 }
9664
9665 if let Some(next_selected_range) = next_selected_range {
9666 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9667 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9668 if action.replace_newest {
9669 s.delete(s.newest_anchor().id);
9670 }
9671 s.insert_range(next_selected_range);
9672 });
9673 } else {
9674 select_prev_state.done = true;
9675 }
9676 }
9677
9678 self.select_prev_state = Some(select_prev_state);
9679 } else {
9680 let mut only_carets = true;
9681 let mut same_text_selected = true;
9682 let mut selected_text = None;
9683
9684 let mut selections_iter = selections.iter().peekable();
9685 while let Some(selection) = selections_iter.next() {
9686 if selection.start != selection.end {
9687 only_carets = false;
9688 }
9689
9690 if same_text_selected {
9691 if selected_text.is_none() {
9692 selected_text =
9693 Some(buffer.text_for_range(selection.range()).collect::<String>());
9694 }
9695
9696 if let Some(next_selection) = selections_iter.peek() {
9697 if next_selection.range().len() == selection.range().len() {
9698 let next_selected_text = buffer
9699 .text_for_range(next_selection.range())
9700 .collect::<String>();
9701 if Some(next_selected_text) != selected_text {
9702 same_text_selected = false;
9703 selected_text = None;
9704 }
9705 } else {
9706 same_text_selected = false;
9707 selected_text = None;
9708 }
9709 }
9710 }
9711 }
9712
9713 if only_carets {
9714 for selection in &mut selections {
9715 let word_range = movement::surrounding_word(
9716 &display_map,
9717 selection.start.to_display_point(&display_map),
9718 );
9719 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9720 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9721 selection.goal = SelectionGoal::None;
9722 selection.reversed = false;
9723 }
9724 if selections.len() == 1 {
9725 let selection = selections
9726 .last()
9727 .expect("ensured that there's only one selection");
9728 let query = buffer
9729 .text_for_range(selection.start..selection.end)
9730 .collect::<String>();
9731 let is_empty = query.is_empty();
9732 let select_state = SelectNextState {
9733 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9734 wordwise: true,
9735 done: is_empty,
9736 };
9737 self.select_prev_state = Some(select_state);
9738 } else {
9739 self.select_prev_state = None;
9740 }
9741
9742 self.unfold_ranges(
9743 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9744 false,
9745 true,
9746 cx,
9747 );
9748 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9749 s.select(selections);
9750 });
9751 } else if let Some(selected_text) = selected_text {
9752 self.select_prev_state = Some(SelectNextState {
9753 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9754 wordwise: false,
9755 done: false,
9756 });
9757 self.select_previous(action, window, cx)?;
9758 }
9759 }
9760 Ok(())
9761 }
9762
9763 pub fn toggle_comments(
9764 &mut self,
9765 action: &ToggleComments,
9766 window: &mut Window,
9767 cx: &mut Context<Self>,
9768 ) {
9769 if self.read_only(cx) {
9770 return;
9771 }
9772 let text_layout_details = &self.text_layout_details(window);
9773 self.transact(window, cx, |this, window, cx| {
9774 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9775 let mut edits = Vec::new();
9776 let mut selection_edit_ranges = Vec::new();
9777 let mut last_toggled_row = None;
9778 let snapshot = this.buffer.read(cx).read(cx);
9779 let empty_str: Arc<str> = Arc::default();
9780 let mut suffixes_inserted = Vec::new();
9781 let ignore_indent = action.ignore_indent;
9782
9783 fn comment_prefix_range(
9784 snapshot: &MultiBufferSnapshot,
9785 row: MultiBufferRow,
9786 comment_prefix: &str,
9787 comment_prefix_whitespace: &str,
9788 ignore_indent: bool,
9789 ) -> Range<Point> {
9790 let indent_size = if ignore_indent {
9791 0
9792 } else {
9793 snapshot.indent_size_for_line(row).len
9794 };
9795
9796 let start = Point::new(row.0, indent_size);
9797
9798 let mut line_bytes = snapshot
9799 .bytes_in_range(start..snapshot.max_point())
9800 .flatten()
9801 .copied();
9802
9803 // If this line currently begins with the line comment prefix, then record
9804 // the range containing the prefix.
9805 if line_bytes
9806 .by_ref()
9807 .take(comment_prefix.len())
9808 .eq(comment_prefix.bytes())
9809 {
9810 // Include any whitespace that matches the comment prefix.
9811 let matching_whitespace_len = line_bytes
9812 .zip(comment_prefix_whitespace.bytes())
9813 .take_while(|(a, b)| a == b)
9814 .count() as u32;
9815 let end = Point::new(
9816 start.row,
9817 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9818 );
9819 start..end
9820 } else {
9821 start..start
9822 }
9823 }
9824
9825 fn comment_suffix_range(
9826 snapshot: &MultiBufferSnapshot,
9827 row: MultiBufferRow,
9828 comment_suffix: &str,
9829 comment_suffix_has_leading_space: bool,
9830 ) -> Range<Point> {
9831 let end = Point::new(row.0, snapshot.line_len(row));
9832 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9833
9834 let mut line_end_bytes = snapshot
9835 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9836 .flatten()
9837 .copied();
9838
9839 let leading_space_len = if suffix_start_column > 0
9840 && line_end_bytes.next() == Some(b' ')
9841 && comment_suffix_has_leading_space
9842 {
9843 1
9844 } else {
9845 0
9846 };
9847
9848 // If this line currently begins with the line comment prefix, then record
9849 // the range containing the prefix.
9850 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9851 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9852 start..end
9853 } else {
9854 end..end
9855 }
9856 }
9857
9858 // TODO: Handle selections that cross excerpts
9859 for selection in &mut selections {
9860 let start_column = snapshot
9861 .indent_size_for_line(MultiBufferRow(selection.start.row))
9862 .len;
9863 let language = if let Some(language) =
9864 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9865 {
9866 language
9867 } else {
9868 continue;
9869 };
9870
9871 selection_edit_ranges.clear();
9872
9873 // If multiple selections contain a given row, avoid processing that
9874 // row more than once.
9875 let mut start_row = MultiBufferRow(selection.start.row);
9876 if last_toggled_row == Some(start_row) {
9877 start_row = start_row.next_row();
9878 }
9879 let end_row =
9880 if selection.end.row > selection.start.row && selection.end.column == 0 {
9881 MultiBufferRow(selection.end.row - 1)
9882 } else {
9883 MultiBufferRow(selection.end.row)
9884 };
9885 last_toggled_row = Some(end_row);
9886
9887 if start_row > end_row {
9888 continue;
9889 }
9890
9891 // If the language has line comments, toggle those.
9892 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9893
9894 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9895 if ignore_indent {
9896 full_comment_prefixes = full_comment_prefixes
9897 .into_iter()
9898 .map(|s| Arc::from(s.trim_end()))
9899 .collect();
9900 }
9901
9902 if !full_comment_prefixes.is_empty() {
9903 let first_prefix = full_comment_prefixes
9904 .first()
9905 .expect("prefixes is non-empty");
9906 let prefix_trimmed_lengths = full_comment_prefixes
9907 .iter()
9908 .map(|p| p.trim_end_matches(' ').len())
9909 .collect::<SmallVec<[usize; 4]>>();
9910
9911 let mut all_selection_lines_are_comments = true;
9912
9913 for row in start_row.0..=end_row.0 {
9914 let row = MultiBufferRow(row);
9915 if start_row < end_row && snapshot.is_line_blank(row) {
9916 continue;
9917 }
9918
9919 let prefix_range = full_comment_prefixes
9920 .iter()
9921 .zip(prefix_trimmed_lengths.iter().copied())
9922 .map(|(prefix, trimmed_prefix_len)| {
9923 comment_prefix_range(
9924 snapshot.deref(),
9925 row,
9926 &prefix[..trimmed_prefix_len],
9927 &prefix[trimmed_prefix_len..],
9928 ignore_indent,
9929 )
9930 })
9931 .max_by_key(|range| range.end.column - range.start.column)
9932 .expect("prefixes is non-empty");
9933
9934 if prefix_range.is_empty() {
9935 all_selection_lines_are_comments = false;
9936 }
9937
9938 selection_edit_ranges.push(prefix_range);
9939 }
9940
9941 if all_selection_lines_are_comments {
9942 edits.extend(
9943 selection_edit_ranges
9944 .iter()
9945 .cloned()
9946 .map(|range| (range, empty_str.clone())),
9947 );
9948 } else {
9949 let min_column = selection_edit_ranges
9950 .iter()
9951 .map(|range| range.start.column)
9952 .min()
9953 .unwrap_or(0);
9954 edits.extend(selection_edit_ranges.iter().map(|range| {
9955 let position = Point::new(range.start.row, min_column);
9956 (position..position, first_prefix.clone())
9957 }));
9958 }
9959 } else if let Some((full_comment_prefix, comment_suffix)) =
9960 language.block_comment_delimiters()
9961 {
9962 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9963 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9964 let prefix_range = comment_prefix_range(
9965 snapshot.deref(),
9966 start_row,
9967 comment_prefix,
9968 comment_prefix_whitespace,
9969 ignore_indent,
9970 );
9971 let suffix_range = comment_suffix_range(
9972 snapshot.deref(),
9973 end_row,
9974 comment_suffix.trim_start_matches(' '),
9975 comment_suffix.starts_with(' '),
9976 );
9977
9978 if prefix_range.is_empty() || suffix_range.is_empty() {
9979 edits.push((
9980 prefix_range.start..prefix_range.start,
9981 full_comment_prefix.clone(),
9982 ));
9983 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9984 suffixes_inserted.push((end_row, comment_suffix.len()));
9985 } else {
9986 edits.push((prefix_range, empty_str.clone()));
9987 edits.push((suffix_range, empty_str.clone()));
9988 }
9989 } else {
9990 continue;
9991 }
9992 }
9993
9994 drop(snapshot);
9995 this.buffer.update(cx, |buffer, cx| {
9996 buffer.edit(edits, None, cx);
9997 });
9998
9999 // Adjust selections so that they end before any comment suffixes that
10000 // were inserted.
10001 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10002 let mut selections = this.selections.all::<Point>(cx);
10003 let snapshot = this.buffer.read(cx).read(cx);
10004 for selection in &mut selections {
10005 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10006 match row.cmp(&MultiBufferRow(selection.end.row)) {
10007 Ordering::Less => {
10008 suffixes_inserted.next();
10009 continue;
10010 }
10011 Ordering::Greater => break,
10012 Ordering::Equal => {
10013 if selection.end.column == snapshot.line_len(row) {
10014 if selection.is_empty() {
10015 selection.start.column -= suffix_len as u32;
10016 }
10017 selection.end.column -= suffix_len as u32;
10018 }
10019 break;
10020 }
10021 }
10022 }
10023 }
10024
10025 drop(snapshot);
10026 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10027 s.select(selections)
10028 });
10029
10030 let selections = this.selections.all::<Point>(cx);
10031 let selections_on_single_row = selections.windows(2).all(|selections| {
10032 selections[0].start.row == selections[1].start.row
10033 && selections[0].end.row == selections[1].end.row
10034 && selections[0].start.row == selections[0].end.row
10035 });
10036 let selections_selecting = selections
10037 .iter()
10038 .any(|selection| selection.start != selection.end);
10039 let advance_downwards = action.advance_downwards
10040 && selections_on_single_row
10041 && !selections_selecting
10042 && !matches!(this.mode, EditorMode::SingleLine { .. });
10043
10044 if advance_downwards {
10045 let snapshot = this.buffer.read(cx).snapshot(cx);
10046
10047 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10048 s.move_cursors_with(|display_snapshot, display_point, _| {
10049 let mut point = display_point.to_point(display_snapshot);
10050 point.row += 1;
10051 point = snapshot.clip_point(point, Bias::Left);
10052 let display_point = point.to_display_point(display_snapshot);
10053 let goal = SelectionGoal::HorizontalPosition(
10054 display_snapshot
10055 .x_for_display_point(display_point, text_layout_details)
10056 .into(),
10057 );
10058 (display_point, goal)
10059 })
10060 });
10061 }
10062 });
10063 }
10064
10065 pub fn select_enclosing_symbol(
10066 &mut self,
10067 _: &SelectEnclosingSymbol,
10068 window: &mut Window,
10069 cx: &mut Context<Self>,
10070 ) {
10071 let buffer = self.buffer.read(cx).snapshot(cx);
10072 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10073
10074 fn update_selection(
10075 selection: &Selection<usize>,
10076 buffer_snap: &MultiBufferSnapshot,
10077 ) -> Option<Selection<usize>> {
10078 let cursor = selection.head();
10079 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10080 for symbol in symbols.iter().rev() {
10081 let start = symbol.range.start.to_offset(buffer_snap);
10082 let end = symbol.range.end.to_offset(buffer_snap);
10083 let new_range = start..end;
10084 if start < selection.start || end > selection.end {
10085 return Some(Selection {
10086 id: selection.id,
10087 start: new_range.start,
10088 end: new_range.end,
10089 goal: SelectionGoal::None,
10090 reversed: selection.reversed,
10091 });
10092 }
10093 }
10094 None
10095 }
10096
10097 let mut selected_larger_symbol = false;
10098 let new_selections = old_selections
10099 .iter()
10100 .map(|selection| match update_selection(selection, &buffer) {
10101 Some(new_selection) => {
10102 if new_selection.range() != selection.range() {
10103 selected_larger_symbol = true;
10104 }
10105 new_selection
10106 }
10107 None => selection.clone(),
10108 })
10109 .collect::<Vec<_>>();
10110
10111 if selected_larger_symbol {
10112 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10113 s.select(new_selections);
10114 });
10115 }
10116 }
10117
10118 pub fn select_larger_syntax_node(
10119 &mut self,
10120 _: &SelectLargerSyntaxNode,
10121 window: &mut Window,
10122 cx: &mut Context<Self>,
10123 ) {
10124 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10125 let buffer = self.buffer.read(cx).snapshot(cx);
10126 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10127
10128 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10129 let mut selected_larger_node = false;
10130 let new_selections = old_selections
10131 .iter()
10132 .map(|selection| {
10133 let old_range = selection.start..selection.end;
10134 let mut new_range = old_range.clone();
10135 let mut new_node = None;
10136 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10137 {
10138 new_node = Some(node);
10139 new_range = containing_range;
10140 if !display_map.intersects_fold(new_range.start)
10141 && !display_map.intersects_fold(new_range.end)
10142 {
10143 break;
10144 }
10145 }
10146
10147 if let Some(node) = new_node {
10148 // Log the ancestor, to support using this action as a way to explore TreeSitter
10149 // nodes. Parent and grandparent are also logged because this operation will not
10150 // visit nodes that have the same range as their parent.
10151 log::info!("Node: {node:?}");
10152 let parent = node.parent();
10153 log::info!("Parent: {parent:?}");
10154 let grandparent = parent.and_then(|x| x.parent());
10155 log::info!("Grandparent: {grandparent:?}");
10156 }
10157
10158 selected_larger_node |= new_range != old_range;
10159 Selection {
10160 id: selection.id,
10161 start: new_range.start,
10162 end: new_range.end,
10163 goal: SelectionGoal::None,
10164 reversed: selection.reversed,
10165 }
10166 })
10167 .collect::<Vec<_>>();
10168
10169 if selected_larger_node {
10170 stack.push(old_selections);
10171 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10172 s.select(new_selections);
10173 });
10174 }
10175 self.select_larger_syntax_node_stack = stack;
10176 }
10177
10178 pub fn select_smaller_syntax_node(
10179 &mut self,
10180 _: &SelectSmallerSyntaxNode,
10181 window: &mut Window,
10182 cx: &mut Context<Self>,
10183 ) {
10184 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10185 if let Some(selections) = stack.pop() {
10186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10187 s.select(selections.to_vec());
10188 });
10189 }
10190 self.select_larger_syntax_node_stack = stack;
10191 }
10192
10193 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10194 if !EditorSettings::get_global(cx).gutter.runnables {
10195 self.clear_tasks();
10196 return Task::ready(());
10197 }
10198 let project = self.project.as_ref().map(Entity::downgrade);
10199 cx.spawn_in(window, |this, mut cx| async move {
10200 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10201 let Some(project) = project.and_then(|p| p.upgrade()) else {
10202 return;
10203 };
10204 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10205 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10206 }) else {
10207 return;
10208 };
10209
10210 let hide_runnables = project
10211 .update(&mut cx, |project, cx| {
10212 // Do not display any test indicators in non-dev server remote projects.
10213 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10214 })
10215 .unwrap_or(true);
10216 if hide_runnables {
10217 return;
10218 }
10219 let new_rows =
10220 cx.background_spawn({
10221 let snapshot = display_snapshot.clone();
10222 async move {
10223 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10224 }
10225 })
10226 .await;
10227
10228 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10229 this.update(&mut cx, |this, _| {
10230 this.clear_tasks();
10231 for (key, value) in rows {
10232 this.insert_tasks(key, value);
10233 }
10234 })
10235 .ok();
10236 })
10237 }
10238 fn fetch_runnable_ranges(
10239 snapshot: &DisplaySnapshot,
10240 range: Range<Anchor>,
10241 ) -> Vec<language::RunnableRange> {
10242 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10243 }
10244
10245 fn runnable_rows(
10246 project: Entity<Project>,
10247 snapshot: DisplaySnapshot,
10248 runnable_ranges: Vec<RunnableRange>,
10249 mut cx: AsyncWindowContext,
10250 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10251 runnable_ranges
10252 .into_iter()
10253 .filter_map(|mut runnable| {
10254 let tasks = cx
10255 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10256 .ok()?;
10257 if tasks.is_empty() {
10258 return None;
10259 }
10260
10261 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10262
10263 let row = snapshot
10264 .buffer_snapshot
10265 .buffer_line_for_row(MultiBufferRow(point.row))?
10266 .1
10267 .start
10268 .row;
10269
10270 let context_range =
10271 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10272 Some((
10273 (runnable.buffer_id, row),
10274 RunnableTasks {
10275 templates: tasks,
10276 offset: MultiBufferOffset(runnable.run_range.start),
10277 context_range,
10278 column: point.column,
10279 extra_variables: runnable.extra_captures,
10280 },
10281 ))
10282 })
10283 .collect()
10284 }
10285
10286 fn templates_with_tags(
10287 project: &Entity<Project>,
10288 runnable: &mut Runnable,
10289 cx: &mut App,
10290 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10291 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10292 let (worktree_id, file) = project
10293 .buffer_for_id(runnable.buffer, cx)
10294 .and_then(|buffer| buffer.read(cx).file())
10295 .map(|file| (file.worktree_id(cx), file.clone()))
10296 .unzip();
10297
10298 (
10299 project.task_store().read(cx).task_inventory().cloned(),
10300 worktree_id,
10301 file,
10302 )
10303 });
10304
10305 let tags = mem::take(&mut runnable.tags);
10306 let mut tags: Vec<_> = tags
10307 .into_iter()
10308 .flat_map(|tag| {
10309 let tag = tag.0.clone();
10310 inventory
10311 .as_ref()
10312 .into_iter()
10313 .flat_map(|inventory| {
10314 inventory.read(cx).list_tasks(
10315 file.clone(),
10316 Some(runnable.language.clone()),
10317 worktree_id,
10318 cx,
10319 )
10320 })
10321 .filter(move |(_, template)| {
10322 template.tags.iter().any(|source_tag| source_tag == &tag)
10323 })
10324 })
10325 .sorted_by_key(|(kind, _)| kind.to_owned())
10326 .collect();
10327 if let Some((leading_tag_source, _)) = tags.first() {
10328 // Strongest source wins; if we have worktree tag binding, prefer that to
10329 // global and language bindings;
10330 // if we have a global binding, prefer that to language binding.
10331 let first_mismatch = tags
10332 .iter()
10333 .position(|(tag_source, _)| tag_source != leading_tag_source);
10334 if let Some(index) = first_mismatch {
10335 tags.truncate(index);
10336 }
10337 }
10338
10339 tags
10340 }
10341
10342 pub fn move_to_enclosing_bracket(
10343 &mut self,
10344 _: &MoveToEnclosingBracket,
10345 window: &mut Window,
10346 cx: &mut Context<Self>,
10347 ) {
10348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10349 s.move_offsets_with(|snapshot, selection| {
10350 let Some(enclosing_bracket_ranges) =
10351 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10352 else {
10353 return;
10354 };
10355
10356 let mut best_length = usize::MAX;
10357 let mut best_inside = false;
10358 let mut best_in_bracket_range = false;
10359 let mut best_destination = None;
10360 for (open, close) in enclosing_bracket_ranges {
10361 let close = close.to_inclusive();
10362 let length = close.end() - open.start;
10363 let inside = selection.start >= open.end && selection.end <= *close.start();
10364 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10365 || close.contains(&selection.head());
10366
10367 // If best is next to a bracket and current isn't, skip
10368 if !in_bracket_range && best_in_bracket_range {
10369 continue;
10370 }
10371
10372 // Prefer smaller lengths unless best is inside and current isn't
10373 if length > best_length && (best_inside || !inside) {
10374 continue;
10375 }
10376
10377 best_length = length;
10378 best_inside = inside;
10379 best_in_bracket_range = in_bracket_range;
10380 best_destination = Some(
10381 if close.contains(&selection.start) && close.contains(&selection.end) {
10382 if inside {
10383 open.end
10384 } else {
10385 open.start
10386 }
10387 } else if inside {
10388 *close.start()
10389 } else {
10390 *close.end()
10391 },
10392 );
10393 }
10394
10395 if let Some(destination) = best_destination {
10396 selection.collapse_to(destination, SelectionGoal::None);
10397 }
10398 })
10399 });
10400 }
10401
10402 pub fn undo_selection(
10403 &mut self,
10404 _: &UndoSelection,
10405 window: &mut Window,
10406 cx: &mut Context<Self>,
10407 ) {
10408 self.end_selection(window, cx);
10409 self.selection_history.mode = SelectionHistoryMode::Undoing;
10410 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10411 self.change_selections(None, window, cx, |s| {
10412 s.select_anchors(entry.selections.to_vec())
10413 });
10414 self.select_next_state = entry.select_next_state;
10415 self.select_prev_state = entry.select_prev_state;
10416 self.add_selections_state = entry.add_selections_state;
10417 self.request_autoscroll(Autoscroll::newest(), cx);
10418 }
10419 self.selection_history.mode = SelectionHistoryMode::Normal;
10420 }
10421
10422 pub fn redo_selection(
10423 &mut self,
10424 _: &RedoSelection,
10425 window: &mut Window,
10426 cx: &mut Context<Self>,
10427 ) {
10428 self.end_selection(window, cx);
10429 self.selection_history.mode = SelectionHistoryMode::Redoing;
10430 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10431 self.change_selections(None, window, cx, |s| {
10432 s.select_anchors(entry.selections.to_vec())
10433 });
10434 self.select_next_state = entry.select_next_state;
10435 self.select_prev_state = entry.select_prev_state;
10436 self.add_selections_state = entry.add_selections_state;
10437 self.request_autoscroll(Autoscroll::newest(), cx);
10438 }
10439 self.selection_history.mode = SelectionHistoryMode::Normal;
10440 }
10441
10442 pub fn expand_excerpts(
10443 &mut self,
10444 action: &ExpandExcerpts,
10445 _: &mut Window,
10446 cx: &mut Context<Self>,
10447 ) {
10448 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10449 }
10450
10451 pub fn expand_excerpts_down(
10452 &mut self,
10453 action: &ExpandExcerptsDown,
10454 _: &mut Window,
10455 cx: &mut Context<Self>,
10456 ) {
10457 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10458 }
10459
10460 pub fn expand_excerpts_up(
10461 &mut self,
10462 action: &ExpandExcerptsUp,
10463 _: &mut Window,
10464 cx: &mut Context<Self>,
10465 ) {
10466 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10467 }
10468
10469 pub fn expand_excerpts_for_direction(
10470 &mut self,
10471 lines: u32,
10472 direction: ExpandExcerptDirection,
10473
10474 cx: &mut Context<Self>,
10475 ) {
10476 let selections = self.selections.disjoint_anchors();
10477
10478 let lines = if lines == 0 {
10479 EditorSettings::get_global(cx).expand_excerpt_lines
10480 } else {
10481 lines
10482 };
10483
10484 self.buffer.update(cx, |buffer, cx| {
10485 let snapshot = buffer.snapshot(cx);
10486 let mut excerpt_ids = selections
10487 .iter()
10488 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10489 .collect::<Vec<_>>();
10490 excerpt_ids.sort();
10491 excerpt_ids.dedup();
10492 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10493 })
10494 }
10495
10496 pub fn expand_excerpt(
10497 &mut self,
10498 excerpt: ExcerptId,
10499 direction: ExpandExcerptDirection,
10500 cx: &mut Context<Self>,
10501 ) {
10502 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10503 self.buffer.update(cx, |buffer, cx| {
10504 buffer.expand_excerpts([excerpt], lines, direction, cx)
10505 })
10506 }
10507
10508 pub fn go_to_singleton_buffer_point(
10509 &mut self,
10510 point: Point,
10511 window: &mut Window,
10512 cx: &mut Context<Self>,
10513 ) {
10514 self.go_to_singleton_buffer_range(point..point, window, cx);
10515 }
10516
10517 pub fn go_to_singleton_buffer_range(
10518 &mut self,
10519 range: Range<Point>,
10520 window: &mut Window,
10521 cx: &mut Context<Self>,
10522 ) {
10523 let multibuffer = self.buffer().read(cx);
10524 let Some(buffer) = multibuffer.as_singleton() else {
10525 return;
10526 };
10527 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10528 return;
10529 };
10530 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10531 return;
10532 };
10533 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10534 s.select_anchor_ranges([start..end])
10535 });
10536 }
10537
10538 fn go_to_diagnostic(
10539 &mut self,
10540 _: &GoToDiagnostic,
10541 window: &mut Window,
10542 cx: &mut Context<Self>,
10543 ) {
10544 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10545 }
10546
10547 fn go_to_prev_diagnostic(
10548 &mut self,
10549 _: &GoToPrevDiagnostic,
10550 window: &mut Window,
10551 cx: &mut Context<Self>,
10552 ) {
10553 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10554 }
10555
10556 pub fn go_to_diagnostic_impl(
10557 &mut self,
10558 direction: Direction,
10559 window: &mut Window,
10560 cx: &mut Context<Self>,
10561 ) {
10562 let buffer = self.buffer.read(cx).snapshot(cx);
10563 let selection = self.selections.newest::<usize>(cx);
10564
10565 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10566 if direction == Direction::Next {
10567 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10568 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10569 return;
10570 };
10571 self.activate_diagnostics(
10572 buffer_id,
10573 popover.local_diagnostic.diagnostic.group_id,
10574 window,
10575 cx,
10576 );
10577 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10578 let primary_range_start = active_diagnostics.primary_range.start;
10579 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10580 let mut new_selection = s.newest_anchor().clone();
10581 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10582 s.select_anchors(vec![new_selection.clone()]);
10583 });
10584 self.refresh_inline_completion(false, true, window, cx);
10585 }
10586 return;
10587 }
10588 }
10589
10590 let active_group_id = self
10591 .active_diagnostics
10592 .as_ref()
10593 .map(|active_group| active_group.group_id);
10594 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10595 active_diagnostics
10596 .primary_range
10597 .to_offset(&buffer)
10598 .to_inclusive()
10599 });
10600 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10601 if active_primary_range.contains(&selection.head()) {
10602 *active_primary_range.start()
10603 } else {
10604 selection.head()
10605 }
10606 } else {
10607 selection.head()
10608 };
10609
10610 let snapshot = self.snapshot(window, cx);
10611 let primary_diagnostics_before = buffer
10612 .diagnostics_in_range::<usize>(0..search_start)
10613 .filter(|entry| entry.diagnostic.is_primary)
10614 .filter(|entry| entry.range.start != entry.range.end)
10615 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10616 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10617 .collect::<Vec<_>>();
10618 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10619 primary_diagnostics_before
10620 .iter()
10621 .position(|entry| entry.diagnostic.group_id == active_group_id)
10622 });
10623
10624 let primary_diagnostics_after = buffer
10625 .diagnostics_in_range::<usize>(search_start..buffer.len())
10626 .filter(|entry| entry.diagnostic.is_primary)
10627 .filter(|entry| entry.range.start != entry.range.end)
10628 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10629 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10630 .collect::<Vec<_>>();
10631 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10632 primary_diagnostics_after
10633 .iter()
10634 .enumerate()
10635 .rev()
10636 .find_map(|(i, entry)| {
10637 if entry.diagnostic.group_id == active_group_id {
10638 Some(i)
10639 } else {
10640 None
10641 }
10642 })
10643 });
10644
10645 let next_primary_diagnostic = match direction {
10646 Direction::Prev => primary_diagnostics_before
10647 .iter()
10648 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10649 .rev()
10650 .next(),
10651 Direction::Next => primary_diagnostics_after
10652 .iter()
10653 .skip(
10654 last_same_group_diagnostic_after
10655 .map(|index| index + 1)
10656 .unwrap_or(0),
10657 )
10658 .next(),
10659 };
10660
10661 // Cycle around to the start of the buffer, potentially moving back to the start of
10662 // the currently active diagnostic.
10663 let cycle_around = || match direction {
10664 Direction::Prev => primary_diagnostics_after
10665 .iter()
10666 .rev()
10667 .chain(primary_diagnostics_before.iter().rev())
10668 .next(),
10669 Direction::Next => primary_diagnostics_before
10670 .iter()
10671 .chain(primary_diagnostics_after.iter())
10672 .next(),
10673 };
10674
10675 if let Some((primary_range, group_id)) = next_primary_diagnostic
10676 .or_else(cycle_around)
10677 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10678 {
10679 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10680 return;
10681 };
10682 self.activate_diagnostics(buffer_id, group_id, window, cx);
10683 if self.active_diagnostics.is_some() {
10684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10685 s.select(vec![Selection {
10686 id: selection.id,
10687 start: primary_range.start,
10688 end: primary_range.start,
10689 reversed: false,
10690 goal: SelectionGoal::None,
10691 }]);
10692 });
10693 self.refresh_inline_completion(false, true, window, cx);
10694 }
10695 }
10696 }
10697
10698 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10699 let snapshot = self.snapshot(window, cx);
10700 let selection = self.selections.newest::<Point>(cx);
10701 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10702 }
10703
10704 fn go_to_hunk_after_position(
10705 &mut self,
10706 snapshot: &EditorSnapshot,
10707 position: Point,
10708 window: &mut Window,
10709 cx: &mut Context<Editor>,
10710 ) -> Option<MultiBufferDiffHunk> {
10711 let mut hunk = snapshot
10712 .buffer_snapshot
10713 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10714 .find(|hunk| hunk.row_range.start.0 > position.row);
10715 if hunk.is_none() {
10716 hunk = snapshot
10717 .buffer_snapshot
10718 .diff_hunks_in_range(Point::zero()..position)
10719 .find(|hunk| hunk.row_range.end.0 < position.row)
10720 }
10721 if let Some(hunk) = &hunk {
10722 let destination = Point::new(hunk.row_range.start.0, 0);
10723 self.unfold_ranges(&[destination..destination], false, false, cx);
10724 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10725 s.select_ranges(vec![destination..destination]);
10726 });
10727 }
10728
10729 hunk
10730 }
10731
10732 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10733 let snapshot = self.snapshot(window, cx);
10734 let selection = self.selections.newest::<Point>(cx);
10735 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10736 }
10737
10738 fn go_to_hunk_before_position(
10739 &mut self,
10740 snapshot: &EditorSnapshot,
10741 position: Point,
10742 window: &mut Window,
10743 cx: &mut Context<Editor>,
10744 ) -> Option<MultiBufferDiffHunk> {
10745 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10746 if hunk.is_none() {
10747 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10748 }
10749 if let Some(hunk) = &hunk {
10750 let destination = Point::new(hunk.row_range.start.0, 0);
10751 self.unfold_ranges(&[destination..destination], false, false, cx);
10752 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10753 s.select_ranges(vec![destination..destination]);
10754 });
10755 }
10756
10757 hunk
10758 }
10759
10760 pub fn go_to_definition(
10761 &mut self,
10762 _: &GoToDefinition,
10763 window: &mut Window,
10764 cx: &mut Context<Self>,
10765 ) -> Task<Result<Navigated>> {
10766 let definition =
10767 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10768 cx.spawn_in(window, |editor, mut cx| async move {
10769 if definition.await? == Navigated::Yes {
10770 return Ok(Navigated::Yes);
10771 }
10772 match editor.update_in(&mut cx, |editor, window, cx| {
10773 editor.find_all_references(&FindAllReferences, window, cx)
10774 })? {
10775 Some(references) => references.await,
10776 None => Ok(Navigated::No),
10777 }
10778 })
10779 }
10780
10781 pub fn go_to_declaration(
10782 &mut self,
10783 _: &GoToDeclaration,
10784 window: &mut Window,
10785 cx: &mut Context<Self>,
10786 ) -> Task<Result<Navigated>> {
10787 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10788 }
10789
10790 pub fn go_to_declaration_split(
10791 &mut self,
10792 _: &GoToDeclaration,
10793 window: &mut Window,
10794 cx: &mut Context<Self>,
10795 ) -> Task<Result<Navigated>> {
10796 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10797 }
10798
10799 pub fn go_to_implementation(
10800 &mut self,
10801 _: &GoToImplementation,
10802 window: &mut Window,
10803 cx: &mut Context<Self>,
10804 ) -> Task<Result<Navigated>> {
10805 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10806 }
10807
10808 pub fn go_to_implementation_split(
10809 &mut self,
10810 _: &GoToImplementationSplit,
10811 window: &mut Window,
10812 cx: &mut Context<Self>,
10813 ) -> Task<Result<Navigated>> {
10814 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10815 }
10816
10817 pub fn go_to_type_definition(
10818 &mut self,
10819 _: &GoToTypeDefinition,
10820 window: &mut Window,
10821 cx: &mut Context<Self>,
10822 ) -> Task<Result<Navigated>> {
10823 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10824 }
10825
10826 pub fn go_to_definition_split(
10827 &mut self,
10828 _: &GoToDefinitionSplit,
10829 window: &mut Window,
10830 cx: &mut Context<Self>,
10831 ) -> Task<Result<Navigated>> {
10832 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10833 }
10834
10835 pub fn go_to_type_definition_split(
10836 &mut self,
10837 _: &GoToTypeDefinitionSplit,
10838 window: &mut Window,
10839 cx: &mut Context<Self>,
10840 ) -> Task<Result<Navigated>> {
10841 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10842 }
10843
10844 fn go_to_definition_of_kind(
10845 &mut self,
10846 kind: GotoDefinitionKind,
10847 split: bool,
10848 window: &mut Window,
10849 cx: &mut Context<Self>,
10850 ) -> Task<Result<Navigated>> {
10851 let Some(provider) = self.semantics_provider.clone() else {
10852 return Task::ready(Ok(Navigated::No));
10853 };
10854 let head = self.selections.newest::<usize>(cx).head();
10855 let buffer = self.buffer.read(cx);
10856 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10857 text_anchor
10858 } else {
10859 return Task::ready(Ok(Navigated::No));
10860 };
10861
10862 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10863 return Task::ready(Ok(Navigated::No));
10864 };
10865
10866 cx.spawn_in(window, |editor, mut cx| async move {
10867 let definitions = definitions.await?;
10868 let navigated = editor
10869 .update_in(&mut cx, |editor, window, cx| {
10870 editor.navigate_to_hover_links(
10871 Some(kind),
10872 definitions
10873 .into_iter()
10874 .filter(|location| {
10875 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10876 })
10877 .map(HoverLink::Text)
10878 .collect::<Vec<_>>(),
10879 split,
10880 window,
10881 cx,
10882 )
10883 })?
10884 .await?;
10885 anyhow::Ok(navigated)
10886 })
10887 }
10888
10889 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10890 let selection = self.selections.newest_anchor();
10891 let head = selection.head();
10892 let tail = selection.tail();
10893
10894 let Some((buffer, start_position)) =
10895 self.buffer.read(cx).text_anchor_for_position(head, cx)
10896 else {
10897 return;
10898 };
10899
10900 let end_position = if head != tail {
10901 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10902 return;
10903 };
10904 Some(pos)
10905 } else {
10906 None
10907 };
10908
10909 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10910 let url = if let Some(end_pos) = end_position {
10911 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10912 } else {
10913 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10914 };
10915
10916 if let Some(url) = url {
10917 editor.update(&mut cx, |_, cx| {
10918 cx.open_url(&url);
10919 })
10920 } else {
10921 Ok(())
10922 }
10923 });
10924
10925 url_finder.detach();
10926 }
10927
10928 pub fn open_selected_filename(
10929 &mut self,
10930 _: &OpenSelectedFilename,
10931 window: &mut Window,
10932 cx: &mut Context<Self>,
10933 ) {
10934 let Some(workspace) = self.workspace() else {
10935 return;
10936 };
10937
10938 let position = self.selections.newest_anchor().head();
10939
10940 let Some((buffer, buffer_position)) =
10941 self.buffer.read(cx).text_anchor_for_position(position, cx)
10942 else {
10943 return;
10944 };
10945
10946 let project = self.project.clone();
10947
10948 cx.spawn_in(window, |_, mut cx| async move {
10949 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10950
10951 if let Some((_, path)) = result {
10952 workspace
10953 .update_in(&mut cx, |workspace, window, cx| {
10954 workspace.open_resolved_path(path, window, cx)
10955 })?
10956 .await?;
10957 }
10958 anyhow::Ok(())
10959 })
10960 .detach();
10961 }
10962
10963 pub(crate) fn navigate_to_hover_links(
10964 &mut self,
10965 kind: Option<GotoDefinitionKind>,
10966 mut definitions: Vec<HoverLink>,
10967 split: bool,
10968 window: &mut Window,
10969 cx: &mut Context<Editor>,
10970 ) -> Task<Result<Navigated>> {
10971 // If there is one definition, just open it directly
10972 if definitions.len() == 1 {
10973 let definition = definitions.pop().unwrap();
10974
10975 enum TargetTaskResult {
10976 Location(Option<Location>),
10977 AlreadyNavigated,
10978 }
10979
10980 let target_task = match definition {
10981 HoverLink::Text(link) => {
10982 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10983 }
10984 HoverLink::InlayHint(lsp_location, server_id) => {
10985 let computation =
10986 self.compute_target_location(lsp_location, server_id, window, cx);
10987 cx.background_spawn(async move {
10988 let location = computation.await?;
10989 Ok(TargetTaskResult::Location(location))
10990 })
10991 }
10992 HoverLink::Url(url) => {
10993 cx.open_url(&url);
10994 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10995 }
10996 HoverLink::File(path) => {
10997 if let Some(workspace) = self.workspace() {
10998 cx.spawn_in(window, |_, mut cx| async move {
10999 workspace
11000 .update_in(&mut cx, |workspace, window, cx| {
11001 workspace.open_resolved_path(path, window, cx)
11002 })?
11003 .await
11004 .map(|_| TargetTaskResult::AlreadyNavigated)
11005 })
11006 } else {
11007 Task::ready(Ok(TargetTaskResult::Location(None)))
11008 }
11009 }
11010 };
11011 cx.spawn_in(window, |editor, mut cx| async move {
11012 let target = match target_task.await.context("target resolution task")? {
11013 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11014 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11015 TargetTaskResult::Location(Some(target)) => target,
11016 };
11017
11018 editor.update_in(&mut cx, |editor, window, cx| {
11019 let Some(workspace) = editor.workspace() else {
11020 return Navigated::No;
11021 };
11022 let pane = workspace.read(cx).active_pane().clone();
11023
11024 let range = target.range.to_point(target.buffer.read(cx));
11025 let range = editor.range_for_match(&range);
11026 let range = collapse_multiline_range(range);
11027
11028 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11029 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11030 } else {
11031 window.defer(cx, move |window, cx| {
11032 let target_editor: Entity<Self> =
11033 workspace.update(cx, |workspace, cx| {
11034 let pane = if split {
11035 workspace.adjacent_pane(window, cx)
11036 } else {
11037 workspace.active_pane().clone()
11038 };
11039
11040 workspace.open_project_item(
11041 pane,
11042 target.buffer.clone(),
11043 true,
11044 true,
11045 window,
11046 cx,
11047 )
11048 });
11049 target_editor.update(cx, |target_editor, cx| {
11050 // When selecting a definition in a different buffer, disable the nav history
11051 // to avoid creating a history entry at the previous cursor location.
11052 pane.update(cx, |pane, _| pane.disable_history());
11053 target_editor.go_to_singleton_buffer_range(range, window, cx);
11054 pane.update(cx, |pane, _| pane.enable_history());
11055 });
11056 });
11057 }
11058 Navigated::Yes
11059 })
11060 })
11061 } else if !definitions.is_empty() {
11062 cx.spawn_in(window, |editor, mut cx| async move {
11063 let (title, location_tasks, workspace) = editor
11064 .update_in(&mut cx, |editor, window, cx| {
11065 let tab_kind = match kind {
11066 Some(GotoDefinitionKind::Implementation) => "Implementations",
11067 _ => "Definitions",
11068 };
11069 let title = definitions
11070 .iter()
11071 .find_map(|definition| match definition {
11072 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11073 let buffer = origin.buffer.read(cx);
11074 format!(
11075 "{} for {}",
11076 tab_kind,
11077 buffer
11078 .text_for_range(origin.range.clone())
11079 .collect::<String>()
11080 )
11081 }),
11082 HoverLink::InlayHint(_, _) => None,
11083 HoverLink::Url(_) => None,
11084 HoverLink::File(_) => None,
11085 })
11086 .unwrap_or(tab_kind.to_string());
11087 let location_tasks = definitions
11088 .into_iter()
11089 .map(|definition| match definition {
11090 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11091 HoverLink::InlayHint(lsp_location, server_id) => editor
11092 .compute_target_location(lsp_location, server_id, window, cx),
11093 HoverLink::Url(_) => Task::ready(Ok(None)),
11094 HoverLink::File(_) => Task::ready(Ok(None)),
11095 })
11096 .collect::<Vec<_>>();
11097 (title, location_tasks, editor.workspace().clone())
11098 })
11099 .context("location tasks preparation")?;
11100
11101 let locations = future::join_all(location_tasks)
11102 .await
11103 .into_iter()
11104 .filter_map(|location| location.transpose())
11105 .collect::<Result<_>>()
11106 .context("location tasks")?;
11107
11108 let Some(workspace) = workspace else {
11109 return Ok(Navigated::No);
11110 };
11111 let opened = workspace
11112 .update_in(&mut cx, |workspace, window, cx| {
11113 Self::open_locations_in_multibuffer(
11114 workspace,
11115 locations,
11116 title,
11117 split,
11118 MultibufferSelectionMode::First,
11119 window,
11120 cx,
11121 )
11122 })
11123 .ok();
11124
11125 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11126 })
11127 } else {
11128 Task::ready(Ok(Navigated::No))
11129 }
11130 }
11131
11132 fn compute_target_location(
11133 &self,
11134 lsp_location: lsp::Location,
11135 server_id: LanguageServerId,
11136 window: &mut Window,
11137 cx: &mut Context<Self>,
11138 ) -> Task<anyhow::Result<Option<Location>>> {
11139 let Some(project) = self.project.clone() else {
11140 return Task::ready(Ok(None));
11141 };
11142
11143 cx.spawn_in(window, move |editor, mut cx| async move {
11144 let location_task = editor.update(&mut cx, |_, cx| {
11145 project.update(cx, |project, cx| {
11146 let language_server_name = project
11147 .language_server_statuses(cx)
11148 .find(|(id, _)| server_id == *id)
11149 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11150 language_server_name.map(|language_server_name| {
11151 project.open_local_buffer_via_lsp(
11152 lsp_location.uri.clone(),
11153 server_id,
11154 language_server_name,
11155 cx,
11156 )
11157 })
11158 })
11159 })?;
11160 let location = match location_task {
11161 Some(task) => Some({
11162 let target_buffer_handle = task.await.context("open local buffer")?;
11163 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11164 let target_start = target_buffer
11165 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11166 let target_end = target_buffer
11167 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11168 target_buffer.anchor_after(target_start)
11169 ..target_buffer.anchor_before(target_end)
11170 })?;
11171 Location {
11172 buffer: target_buffer_handle,
11173 range,
11174 }
11175 }),
11176 None => None,
11177 };
11178 Ok(location)
11179 })
11180 }
11181
11182 pub fn find_all_references(
11183 &mut self,
11184 _: &FindAllReferences,
11185 window: &mut Window,
11186 cx: &mut Context<Self>,
11187 ) -> Option<Task<Result<Navigated>>> {
11188 let selection = self.selections.newest::<usize>(cx);
11189 let multi_buffer = self.buffer.read(cx);
11190 let head = selection.head();
11191
11192 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11193 let head_anchor = multi_buffer_snapshot.anchor_at(
11194 head,
11195 if head < selection.tail() {
11196 Bias::Right
11197 } else {
11198 Bias::Left
11199 },
11200 );
11201
11202 match self
11203 .find_all_references_task_sources
11204 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11205 {
11206 Ok(_) => {
11207 log::info!(
11208 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11209 );
11210 return None;
11211 }
11212 Err(i) => {
11213 self.find_all_references_task_sources.insert(i, head_anchor);
11214 }
11215 }
11216
11217 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11218 let workspace = self.workspace()?;
11219 let project = workspace.read(cx).project().clone();
11220 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11221 Some(cx.spawn_in(window, |editor, mut cx| async move {
11222 let _cleanup = defer({
11223 let mut cx = cx.clone();
11224 move || {
11225 let _ = editor.update(&mut cx, |editor, _| {
11226 if let Ok(i) =
11227 editor
11228 .find_all_references_task_sources
11229 .binary_search_by(|anchor| {
11230 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11231 })
11232 {
11233 editor.find_all_references_task_sources.remove(i);
11234 }
11235 });
11236 }
11237 });
11238
11239 let locations = references.await?;
11240 if locations.is_empty() {
11241 return anyhow::Ok(Navigated::No);
11242 }
11243
11244 workspace.update_in(&mut cx, |workspace, window, cx| {
11245 let title = locations
11246 .first()
11247 .as_ref()
11248 .map(|location| {
11249 let buffer = location.buffer.read(cx);
11250 format!(
11251 "References to `{}`",
11252 buffer
11253 .text_for_range(location.range.clone())
11254 .collect::<String>()
11255 )
11256 })
11257 .unwrap();
11258 Self::open_locations_in_multibuffer(
11259 workspace,
11260 locations,
11261 title,
11262 false,
11263 MultibufferSelectionMode::First,
11264 window,
11265 cx,
11266 );
11267 Navigated::Yes
11268 })
11269 }))
11270 }
11271
11272 /// Opens a multibuffer with the given project locations in it
11273 pub fn open_locations_in_multibuffer(
11274 workspace: &mut Workspace,
11275 mut locations: Vec<Location>,
11276 title: String,
11277 split: bool,
11278 multibuffer_selection_mode: MultibufferSelectionMode,
11279 window: &mut Window,
11280 cx: &mut Context<Workspace>,
11281 ) {
11282 // If there are multiple definitions, open them in a multibuffer
11283 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11284 let mut locations = locations.into_iter().peekable();
11285 let mut ranges = Vec::new();
11286 let capability = workspace.project().read(cx).capability();
11287
11288 let excerpt_buffer = cx.new(|cx| {
11289 let mut multibuffer = MultiBuffer::new(capability);
11290 while let Some(location) = locations.next() {
11291 let buffer = location.buffer.read(cx);
11292 let mut ranges_for_buffer = Vec::new();
11293 let range = location.range.to_offset(buffer);
11294 ranges_for_buffer.push(range.clone());
11295
11296 while let Some(next_location) = locations.peek() {
11297 if next_location.buffer == location.buffer {
11298 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11299 locations.next();
11300 } else {
11301 break;
11302 }
11303 }
11304
11305 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11306 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11307 location.buffer.clone(),
11308 ranges_for_buffer,
11309 DEFAULT_MULTIBUFFER_CONTEXT,
11310 cx,
11311 ))
11312 }
11313
11314 multibuffer.with_title(title)
11315 });
11316
11317 let editor = cx.new(|cx| {
11318 Editor::for_multibuffer(
11319 excerpt_buffer,
11320 Some(workspace.project().clone()),
11321 true,
11322 window,
11323 cx,
11324 )
11325 });
11326 editor.update(cx, |editor, cx| {
11327 match multibuffer_selection_mode {
11328 MultibufferSelectionMode::First => {
11329 if let Some(first_range) = ranges.first() {
11330 editor.change_selections(None, window, cx, |selections| {
11331 selections.clear_disjoint();
11332 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11333 });
11334 }
11335 editor.highlight_background::<Self>(
11336 &ranges,
11337 |theme| theme.editor_highlighted_line_background,
11338 cx,
11339 );
11340 }
11341 MultibufferSelectionMode::All => {
11342 editor.change_selections(None, window, cx, |selections| {
11343 selections.clear_disjoint();
11344 selections.select_anchor_ranges(ranges);
11345 });
11346 }
11347 }
11348 editor.register_buffers_with_language_servers(cx);
11349 });
11350
11351 let item = Box::new(editor);
11352 let item_id = item.item_id();
11353
11354 if split {
11355 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11356 } else {
11357 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11358 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11359 pane.close_current_preview_item(window, cx)
11360 } else {
11361 None
11362 }
11363 });
11364 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11365 }
11366 workspace.active_pane().update(cx, |pane, cx| {
11367 pane.set_preview_item_id(Some(item_id), cx);
11368 });
11369 }
11370
11371 pub fn rename(
11372 &mut self,
11373 _: &Rename,
11374 window: &mut Window,
11375 cx: &mut Context<Self>,
11376 ) -> Option<Task<Result<()>>> {
11377 use language::ToOffset as _;
11378
11379 let provider = self.semantics_provider.clone()?;
11380 let selection = self.selections.newest_anchor().clone();
11381 let (cursor_buffer, cursor_buffer_position) = self
11382 .buffer
11383 .read(cx)
11384 .text_anchor_for_position(selection.head(), cx)?;
11385 let (tail_buffer, cursor_buffer_position_end) = self
11386 .buffer
11387 .read(cx)
11388 .text_anchor_for_position(selection.tail(), cx)?;
11389 if tail_buffer != cursor_buffer {
11390 return None;
11391 }
11392
11393 let snapshot = cursor_buffer.read(cx).snapshot();
11394 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11395 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11396 let prepare_rename = provider
11397 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11398 .unwrap_or_else(|| Task::ready(Ok(None)));
11399 drop(snapshot);
11400
11401 Some(cx.spawn_in(window, |this, mut cx| async move {
11402 let rename_range = if let Some(range) = prepare_rename.await? {
11403 Some(range)
11404 } else {
11405 this.update(&mut cx, |this, cx| {
11406 let buffer = this.buffer.read(cx).snapshot(cx);
11407 let mut buffer_highlights = this
11408 .document_highlights_for_position(selection.head(), &buffer)
11409 .filter(|highlight| {
11410 highlight.start.excerpt_id == selection.head().excerpt_id
11411 && highlight.end.excerpt_id == selection.head().excerpt_id
11412 });
11413 buffer_highlights
11414 .next()
11415 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11416 })?
11417 };
11418 if let Some(rename_range) = rename_range {
11419 this.update_in(&mut cx, |this, window, cx| {
11420 let snapshot = cursor_buffer.read(cx).snapshot();
11421 let rename_buffer_range = rename_range.to_offset(&snapshot);
11422 let cursor_offset_in_rename_range =
11423 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11424 let cursor_offset_in_rename_range_end =
11425 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11426
11427 this.take_rename(false, window, cx);
11428 let buffer = this.buffer.read(cx).read(cx);
11429 let cursor_offset = selection.head().to_offset(&buffer);
11430 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11431 let rename_end = rename_start + rename_buffer_range.len();
11432 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11433 let mut old_highlight_id = None;
11434 let old_name: Arc<str> = buffer
11435 .chunks(rename_start..rename_end, true)
11436 .map(|chunk| {
11437 if old_highlight_id.is_none() {
11438 old_highlight_id = chunk.syntax_highlight_id;
11439 }
11440 chunk.text
11441 })
11442 .collect::<String>()
11443 .into();
11444
11445 drop(buffer);
11446
11447 // Position the selection in the rename editor so that it matches the current selection.
11448 this.show_local_selections = false;
11449 let rename_editor = cx.new(|cx| {
11450 let mut editor = Editor::single_line(window, cx);
11451 editor.buffer.update(cx, |buffer, cx| {
11452 buffer.edit([(0..0, old_name.clone())], None, cx)
11453 });
11454 let rename_selection_range = match cursor_offset_in_rename_range
11455 .cmp(&cursor_offset_in_rename_range_end)
11456 {
11457 Ordering::Equal => {
11458 editor.select_all(&SelectAll, window, cx);
11459 return editor;
11460 }
11461 Ordering::Less => {
11462 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11463 }
11464 Ordering::Greater => {
11465 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11466 }
11467 };
11468 if rename_selection_range.end > old_name.len() {
11469 editor.select_all(&SelectAll, window, cx);
11470 } else {
11471 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11472 s.select_ranges([rename_selection_range]);
11473 });
11474 }
11475 editor
11476 });
11477 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11478 if e == &EditorEvent::Focused {
11479 cx.emit(EditorEvent::FocusedIn)
11480 }
11481 })
11482 .detach();
11483
11484 let write_highlights =
11485 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11486 let read_highlights =
11487 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11488 let ranges = write_highlights
11489 .iter()
11490 .flat_map(|(_, ranges)| ranges.iter())
11491 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11492 .cloned()
11493 .collect();
11494
11495 this.highlight_text::<Rename>(
11496 ranges,
11497 HighlightStyle {
11498 fade_out: Some(0.6),
11499 ..Default::default()
11500 },
11501 cx,
11502 );
11503 let rename_focus_handle = rename_editor.focus_handle(cx);
11504 window.focus(&rename_focus_handle);
11505 let block_id = this.insert_blocks(
11506 [BlockProperties {
11507 style: BlockStyle::Flex,
11508 placement: BlockPlacement::Below(range.start),
11509 height: 1,
11510 render: Arc::new({
11511 let rename_editor = rename_editor.clone();
11512 move |cx: &mut BlockContext| {
11513 let mut text_style = cx.editor_style.text.clone();
11514 if let Some(highlight_style) = old_highlight_id
11515 .and_then(|h| h.style(&cx.editor_style.syntax))
11516 {
11517 text_style = text_style.highlight(highlight_style);
11518 }
11519 div()
11520 .block_mouse_down()
11521 .pl(cx.anchor_x)
11522 .child(EditorElement::new(
11523 &rename_editor,
11524 EditorStyle {
11525 background: cx.theme().system().transparent,
11526 local_player: cx.editor_style.local_player,
11527 text: text_style,
11528 scrollbar_width: cx.editor_style.scrollbar_width,
11529 syntax: cx.editor_style.syntax.clone(),
11530 status: cx.editor_style.status.clone(),
11531 inlay_hints_style: HighlightStyle {
11532 font_weight: Some(FontWeight::BOLD),
11533 ..make_inlay_hints_style(cx.app)
11534 },
11535 inline_completion_styles: make_suggestion_styles(
11536 cx.app,
11537 ),
11538 ..EditorStyle::default()
11539 },
11540 ))
11541 .into_any_element()
11542 }
11543 }),
11544 priority: 0,
11545 }],
11546 Some(Autoscroll::fit()),
11547 cx,
11548 )[0];
11549 this.pending_rename = Some(RenameState {
11550 range,
11551 old_name,
11552 editor: rename_editor,
11553 block_id,
11554 });
11555 })?;
11556 }
11557
11558 Ok(())
11559 }))
11560 }
11561
11562 pub fn confirm_rename(
11563 &mut self,
11564 _: &ConfirmRename,
11565 window: &mut Window,
11566 cx: &mut Context<Self>,
11567 ) -> Option<Task<Result<()>>> {
11568 let rename = self.take_rename(false, window, cx)?;
11569 let workspace = self.workspace()?.downgrade();
11570 let (buffer, start) = self
11571 .buffer
11572 .read(cx)
11573 .text_anchor_for_position(rename.range.start, cx)?;
11574 let (end_buffer, _) = self
11575 .buffer
11576 .read(cx)
11577 .text_anchor_for_position(rename.range.end, cx)?;
11578 if buffer != end_buffer {
11579 return None;
11580 }
11581
11582 let old_name = rename.old_name;
11583 let new_name = rename.editor.read(cx).text(cx);
11584
11585 let rename = self.semantics_provider.as_ref()?.perform_rename(
11586 &buffer,
11587 start,
11588 new_name.clone(),
11589 cx,
11590 )?;
11591
11592 Some(cx.spawn_in(window, |editor, mut cx| async move {
11593 let project_transaction = rename.await?;
11594 Self::open_project_transaction(
11595 &editor,
11596 workspace,
11597 project_transaction,
11598 format!("Rename: {} → {}", old_name, new_name),
11599 cx.clone(),
11600 )
11601 .await?;
11602
11603 editor.update(&mut cx, |editor, cx| {
11604 editor.refresh_document_highlights(cx);
11605 })?;
11606 Ok(())
11607 }))
11608 }
11609
11610 fn take_rename(
11611 &mut self,
11612 moving_cursor: bool,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) -> Option<RenameState> {
11616 let rename = self.pending_rename.take()?;
11617 if rename.editor.focus_handle(cx).is_focused(window) {
11618 window.focus(&self.focus_handle);
11619 }
11620
11621 self.remove_blocks(
11622 [rename.block_id].into_iter().collect(),
11623 Some(Autoscroll::fit()),
11624 cx,
11625 );
11626 self.clear_highlights::<Rename>(cx);
11627 self.show_local_selections = true;
11628
11629 if moving_cursor {
11630 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11631 editor.selections.newest::<usize>(cx).head()
11632 });
11633
11634 // Update the selection to match the position of the selection inside
11635 // the rename editor.
11636 let snapshot = self.buffer.read(cx).read(cx);
11637 let rename_range = rename.range.to_offset(&snapshot);
11638 let cursor_in_editor = snapshot
11639 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11640 .min(rename_range.end);
11641 drop(snapshot);
11642
11643 self.change_selections(None, window, cx, |s| {
11644 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11645 });
11646 } else {
11647 self.refresh_document_highlights(cx);
11648 }
11649
11650 Some(rename)
11651 }
11652
11653 pub fn pending_rename(&self) -> Option<&RenameState> {
11654 self.pending_rename.as_ref()
11655 }
11656
11657 fn format(
11658 &mut self,
11659 _: &Format,
11660 window: &mut Window,
11661 cx: &mut Context<Self>,
11662 ) -> Option<Task<Result<()>>> {
11663 let project = match &self.project {
11664 Some(project) => project.clone(),
11665 None => return None,
11666 };
11667
11668 Some(self.perform_format(
11669 project,
11670 FormatTrigger::Manual,
11671 FormatTarget::Buffers,
11672 window,
11673 cx,
11674 ))
11675 }
11676
11677 fn format_selections(
11678 &mut self,
11679 _: &FormatSelections,
11680 window: &mut Window,
11681 cx: &mut Context<Self>,
11682 ) -> Option<Task<Result<()>>> {
11683 let project = match &self.project {
11684 Some(project) => project.clone(),
11685 None => return None,
11686 };
11687
11688 let ranges = self
11689 .selections
11690 .all_adjusted(cx)
11691 .into_iter()
11692 .map(|selection| selection.range())
11693 .collect_vec();
11694
11695 Some(self.perform_format(
11696 project,
11697 FormatTrigger::Manual,
11698 FormatTarget::Ranges(ranges),
11699 window,
11700 cx,
11701 ))
11702 }
11703
11704 fn perform_format(
11705 &mut self,
11706 project: Entity<Project>,
11707 trigger: FormatTrigger,
11708 target: FormatTarget,
11709 window: &mut Window,
11710 cx: &mut Context<Self>,
11711 ) -> Task<Result<()>> {
11712 let buffer = self.buffer.clone();
11713 let (buffers, target) = match target {
11714 FormatTarget::Buffers => {
11715 let mut buffers = buffer.read(cx).all_buffers();
11716 if trigger == FormatTrigger::Save {
11717 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11718 }
11719 (buffers, LspFormatTarget::Buffers)
11720 }
11721 FormatTarget::Ranges(selection_ranges) => {
11722 let multi_buffer = buffer.read(cx);
11723 let snapshot = multi_buffer.read(cx);
11724 let mut buffers = HashSet::default();
11725 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11726 BTreeMap::new();
11727 for selection_range in selection_ranges {
11728 for (buffer, buffer_range, _) in
11729 snapshot.range_to_buffer_ranges(selection_range)
11730 {
11731 let buffer_id = buffer.remote_id();
11732 let start = buffer.anchor_before(buffer_range.start);
11733 let end = buffer.anchor_after(buffer_range.end);
11734 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11735 buffer_id_to_ranges
11736 .entry(buffer_id)
11737 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11738 .or_insert_with(|| vec![start..end]);
11739 }
11740 }
11741 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11742 }
11743 };
11744
11745 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11746 let format = project.update(cx, |project, cx| {
11747 project.format(buffers, target, true, trigger, cx)
11748 });
11749
11750 cx.spawn_in(window, |_, mut cx| async move {
11751 let transaction = futures::select_biased! {
11752 () = timeout => {
11753 log::warn!("timed out waiting for formatting");
11754 None
11755 }
11756 transaction = format.log_err().fuse() => transaction,
11757 };
11758
11759 buffer
11760 .update(&mut cx, |buffer, cx| {
11761 if let Some(transaction) = transaction {
11762 if !buffer.is_singleton() {
11763 buffer.push_transaction(&transaction.0, cx);
11764 }
11765 }
11766
11767 cx.notify();
11768 })
11769 .ok();
11770
11771 Ok(())
11772 })
11773 }
11774
11775 fn restart_language_server(
11776 &mut self,
11777 _: &RestartLanguageServer,
11778 _: &mut Window,
11779 cx: &mut Context<Self>,
11780 ) {
11781 if let Some(project) = self.project.clone() {
11782 self.buffer.update(cx, |multi_buffer, cx| {
11783 project.update(cx, |project, cx| {
11784 project.restart_language_servers_for_buffers(
11785 multi_buffer.all_buffers().into_iter().collect(),
11786 cx,
11787 );
11788 });
11789 })
11790 }
11791 }
11792
11793 fn cancel_language_server_work(
11794 workspace: &mut Workspace,
11795 _: &actions::CancelLanguageServerWork,
11796 _: &mut Window,
11797 cx: &mut Context<Workspace>,
11798 ) {
11799 let project = workspace.project();
11800 let buffers = workspace
11801 .active_item(cx)
11802 .and_then(|item| item.act_as::<Editor>(cx))
11803 .map_or(HashSet::default(), |editor| {
11804 editor.read(cx).buffer.read(cx).all_buffers()
11805 });
11806 project.update(cx, |project, cx| {
11807 project.cancel_language_server_work_for_buffers(buffers, cx);
11808 });
11809 }
11810
11811 fn show_character_palette(
11812 &mut self,
11813 _: &ShowCharacterPalette,
11814 window: &mut Window,
11815 _: &mut Context<Self>,
11816 ) {
11817 window.show_character_palette();
11818 }
11819
11820 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11821 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11822 let buffer = self.buffer.read(cx).snapshot(cx);
11823 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11824 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11825 let is_valid = buffer
11826 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11827 .any(|entry| {
11828 entry.diagnostic.is_primary
11829 && !entry.range.is_empty()
11830 && entry.range.start == primary_range_start
11831 && entry.diagnostic.message == active_diagnostics.primary_message
11832 });
11833
11834 if is_valid != active_diagnostics.is_valid {
11835 active_diagnostics.is_valid = is_valid;
11836 let mut new_styles = HashMap::default();
11837 for (block_id, diagnostic) in &active_diagnostics.blocks {
11838 new_styles.insert(
11839 *block_id,
11840 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11841 );
11842 }
11843 self.display_map.update(cx, |display_map, _cx| {
11844 display_map.replace_blocks(new_styles)
11845 });
11846 }
11847 }
11848 }
11849
11850 fn activate_diagnostics(
11851 &mut self,
11852 buffer_id: BufferId,
11853 group_id: usize,
11854 window: &mut Window,
11855 cx: &mut Context<Self>,
11856 ) {
11857 self.dismiss_diagnostics(cx);
11858 let snapshot = self.snapshot(window, cx);
11859 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11860 let buffer = self.buffer.read(cx).snapshot(cx);
11861
11862 let mut primary_range = None;
11863 let mut primary_message = None;
11864 let diagnostic_group = buffer
11865 .diagnostic_group(buffer_id, group_id)
11866 .filter_map(|entry| {
11867 let start = entry.range.start;
11868 let end = entry.range.end;
11869 if snapshot.is_line_folded(MultiBufferRow(start.row))
11870 && (start.row == end.row
11871 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11872 {
11873 return None;
11874 }
11875 if entry.diagnostic.is_primary {
11876 primary_range = Some(entry.range.clone());
11877 primary_message = Some(entry.diagnostic.message.clone());
11878 }
11879 Some(entry)
11880 })
11881 .collect::<Vec<_>>();
11882 let primary_range = primary_range?;
11883 let primary_message = primary_message?;
11884
11885 let blocks = display_map
11886 .insert_blocks(
11887 diagnostic_group.iter().map(|entry| {
11888 let diagnostic = entry.diagnostic.clone();
11889 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11890 BlockProperties {
11891 style: BlockStyle::Fixed,
11892 placement: BlockPlacement::Below(
11893 buffer.anchor_after(entry.range.start),
11894 ),
11895 height: message_height,
11896 render: diagnostic_block_renderer(diagnostic, None, true, true),
11897 priority: 0,
11898 }
11899 }),
11900 cx,
11901 )
11902 .into_iter()
11903 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11904 .collect();
11905
11906 Some(ActiveDiagnosticGroup {
11907 primary_range: buffer.anchor_before(primary_range.start)
11908 ..buffer.anchor_after(primary_range.end),
11909 primary_message,
11910 group_id,
11911 blocks,
11912 is_valid: true,
11913 })
11914 });
11915 }
11916
11917 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11918 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11919 self.display_map.update(cx, |display_map, cx| {
11920 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11921 });
11922 cx.notify();
11923 }
11924 }
11925
11926 pub fn set_selections_from_remote(
11927 &mut self,
11928 selections: Vec<Selection<Anchor>>,
11929 pending_selection: Option<Selection<Anchor>>,
11930 window: &mut Window,
11931 cx: &mut Context<Self>,
11932 ) {
11933 let old_cursor_position = self.selections.newest_anchor().head();
11934 self.selections.change_with(cx, |s| {
11935 s.select_anchors(selections);
11936 if let Some(pending_selection) = pending_selection {
11937 s.set_pending(pending_selection, SelectMode::Character);
11938 } else {
11939 s.clear_pending();
11940 }
11941 });
11942 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11943 }
11944
11945 fn push_to_selection_history(&mut self) {
11946 self.selection_history.push(SelectionHistoryEntry {
11947 selections: self.selections.disjoint_anchors(),
11948 select_next_state: self.select_next_state.clone(),
11949 select_prev_state: self.select_prev_state.clone(),
11950 add_selections_state: self.add_selections_state.clone(),
11951 });
11952 }
11953
11954 pub fn transact(
11955 &mut self,
11956 window: &mut Window,
11957 cx: &mut Context<Self>,
11958 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11959 ) -> Option<TransactionId> {
11960 self.start_transaction_at(Instant::now(), window, cx);
11961 update(self, window, cx);
11962 self.end_transaction_at(Instant::now(), cx)
11963 }
11964
11965 pub fn start_transaction_at(
11966 &mut self,
11967 now: Instant,
11968 window: &mut Window,
11969 cx: &mut Context<Self>,
11970 ) {
11971 self.end_selection(window, cx);
11972 if let Some(tx_id) = self
11973 .buffer
11974 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11975 {
11976 self.selection_history
11977 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11978 cx.emit(EditorEvent::TransactionBegun {
11979 transaction_id: tx_id,
11980 })
11981 }
11982 }
11983
11984 pub fn end_transaction_at(
11985 &mut self,
11986 now: Instant,
11987 cx: &mut Context<Self>,
11988 ) -> Option<TransactionId> {
11989 if let Some(transaction_id) = self
11990 .buffer
11991 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11992 {
11993 if let Some((_, end_selections)) =
11994 self.selection_history.transaction_mut(transaction_id)
11995 {
11996 *end_selections = Some(self.selections.disjoint_anchors());
11997 } else {
11998 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11999 }
12000
12001 cx.emit(EditorEvent::Edited { transaction_id });
12002 Some(transaction_id)
12003 } else {
12004 None
12005 }
12006 }
12007
12008 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12009 if self.selection_mark_mode {
12010 self.change_selections(None, window, cx, |s| {
12011 s.move_with(|_, sel| {
12012 sel.collapse_to(sel.head(), SelectionGoal::None);
12013 });
12014 })
12015 }
12016 self.selection_mark_mode = true;
12017 cx.notify();
12018 }
12019
12020 pub fn swap_selection_ends(
12021 &mut self,
12022 _: &actions::SwapSelectionEnds,
12023 window: &mut Window,
12024 cx: &mut Context<Self>,
12025 ) {
12026 self.change_selections(None, window, cx, |s| {
12027 s.move_with(|_, sel| {
12028 if sel.start != sel.end {
12029 sel.reversed = !sel.reversed
12030 }
12031 });
12032 });
12033 self.request_autoscroll(Autoscroll::newest(), cx);
12034 cx.notify();
12035 }
12036
12037 pub fn toggle_fold(
12038 &mut self,
12039 _: &actions::ToggleFold,
12040 window: &mut Window,
12041 cx: &mut Context<Self>,
12042 ) {
12043 if self.is_singleton(cx) {
12044 let selection = self.selections.newest::<Point>(cx);
12045
12046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12047 let range = if selection.is_empty() {
12048 let point = selection.head().to_display_point(&display_map);
12049 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12050 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12051 .to_point(&display_map);
12052 start..end
12053 } else {
12054 selection.range()
12055 };
12056 if display_map.folds_in_range(range).next().is_some() {
12057 self.unfold_lines(&Default::default(), window, cx)
12058 } else {
12059 self.fold(&Default::default(), window, cx)
12060 }
12061 } else {
12062 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12063 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12064 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12065 .map(|(snapshot, _, _)| snapshot.remote_id())
12066 .collect();
12067
12068 for buffer_id in buffer_ids {
12069 if self.is_buffer_folded(buffer_id, cx) {
12070 self.unfold_buffer(buffer_id, cx);
12071 } else {
12072 self.fold_buffer(buffer_id, cx);
12073 }
12074 }
12075 }
12076 }
12077
12078 pub fn toggle_fold_recursive(
12079 &mut self,
12080 _: &actions::ToggleFoldRecursive,
12081 window: &mut Window,
12082 cx: &mut Context<Self>,
12083 ) {
12084 let selection = self.selections.newest::<Point>(cx);
12085
12086 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12087 let range = if selection.is_empty() {
12088 let point = selection.head().to_display_point(&display_map);
12089 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12090 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12091 .to_point(&display_map);
12092 start..end
12093 } else {
12094 selection.range()
12095 };
12096 if display_map.folds_in_range(range).next().is_some() {
12097 self.unfold_recursive(&Default::default(), window, cx)
12098 } else {
12099 self.fold_recursive(&Default::default(), window, cx)
12100 }
12101 }
12102
12103 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12104 if self.is_singleton(cx) {
12105 let mut to_fold = Vec::new();
12106 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12107 let selections = self.selections.all_adjusted(cx);
12108
12109 for selection in selections {
12110 let range = selection.range().sorted();
12111 let buffer_start_row = range.start.row;
12112
12113 if range.start.row != range.end.row {
12114 let mut found = false;
12115 let mut row = range.start.row;
12116 while row <= range.end.row {
12117 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12118 {
12119 found = true;
12120 row = crease.range().end.row + 1;
12121 to_fold.push(crease);
12122 } else {
12123 row += 1
12124 }
12125 }
12126 if found {
12127 continue;
12128 }
12129 }
12130
12131 for row in (0..=range.start.row).rev() {
12132 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12133 if crease.range().end.row >= buffer_start_row {
12134 to_fold.push(crease);
12135 if row <= range.start.row {
12136 break;
12137 }
12138 }
12139 }
12140 }
12141 }
12142
12143 self.fold_creases(to_fold, true, window, cx);
12144 } else {
12145 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12146
12147 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12148 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12149 .map(|(snapshot, _, _)| snapshot.remote_id())
12150 .collect();
12151 for buffer_id in buffer_ids {
12152 self.fold_buffer(buffer_id, cx);
12153 }
12154 }
12155 }
12156
12157 fn fold_at_level(
12158 &mut self,
12159 fold_at: &FoldAtLevel,
12160 window: &mut Window,
12161 cx: &mut Context<Self>,
12162 ) {
12163 if !self.buffer.read(cx).is_singleton() {
12164 return;
12165 }
12166
12167 let fold_at_level = fold_at.0;
12168 let snapshot = self.buffer.read(cx).snapshot(cx);
12169 let mut to_fold = Vec::new();
12170 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12171
12172 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12173 while start_row < end_row {
12174 match self
12175 .snapshot(window, cx)
12176 .crease_for_buffer_row(MultiBufferRow(start_row))
12177 {
12178 Some(crease) => {
12179 let nested_start_row = crease.range().start.row + 1;
12180 let nested_end_row = crease.range().end.row;
12181
12182 if current_level < fold_at_level {
12183 stack.push((nested_start_row, nested_end_row, current_level + 1));
12184 } else if current_level == fold_at_level {
12185 to_fold.push(crease);
12186 }
12187
12188 start_row = nested_end_row + 1;
12189 }
12190 None => start_row += 1,
12191 }
12192 }
12193 }
12194
12195 self.fold_creases(to_fold, true, window, cx);
12196 }
12197
12198 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12199 if self.buffer.read(cx).is_singleton() {
12200 let mut fold_ranges = Vec::new();
12201 let snapshot = self.buffer.read(cx).snapshot(cx);
12202
12203 for row in 0..snapshot.max_row().0 {
12204 if let Some(foldable_range) = self
12205 .snapshot(window, cx)
12206 .crease_for_buffer_row(MultiBufferRow(row))
12207 {
12208 fold_ranges.push(foldable_range);
12209 }
12210 }
12211
12212 self.fold_creases(fold_ranges, true, window, cx);
12213 } else {
12214 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12215 editor
12216 .update_in(&mut cx, |editor, _, cx| {
12217 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12218 editor.fold_buffer(buffer_id, cx);
12219 }
12220 })
12221 .ok();
12222 });
12223 }
12224 }
12225
12226 pub fn fold_function_bodies(
12227 &mut self,
12228 _: &actions::FoldFunctionBodies,
12229 window: &mut Window,
12230 cx: &mut Context<Self>,
12231 ) {
12232 let snapshot = self.buffer.read(cx).snapshot(cx);
12233
12234 let ranges = snapshot
12235 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12236 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12237 .collect::<Vec<_>>();
12238
12239 let creases = ranges
12240 .into_iter()
12241 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12242 .collect();
12243
12244 self.fold_creases(creases, true, window, cx);
12245 }
12246
12247 pub fn fold_recursive(
12248 &mut self,
12249 _: &actions::FoldRecursive,
12250 window: &mut Window,
12251 cx: &mut Context<Self>,
12252 ) {
12253 let mut to_fold = Vec::new();
12254 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12255 let selections = self.selections.all_adjusted(cx);
12256
12257 for selection in selections {
12258 let range = selection.range().sorted();
12259 let buffer_start_row = range.start.row;
12260
12261 if range.start.row != range.end.row {
12262 let mut found = false;
12263 for row in range.start.row..=range.end.row {
12264 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12265 found = true;
12266 to_fold.push(crease);
12267 }
12268 }
12269 if found {
12270 continue;
12271 }
12272 }
12273
12274 for row in (0..=range.start.row).rev() {
12275 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12276 if crease.range().end.row >= buffer_start_row {
12277 to_fold.push(crease);
12278 } else {
12279 break;
12280 }
12281 }
12282 }
12283 }
12284
12285 self.fold_creases(to_fold, true, window, cx);
12286 }
12287
12288 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12289 let buffer_row = fold_at.buffer_row;
12290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12291
12292 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12293 let autoscroll = self
12294 .selections
12295 .all::<Point>(cx)
12296 .iter()
12297 .any(|selection| crease.range().overlaps(&selection.range()));
12298
12299 self.fold_creases(vec![crease], autoscroll, window, cx);
12300 }
12301 }
12302
12303 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12304 if self.is_singleton(cx) {
12305 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12306 let buffer = &display_map.buffer_snapshot;
12307 let selections = self.selections.all::<Point>(cx);
12308 let ranges = selections
12309 .iter()
12310 .map(|s| {
12311 let range = s.display_range(&display_map).sorted();
12312 let mut start = range.start.to_point(&display_map);
12313 let mut end = range.end.to_point(&display_map);
12314 start.column = 0;
12315 end.column = buffer.line_len(MultiBufferRow(end.row));
12316 start..end
12317 })
12318 .collect::<Vec<_>>();
12319
12320 self.unfold_ranges(&ranges, true, true, cx);
12321 } else {
12322 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12323 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12324 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12325 .map(|(snapshot, _, _)| snapshot.remote_id())
12326 .collect();
12327 for buffer_id in buffer_ids {
12328 self.unfold_buffer(buffer_id, cx);
12329 }
12330 }
12331 }
12332
12333 pub fn unfold_recursive(
12334 &mut self,
12335 _: &UnfoldRecursive,
12336 _window: &mut Window,
12337 cx: &mut Context<Self>,
12338 ) {
12339 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12340 let selections = self.selections.all::<Point>(cx);
12341 let ranges = selections
12342 .iter()
12343 .map(|s| {
12344 let mut range = s.display_range(&display_map).sorted();
12345 *range.start.column_mut() = 0;
12346 *range.end.column_mut() = display_map.line_len(range.end.row());
12347 let start = range.start.to_point(&display_map);
12348 let end = range.end.to_point(&display_map);
12349 start..end
12350 })
12351 .collect::<Vec<_>>();
12352
12353 self.unfold_ranges(&ranges, true, true, cx);
12354 }
12355
12356 pub fn unfold_at(
12357 &mut self,
12358 unfold_at: &UnfoldAt,
12359 _window: &mut Window,
12360 cx: &mut Context<Self>,
12361 ) {
12362 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12363
12364 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12365 ..Point::new(
12366 unfold_at.buffer_row.0,
12367 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12368 );
12369
12370 let autoscroll = self
12371 .selections
12372 .all::<Point>(cx)
12373 .iter()
12374 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12375
12376 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12377 }
12378
12379 pub fn unfold_all(
12380 &mut self,
12381 _: &actions::UnfoldAll,
12382 _window: &mut Window,
12383 cx: &mut Context<Self>,
12384 ) {
12385 if self.buffer.read(cx).is_singleton() {
12386 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12387 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12388 } else {
12389 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12390 editor
12391 .update(&mut cx, |editor, cx| {
12392 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12393 editor.unfold_buffer(buffer_id, cx);
12394 }
12395 })
12396 .ok();
12397 });
12398 }
12399 }
12400
12401 pub fn fold_selected_ranges(
12402 &mut self,
12403 _: &FoldSelectedRanges,
12404 window: &mut Window,
12405 cx: &mut Context<Self>,
12406 ) {
12407 let selections = self.selections.all::<Point>(cx);
12408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12409 let line_mode = self.selections.line_mode;
12410 let ranges = selections
12411 .into_iter()
12412 .map(|s| {
12413 if line_mode {
12414 let start = Point::new(s.start.row, 0);
12415 let end = Point::new(
12416 s.end.row,
12417 display_map
12418 .buffer_snapshot
12419 .line_len(MultiBufferRow(s.end.row)),
12420 );
12421 Crease::simple(start..end, display_map.fold_placeholder.clone())
12422 } else {
12423 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12424 }
12425 })
12426 .collect::<Vec<_>>();
12427 self.fold_creases(ranges, true, window, cx);
12428 }
12429
12430 pub fn fold_ranges<T: ToOffset + Clone>(
12431 &mut self,
12432 ranges: Vec<Range<T>>,
12433 auto_scroll: bool,
12434 window: &mut Window,
12435 cx: &mut Context<Self>,
12436 ) {
12437 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12438 let ranges = ranges
12439 .into_iter()
12440 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12441 .collect::<Vec<_>>();
12442 self.fold_creases(ranges, auto_scroll, window, cx);
12443 }
12444
12445 pub fn fold_creases<T: ToOffset + Clone>(
12446 &mut self,
12447 creases: Vec<Crease<T>>,
12448 auto_scroll: bool,
12449 window: &mut Window,
12450 cx: &mut Context<Self>,
12451 ) {
12452 if creases.is_empty() {
12453 return;
12454 }
12455
12456 let mut buffers_affected = HashSet::default();
12457 let multi_buffer = self.buffer().read(cx);
12458 for crease in &creases {
12459 if let Some((_, buffer, _)) =
12460 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12461 {
12462 buffers_affected.insert(buffer.read(cx).remote_id());
12463 };
12464 }
12465
12466 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12467
12468 if auto_scroll {
12469 self.request_autoscroll(Autoscroll::fit(), cx);
12470 }
12471
12472 cx.notify();
12473
12474 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12475 // Clear diagnostics block when folding a range that contains it.
12476 let snapshot = self.snapshot(window, cx);
12477 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12478 drop(snapshot);
12479 self.active_diagnostics = Some(active_diagnostics);
12480 self.dismiss_diagnostics(cx);
12481 } else {
12482 self.active_diagnostics = Some(active_diagnostics);
12483 }
12484 }
12485
12486 self.scrollbar_marker_state.dirty = true;
12487 }
12488
12489 /// Removes any folds whose ranges intersect any of the given ranges.
12490 pub fn unfold_ranges<T: ToOffset + Clone>(
12491 &mut self,
12492 ranges: &[Range<T>],
12493 inclusive: bool,
12494 auto_scroll: bool,
12495 cx: &mut Context<Self>,
12496 ) {
12497 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12498 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12499 });
12500 }
12501
12502 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12503 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12504 return;
12505 }
12506 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12507 self.display_map
12508 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12509 cx.emit(EditorEvent::BufferFoldToggled {
12510 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12511 folded: true,
12512 });
12513 cx.notify();
12514 }
12515
12516 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12517 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12518 return;
12519 }
12520 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12521 self.display_map.update(cx, |display_map, cx| {
12522 display_map.unfold_buffer(buffer_id, cx);
12523 });
12524 cx.emit(EditorEvent::BufferFoldToggled {
12525 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12526 folded: false,
12527 });
12528 cx.notify();
12529 }
12530
12531 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12532 self.display_map.read(cx).is_buffer_folded(buffer)
12533 }
12534
12535 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12536 self.display_map.read(cx).folded_buffers()
12537 }
12538
12539 /// Removes any folds with the given ranges.
12540 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12541 &mut self,
12542 ranges: &[Range<T>],
12543 type_id: TypeId,
12544 auto_scroll: bool,
12545 cx: &mut Context<Self>,
12546 ) {
12547 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12548 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12549 });
12550 }
12551
12552 fn remove_folds_with<T: ToOffset + Clone>(
12553 &mut self,
12554 ranges: &[Range<T>],
12555 auto_scroll: bool,
12556 cx: &mut Context<Self>,
12557 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12558 ) {
12559 if ranges.is_empty() {
12560 return;
12561 }
12562
12563 let mut buffers_affected = HashSet::default();
12564 let multi_buffer = self.buffer().read(cx);
12565 for range in ranges {
12566 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12567 buffers_affected.insert(buffer.read(cx).remote_id());
12568 };
12569 }
12570
12571 self.display_map.update(cx, update);
12572
12573 if auto_scroll {
12574 self.request_autoscroll(Autoscroll::fit(), cx);
12575 }
12576
12577 cx.notify();
12578 self.scrollbar_marker_state.dirty = true;
12579 self.active_indent_guides_state.dirty = true;
12580 }
12581
12582 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12583 self.display_map.read(cx).fold_placeholder.clone()
12584 }
12585
12586 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12587 self.buffer.update(cx, |buffer, cx| {
12588 buffer.set_all_diff_hunks_expanded(cx);
12589 });
12590 }
12591
12592 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12593 self.distinguish_unstaged_diff_hunks = true;
12594 }
12595
12596 pub fn expand_all_diff_hunks(
12597 &mut self,
12598 _: &ExpandAllHunkDiffs,
12599 _window: &mut Window,
12600 cx: &mut Context<Self>,
12601 ) {
12602 self.buffer.update(cx, |buffer, cx| {
12603 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12604 });
12605 }
12606
12607 pub fn toggle_selected_diff_hunks(
12608 &mut self,
12609 _: &ToggleSelectedDiffHunks,
12610 _window: &mut Window,
12611 cx: &mut Context<Self>,
12612 ) {
12613 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12614 self.toggle_diff_hunks_in_ranges(ranges, cx);
12615 }
12616
12617 fn diff_hunks_in_ranges<'a>(
12618 &'a self,
12619 ranges: &'a [Range<Anchor>],
12620 buffer: &'a MultiBufferSnapshot,
12621 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12622 ranges.iter().flat_map(move |range| {
12623 let end_excerpt_id = range.end.excerpt_id;
12624 let range = range.to_point(buffer);
12625 let mut peek_end = range.end;
12626 if range.end.row < buffer.max_row().0 {
12627 peek_end = Point::new(range.end.row + 1, 0);
12628 }
12629 buffer
12630 .diff_hunks_in_range(range.start..peek_end)
12631 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12632 })
12633 }
12634
12635 pub fn has_stageable_diff_hunks_in_ranges(
12636 &self,
12637 ranges: &[Range<Anchor>],
12638 snapshot: &MultiBufferSnapshot,
12639 ) -> bool {
12640 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12641 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12642 }
12643
12644 pub fn toggle_staged_selected_diff_hunks(
12645 &mut self,
12646 _: &ToggleStagedSelectedDiffHunks,
12647 _window: &mut Window,
12648 cx: &mut Context<Self>,
12649 ) {
12650 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12651 self.stage_or_unstage_diff_hunks(&ranges, cx);
12652 }
12653
12654 pub fn stage_or_unstage_diff_hunks(
12655 &mut self,
12656 ranges: &[Range<Anchor>],
12657 cx: &mut Context<Self>,
12658 ) {
12659 let Some(project) = &self.project else {
12660 return;
12661 };
12662 let snapshot = self.buffer.read(cx).snapshot(cx);
12663 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12664
12665 let chunk_by = self
12666 .diff_hunks_in_ranges(&ranges, &snapshot)
12667 .chunk_by(|hunk| hunk.buffer_id);
12668 for (buffer_id, hunks) in &chunk_by {
12669 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12670 log::debug!("no buffer for id");
12671 continue;
12672 };
12673 let buffer = buffer.read(cx).snapshot();
12674 let Some((repo, path)) = project
12675 .read(cx)
12676 .repository_and_path_for_buffer_id(buffer_id, cx)
12677 else {
12678 log::debug!("no git repo for buffer id");
12679 continue;
12680 };
12681 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12682 log::debug!("no diff for buffer id");
12683 continue;
12684 };
12685 let Some(secondary_diff) = diff.secondary_diff() else {
12686 log::debug!("no secondary diff for buffer id");
12687 continue;
12688 };
12689
12690 let edits = diff.secondary_edits_for_stage_or_unstage(
12691 stage,
12692 hunks.map(|hunk| {
12693 (
12694 hunk.diff_base_byte_range.clone(),
12695 hunk.secondary_diff_base_byte_range.clone(),
12696 hunk.buffer_range.clone(),
12697 )
12698 }),
12699 &buffer,
12700 );
12701
12702 let index_base = secondary_diff.base_text().map_or_else(
12703 || Rope::from(""),
12704 |snapshot| snapshot.text.as_rope().clone(),
12705 );
12706 let index_buffer = cx.new(|cx| {
12707 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12708 });
12709 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12710 index_buffer.edit(edits, None, cx);
12711 index_buffer.snapshot().as_rope().to_string()
12712 });
12713 let new_index_text = if new_index_text.is_empty()
12714 && (diff.is_single_insertion
12715 || buffer
12716 .file()
12717 .map_or(false, |file| file.disk_state() == DiskState::New))
12718 {
12719 log::debug!("removing from index");
12720 None
12721 } else {
12722 Some(new_index_text)
12723 };
12724
12725 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12726 }
12727 }
12728
12729 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12730 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12731 self.buffer
12732 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12733 }
12734
12735 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12736 self.buffer.update(cx, |buffer, cx| {
12737 let ranges = vec![Anchor::min()..Anchor::max()];
12738 if !buffer.all_diff_hunks_expanded()
12739 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12740 {
12741 buffer.collapse_diff_hunks(ranges, cx);
12742 true
12743 } else {
12744 false
12745 }
12746 })
12747 }
12748
12749 fn toggle_diff_hunks_in_ranges(
12750 &mut self,
12751 ranges: Vec<Range<Anchor>>,
12752 cx: &mut Context<'_, Editor>,
12753 ) {
12754 self.buffer.update(cx, |buffer, cx| {
12755 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12756 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12757 })
12758 }
12759
12760 fn toggle_diff_hunks_in_ranges_narrow(
12761 &mut self,
12762 ranges: Vec<Range<Anchor>>,
12763 cx: &mut Context<'_, Editor>,
12764 ) {
12765 self.buffer.update(cx, |buffer, cx| {
12766 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12767 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12768 })
12769 }
12770
12771 pub(crate) fn apply_all_diff_hunks(
12772 &mut self,
12773 _: &ApplyAllDiffHunks,
12774 window: &mut Window,
12775 cx: &mut Context<Self>,
12776 ) {
12777 let buffers = self.buffer.read(cx).all_buffers();
12778 for branch_buffer in buffers {
12779 branch_buffer.update(cx, |branch_buffer, cx| {
12780 branch_buffer.merge_into_base(Vec::new(), cx);
12781 });
12782 }
12783
12784 if let Some(project) = self.project.clone() {
12785 self.save(true, project, window, cx).detach_and_log_err(cx);
12786 }
12787 }
12788
12789 pub(crate) fn apply_selected_diff_hunks(
12790 &mut self,
12791 _: &ApplyDiffHunk,
12792 window: &mut Window,
12793 cx: &mut Context<Self>,
12794 ) {
12795 let snapshot = self.snapshot(window, cx);
12796 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12797 let mut ranges_by_buffer = HashMap::default();
12798 self.transact(window, cx, |editor, _window, cx| {
12799 for hunk in hunks {
12800 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12801 ranges_by_buffer
12802 .entry(buffer.clone())
12803 .or_insert_with(Vec::new)
12804 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12805 }
12806 }
12807
12808 for (buffer, ranges) in ranges_by_buffer {
12809 buffer.update(cx, |buffer, cx| {
12810 buffer.merge_into_base(ranges, cx);
12811 });
12812 }
12813 });
12814
12815 if let Some(project) = self.project.clone() {
12816 self.save(true, project, window, cx).detach_and_log_err(cx);
12817 }
12818 }
12819
12820 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12821 if hovered != self.gutter_hovered {
12822 self.gutter_hovered = hovered;
12823 cx.notify();
12824 }
12825 }
12826
12827 pub fn insert_blocks(
12828 &mut self,
12829 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12830 autoscroll: Option<Autoscroll>,
12831 cx: &mut Context<Self>,
12832 ) -> Vec<CustomBlockId> {
12833 let blocks = self
12834 .display_map
12835 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12836 if let Some(autoscroll) = autoscroll {
12837 self.request_autoscroll(autoscroll, cx);
12838 }
12839 cx.notify();
12840 blocks
12841 }
12842
12843 pub fn resize_blocks(
12844 &mut self,
12845 heights: HashMap<CustomBlockId, u32>,
12846 autoscroll: Option<Autoscroll>,
12847 cx: &mut Context<Self>,
12848 ) {
12849 self.display_map
12850 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12851 if let Some(autoscroll) = autoscroll {
12852 self.request_autoscroll(autoscroll, cx);
12853 }
12854 cx.notify();
12855 }
12856
12857 pub fn replace_blocks(
12858 &mut self,
12859 renderers: HashMap<CustomBlockId, RenderBlock>,
12860 autoscroll: Option<Autoscroll>,
12861 cx: &mut Context<Self>,
12862 ) {
12863 self.display_map
12864 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12865 if let Some(autoscroll) = autoscroll {
12866 self.request_autoscroll(autoscroll, cx);
12867 }
12868 cx.notify();
12869 }
12870
12871 pub fn remove_blocks(
12872 &mut self,
12873 block_ids: HashSet<CustomBlockId>,
12874 autoscroll: Option<Autoscroll>,
12875 cx: &mut Context<Self>,
12876 ) {
12877 self.display_map.update(cx, |display_map, cx| {
12878 display_map.remove_blocks(block_ids, cx)
12879 });
12880 if let Some(autoscroll) = autoscroll {
12881 self.request_autoscroll(autoscroll, cx);
12882 }
12883 cx.notify();
12884 }
12885
12886 pub fn row_for_block(
12887 &self,
12888 block_id: CustomBlockId,
12889 cx: &mut Context<Self>,
12890 ) -> Option<DisplayRow> {
12891 self.display_map
12892 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12893 }
12894
12895 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12896 self.focused_block = Some(focused_block);
12897 }
12898
12899 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12900 self.focused_block.take()
12901 }
12902
12903 pub fn insert_creases(
12904 &mut self,
12905 creases: impl IntoIterator<Item = Crease<Anchor>>,
12906 cx: &mut Context<Self>,
12907 ) -> Vec<CreaseId> {
12908 self.display_map
12909 .update(cx, |map, cx| map.insert_creases(creases, cx))
12910 }
12911
12912 pub fn remove_creases(
12913 &mut self,
12914 ids: impl IntoIterator<Item = CreaseId>,
12915 cx: &mut Context<Self>,
12916 ) {
12917 self.display_map
12918 .update(cx, |map, cx| map.remove_creases(ids, cx));
12919 }
12920
12921 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12922 self.display_map
12923 .update(cx, |map, cx| map.snapshot(cx))
12924 .longest_row()
12925 }
12926
12927 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12928 self.display_map
12929 .update(cx, |map, cx| map.snapshot(cx))
12930 .max_point()
12931 }
12932
12933 pub fn text(&self, cx: &App) -> String {
12934 self.buffer.read(cx).read(cx).text()
12935 }
12936
12937 pub fn is_empty(&self, cx: &App) -> bool {
12938 self.buffer.read(cx).read(cx).is_empty()
12939 }
12940
12941 pub fn text_option(&self, cx: &App) -> Option<String> {
12942 let text = self.text(cx);
12943 let text = text.trim();
12944
12945 if text.is_empty() {
12946 return None;
12947 }
12948
12949 Some(text.to_string())
12950 }
12951
12952 pub fn set_text(
12953 &mut self,
12954 text: impl Into<Arc<str>>,
12955 window: &mut Window,
12956 cx: &mut Context<Self>,
12957 ) {
12958 self.transact(window, cx, |this, _, cx| {
12959 this.buffer
12960 .read(cx)
12961 .as_singleton()
12962 .expect("you can only call set_text on editors for singleton buffers")
12963 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12964 });
12965 }
12966
12967 pub fn display_text(&self, cx: &mut App) -> String {
12968 self.display_map
12969 .update(cx, |map, cx| map.snapshot(cx))
12970 .text()
12971 }
12972
12973 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12974 let mut wrap_guides = smallvec::smallvec![];
12975
12976 if self.show_wrap_guides == Some(false) {
12977 return wrap_guides;
12978 }
12979
12980 let settings = self.buffer.read(cx).settings_at(0, cx);
12981 if settings.show_wrap_guides {
12982 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12983 wrap_guides.push((soft_wrap as usize, true));
12984 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12985 wrap_guides.push((soft_wrap as usize, true));
12986 }
12987 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12988 }
12989
12990 wrap_guides
12991 }
12992
12993 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12994 let settings = self.buffer.read(cx).settings_at(0, cx);
12995 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12996 match mode {
12997 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12998 SoftWrap::None
12999 }
13000 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13001 language_settings::SoftWrap::PreferredLineLength => {
13002 SoftWrap::Column(settings.preferred_line_length)
13003 }
13004 language_settings::SoftWrap::Bounded => {
13005 SoftWrap::Bounded(settings.preferred_line_length)
13006 }
13007 }
13008 }
13009
13010 pub fn set_soft_wrap_mode(
13011 &mut self,
13012 mode: language_settings::SoftWrap,
13013
13014 cx: &mut Context<Self>,
13015 ) {
13016 self.soft_wrap_mode_override = Some(mode);
13017 cx.notify();
13018 }
13019
13020 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13021 self.text_style_refinement = Some(style);
13022 }
13023
13024 /// called by the Element so we know what style we were most recently rendered with.
13025 pub(crate) fn set_style(
13026 &mut self,
13027 style: EditorStyle,
13028 window: &mut Window,
13029 cx: &mut Context<Self>,
13030 ) {
13031 let rem_size = window.rem_size();
13032 self.display_map.update(cx, |map, cx| {
13033 map.set_font(
13034 style.text.font(),
13035 style.text.font_size.to_pixels(rem_size),
13036 cx,
13037 )
13038 });
13039 self.style = Some(style);
13040 }
13041
13042 pub fn style(&self) -> Option<&EditorStyle> {
13043 self.style.as_ref()
13044 }
13045
13046 // Called by the element. This method is not designed to be called outside of the editor
13047 // element's layout code because it does not notify when rewrapping is computed synchronously.
13048 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13049 self.display_map
13050 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13051 }
13052
13053 pub fn set_soft_wrap(&mut self) {
13054 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13055 }
13056
13057 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13058 if self.soft_wrap_mode_override.is_some() {
13059 self.soft_wrap_mode_override.take();
13060 } else {
13061 let soft_wrap = match self.soft_wrap_mode(cx) {
13062 SoftWrap::GitDiff => return,
13063 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13064 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13065 language_settings::SoftWrap::None
13066 }
13067 };
13068 self.soft_wrap_mode_override = Some(soft_wrap);
13069 }
13070 cx.notify();
13071 }
13072
13073 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13074 let Some(workspace) = self.workspace() else {
13075 return;
13076 };
13077 let fs = workspace.read(cx).app_state().fs.clone();
13078 let current_show = TabBarSettings::get_global(cx).show;
13079 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13080 setting.show = Some(!current_show);
13081 });
13082 }
13083
13084 pub fn toggle_indent_guides(
13085 &mut self,
13086 _: &ToggleIndentGuides,
13087 _: &mut Window,
13088 cx: &mut Context<Self>,
13089 ) {
13090 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13091 self.buffer
13092 .read(cx)
13093 .settings_at(0, cx)
13094 .indent_guides
13095 .enabled
13096 });
13097 self.show_indent_guides = Some(!currently_enabled);
13098 cx.notify();
13099 }
13100
13101 fn should_show_indent_guides(&self) -> Option<bool> {
13102 self.show_indent_guides
13103 }
13104
13105 pub fn toggle_line_numbers(
13106 &mut self,
13107 _: &ToggleLineNumbers,
13108 _: &mut Window,
13109 cx: &mut Context<Self>,
13110 ) {
13111 let mut editor_settings = EditorSettings::get_global(cx).clone();
13112 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13113 EditorSettings::override_global(editor_settings, cx);
13114 }
13115
13116 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13117 self.use_relative_line_numbers
13118 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13119 }
13120
13121 pub fn toggle_relative_line_numbers(
13122 &mut self,
13123 _: &ToggleRelativeLineNumbers,
13124 _: &mut Window,
13125 cx: &mut Context<Self>,
13126 ) {
13127 let is_relative = self.should_use_relative_line_numbers(cx);
13128 self.set_relative_line_number(Some(!is_relative), cx)
13129 }
13130
13131 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13132 self.use_relative_line_numbers = is_relative;
13133 cx.notify();
13134 }
13135
13136 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13137 self.show_gutter = show_gutter;
13138 cx.notify();
13139 }
13140
13141 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13142 self.show_scrollbars = show_scrollbars;
13143 cx.notify();
13144 }
13145
13146 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13147 self.show_line_numbers = Some(show_line_numbers);
13148 cx.notify();
13149 }
13150
13151 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13152 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13153 cx.notify();
13154 }
13155
13156 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13157 self.show_code_actions = Some(show_code_actions);
13158 cx.notify();
13159 }
13160
13161 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13162 self.show_runnables = Some(show_runnables);
13163 cx.notify();
13164 }
13165
13166 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13167 if self.display_map.read(cx).masked != masked {
13168 self.display_map.update(cx, |map, _| map.masked = masked);
13169 }
13170 cx.notify()
13171 }
13172
13173 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13174 self.show_wrap_guides = Some(show_wrap_guides);
13175 cx.notify();
13176 }
13177
13178 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13179 self.show_indent_guides = Some(show_indent_guides);
13180 cx.notify();
13181 }
13182
13183 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13184 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13185 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13186 if let Some(dir) = file.abs_path(cx).parent() {
13187 return Some(dir.to_owned());
13188 }
13189 }
13190
13191 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13192 return Some(project_path.path.to_path_buf());
13193 }
13194 }
13195
13196 None
13197 }
13198
13199 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13200 self.active_excerpt(cx)?
13201 .1
13202 .read(cx)
13203 .file()
13204 .and_then(|f| f.as_local())
13205 }
13206
13207 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13208 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13209 let buffer = buffer.read(cx);
13210 if let Some(project_path) = buffer.project_path(cx) {
13211 let project = self.project.as_ref()?.read(cx);
13212 project.absolute_path(&project_path, cx)
13213 } else {
13214 buffer
13215 .file()
13216 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13217 }
13218 })
13219 }
13220
13221 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13222 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13223 let project_path = buffer.read(cx).project_path(cx)?;
13224 let project = self.project.as_ref()?.read(cx);
13225 let entry = project.entry_for_path(&project_path, cx)?;
13226 let path = entry.path.to_path_buf();
13227 Some(path)
13228 })
13229 }
13230
13231 pub fn reveal_in_finder(
13232 &mut self,
13233 _: &RevealInFileManager,
13234 _window: &mut Window,
13235 cx: &mut Context<Self>,
13236 ) {
13237 if let Some(target) = self.target_file(cx) {
13238 cx.reveal_path(&target.abs_path(cx));
13239 }
13240 }
13241
13242 pub fn copy_path(
13243 &mut self,
13244 _: &zed_actions::workspace::CopyPath,
13245 _window: &mut Window,
13246 cx: &mut Context<Self>,
13247 ) {
13248 if let Some(path) = self.target_file_abs_path(cx) {
13249 if let Some(path) = path.to_str() {
13250 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13251 }
13252 }
13253 }
13254
13255 pub fn copy_relative_path(
13256 &mut self,
13257 _: &zed_actions::workspace::CopyRelativePath,
13258 _window: &mut Window,
13259 cx: &mut Context<Self>,
13260 ) {
13261 if let Some(path) = self.target_file_path(cx) {
13262 if let Some(path) = path.to_str() {
13263 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13264 }
13265 }
13266 }
13267
13268 pub fn copy_file_name_without_extension(
13269 &mut self,
13270 _: &CopyFileNameWithoutExtension,
13271 _: &mut Window,
13272 cx: &mut Context<Self>,
13273 ) {
13274 if let Some(file) = self.target_file(cx) {
13275 if let Some(file_stem) = file.path().file_stem() {
13276 if let Some(name) = file_stem.to_str() {
13277 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13278 }
13279 }
13280 }
13281 }
13282
13283 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13284 if let Some(file) = self.target_file(cx) {
13285 if let Some(file_name) = file.path().file_name() {
13286 if let Some(name) = file_name.to_str() {
13287 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13288 }
13289 }
13290 }
13291 }
13292
13293 pub fn toggle_git_blame(
13294 &mut self,
13295 _: &ToggleGitBlame,
13296 window: &mut Window,
13297 cx: &mut Context<Self>,
13298 ) {
13299 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13300
13301 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13302 self.start_git_blame(true, window, cx);
13303 }
13304
13305 cx.notify();
13306 }
13307
13308 pub fn toggle_git_blame_inline(
13309 &mut self,
13310 _: &ToggleGitBlameInline,
13311 window: &mut Window,
13312 cx: &mut Context<Self>,
13313 ) {
13314 self.toggle_git_blame_inline_internal(true, window, cx);
13315 cx.notify();
13316 }
13317
13318 pub fn git_blame_inline_enabled(&self) -> bool {
13319 self.git_blame_inline_enabled
13320 }
13321
13322 pub fn toggle_selection_menu(
13323 &mut self,
13324 _: &ToggleSelectionMenu,
13325 _: &mut Window,
13326 cx: &mut Context<Self>,
13327 ) {
13328 self.show_selection_menu = self
13329 .show_selection_menu
13330 .map(|show_selections_menu| !show_selections_menu)
13331 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13332
13333 cx.notify();
13334 }
13335
13336 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13337 self.show_selection_menu
13338 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13339 }
13340
13341 fn start_git_blame(
13342 &mut self,
13343 user_triggered: bool,
13344 window: &mut Window,
13345 cx: &mut Context<Self>,
13346 ) {
13347 if let Some(project) = self.project.as_ref() {
13348 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13349 return;
13350 };
13351
13352 if buffer.read(cx).file().is_none() {
13353 return;
13354 }
13355
13356 let focused = self.focus_handle(cx).contains_focused(window, cx);
13357
13358 let project = project.clone();
13359 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13360 self.blame_subscription =
13361 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13362 self.blame = Some(blame);
13363 }
13364 }
13365
13366 fn toggle_git_blame_inline_internal(
13367 &mut self,
13368 user_triggered: bool,
13369 window: &mut Window,
13370 cx: &mut Context<Self>,
13371 ) {
13372 if self.git_blame_inline_enabled {
13373 self.git_blame_inline_enabled = false;
13374 self.show_git_blame_inline = false;
13375 self.show_git_blame_inline_delay_task.take();
13376 } else {
13377 self.git_blame_inline_enabled = true;
13378 self.start_git_blame_inline(user_triggered, window, cx);
13379 }
13380
13381 cx.notify();
13382 }
13383
13384 fn start_git_blame_inline(
13385 &mut self,
13386 user_triggered: bool,
13387 window: &mut Window,
13388 cx: &mut Context<Self>,
13389 ) {
13390 self.start_git_blame(user_triggered, window, cx);
13391
13392 if ProjectSettings::get_global(cx)
13393 .git
13394 .inline_blame_delay()
13395 .is_some()
13396 {
13397 self.start_inline_blame_timer(window, cx);
13398 } else {
13399 self.show_git_blame_inline = true
13400 }
13401 }
13402
13403 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13404 self.blame.as_ref()
13405 }
13406
13407 pub fn show_git_blame_gutter(&self) -> bool {
13408 self.show_git_blame_gutter
13409 }
13410
13411 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13412 self.show_git_blame_gutter && self.has_blame_entries(cx)
13413 }
13414
13415 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13416 self.show_git_blame_inline
13417 && self.focus_handle.is_focused(window)
13418 && !self.newest_selection_head_on_empty_line(cx)
13419 && self.has_blame_entries(cx)
13420 }
13421
13422 fn has_blame_entries(&self, cx: &App) -> bool {
13423 self.blame()
13424 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13425 }
13426
13427 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13428 let cursor_anchor = self.selections.newest_anchor().head();
13429
13430 let snapshot = self.buffer.read(cx).snapshot(cx);
13431 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13432
13433 snapshot.line_len(buffer_row) == 0
13434 }
13435
13436 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13437 let buffer_and_selection = maybe!({
13438 let selection = self.selections.newest::<Point>(cx);
13439 let selection_range = selection.range();
13440
13441 let multi_buffer = self.buffer().read(cx);
13442 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13443 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13444
13445 let (buffer, range, _) = if selection.reversed {
13446 buffer_ranges.first()
13447 } else {
13448 buffer_ranges.last()
13449 }?;
13450
13451 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13452 ..text::ToPoint::to_point(&range.end, &buffer).row;
13453 Some((
13454 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13455 selection,
13456 ))
13457 });
13458
13459 let Some((buffer, selection)) = buffer_and_selection else {
13460 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13461 };
13462
13463 let Some(project) = self.project.as_ref() else {
13464 return Task::ready(Err(anyhow!("editor does not have project")));
13465 };
13466
13467 project.update(cx, |project, cx| {
13468 project.get_permalink_to_line(&buffer, selection, cx)
13469 })
13470 }
13471
13472 pub fn copy_permalink_to_line(
13473 &mut self,
13474 _: &CopyPermalinkToLine,
13475 window: &mut Window,
13476 cx: &mut Context<Self>,
13477 ) {
13478 let permalink_task = self.get_permalink_to_line(cx);
13479 let workspace = self.workspace();
13480
13481 cx.spawn_in(window, |_, mut cx| async move {
13482 match permalink_task.await {
13483 Ok(permalink) => {
13484 cx.update(|_, cx| {
13485 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13486 })
13487 .ok();
13488 }
13489 Err(err) => {
13490 let message = format!("Failed to copy permalink: {err}");
13491
13492 Err::<(), anyhow::Error>(err).log_err();
13493
13494 if let Some(workspace) = workspace {
13495 workspace
13496 .update_in(&mut cx, |workspace, _, cx| {
13497 struct CopyPermalinkToLine;
13498
13499 workspace.show_toast(
13500 Toast::new(
13501 NotificationId::unique::<CopyPermalinkToLine>(),
13502 message,
13503 ),
13504 cx,
13505 )
13506 })
13507 .ok();
13508 }
13509 }
13510 }
13511 })
13512 .detach();
13513 }
13514
13515 pub fn copy_file_location(
13516 &mut self,
13517 _: &CopyFileLocation,
13518 _: &mut Window,
13519 cx: &mut Context<Self>,
13520 ) {
13521 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13522 if let Some(file) = self.target_file(cx) {
13523 if let Some(path) = file.path().to_str() {
13524 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13525 }
13526 }
13527 }
13528
13529 pub fn open_permalink_to_line(
13530 &mut self,
13531 _: &OpenPermalinkToLine,
13532 window: &mut Window,
13533 cx: &mut Context<Self>,
13534 ) {
13535 let permalink_task = self.get_permalink_to_line(cx);
13536 let workspace = self.workspace();
13537
13538 cx.spawn_in(window, |_, mut cx| async move {
13539 match permalink_task.await {
13540 Ok(permalink) => {
13541 cx.update(|_, cx| {
13542 cx.open_url(permalink.as_ref());
13543 })
13544 .ok();
13545 }
13546 Err(err) => {
13547 let message = format!("Failed to open permalink: {err}");
13548
13549 Err::<(), anyhow::Error>(err).log_err();
13550
13551 if let Some(workspace) = workspace {
13552 workspace
13553 .update(&mut cx, |workspace, cx| {
13554 struct OpenPermalinkToLine;
13555
13556 workspace.show_toast(
13557 Toast::new(
13558 NotificationId::unique::<OpenPermalinkToLine>(),
13559 message,
13560 ),
13561 cx,
13562 )
13563 })
13564 .ok();
13565 }
13566 }
13567 }
13568 })
13569 .detach();
13570 }
13571
13572 pub fn insert_uuid_v4(
13573 &mut self,
13574 _: &InsertUuidV4,
13575 window: &mut Window,
13576 cx: &mut Context<Self>,
13577 ) {
13578 self.insert_uuid(UuidVersion::V4, window, cx);
13579 }
13580
13581 pub fn insert_uuid_v7(
13582 &mut self,
13583 _: &InsertUuidV7,
13584 window: &mut Window,
13585 cx: &mut Context<Self>,
13586 ) {
13587 self.insert_uuid(UuidVersion::V7, window, cx);
13588 }
13589
13590 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13591 self.transact(window, cx, |this, window, cx| {
13592 let edits = this
13593 .selections
13594 .all::<Point>(cx)
13595 .into_iter()
13596 .map(|selection| {
13597 let uuid = match version {
13598 UuidVersion::V4 => uuid::Uuid::new_v4(),
13599 UuidVersion::V7 => uuid::Uuid::now_v7(),
13600 };
13601
13602 (selection.range(), uuid.to_string())
13603 });
13604 this.edit(edits, cx);
13605 this.refresh_inline_completion(true, false, window, cx);
13606 });
13607 }
13608
13609 pub fn open_selections_in_multibuffer(
13610 &mut self,
13611 _: &OpenSelectionsInMultibuffer,
13612 window: &mut Window,
13613 cx: &mut Context<Self>,
13614 ) {
13615 let multibuffer = self.buffer.read(cx);
13616
13617 let Some(buffer) = multibuffer.as_singleton() else {
13618 return;
13619 };
13620
13621 let Some(workspace) = self.workspace() else {
13622 return;
13623 };
13624
13625 let locations = self
13626 .selections
13627 .disjoint_anchors()
13628 .iter()
13629 .map(|range| Location {
13630 buffer: buffer.clone(),
13631 range: range.start.text_anchor..range.end.text_anchor,
13632 })
13633 .collect::<Vec<_>>();
13634
13635 let title = multibuffer.title(cx).to_string();
13636
13637 cx.spawn_in(window, |_, mut cx| async move {
13638 workspace.update_in(&mut cx, |workspace, window, cx| {
13639 Self::open_locations_in_multibuffer(
13640 workspace,
13641 locations,
13642 format!("Selections for '{title}'"),
13643 false,
13644 MultibufferSelectionMode::All,
13645 window,
13646 cx,
13647 );
13648 })
13649 })
13650 .detach();
13651 }
13652
13653 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13654 /// last highlight added will be used.
13655 ///
13656 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13657 pub fn highlight_rows<T: 'static>(
13658 &mut self,
13659 range: Range<Anchor>,
13660 color: Hsla,
13661 should_autoscroll: bool,
13662 cx: &mut Context<Self>,
13663 ) {
13664 let snapshot = self.buffer().read(cx).snapshot(cx);
13665 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13666 let ix = row_highlights.binary_search_by(|highlight| {
13667 Ordering::Equal
13668 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13669 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13670 });
13671
13672 if let Err(mut ix) = ix {
13673 let index = post_inc(&mut self.highlight_order);
13674
13675 // If this range intersects with the preceding highlight, then merge it with
13676 // the preceding highlight. Otherwise insert a new highlight.
13677 let mut merged = false;
13678 if ix > 0 {
13679 let prev_highlight = &mut row_highlights[ix - 1];
13680 if prev_highlight
13681 .range
13682 .end
13683 .cmp(&range.start, &snapshot)
13684 .is_ge()
13685 {
13686 ix -= 1;
13687 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13688 prev_highlight.range.end = range.end;
13689 }
13690 merged = true;
13691 prev_highlight.index = index;
13692 prev_highlight.color = color;
13693 prev_highlight.should_autoscroll = should_autoscroll;
13694 }
13695 }
13696
13697 if !merged {
13698 row_highlights.insert(
13699 ix,
13700 RowHighlight {
13701 range: range.clone(),
13702 index,
13703 color,
13704 should_autoscroll,
13705 },
13706 );
13707 }
13708
13709 // If any of the following highlights intersect with this one, merge them.
13710 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13711 let highlight = &row_highlights[ix];
13712 if next_highlight
13713 .range
13714 .start
13715 .cmp(&highlight.range.end, &snapshot)
13716 .is_le()
13717 {
13718 if next_highlight
13719 .range
13720 .end
13721 .cmp(&highlight.range.end, &snapshot)
13722 .is_gt()
13723 {
13724 row_highlights[ix].range.end = next_highlight.range.end;
13725 }
13726 row_highlights.remove(ix + 1);
13727 } else {
13728 break;
13729 }
13730 }
13731 }
13732 }
13733
13734 /// Remove any highlighted row ranges of the given type that intersect the
13735 /// given ranges.
13736 pub fn remove_highlighted_rows<T: 'static>(
13737 &mut self,
13738 ranges_to_remove: Vec<Range<Anchor>>,
13739 cx: &mut Context<Self>,
13740 ) {
13741 let snapshot = self.buffer().read(cx).snapshot(cx);
13742 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13743 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13744 row_highlights.retain(|highlight| {
13745 while let Some(range_to_remove) = ranges_to_remove.peek() {
13746 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13747 Ordering::Less | Ordering::Equal => {
13748 ranges_to_remove.next();
13749 }
13750 Ordering::Greater => {
13751 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13752 Ordering::Less | Ordering::Equal => {
13753 return false;
13754 }
13755 Ordering::Greater => break,
13756 }
13757 }
13758 }
13759 }
13760
13761 true
13762 })
13763 }
13764
13765 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13766 pub fn clear_row_highlights<T: 'static>(&mut self) {
13767 self.highlighted_rows.remove(&TypeId::of::<T>());
13768 }
13769
13770 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13771 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13772 self.highlighted_rows
13773 .get(&TypeId::of::<T>())
13774 .map_or(&[] as &[_], |vec| vec.as_slice())
13775 .iter()
13776 .map(|highlight| (highlight.range.clone(), highlight.color))
13777 }
13778
13779 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13780 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13781 /// Allows to ignore certain kinds of highlights.
13782 pub fn highlighted_display_rows(
13783 &self,
13784 window: &mut Window,
13785 cx: &mut App,
13786 ) -> BTreeMap<DisplayRow, Background> {
13787 let snapshot = self.snapshot(window, cx);
13788 let mut used_highlight_orders = HashMap::default();
13789 self.highlighted_rows
13790 .iter()
13791 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13792 .fold(
13793 BTreeMap::<DisplayRow, Background>::new(),
13794 |mut unique_rows, highlight| {
13795 let start = highlight.range.start.to_display_point(&snapshot);
13796 let end = highlight.range.end.to_display_point(&snapshot);
13797 let start_row = start.row().0;
13798 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13799 && end.column() == 0
13800 {
13801 end.row().0.saturating_sub(1)
13802 } else {
13803 end.row().0
13804 };
13805 for row in start_row..=end_row {
13806 let used_index =
13807 used_highlight_orders.entry(row).or_insert(highlight.index);
13808 if highlight.index >= *used_index {
13809 *used_index = highlight.index;
13810 unique_rows.insert(DisplayRow(row), highlight.color.into());
13811 }
13812 }
13813 unique_rows
13814 },
13815 )
13816 }
13817
13818 pub fn highlighted_display_row_for_autoscroll(
13819 &self,
13820 snapshot: &DisplaySnapshot,
13821 ) -> Option<DisplayRow> {
13822 self.highlighted_rows
13823 .values()
13824 .flat_map(|highlighted_rows| highlighted_rows.iter())
13825 .filter_map(|highlight| {
13826 if highlight.should_autoscroll {
13827 Some(highlight.range.start.to_display_point(snapshot).row())
13828 } else {
13829 None
13830 }
13831 })
13832 .min()
13833 }
13834
13835 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13836 self.highlight_background::<SearchWithinRange>(
13837 ranges,
13838 |colors| colors.editor_document_highlight_read_background,
13839 cx,
13840 )
13841 }
13842
13843 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13844 self.breadcrumb_header = Some(new_header);
13845 }
13846
13847 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13848 self.clear_background_highlights::<SearchWithinRange>(cx);
13849 }
13850
13851 pub fn highlight_background<T: 'static>(
13852 &mut self,
13853 ranges: &[Range<Anchor>],
13854 color_fetcher: fn(&ThemeColors) -> Hsla,
13855 cx: &mut Context<Self>,
13856 ) {
13857 self.background_highlights
13858 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13859 self.scrollbar_marker_state.dirty = true;
13860 cx.notify();
13861 }
13862
13863 pub fn clear_background_highlights<T: 'static>(
13864 &mut self,
13865 cx: &mut Context<Self>,
13866 ) -> Option<BackgroundHighlight> {
13867 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13868 if !text_highlights.1.is_empty() {
13869 self.scrollbar_marker_state.dirty = true;
13870 cx.notify();
13871 }
13872 Some(text_highlights)
13873 }
13874
13875 pub fn highlight_gutter<T: 'static>(
13876 &mut self,
13877 ranges: &[Range<Anchor>],
13878 color_fetcher: fn(&App) -> Hsla,
13879 cx: &mut Context<Self>,
13880 ) {
13881 self.gutter_highlights
13882 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13883 cx.notify();
13884 }
13885
13886 pub fn clear_gutter_highlights<T: 'static>(
13887 &mut self,
13888 cx: &mut Context<Self>,
13889 ) -> Option<GutterHighlight> {
13890 cx.notify();
13891 self.gutter_highlights.remove(&TypeId::of::<T>())
13892 }
13893
13894 #[cfg(feature = "test-support")]
13895 pub fn all_text_background_highlights(
13896 &self,
13897 window: &mut Window,
13898 cx: &mut Context<Self>,
13899 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13900 let snapshot = self.snapshot(window, cx);
13901 let buffer = &snapshot.buffer_snapshot;
13902 let start = buffer.anchor_before(0);
13903 let end = buffer.anchor_after(buffer.len());
13904 let theme = cx.theme().colors();
13905 self.background_highlights_in_range(start..end, &snapshot, theme)
13906 }
13907
13908 #[cfg(feature = "test-support")]
13909 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13910 let snapshot = self.buffer().read(cx).snapshot(cx);
13911
13912 let highlights = self
13913 .background_highlights
13914 .get(&TypeId::of::<items::BufferSearchHighlights>());
13915
13916 if let Some((_color, ranges)) = highlights {
13917 ranges
13918 .iter()
13919 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13920 .collect_vec()
13921 } else {
13922 vec![]
13923 }
13924 }
13925
13926 fn document_highlights_for_position<'a>(
13927 &'a self,
13928 position: Anchor,
13929 buffer: &'a MultiBufferSnapshot,
13930 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13931 let read_highlights = self
13932 .background_highlights
13933 .get(&TypeId::of::<DocumentHighlightRead>())
13934 .map(|h| &h.1);
13935 let write_highlights = self
13936 .background_highlights
13937 .get(&TypeId::of::<DocumentHighlightWrite>())
13938 .map(|h| &h.1);
13939 let left_position = position.bias_left(buffer);
13940 let right_position = position.bias_right(buffer);
13941 read_highlights
13942 .into_iter()
13943 .chain(write_highlights)
13944 .flat_map(move |ranges| {
13945 let start_ix = match ranges.binary_search_by(|probe| {
13946 let cmp = probe.end.cmp(&left_position, buffer);
13947 if cmp.is_ge() {
13948 Ordering::Greater
13949 } else {
13950 Ordering::Less
13951 }
13952 }) {
13953 Ok(i) | Err(i) => i,
13954 };
13955
13956 ranges[start_ix..]
13957 .iter()
13958 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13959 })
13960 }
13961
13962 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13963 self.background_highlights
13964 .get(&TypeId::of::<T>())
13965 .map_or(false, |(_, highlights)| !highlights.is_empty())
13966 }
13967
13968 pub fn background_highlights_in_range(
13969 &self,
13970 search_range: Range<Anchor>,
13971 display_snapshot: &DisplaySnapshot,
13972 theme: &ThemeColors,
13973 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13974 let mut results = Vec::new();
13975 for (color_fetcher, ranges) in self.background_highlights.values() {
13976 let color = color_fetcher(theme);
13977 let start_ix = match ranges.binary_search_by(|probe| {
13978 let cmp = probe
13979 .end
13980 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13981 if cmp.is_gt() {
13982 Ordering::Greater
13983 } else {
13984 Ordering::Less
13985 }
13986 }) {
13987 Ok(i) | Err(i) => i,
13988 };
13989 for range in &ranges[start_ix..] {
13990 if range
13991 .start
13992 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13993 .is_ge()
13994 {
13995 break;
13996 }
13997
13998 let start = range.start.to_display_point(display_snapshot);
13999 let end = range.end.to_display_point(display_snapshot);
14000 results.push((start..end, color))
14001 }
14002 }
14003 results
14004 }
14005
14006 pub fn background_highlight_row_ranges<T: 'static>(
14007 &self,
14008 search_range: Range<Anchor>,
14009 display_snapshot: &DisplaySnapshot,
14010 count: usize,
14011 ) -> Vec<RangeInclusive<DisplayPoint>> {
14012 let mut results = Vec::new();
14013 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14014 return vec![];
14015 };
14016
14017 let start_ix = match ranges.binary_search_by(|probe| {
14018 let cmp = probe
14019 .end
14020 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14021 if cmp.is_gt() {
14022 Ordering::Greater
14023 } else {
14024 Ordering::Less
14025 }
14026 }) {
14027 Ok(i) | Err(i) => i,
14028 };
14029 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14030 if let (Some(start_display), Some(end_display)) = (start, end) {
14031 results.push(
14032 start_display.to_display_point(display_snapshot)
14033 ..=end_display.to_display_point(display_snapshot),
14034 );
14035 }
14036 };
14037 let mut start_row: Option<Point> = None;
14038 let mut end_row: Option<Point> = None;
14039 if ranges.len() > count {
14040 return Vec::new();
14041 }
14042 for range in &ranges[start_ix..] {
14043 if range
14044 .start
14045 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14046 .is_ge()
14047 {
14048 break;
14049 }
14050 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14051 if let Some(current_row) = &end_row {
14052 if end.row == current_row.row {
14053 continue;
14054 }
14055 }
14056 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14057 if start_row.is_none() {
14058 assert_eq!(end_row, None);
14059 start_row = Some(start);
14060 end_row = Some(end);
14061 continue;
14062 }
14063 if let Some(current_end) = end_row.as_mut() {
14064 if start.row > current_end.row + 1 {
14065 push_region(start_row, end_row);
14066 start_row = Some(start);
14067 end_row = Some(end);
14068 } else {
14069 // Merge two hunks.
14070 *current_end = end;
14071 }
14072 } else {
14073 unreachable!();
14074 }
14075 }
14076 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14077 push_region(start_row, end_row);
14078 results
14079 }
14080
14081 pub fn gutter_highlights_in_range(
14082 &self,
14083 search_range: Range<Anchor>,
14084 display_snapshot: &DisplaySnapshot,
14085 cx: &App,
14086 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14087 let mut results = Vec::new();
14088 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14089 let color = color_fetcher(cx);
14090 let start_ix = match ranges.binary_search_by(|probe| {
14091 let cmp = probe
14092 .end
14093 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14094 if cmp.is_gt() {
14095 Ordering::Greater
14096 } else {
14097 Ordering::Less
14098 }
14099 }) {
14100 Ok(i) | Err(i) => i,
14101 };
14102 for range in &ranges[start_ix..] {
14103 if range
14104 .start
14105 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14106 .is_ge()
14107 {
14108 break;
14109 }
14110
14111 let start = range.start.to_display_point(display_snapshot);
14112 let end = range.end.to_display_point(display_snapshot);
14113 results.push((start..end, color))
14114 }
14115 }
14116 results
14117 }
14118
14119 /// Get the text ranges corresponding to the redaction query
14120 pub fn redacted_ranges(
14121 &self,
14122 search_range: Range<Anchor>,
14123 display_snapshot: &DisplaySnapshot,
14124 cx: &App,
14125 ) -> Vec<Range<DisplayPoint>> {
14126 display_snapshot
14127 .buffer_snapshot
14128 .redacted_ranges(search_range, |file| {
14129 if let Some(file) = file {
14130 file.is_private()
14131 && EditorSettings::get(
14132 Some(SettingsLocation {
14133 worktree_id: file.worktree_id(cx),
14134 path: file.path().as_ref(),
14135 }),
14136 cx,
14137 )
14138 .redact_private_values
14139 } else {
14140 false
14141 }
14142 })
14143 .map(|range| {
14144 range.start.to_display_point(display_snapshot)
14145 ..range.end.to_display_point(display_snapshot)
14146 })
14147 .collect()
14148 }
14149
14150 pub fn highlight_text<T: 'static>(
14151 &mut self,
14152 ranges: Vec<Range<Anchor>>,
14153 style: HighlightStyle,
14154 cx: &mut Context<Self>,
14155 ) {
14156 self.display_map.update(cx, |map, _| {
14157 map.highlight_text(TypeId::of::<T>(), ranges, style)
14158 });
14159 cx.notify();
14160 }
14161
14162 pub(crate) fn highlight_inlays<T: 'static>(
14163 &mut self,
14164 highlights: Vec<InlayHighlight>,
14165 style: HighlightStyle,
14166 cx: &mut Context<Self>,
14167 ) {
14168 self.display_map.update(cx, |map, _| {
14169 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14170 });
14171 cx.notify();
14172 }
14173
14174 pub fn text_highlights<'a, T: 'static>(
14175 &'a self,
14176 cx: &'a App,
14177 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14178 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14179 }
14180
14181 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14182 let cleared = self
14183 .display_map
14184 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14185 if cleared {
14186 cx.notify();
14187 }
14188 }
14189
14190 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14191 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14192 && self.focus_handle.is_focused(window)
14193 }
14194
14195 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14196 self.show_cursor_when_unfocused = is_enabled;
14197 cx.notify();
14198 }
14199
14200 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14201 cx.notify();
14202 }
14203
14204 fn on_buffer_event(
14205 &mut self,
14206 multibuffer: &Entity<MultiBuffer>,
14207 event: &multi_buffer::Event,
14208 window: &mut Window,
14209 cx: &mut Context<Self>,
14210 ) {
14211 match event {
14212 multi_buffer::Event::Edited {
14213 singleton_buffer_edited,
14214 edited_buffer: buffer_edited,
14215 } => {
14216 self.scrollbar_marker_state.dirty = true;
14217 self.active_indent_guides_state.dirty = true;
14218 self.refresh_active_diagnostics(cx);
14219 self.refresh_code_actions(window, cx);
14220 if self.has_active_inline_completion() {
14221 self.update_visible_inline_completion(window, cx);
14222 }
14223 if let Some(buffer) = buffer_edited {
14224 let buffer_id = buffer.read(cx).remote_id();
14225 if !self.registered_buffers.contains_key(&buffer_id) {
14226 if let Some(project) = self.project.as_ref() {
14227 project.update(cx, |project, cx| {
14228 self.registered_buffers.insert(
14229 buffer_id,
14230 project.register_buffer_with_language_servers(&buffer, cx),
14231 );
14232 })
14233 }
14234 }
14235 }
14236 cx.emit(EditorEvent::BufferEdited);
14237 cx.emit(SearchEvent::MatchesInvalidated);
14238 if *singleton_buffer_edited {
14239 if let Some(project) = &self.project {
14240 #[allow(clippy::mutable_key_type)]
14241 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14242 multibuffer
14243 .all_buffers()
14244 .into_iter()
14245 .filter_map(|buffer| {
14246 buffer.update(cx, |buffer, cx| {
14247 let language = buffer.language()?;
14248 let should_discard = project.update(cx, |project, cx| {
14249 project.is_local()
14250 && !project.has_language_servers_for(buffer, cx)
14251 });
14252 should_discard.not().then_some(language.clone())
14253 })
14254 })
14255 .collect::<HashSet<_>>()
14256 });
14257 if !languages_affected.is_empty() {
14258 self.refresh_inlay_hints(
14259 InlayHintRefreshReason::BufferEdited(languages_affected),
14260 cx,
14261 );
14262 }
14263 }
14264 }
14265
14266 let Some(project) = &self.project else { return };
14267 let (telemetry, is_via_ssh) = {
14268 let project = project.read(cx);
14269 let telemetry = project.client().telemetry().clone();
14270 let is_via_ssh = project.is_via_ssh();
14271 (telemetry, is_via_ssh)
14272 };
14273 refresh_linked_ranges(self, window, cx);
14274 telemetry.log_edit_event("editor", is_via_ssh);
14275 }
14276 multi_buffer::Event::ExcerptsAdded {
14277 buffer,
14278 predecessor,
14279 excerpts,
14280 } => {
14281 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14282 let buffer_id = buffer.read(cx).remote_id();
14283 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14284 if let Some(project) = &self.project {
14285 get_uncommitted_diff_for_buffer(
14286 project,
14287 [buffer.clone()],
14288 self.buffer.clone(),
14289 cx,
14290 )
14291 .detach();
14292 }
14293 }
14294 cx.emit(EditorEvent::ExcerptsAdded {
14295 buffer: buffer.clone(),
14296 predecessor: *predecessor,
14297 excerpts: excerpts.clone(),
14298 });
14299 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14300 }
14301 multi_buffer::Event::ExcerptsRemoved { ids } => {
14302 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14303 let buffer = self.buffer.read(cx);
14304 self.registered_buffers
14305 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14306 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14307 }
14308 multi_buffer::Event::ExcerptsEdited { ids } => {
14309 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14310 }
14311 multi_buffer::Event::ExcerptsExpanded { ids } => {
14312 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14313 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14314 }
14315 multi_buffer::Event::Reparsed(buffer_id) => {
14316 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14317
14318 cx.emit(EditorEvent::Reparsed(*buffer_id));
14319 }
14320 multi_buffer::Event::DiffHunksToggled => {
14321 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14322 }
14323 multi_buffer::Event::LanguageChanged(buffer_id) => {
14324 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14325 cx.emit(EditorEvent::Reparsed(*buffer_id));
14326 cx.notify();
14327 }
14328 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14329 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14330 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14331 cx.emit(EditorEvent::TitleChanged)
14332 }
14333 // multi_buffer::Event::DiffBaseChanged => {
14334 // self.scrollbar_marker_state.dirty = true;
14335 // cx.emit(EditorEvent::DiffBaseChanged);
14336 // cx.notify();
14337 // }
14338 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14339 multi_buffer::Event::DiagnosticsUpdated => {
14340 self.refresh_active_diagnostics(cx);
14341 self.scrollbar_marker_state.dirty = true;
14342 cx.notify();
14343 }
14344 _ => {}
14345 };
14346 }
14347
14348 fn on_display_map_changed(
14349 &mut self,
14350 _: Entity<DisplayMap>,
14351 _: &mut Window,
14352 cx: &mut Context<Self>,
14353 ) {
14354 cx.notify();
14355 }
14356
14357 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14358 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14359 self.refresh_inline_completion(true, false, window, cx);
14360 self.refresh_inlay_hints(
14361 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14362 self.selections.newest_anchor().head(),
14363 &self.buffer.read(cx).snapshot(cx),
14364 cx,
14365 )),
14366 cx,
14367 );
14368
14369 let old_cursor_shape = self.cursor_shape;
14370
14371 {
14372 let editor_settings = EditorSettings::get_global(cx);
14373 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14374 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14375 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14376 }
14377
14378 if old_cursor_shape != self.cursor_shape {
14379 cx.emit(EditorEvent::CursorShapeChanged);
14380 }
14381
14382 let project_settings = ProjectSettings::get_global(cx);
14383 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14384
14385 if self.mode == EditorMode::Full {
14386 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14387 if self.git_blame_inline_enabled != inline_blame_enabled {
14388 self.toggle_git_blame_inline_internal(false, window, cx);
14389 }
14390 }
14391
14392 cx.notify();
14393 }
14394
14395 pub fn set_searchable(&mut self, searchable: bool) {
14396 self.searchable = searchable;
14397 }
14398
14399 pub fn searchable(&self) -> bool {
14400 self.searchable
14401 }
14402
14403 fn open_proposed_changes_editor(
14404 &mut self,
14405 _: &OpenProposedChangesEditor,
14406 window: &mut Window,
14407 cx: &mut Context<Self>,
14408 ) {
14409 let Some(workspace) = self.workspace() else {
14410 cx.propagate();
14411 return;
14412 };
14413
14414 let selections = self.selections.all::<usize>(cx);
14415 let multi_buffer = self.buffer.read(cx);
14416 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14417 let mut new_selections_by_buffer = HashMap::default();
14418 for selection in selections {
14419 for (buffer, range, _) in
14420 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14421 {
14422 let mut range = range.to_point(buffer);
14423 range.start.column = 0;
14424 range.end.column = buffer.line_len(range.end.row);
14425 new_selections_by_buffer
14426 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14427 .or_insert(Vec::new())
14428 .push(range)
14429 }
14430 }
14431
14432 let proposed_changes_buffers = new_selections_by_buffer
14433 .into_iter()
14434 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14435 .collect::<Vec<_>>();
14436 let proposed_changes_editor = cx.new(|cx| {
14437 ProposedChangesEditor::new(
14438 "Proposed changes",
14439 proposed_changes_buffers,
14440 self.project.clone(),
14441 window,
14442 cx,
14443 )
14444 });
14445
14446 window.defer(cx, move |window, cx| {
14447 workspace.update(cx, |workspace, cx| {
14448 workspace.active_pane().update(cx, |pane, cx| {
14449 pane.add_item(
14450 Box::new(proposed_changes_editor),
14451 true,
14452 true,
14453 None,
14454 window,
14455 cx,
14456 );
14457 });
14458 });
14459 });
14460 }
14461
14462 pub fn open_excerpts_in_split(
14463 &mut self,
14464 _: &OpenExcerptsSplit,
14465 window: &mut Window,
14466 cx: &mut Context<Self>,
14467 ) {
14468 self.open_excerpts_common(None, true, window, cx)
14469 }
14470
14471 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14472 self.open_excerpts_common(None, false, window, cx)
14473 }
14474
14475 fn open_excerpts_common(
14476 &mut self,
14477 jump_data: Option<JumpData>,
14478 split: bool,
14479 window: &mut Window,
14480 cx: &mut Context<Self>,
14481 ) {
14482 let Some(workspace) = self.workspace() else {
14483 cx.propagate();
14484 return;
14485 };
14486
14487 if self.buffer.read(cx).is_singleton() {
14488 cx.propagate();
14489 return;
14490 }
14491
14492 let mut new_selections_by_buffer = HashMap::default();
14493 match &jump_data {
14494 Some(JumpData::MultiBufferPoint {
14495 excerpt_id,
14496 position,
14497 anchor,
14498 line_offset_from_top,
14499 }) => {
14500 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14501 if let Some(buffer) = multi_buffer_snapshot
14502 .buffer_id_for_excerpt(*excerpt_id)
14503 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14504 {
14505 let buffer_snapshot = buffer.read(cx).snapshot();
14506 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14507 language::ToPoint::to_point(anchor, &buffer_snapshot)
14508 } else {
14509 buffer_snapshot.clip_point(*position, Bias::Left)
14510 };
14511 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14512 new_selections_by_buffer.insert(
14513 buffer,
14514 (
14515 vec![jump_to_offset..jump_to_offset],
14516 Some(*line_offset_from_top),
14517 ),
14518 );
14519 }
14520 }
14521 Some(JumpData::MultiBufferRow {
14522 row,
14523 line_offset_from_top,
14524 }) => {
14525 let point = MultiBufferPoint::new(row.0, 0);
14526 if let Some((buffer, buffer_point, _)) =
14527 self.buffer.read(cx).point_to_buffer_point(point, cx)
14528 {
14529 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14530 new_selections_by_buffer
14531 .entry(buffer)
14532 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14533 .0
14534 .push(buffer_offset..buffer_offset)
14535 }
14536 }
14537 None => {
14538 let selections = self.selections.all::<usize>(cx);
14539 let multi_buffer = self.buffer.read(cx);
14540 for selection in selections {
14541 for (buffer, mut range, _) in multi_buffer
14542 .snapshot(cx)
14543 .range_to_buffer_ranges(selection.range())
14544 {
14545 // When editing branch buffers, jump to the corresponding location
14546 // in their base buffer.
14547 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14548 let buffer = buffer_handle.read(cx);
14549 if let Some(base_buffer) = buffer.base_buffer() {
14550 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14551 buffer_handle = base_buffer;
14552 }
14553
14554 if selection.reversed {
14555 mem::swap(&mut range.start, &mut range.end);
14556 }
14557 new_selections_by_buffer
14558 .entry(buffer_handle)
14559 .or_insert((Vec::new(), None))
14560 .0
14561 .push(range)
14562 }
14563 }
14564 }
14565 }
14566
14567 if new_selections_by_buffer.is_empty() {
14568 return;
14569 }
14570
14571 // We defer the pane interaction because we ourselves are a workspace item
14572 // and activating a new item causes the pane to call a method on us reentrantly,
14573 // which panics if we're on the stack.
14574 window.defer(cx, move |window, cx| {
14575 workspace.update(cx, |workspace, cx| {
14576 let pane = if split {
14577 workspace.adjacent_pane(window, cx)
14578 } else {
14579 workspace.active_pane().clone()
14580 };
14581
14582 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14583 let editor = buffer
14584 .read(cx)
14585 .file()
14586 .is_none()
14587 .then(|| {
14588 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14589 // so `workspace.open_project_item` will never find them, always opening a new editor.
14590 // Instead, we try to activate the existing editor in the pane first.
14591 let (editor, pane_item_index) =
14592 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14593 let editor = item.downcast::<Editor>()?;
14594 let singleton_buffer =
14595 editor.read(cx).buffer().read(cx).as_singleton()?;
14596 if singleton_buffer == buffer {
14597 Some((editor, i))
14598 } else {
14599 None
14600 }
14601 })?;
14602 pane.update(cx, |pane, cx| {
14603 pane.activate_item(pane_item_index, true, true, window, cx)
14604 });
14605 Some(editor)
14606 })
14607 .flatten()
14608 .unwrap_or_else(|| {
14609 workspace.open_project_item::<Self>(
14610 pane.clone(),
14611 buffer,
14612 true,
14613 true,
14614 window,
14615 cx,
14616 )
14617 });
14618
14619 editor.update(cx, |editor, cx| {
14620 let autoscroll = match scroll_offset {
14621 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14622 None => Autoscroll::newest(),
14623 };
14624 let nav_history = editor.nav_history.take();
14625 editor.change_selections(Some(autoscroll), window, cx, |s| {
14626 s.select_ranges(ranges);
14627 });
14628 editor.nav_history = nav_history;
14629 });
14630 }
14631 })
14632 });
14633 }
14634
14635 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14636 let snapshot = self.buffer.read(cx).read(cx);
14637 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14638 Some(
14639 ranges
14640 .iter()
14641 .map(move |range| {
14642 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14643 })
14644 .collect(),
14645 )
14646 }
14647
14648 fn selection_replacement_ranges(
14649 &self,
14650 range: Range<OffsetUtf16>,
14651 cx: &mut App,
14652 ) -> Vec<Range<OffsetUtf16>> {
14653 let selections = self.selections.all::<OffsetUtf16>(cx);
14654 let newest_selection = selections
14655 .iter()
14656 .max_by_key(|selection| selection.id)
14657 .unwrap();
14658 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14659 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14660 let snapshot = self.buffer.read(cx).read(cx);
14661 selections
14662 .into_iter()
14663 .map(|mut selection| {
14664 selection.start.0 =
14665 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14666 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14667 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14668 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14669 })
14670 .collect()
14671 }
14672
14673 fn report_editor_event(
14674 &self,
14675 event_type: &'static str,
14676 file_extension: Option<String>,
14677 cx: &App,
14678 ) {
14679 if cfg!(any(test, feature = "test-support")) {
14680 return;
14681 }
14682
14683 let Some(project) = &self.project else { return };
14684
14685 // If None, we are in a file without an extension
14686 let file = self
14687 .buffer
14688 .read(cx)
14689 .as_singleton()
14690 .and_then(|b| b.read(cx).file());
14691 let file_extension = file_extension.or(file
14692 .as_ref()
14693 .and_then(|file| Path::new(file.file_name(cx)).extension())
14694 .and_then(|e| e.to_str())
14695 .map(|a| a.to_string()));
14696
14697 let vim_mode = cx
14698 .global::<SettingsStore>()
14699 .raw_user_settings()
14700 .get("vim_mode")
14701 == Some(&serde_json::Value::Bool(true));
14702
14703 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14704 let copilot_enabled = edit_predictions_provider
14705 == language::language_settings::EditPredictionProvider::Copilot;
14706 let copilot_enabled_for_language = self
14707 .buffer
14708 .read(cx)
14709 .settings_at(0, cx)
14710 .show_edit_predictions;
14711
14712 let project = project.read(cx);
14713 telemetry::event!(
14714 event_type,
14715 file_extension,
14716 vim_mode,
14717 copilot_enabled,
14718 copilot_enabled_for_language,
14719 edit_predictions_provider,
14720 is_via_ssh = project.is_via_ssh(),
14721 );
14722 }
14723
14724 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14725 /// with each line being an array of {text, highlight} objects.
14726 fn copy_highlight_json(
14727 &mut self,
14728 _: &CopyHighlightJson,
14729 window: &mut Window,
14730 cx: &mut Context<Self>,
14731 ) {
14732 #[derive(Serialize)]
14733 struct Chunk<'a> {
14734 text: String,
14735 highlight: Option<&'a str>,
14736 }
14737
14738 let snapshot = self.buffer.read(cx).snapshot(cx);
14739 let range = self
14740 .selected_text_range(false, window, cx)
14741 .and_then(|selection| {
14742 if selection.range.is_empty() {
14743 None
14744 } else {
14745 Some(selection.range)
14746 }
14747 })
14748 .unwrap_or_else(|| 0..snapshot.len());
14749
14750 let chunks = snapshot.chunks(range, true);
14751 let mut lines = Vec::new();
14752 let mut line: VecDeque<Chunk> = VecDeque::new();
14753
14754 let Some(style) = self.style.as_ref() else {
14755 return;
14756 };
14757
14758 for chunk in chunks {
14759 let highlight = chunk
14760 .syntax_highlight_id
14761 .and_then(|id| id.name(&style.syntax));
14762 let mut chunk_lines = chunk.text.split('\n').peekable();
14763 while let Some(text) = chunk_lines.next() {
14764 let mut merged_with_last_token = false;
14765 if let Some(last_token) = line.back_mut() {
14766 if last_token.highlight == highlight {
14767 last_token.text.push_str(text);
14768 merged_with_last_token = true;
14769 }
14770 }
14771
14772 if !merged_with_last_token {
14773 line.push_back(Chunk {
14774 text: text.into(),
14775 highlight,
14776 });
14777 }
14778
14779 if chunk_lines.peek().is_some() {
14780 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14781 line.pop_front();
14782 }
14783 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14784 line.pop_back();
14785 }
14786
14787 lines.push(mem::take(&mut line));
14788 }
14789 }
14790 }
14791
14792 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14793 return;
14794 };
14795 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14796 }
14797
14798 pub fn open_context_menu(
14799 &mut self,
14800 _: &OpenContextMenu,
14801 window: &mut Window,
14802 cx: &mut Context<Self>,
14803 ) {
14804 self.request_autoscroll(Autoscroll::newest(), cx);
14805 let position = self.selections.newest_display(cx).start;
14806 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14807 }
14808
14809 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14810 &self.inlay_hint_cache
14811 }
14812
14813 pub fn replay_insert_event(
14814 &mut self,
14815 text: &str,
14816 relative_utf16_range: Option<Range<isize>>,
14817 window: &mut Window,
14818 cx: &mut Context<Self>,
14819 ) {
14820 if !self.input_enabled {
14821 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14822 return;
14823 }
14824 if let Some(relative_utf16_range) = relative_utf16_range {
14825 let selections = self.selections.all::<OffsetUtf16>(cx);
14826 self.change_selections(None, window, cx, |s| {
14827 let new_ranges = selections.into_iter().map(|range| {
14828 let start = OffsetUtf16(
14829 range
14830 .head()
14831 .0
14832 .saturating_add_signed(relative_utf16_range.start),
14833 );
14834 let end = OffsetUtf16(
14835 range
14836 .head()
14837 .0
14838 .saturating_add_signed(relative_utf16_range.end),
14839 );
14840 start..end
14841 });
14842 s.select_ranges(new_ranges);
14843 });
14844 }
14845
14846 self.handle_input(text, window, cx);
14847 }
14848
14849 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14850 let Some(provider) = self.semantics_provider.as_ref() else {
14851 return false;
14852 };
14853
14854 let mut supports = false;
14855 self.buffer().update(cx, |this, cx| {
14856 this.for_each_buffer(|buffer| {
14857 supports |= provider.supports_inlay_hints(buffer, cx);
14858 });
14859 });
14860
14861 supports
14862 }
14863
14864 pub fn is_focused(&self, window: &Window) -> bool {
14865 self.focus_handle.is_focused(window)
14866 }
14867
14868 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14869 cx.emit(EditorEvent::Focused);
14870
14871 if let Some(descendant) = self
14872 .last_focused_descendant
14873 .take()
14874 .and_then(|descendant| descendant.upgrade())
14875 {
14876 window.focus(&descendant);
14877 } else {
14878 if let Some(blame) = self.blame.as_ref() {
14879 blame.update(cx, GitBlame::focus)
14880 }
14881
14882 self.blink_manager.update(cx, BlinkManager::enable);
14883 self.show_cursor_names(window, cx);
14884 self.buffer.update(cx, |buffer, cx| {
14885 buffer.finalize_last_transaction(cx);
14886 if self.leader_peer_id.is_none() {
14887 buffer.set_active_selections(
14888 &self.selections.disjoint_anchors(),
14889 self.selections.line_mode,
14890 self.cursor_shape,
14891 cx,
14892 );
14893 }
14894 });
14895 }
14896 }
14897
14898 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14899 cx.emit(EditorEvent::FocusedIn)
14900 }
14901
14902 fn handle_focus_out(
14903 &mut self,
14904 event: FocusOutEvent,
14905 _window: &mut Window,
14906 _cx: &mut Context<Self>,
14907 ) {
14908 if event.blurred != self.focus_handle {
14909 self.last_focused_descendant = Some(event.blurred);
14910 }
14911 }
14912
14913 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14914 self.blink_manager.update(cx, BlinkManager::disable);
14915 self.buffer
14916 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14917
14918 if let Some(blame) = self.blame.as_ref() {
14919 blame.update(cx, GitBlame::blur)
14920 }
14921 if !self.hover_state.focused(window, cx) {
14922 hide_hover(self, cx);
14923 }
14924 if !self
14925 .context_menu
14926 .borrow()
14927 .as_ref()
14928 .is_some_and(|context_menu| context_menu.focused(window, cx))
14929 {
14930 self.hide_context_menu(window, cx);
14931 }
14932 self.discard_inline_completion(false, cx);
14933 cx.emit(EditorEvent::Blurred);
14934 cx.notify();
14935 }
14936
14937 pub fn register_action<A: Action>(
14938 &mut self,
14939 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14940 ) -> Subscription {
14941 let id = self.next_editor_action_id.post_inc();
14942 let listener = Arc::new(listener);
14943 self.editor_actions.borrow_mut().insert(
14944 id,
14945 Box::new(move |window, _| {
14946 let listener = listener.clone();
14947 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14948 let action = action.downcast_ref().unwrap();
14949 if phase == DispatchPhase::Bubble {
14950 listener(action, window, cx)
14951 }
14952 })
14953 }),
14954 );
14955
14956 let editor_actions = self.editor_actions.clone();
14957 Subscription::new(move || {
14958 editor_actions.borrow_mut().remove(&id);
14959 })
14960 }
14961
14962 pub fn file_header_size(&self) -> u32 {
14963 FILE_HEADER_HEIGHT
14964 }
14965
14966 pub fn revert(
14967 &mut self,
14968 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14969 window: &mut Window,
14970 cx: &mut Context<Self>,
14971 ) {
14972 self.buffer().update(cx, |multi_buffer, cx| {
14973 for (buffer_id, changes) in revert_changes {
14974 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14975 buffer.update(cx, |buffer, cx| {
14976 buffer.edit(
14977 changes.into_iter().map(|(range, text)| {
14978 (range, text.to_string().map(Arc::<str>::from))
14979 }),
14980 None,
14981 cx,
14982 );
14983 });
14984 }
14985 }
14986 });
14987 self.change_selections(None, window, cx, |selections| selections.refresh());
14988 }
14989
14990 pub fn to_pixel_point(
14991 &self,
14992 source: multi_buffer::Anchor,
14993 editor_snapshot: &EditorSnapshot,
14994 window: &mut Window,
14995 ) -> Option<gpui::Point<Pixels>> {
14996 let source_point = source.to_display_point(editor_snapshot);
14997 self.display_to_pixel_point(source_point, editor_snapshot, window)
14998 }
14999
15000 pub fn display_to_pixel_point(
15001 &self,
15002 source: DisplayPoint,
15003 editor_snapshot: &EditorSnapshot,
15004 window: &mut Window,
15005 ) -> Option<gpui::Point<Pixels>> {
15006 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15007 let text_layout_details = self.text_layout_details(window);
15008 let scroll_top = text_layout_details
15009 .scroll_anchor
15010 .scroll_position(editor_snapshot)
15011 .y;
15012
15013 if source.row().as_f32() < scroll_top.floor() {
15014 return None;
15015 }
15016 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15017 let source_y = line_height * (source.row().as_f32() - scroll_top);
15018 Some(gpui::Point::new(source_x, source_y))
15019 }
15020
15021 pub fn has_visible_completions_menu(&self) -> bool {
15022 !self.edit_prediction_preview_is_active()
15023 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15024 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15025 })
15026 }
15027
15028 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15029 self.addons
15030 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15031 }
15032
15033 pub fn unregister_addon<T: Addon>(&mut self) {
15034 self.addons.remove(&std::any::TypeId::of::<T>());
15035 }
15036
15037 pub fn addon<T: Addon>(&self) -> Option<&T> {
15038 let type_id = std::any::TypeId::of::<T>();
15039 self.addons
15040 .get(&type_id)
15041 .and_then(|item| item.to_any().downcast_ref::<T>())
15042 }
15043
15044 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15045 let text_layout_details = self.text_layout_details(window);
15046 let style = &text_layout_details.editor_style;
15047 let font_id = window.text_system().resolve_font(&style.text.font());
15048 let font_size = style.text.font_size.to_pixels(window.rem_size());
15049 let line_height = style.text.line_height_in_pixels(window.rem_size());
15050 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15051
15052 gpui::Size::new(em_width, line_height)
15053 }
15054
15055 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15056 self.load_diff_task.clone()
15057 }
15058
15059 fn read_selections_from_db(
15060 &mut self,
15061 item_id: u64,
15062 workspace_id: WorkspaceId,
15063 window: &mut Window,
15064 cx: &mut Context<Editor>,
15065 ) {
15066 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
15067 return;
15068 }
15069 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15070 return;
15071 };
15072 if selections.is_empty() {
15073 return;
15074 }
15075
15076 let snapshot = self.buffer.read(cx).snapshot(cx);
15077 self.change_selections(None, window, cx, |s| {
15078 s.select_ranges(selections.into_iter().map(|(start, end)| {
15079 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15080 }));
15081 });
15082 }
15083}
15084
15085fn get_uncommitted_diff_for_buffer(
15086 project: &Entity<Project>,
15087 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15088 buffer: Entity<MultiBuffer>,
15089 cx: &mut App,
15090) -> Task<()> {
15091 let mut tasks = Vec::new();
15092 project.update(cx, |project, cx| {
15093 for buffer in buffers {
15094 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15095 }
15096 });
15097 cx.spawn(|mut cx| async move {
15098 let diffs = futures::future::join_all(tasks).await;
15099 buffer
15100 .update(&mut cx, |buffer, cx| {
15101 for diff in diffs.into_iter().flatten() {
15102 buffer.add_diff(diff, cx);
15103 }
15104 })
15105 .ok();
15106 })
15107}
15108
15109fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15110 let tab_size = tab_size.get() as usize;
15111 let mut width = offset;
15112
15113 for ch in text.chars() {
15114 width += if ch == '\t' {
15115 tab_size - (width % tab_size)
15116 } else {
15117 1
15118 };
15119 }
15120
15121 width - offset
15122}
15123
15124#[cfg(test)]
15125mod tests {
15126 use super::*;
15127
15128 #[test]
15129 fn test_string_size_with_expanded_tabs() {
15130 let nz = |val| NonZeroU32::new(val).unwrap();
15131 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15132 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15133 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15134 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15135 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15136 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15137 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15138 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15139 }
15140}
15141
15142/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15143struct WordBreakingTokenizer<'a> {
15144 input: &'a str,
15145}
15146
15147impl<'a> WordBreakingTokenizer<'a> {
15148 fn new(input: &'a str) -> Self {
15149 Self { input }
15150 }
15151}
15152
15153fn is_char_ideographic(ch: char) -> bool {
15154 use unicode_script::Script::*;
15155 use unicode_script::UnicodeScript;
15156 matches!(ch.script(), Han | Tangut | Yi)
15157}
15158
15159fn is_grapheme_ideographic(text: &str) -> bool {
15160 text.chars().any(is_char_ideographic)
15161}
15162
15163fn is_grapheme_whitespace(text: &str) -> bool {
15164 text.chars().any(|x| x.is_whitespace())
15165}
15166
15167fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15168 text.chars().next().map_or(false, |ch| {
15169 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15170 })
15171}
15172
15173#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15174struct WordBreakToken<'a> {
15175 token: &'a str,
15176 grapheme_len: usize,
15177 is_whitespace: bool,
15178}
15179
15180impl<'a> Iterator for WordBreakingTokenizer<'a> {
15181 /// Yields a span, the count of graphemes in the token, and whether it was
15182 /// whitespace. Note that it also breaks at word boundaries.
15183 type Item = WordBreakToken<'a>;
15184
15185 fn next(&mut self) -> Option<Self::Item> {
15186 use unicode_segmentation::UnicodeSegmentation;
15187 if self.input.is_empty() {
15188 return None;
15189 }
15190
15191 let mut iter = self.input.graphemes(true).peekable();
15192 let mut offset = 0;
15193 let mut graphemes = 0;
15194 if let Some(first_grapheme) = iter.next() {
15195 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15196 offset += first_grapheme.len();
15197 graphemes += 1;
15198 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15199 if let Some(grapheme) = iter.peek().copied() {
15200 if should_stay_with_preceding_ideograph(grapheme) {
15201 offset += grapheme.len();
15202 graphemes += 1;
15203 }
15204 }
15205 } else {
15206 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15207 let mut next_word_bound = words.peek().copied();
15208 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15209 next_word_bound = words.next();
15210 }
15211 while let Some(grapheme) = iter.peek().copied() {
15212 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15213 break;
15214 };
15215 if is_grapheme_whitespace(grapheme) != is_whitespace {
15216 break;
15217 };
15218 offset += grapheme.len();
15219 graphemes += 1;
15220 iter.next();
15221 }
15222 }
15223 let token = &self.input[..offset];
15224 self.input = &self.input[offset..];
15225 if is_whitespace {
15226 Some(WordBreakToken {
15227 token: " ",
15228 grapheme_len: 1,
15229 is_whitespace: true,
15230 })
15231 } else {
15232 Some(WordBreakToken {
15233 token,
15234 grapheme_len: graphemes,
15235 is_whitespace: false,
15236 })
15237 }
15238 } else {
15239 None
15240 }
15241 }
15242}
15243
15244#[test]
15245fn test_word_breaking_tokenizer() {
15246 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15247 ("", &[]),
15248 (" ", &[(" ", 1, true)]),
15249 ("Ʒ", &[("Ʒ", 1, false)]),
15250 ("Ǽ", &[("Ǽ", 1, false)]),
15251 ("⋑", &[("⋑", 1, false)]),
15252 ("⋑⋑", &[("⋑⋑", 2, false)]),
15253 (
15254 "原理,进而",
15255 &[
15256 ("原", 1, false),
15257 ("理,", 2, false),
15258 ("进", 1, false),
15259 ("而", 1, false),
15260 ],
15261 ),
15262 (
15263 "hello world",
15264 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15265 ),
15266 (
15267 "hello, world",
15268 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15269 ),
15270 (
15271 " hello world",
15272 &[
15273 (" ", 1, true),
15274 ("hello", 5, false),
15275 (" ", 1, true),
15276 ("world", 5, false),
15277 ],
15278 ),
15279 (
15280 "这是什么 \n 钢笔",
15281 &[
15282 ("这", 1, false),
15283 ("是", 1, false),
15284 ("什", 1, false),
15285 ("么", 1, false),
15286 (" ", 1, true),
15287 ("钢", 1, false),
15288 ("笔", 1, false),
15289 ],
15290 ),
15291 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15292 ];
15293
15294 for (input, result) in tests {
15295 assert_eq!(
15296 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15297 result
15298 .iter()
15299 .copied()
15300 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15301 token,
15302 grapheme_len,
15303 is_whitespace,
15304 })
15305 .collect::<Vec<_>>()
15306 );
15307 }
15308}
15309
15310fn wrap_with_prefix(
15311 line_prefix: String,
15312 unwrapped_text: String,
15313 wrap_column: usize,
15314 tab_size: NonZeroU32,
15315) -> String {
15316 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15317 let mut wrapped_text = String::new();
15318 let mut current_line = line_prefix.clone();
15319
15320 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15321 let mut current_line_len = line_prefix_len;
15322 for WordBreakToken {
15323 token,
15324 grapheme_len,
15325 is_whitespace,
15326 } in tokenizer
15327 {
15328 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15329 wrapped_text.push_str(current_line.trim_end());
15330 wrapped_text.push('\n');
15331 current_line.truncate(line_prefix.len());
15332 current_line_len = line_prefix_len;
15333 if !is_whitespace {
15334 current_line.push_str(token);
15335 current_line_len += grapheme_len;
15336 }
15337 } else if !is_whitespace {
15338 current_line.push_str(token);
15339 current_line_len += grapheme_len;
15340 } else if current_line_len != line_prefix_len {
15341 current_line.push(' ');
15342 current_line_len += 1;
15343 }
15344 }
15345
15346 if !current_line.is_empty() {
15347 wrapped_text.push_str(¤t_line);
15348 }
15349 wrapped_text
15350}
15351
15352#[test]
15353fn test_wrap_with_prefix() {
15354 assert_eq!(
15355 wrap_with_prefix(
15356 "# ".to_string(),
15357 "abcdefg".to_string(),
15358 4,
15359 NonZeroU32::new(4).unwrap()
15360 ),
15361 "# abcdefg"
15362 );
15363 assert_eq!(
15364 wrap_with_prefix(
15365 "".to_string(),
15366 "\thello world".to_string(),
15367 8,
15368 NonZeroU32::new(4).unwrap()
15369 ),
15370 "hello\nworld"
15371 );
15372 assert_eq!(
15373 wrap_with_prefix(
15374 "// ".to_string(),
15375 "xx \nyy zz aa bb cc".to_string(),
15376 12,
15377 NonZeroU32::new(4).unwrap()
15378 ),
15379 "// xx yy zz\n// aa bb cc"
15380 );
15381 assert_eq!(
15382 wrap_with_prefix(
15383 String::new(),
15384 "这是什么 \n 钢笔".to_string(),
15385 3,
15386 NonZeroU32::new(4).unwrap()
15387 ),
15388 "这是什\n么 钢\n笔"
15389 );
15390}
15391
15392pub trait CollaborationHub {
15393 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15394 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15395 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15396}
15397
15398impl CollaborationHub for Entity<Project> {
15399 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15400 self.read(cx).collaborators()
15401 }
15402
15403 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15404 self.read(cx).user_store().read(cx).participant_indices()
15405 }
15406
15407 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15408 let this = self.read(cx);
15409 let user_ids = this.collaborators().values().map(|c| c.user_id);
15410 this.user_store().read_with(cx, |user_store, cx| {
15411 user_store.participant_names(user_ids, cx)
15412 })
15413 }
15414}
15415
15416pub trait SemanticsProvider {
15417 fn hover(
15418 &self,
15419 buffer: &Entity<Buffer>,
15420 position: text::Anchor,
15421 cx: &mut App,
15422 ) -> Option<Task<Vec<project::Hover>>>;
15423
15424 fn inlay_hints(
15425 &self,
15426 buffer_handle: Entity<Buffer>,
15427 range: Range<text::Anchor>,
15428 cx: &mut App,
15429 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15430
15431 fn resolve_inlay_hint(
15432 &self,
15433 hint: InlayHint,
15434 buffer_handle: Entity<Buffer>,
15435 server_id: LanguageServerId,
15436 cx: &mut App,
15437 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15438
15439 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15440
15441 fn document_highlights(
15442 &self,
15443 buffer: &Entity<Buffer>,
15444 position: text::Anchor,
15445 cx: &mut App,
15446 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15447
15448 fn definitions(
15449 &self,
15450 buffer: &Entity<Buffer>,
15451 position: text::Anchor,
15452 kind: GotoDefinitionKind,
15453 cx: &mut App,
15454 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15455
15456 fn range_for_rename(
15457 &self,
15458 buffer: &Entity<Buffer>,
15459 position: text::Anchor,
15460 cx: &mut App,
15461 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15462
15463 fn perform_rename(
15464 &self,
15465 buffer: &Entity<Buffer>,
15466 position: text::Anchor,
15467 new_name: String,
15468 cx: &mut App,
15469 ) -> Option<Task<Result<ProjectTransaction>>>;
15470}
15471
15472pub trait CompletionProvider {
15473 fn completions(
15474 &self,
15475 buffer: &Entity<Buffer>,
15476 buffer_position: text::Anchor,
15477 trigger: CompletionContext,
15478 window: &mut Window,
15479 cx: &mut Context<Editor>,
15480 ) -> Task<Result<Vec<Completion>>>;
15481
15482 fn resolve_completions(
15483 &self,
15484 buffer: Entity<Buffer>,
15485 completion_indices: Vec<usize>,
15486 completions: Rc<RefCell<Box<[Completion]>>>,
15487 cx: &mut Context<Editor>,
15488 ) -> Task<Result<bool>>;
15489
15490 fn apply_additional_edits_for_completion(
15491 &self,
15492 _buffer: Entity<Buffer>,
15493 _completions: Rc<RefCell<Box<[Completion]>>>,
15494 _completion_index: usize,
15495 _push_to_history: bool,
15496 _cx: &mut Context<Editor>,
15497 ) -> Task<Result<Option<language::Transaction>>> {
15498 Task::ready(Ok(None))
15499 }
15500
15501 fn is_completion_trigger(
15502 &self,
15503 buffer: &Entity<Buffer>,
15504 position: language::Anchor,
15505 text: &str,
15506 trigger_in_words: bool,
15507 cx: &mut Context<Editor>,
15508 ) -> bool;
15509
15510 fn sort_completions(&self) -> bool {
15511 true
15512 }
15513}
15514
15515pub trait CodeActionProvider {
15516 fn id(&self) -> Arc<str>;
15517
15518 fn code_actions(
15519 &self,
15520 buffer: &Entity<Buffer>,
15521 range: Range<text::Anchor>,
15522 window: &mut Window,
15523 cx: &mut App,
15524 ) -> Task<Result<Vec<CodeAction>>>;
15525
15526 fn apply_code_action(
15527 &self,
15528 buffer_handle: Entity<Buffer>,
15529 action: CodeAction,
15530 excerpt_id: ExcerptId,
15531 push_to_history: bool,
15532 window: &mut Window,
15533 cx: &mut App,
15534 ) -> Task<Result<ProjectTransaction>>;
15535}
15536
15537impl CodeActionProvider for Entity<Project> {
15538 fn id(&self) -> Arc<str> {
15539 "project".into()
15540 }
15541
15542 fn code_actions(
15543 &self,
15544 buffer: &Entity<Buffer>,
15545 range: Range<text::Anchor>,
15546 _window: &mut Window,
15547 cx: &mut App,
15548 ) -> Task<Result<Vec<CodeAction>>> {
15549 self.update(cx, |project, cx| {
15550 project.code_actions(buffer, range, None, cx)
15551 })
15552 }
15553
15554 fn apply_code_action(
15555 &self,
15556 buffer_handle: Entity<Buffer>,
15557 action: CodeAction,
15558 _excerpt_id: ExcerptId,
15559 push_to_history: bool,
15560 _window: &mut Window,
15561 cx: &mut App,
15562 ) -> Task<Result<ProjectTransaction>> {
15563 self.update(cx, |project, cx| {
15564 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15565 })
15566 }
15567}
15568
15569fn snippet_completions(
15570 project: &Project,
15571 buffer: &Entity<Buffer>,
15572 buffer_position: text::Anchor,
15573 cx: &mut App,
15574) -> Task<Result<Vec<Completion>>> {
15575 let language = buffer.read(cx).language_at(buffer_position);
15576 let language_name = language.as_ref().map(|language| language.lsp_id());
15577 let snippet_store = project.snippets().read(cx);
15578 let snippets = snippet_store.snippets_for(language_name, cx);
15579
15580 if snippets.is_empty() {
15581 return Task::ready(Ok(vec![]));
15582 }
15583 let snapshot = buffer.read(cx).text_snapshot();
15584 let chars: String = snapshot
15585 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15586 .collect();
15587
15588 let scope = language.map(|language| language.default_scope());
15589 let executor = cx.background_executor().clone();
15590
15591 cx.background_spawn(async move {
15592 let classifier = CharClassifier::new(scope).for_completion(true);
15593 let mut last_word = chars
15594 .chars()
15595 .take_while(|c| classifier.is_word(*c))
15596 .collect::<String>();
15597 last_word = last_word.chars().rev().collect();
15598
15599 if last_word.is_empty() {
15600 return Ok(vec![]);
15601 }
15602
15603 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15604 let to_lsp = |point: &text::Anchor| {
15605 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15606 point_to_lsp(end)
15607 };
15608 let lsp_end = to_lsp(&buffer_position);
15609
15610 let candidates = snippets
15611 .iter()
15612 .enumerate()
15613 .flat_map(|(ix, snippet)| {
15614 snippet
15615 .prefix
15616 .iter()
15617 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15618 })
15619 .collect::<Vec<StringMatchCandidate>>();
15620
15621 let mut matches = fuzzy::match_strings(
15622 &candidates,
15623 &last_word,
15624 last_word.chars().any(|c| c.is_uppercase()),
15625 100,
15626 &Default::default(),
15627 executor,
15628 )
15629 .await;
15630
15631 // Remove all candidates where the query's start does not match the start of any word in the candidate
15632 if let Some(query_start) = last_word.chars().next() {
15633 matches.retain(|string_match| {
15634 split_words(&string_match.string).any(|word| {
15635 // Check that the first codepoint of the word as lowercase matches the first
15636 // codepoint of the query as lowercase
15637 word.chars()
15638 .flat_map(|codepoint| codepoint.to_lowercase())
15639 .zip(query_start.to_lowercase())
15640 .all(|(word_cp, query_cp)| word_cp == query_cp)
15641 })
15642 });
15643 }
15644
15645 let matched_strings = matches
15646 .into_iter()
15647 .map(|m| m.string)
15648 .collect::<HashSet<_>>();
15649
15650 let result: Vec<Completion> = snippets
15651 .into_iter()
15652 .filter_map(|snippet| {
15653 let matching_prefix = snippet
15654 .prefix
15655 .iter()
15656 .find(|prefix| matched_strings.contains(*prefix))?;
15657 let start = as_offset - last_word.len();
15658 let start = snapshot.anchor_before(start);
15659 let range = start..buffer_position;
15660 let lsp_start = to_lsp(&start);
15661 let lsp_range = lsp::Range {
15662 start: lsp_start,
15663 end: lsp_end,
15664 };
15665 Some(Completion {
15666 old_range: range,
15667 new_text: snippet.body.clone(),
15668 resolved: false,
15669 label: CodeLabel {
15670 text: matching_prefix.clone(),
15671 runs: vec![],
15672 filter_range: 0..matching_prefix.len(),
15673 },
15674 server_id: LanguageServerId(usize::MAX),
15675 documentation: snippet
15676 .description
15677 .clone()
15678 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15679 lsp_completion: lsp::CompletionItem {
15680 label: snippet.prefix.first().unwrap().clone(),
15681 kind: Some(CompletionItemKind::SNIPPET),
15682 label_details: snippet.description.as_ref().map(|description| {
15683 lsp::CompletionItemLabelDetails {
15684 detail: Some(description.clone()),
15685 description: None,
15686 }
15687 }),
15688 insert_text_format: Some(InsertTextFormat::SNIPPET),
15689 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15690 lsp::InsertReplaceEdit {
15691 new_text: snippet.body.clone(),
15692 insert: lsp_range,
15693 replace: lsp_range,
15694 },
15695 )),
15696 filter_text: Some(snippet.body.clone()),
15697 sort_text: Some(char::MAX.to_string()),
15698 ..Default::default()
15699 },
15700 confirm: None,
15701 })
15702 })
15703 .collect();
15704
15705 Ok(result)
15706 })
15707}
15708
15709impl CompletionProvider for Entity<Project> {
15710 fn completions(
15711 &self,
15712 buffer: &Entity<Buffer>,
15713 buffer_position: text::Anchor,
15714 options: CompletionContext,
15715 _window: &mut Window,
15716 cx: &mut Context<Editor>,
15717 ) -> Task<Result<Vec<Completion>>> {
15718 self.update(cx, |project, cx| {
15719 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15720 let project_completions = project.completions(buffer, buffer_position, options, cx);
15721 cx.background_spawn(async move {
15722 let mut completions = project_completions.await?;
15723 let snippets_completions = snippets.await?;
15724 completions.extend(snippets_completions);
15725 Ok(completions)
15726 })
15727 })
15728 }
15729
15730 fn resolve_completions(
15731 &self,
15732 buffer: Entity<Buffer>,
15733 completion_indices: Vec<usize>,
15734 completions: Rc<RefCell<Box<[Completion]>>>,
15735 cx: &mut Context<Editor>,
15736 ) -> Task<Result<bool>> {
15737 self.update(cx, |project, cx| {
15738 project.lsp_store().update(cx, |lsp_store, cx| {
15739 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15740 })
15741 })
15742 }
15743
15744 fn apply_additional_edits_for_completion(
15745 &self,
15746 buffer: Entity<Buffer>,
15747 completions: Rc<RefCell<Box<[Completion]>>>,
15748 completion_index: usize,
15749 push_to_history: bool,
15750 cx: &mut Context<Editor>,
15751 ) -> Task<Result<Option<language::Transaction>>> {
15752 self.update(cx, |project, cx| {
15753 project.lsp_store().update(cx, |lsp_store, cx| {
15754 lsp_store.apply_additional_edits_for_completion(
15755 buffer,
15756 completions,
15757 completion_index,
15758 push_to_history,
15759 cx,
15760 )
15761 })
15762 })
15763 }
15764
15765 fn is_completion_trigger(
15766 &self,
15767 buffer: &Entity<Buffer>,
15768 position: language::Anchor,
15769 text: &str,
15770 trigger_in_words: bool,
15771 cx: &mut Context<Editor>,
15772 ) -> bool {
15773 let mut chars = text.chars();
15774 let char = if let Some(char) = chars.next() {
15775 char
15776 } else {
15777 return false;
15778 };
15779 if chars.next().is_some() {
15780 return false;
15781 }
15782
15783 let buffer = buffer.read(cx);
15784 let snapshot = buffer.snapshot();
15785 if !snapshot.settings_at(position, cx).show_completions_on_input {
15786 return false;
15787 }
15788 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15789 if trigger_in_words && classifier.is_word(char) {
15790 return true;
15791 }
15792
15793 buffer.completion_triggers().contains(text)
15794 }
15795}
15796
15797impl SemanticsProvider for Entity<Project> {
15798 fn hover(
15799 &self,
15800 buffer: &Entity<Buffer>,
15801 position: text::Anchor,
15802 cx: &mut App,
15803 ) -> Option<Task<Vec<project::Hover>>> {
15804 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15805 }
15806
15807 fn document_highlights(
15808 &self,
15809 buffer: &Entity<Buffer>,
15810 position: text::Anchor,
15811 cx: &mut App,
15812 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15813 Some(self.update(cx, |project, cx| {
15814 project.document_highlights(buffer, position, cx)
15815 }))
15816 }
15817
15818 fn definitions(
15819 &self,
15820 buffer: &Entity<Buffer>,
15821 position: text::Anchor,
15822 kind: GotoDefinitionKind,
15823 cx: &mut App,
15824 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15825 Some(self.update(cx, |project, cx| match kind {
15826 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15827 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15828 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15829 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15830 }))
15831 }
15832
15833 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15834 // TODO: make this work for remote projects
15835 self.update(cx, |this, cx| {
15836 buffer.update(cx, |buffer, cx| {
15837 this.any_language_server_supports_inlay_hints(buffer, cx)
15838 })
15839 })
15840 }
15841
15842 fn inlay_hints(
15843 &self,
15844 buffer_handle: Entity<Buffer>,
15845 range: Range<text::Anchor>,
15846 cx: &mut App,
15847 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15848 Some(self.update(cx, |project, cx| {
15849 project.inlay_hints(buffer_handle, range, cx)
15850 }))
15851 }
15852
15853 fn resolve_inlay_hint(
15854 &self,
15855 hint: InlayHint,
15856 buffer_handle: Entity<Buffer>,
15857 server_id: LanguageServerId,
15858 cx: &mut App,
15859 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15860 Some(self.update(cx, |project, cx| {
15861 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15862 }))
15863 }
15864
15865 fn range_for_rename(
15866 &self,
15867 buffer: &Entity<Buffer>,
15868 position: text::Anchor,
15869 cx: &mut App,
15870 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15871 Some(self.update(cx, |project, cx| {
15872 let buffer = buffer.clone();
15873 let task = project.prepare_rename(buffer.clone(), position, cx);
15874 cx.spawn(|_, mut cx| async move {
15875 Ok(match task.await? {
15876 PrepareRenameResponse::Success(range) => Some(range),
15877 PrepareRenameResponse::InvalidPosition => None,
15878 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15879 // Fallback on using TreeSitter info to determine identifier range
15880 buffer.update(&mut cx, |buffer, _| {
15881 let snapshot = buffer.snapshot();
15882 let (range, kind) = snapshot.surrounding_word(position);
15883 if kind != Some(CharKind::Word) {
15884 return None;
15885 }
15886 Some(
15887 snapshot.anchor_before(range.start)
15888 ..snapshot.anchor_after(range.end),
15889 )
15890 })?
15891 }
15892 })
15893 })
15894 }))
15895 }
15896
15897 fn perform_rename(
15898 &self,
15899 buffer: &Entity<Buffer>,
15900 position: text::Anchor,
15901 new_name: String,
15902 cx: &mut App,
15903 ) -> Option<Task<Result<ProjectTransaction>>> {
15904 Some(self.update(cx, |project, cx| {
15905 project.perform_rename(buffer.clone(), position, new_name, cx)
15906 }))
15907 }
15908}
15909
15910fn inlay_hint_settings(
15911 location: Anchor,
15912 snapshot: &MultiBufferSnapshot,
15913 cx: &mut Context<Editor>,
15914) -> InlayHintSettings {
15915 let file = snapshot.file_at(location);
15916 let language = snapshot.language_at(location).map(|l| l.name());
15917 language_settings(language, file, cx).inlay_hints
15918}
15919
15920fn consume_contiguous_rows(
15921 contiguous_row_selections: &mut Vec<Selection<Point>>,
15922 selection: &Selection<Point>,
15923 display_map: &DisplaySnapshot,
15924 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15925) -> (MultiBufferRow, MultiBufferRow) {
15926 contiguous_row_selections.push(selection.clone());
15927 let start_row = MultiBufferRow(selection.start.row);
15928 let mut end_row = ending_row(selection, display_map);
15929
15930 while let Some(next_selection) = selections.peek() {
15931 if next_selection.start.row <= end_row.0 {
15932 end_row = ending_row(next_selection, display_map);
15933 contiguous_row_selections.push(selections.next().unwrap().clone());
15934 } else {
15935 break;
15936 }
15937 }
15938 (start_row, end_row)
15939}
15940
15941fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15942 if next_selection.end.column > 0 || next_selection.is_empty() {
15943 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15944 } else {
15945 MultiBufferRow(next_selection.end.row)
15946 }
15947}
15948
15949impl EditorSnapshot {
15950 pub fn remote_selections_in_range<'a>(
15951 &'a self,
15952 range: &'a Range<Anchor>,
15953 collaboration_hub: &dyn CollaborationHub,
15954 cx: &'a App,
15955 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15956 let participant_names = collaboration_hub.user_names(cx);
15957 let participant_indices = collaboration_hub.user_participant_indices(cx);
15958 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15959 let collaborators_by_replica_id = collaborators_by_peer_id
15960 .iter()
15961 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15962 .collect::<HashMap<_, _>>();
15963 self.buffer_snapshot
15964 .selections_in_range(range, false)
15965 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15966 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15967 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15968 let user_name = participant_names.get(&collaborator.user_id).cloned();
15969 Some(RemoteSelection {
15970 replica_id,
15971 selection,
15972 cursor_shape,
15973 line_mode,
15974 participant_index,
15975 peer_id: collaborator.peer_id,
15976 user_name,
15977 })
15978 })
15979 }
15980
15981 pub fn hunks_for_ranges(
15982 &self,
15983 ranges: impl Iterator<Item = Range<Point>>,
15984 ) -> Vec<MultiBufferDiffHunk> {
15985 let mut hunks = Vec::new();
15986 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15987 HashMap::default();
15988 for query_range in ranges {
15989 let query_rows =
15990 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15991 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15992 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15993 ) {
15994 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15995 // when the caret is just above or just below the deleted hunk.
15996 let allow_adjacent = hunk.status().is_removed();
15997 let related_to_selection = if allow_adjacent {
15998 hunk.row_range.overlaps(&query_rows)
15999 || hunk.row_range.start == query_rows.end
16000 || hunk.row_range.end == query_rows.start
16001 } else {
16002 hunk.row_range.overlaps(&query_rows)
16003 };
16004 if related_to_selection {
16005 if !processed_buffer_rows
16006 .entry(hunk.buffer_id)
16007 .or_default()
16008 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16009 {
16010 continue;
16011 }
16012 hunks.push(hunk);
16013 }
16014 }
16015 }
16016
16017 hunks
16018 }
16019
16020 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16021 self.display_snapshot.buffer_snapshot.language_at(position)
16022 }
16023
16024 pub fn is_focused(&self) -> bool {
16025 self.is_focused
16026 }
16027
16028 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16029 self.placeholder_text.as_ref()
16030 }
16031
16032 pub fn scroll_position(&self) -> gpui::Point<f32> {
16033 self.scroll_anchor.scroll_position(&self.display_snapshot)
16034 }
16035
16036 fn gutter_dimensions(
16037 &self,
16038 font_id: FontId,
16039 font_size: Pixels,
16040 max_line_number_width: Pixels,
16041 cx: &App,
16042 ) -> Option<GutterDimensions> {
16043 if !self.show_gutter {
16044 return None;
16045 }
16046
16047 let descent = cx.text_system().descent(font_id, font_size);
16048 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16049 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16050
16051 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16052 matches!(
16053 ProjectSettings::get_global(cx).git.git_gutter,
16054 Some(GitGutterSetting::TrackedFiles)
16055 )
16056 });
16057 let gutter_settings = EditorSettings::get_global(cx).gutter;
16058 let show_line_numbers = self
16059 .show_line_numbers
16060 .unwrap_or(gutter_settings.line_numbers);
16061 let line_gutter_width = if show_line_numbers {
16062 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16063 let min_width_for_number_on_gutter = em_advance * 4.0;
16064 max_line_number_width.max(min_width_for_number_on_gutter)
16065 } else {
16066 0.0.into()
16067 };
16068
16069 let show_code_actions = self
16070 .show_code_actions
16071 .unwrap_or(gutter_settings.code_actions);
16072
16073 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16074
16075 let git_blame_entries_width =
16076 self.git_blame_gutter_max_author_length
16077 .map(|max_author_length| {
16078 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16079
16080 /// The number of characters to dedicate to gaps and margins.
16081 const SPACING_WIDTH: usize = 4;
16082
16083 let max_char_count = max_author_length
16084 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16085 + ::git::SHORT_SHA_LENGTH
16086 + MAX_RELATIVE_TIMESTAMP.len()
16087 + SPACING_WIDTH;
16088
16089 em_advance * max_char_count
16090 });
16091
16092 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16093 left_padding += if show_code_actions || show_runnables {
16094 em_width * 3.0
16095 } else if show_git_gutter && show_line_numbers {
16096 em_width * 2.0
16097 } else if show_git_gutter || show_line_numbers {
16098 em_width
16099 } else {
16100 px(0.)
16101 };
16102
16103 let right_padding = if gutter_settings.folds && show_line_numbers {
16104 em_width * 4.0
16105 } else if gutter_settings.folds {
16106 em_width * 3.0
16107 } else if show_line_numbers {
16108 em_width
16109 } else {
16110 px(0.)
16111 };
16112
16113 Some(GutterDimensions {
16114 left_padding,
16115 right_padding,
16116 width: line_gutter_width + left_padding + right_padding,
16117 margin: -descent,
16118 git_blame_entries_width,
16119 })
16120 }
16121
16122 pub fn render_crease_toggle(
16123 &self,
16124 buffer_row: MultiBufferRow,
16125 row_contains_cursor: bool,
16126 editor: Entity<Editor>,
16127 window: &mut Window,
16128 cx: &mut App,
16129 ) -> Option<AnyElement> {
16130 let folded = self.is_line_folded(buffer_row);
16131 let mut is_foldable = false;
16132
16133 if let Some(crease) = self
16134 .crease_snapshot
16135 .query_row(buffer_row, &self.buffer_snapshot)
16136 {
16137 is_foldable = true;
16138 match crease {
16139 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16140 if let Some(render_toggle) = render_toggle {
16141 let toggle_callback =
16142 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16143 if folded {
16144 editor.update(cx, |editor, cx| {
16145 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16146 });
16147 } else {
16148 editor.update(cx, |editor, cx| {
16149 editor.unfold_at(
16150 &crate::UnfoldAt { buffer_row },
16151 window,
16152 cx,
16153 )
16154 });
16155 }
16156 });
16157 return Some((render_toggle)(
16158 buffer_row,
16159 folded,
16160 toggle_callback,
16161 window,
16162 cx,
16163 ));
16164 }
16165 }
16166 }
16167 }
16168
16169 is_foldable |= self.starts_indent(buffer_row);
16170
16171 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16172 Some(
16173 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16174 .toggle_state(folded)
16175 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16176 if folded {
16177 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16178 } else {
16179 this.fold_at(&FoldAt { buffer_row }, window, cx);
16180 }
16181 }))
16182 .into_any_element(),
16183 )
16184 } else {
16185 None
16186 }
16187 }
16188
16189 pub fn render_crease_trailer(
16190 &self,
16191 buffer_row: MultiBufferRow,
16192 window: &mut Window,
16193 cx: &mut App,
16194 ) -> Option<AnyElement> {
16195 let folded = self.is_line_folded(buffer_row);
16196 if let Crease::Inline { render_trailer, .. } = self
16197 .crease_snapshot
16198 .query_row(buffer_row, &self.buffer_snapshot)?
16199 {
16200 let render_trailer = render_trailer.as_ref()?;
16201 Some(render_trailer(buffer_row, folded, window, cx))
16202 } else {
16203 None
16204 }
16205 }
16206}
16207
16208impl Deref for EditorSnapshot {
16209 type Target = DisplaySnapshot;
16210
16211 fn deref(&self) -> &Self::Target {
16212 &self.display_snapshot
16213 }
16214}
16215
16216#[derive(Clone, Debug, PartialEq, Eq)]
16217pub enum EditorEvent {
16218 InputIgnored {
16219 text: Arc<str>,
16220 },
16221 InputHandled {
16222 utf16_range_to_replace: Option<Range<isize>>,
16223 text: Arc<str>,
16224 },
16225 ExcerptsAdded {
16226 buffer: Entity<Buffer>,
16227 predecessor: ExcerptId,
16228 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16229 },
16230 ExcerptsRemoved {
16231 ids: Vec<ExcerptId>,
16232 },
16233 BufferFoldToggled {
16234 ids: Vec<ExcerptId>,
16235 folded: bool,
16236 },
16237 ExcerptsEdited {
16238 ids: Vec<ExcerptId>,
16239 },
16240 ExcerptsExpanded {
16241 ids: Vec<ExcerptId>,
16242 },
16243 BufferEdited,
16244 Edited {
16245 transaction_id: clock::Lamport,
16246 },
16247 Reparsed(BufferId),
16248 Focused,
16249 FocusedIn,
16250 Blurred,
16251 DirtyChanged,
16252 Saved,
16253 TitleChanged,
16254 DiffBaseChanged,
16255 SelectionsChanged {
16256 local: bool,
16257 },
16258 ScrollPositionChanged {
16259 local: bool,
16260 autoscroll: bool,
16261 },
16262 Closed,
16263 TransactionUndone {
16264 transaction_id: clock::Lamport,
16265 },
16266 TransactionBegun {
16267 transaction_id: clock::Lamport,
16268 },
16269 Reloaded,
16270 CursorShapeChanged,
16271}
16272
16273impl EventEmitter<EditorEvent> for Editor {}
16274
16275impl Focusable for Editor {
16276 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16277 self.focus_handle.clone()
16278 }
16279}
16280
16281impl Render for Editor {
16282 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16283 let settings = ThemeSettings::get_global(cx);
16284
16285 let mut text_style = match self.mode {
16286 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16287 color: cx.theme().colors().editor_foreground,
16288 font_family: settings.ui_font.family.clone(),
16289 font_features: settings.ui_font.features.clone(),
16290 font_fallbacks: settings.ui_font.fallbacks.clone(),
16291 font_size: rems(0.875).into(),
16292 font_weight: settings.ui_font.weight,
16293 line_height: relative(settings.buffer_line_height.value()),
16294 ..Default::default()
16295 },
16296 EditorMode::Full => TextStyle {
16297 color: cx.theme().colors().editor_foreground,
16298 font_family: settings.buffer_font.family.clone(),
16299 font_features: settings.buffer_font.features.clone(),
16300 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16301 font_size: settings.buffer_font_size(cx).into(),
16302 font_weight: settings.buffer_font.weight,
16303 line_height: relative(settings.buffer_line_height.value()),
16304 ..Default::default()
16305 },
16306 };
16307 if let Some(text_style_refinement) = &self.text_style_refinement {
16308 text_style.refine(text_style_refinement)
16309 }
16310
16311 let background = match self.mode {
16312 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16313 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16314 EditorMode::Full => cx.theme().colors().editor_background,
16315 };
16316
16317 EditorElement::new(
16318 &cx.entity(),
16319 EditorStyle {
16320 background,
16321 local_player: cx.theme().players().local(),
16322 text: text_style,
16323 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16324 syntax: cx.theme().syntax().clone(),
16325 status: cx.theme().status().clone(),
16326 inlay_hints_style: make_inlay_hints_style(cx),
16327 inline_completion_styles: make_suggestion_styles(cx),
16328 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16329 },
16330 )
16331 }
16332}
16333
16334impl EntityInputHandler for Editor {
16335 fn text_for_range(
16336 &mut self,
16337 range_utf16: Range<usize>,
16338 adjusted_range: &mut Option<Range<usize>>,
16339 _: &mut Window,
16340 cx: &mut Context<Self>,
16341 ) -> Option<String> {
16342 let snapshot = self.buffer.read(cx).read(cx);
16343 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16344 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16345 if (start.0..end.0) != range_utf16 {
16346 adjusted_range.replace(start.0..end.0);
16347 }
16348 Some(snapshot.text_for_range(start..end).collect())
16349 }
16350
16351 fn selected_text_range(
16352 &mut self,
16353 ignore_disabled_input: bool,
16354 _: &mut Window,
16355 cx: &mut Context<Self>,
16356 ) -> Option<UTF16Selection> {
16357 // Prevent the IME menu from appearing when holding down an alphabetic key
16358 // while input is disabled.
16359 if !ignore_disabled_input && !self.input_enabled {
16360 return None;
16361 }
16362
16363 let selection = self.selections.newest::<OffsetUtf16>(cx);
16364 let range = selection.range();
16365
16366 Some(UTF16Selection {
16367 range: range.start.0..range.end.0,
16368 reversed: selection.reversed,
16369 })
16370 }
16371
16372 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16373 let snapshot = self.buffer.read(cx).read(cx);
16374 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16375 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16376 }
16377
16378 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16379 self.clear_highlights::<InputComposition>(cx);
16380 self.ime_transaction.take();
16381 }
16382
16383 fn replace_text_in_range(
16384 &mut self,
16385 range_utf16: Option<Range<usize>>,
16386 text: &str,
16387 window: &mut Window,
16388 cx: &mut Context<Self>,
16389 ) {
16390 if !self.input_enabled {
16391 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16392 return;
16393 }
16394
16395 self.transact(window, cx, |this, window, cx| {
16396 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16397 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16398 Some(this.selection_replacement_ranges(range_utf16, cx))
16399 } else {
16400 this.marked_text_ranges(cx)
16401 };
16402
16403 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16404 let newest_selection_id = this.selections.newest_anchor().id;
16405 this.selections
16406 .all::<OffsetUtf16>(cx)
16407 .iter()
16408 .zip(ranges_to_replace.iter())
16409 .find_map(|(selection, range)| {
16410 if selection.id == newest_selection_id {
16411 Some(
16412 (range.start.0 as isize - selection.head().0 as isize)
16413 ..(range.end.0 as isize - selection.head().0 as isize),
16414 )
16415 } else {
16416 None
16417 }
16418 })
16419 });
16420
16421 cx.emit(EditorEvent::InputHandled {
16422 utf16_range_to_replace: range_to_replace,
16423 text: text.into(),
16424 });
16425
16426 if let Some(new_selected_ranges) = new_selected_ranges {
16427 this.change_selections(None, window, cx, |selections| {
16428 selections.select_ranges(new_selected_ranges)
16429 });
16430 this.backspace(&Default::default(), window, cx);
16431 }
16432
16433 this.handle_input(text, window, cx);
16434 });
16435
16436 if let Some(transaction) = self.ime_transaction {
16437 self.buffer.update(cx, |buffer, cx| {
16438 buffer.group_until_transaction(transaction, cx);
16439 });
16440 }
16441
16442 self.unmark_text(window, cx);
16443 }
16444
16445 fn replace_and_mark_text_in_range(
16446 &mut self,
16447 range_utf16: Option<Range<usize>>,
16448 text: &str,
16449 new_selected_range_utf16: Option<Range<usize>>,
16450 window: &mut Window,
16451 cx: &mut Context<Self>,
16452 ) {
16453 if !self.input_enabled {
16454 return;
16455 }
16456
16457 let transaction = self.transact(window, cx, |this, window, cx| {
16458 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16459 let snapshot = this.buffer.read(cx).read(cx);
16460 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16461 for marked_range in &mut marked_ranges {
16462 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16463 marked_range.start.0 += relative_range_utf16.start;
16464 marked_range.start =
16465 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16466 marked_range.end =
16467 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16468 }
16469 }
16470 Some(marked_ranges)
16471 } else if let Some(range_utf16) = range_utf16 {
16472 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16473 Some(this.selection_replacement_ranges(range_utf16, cx))
16474 } else {
16475 None
16476 };
16477
16478 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16479 let newest_selection_id = this.selections.newest_anchor().id;
16480 this.selections
16481 .all::<OffsetUtf16>(cx)
16482 .iter()
16483 .zip(ranges_to_replace.iter())
16484 .find_map(|(selection, range)| {
16485 if selection.id == newest_selection_id {
16486 Some(
16487 (range.start.0 as isize - selection.head().0 as isize)
16488 ..(range.end.0 as isize - selection.head().0 as isize),
16489 )
16490 } else {
16491 None
16492 }
16493 })
16494 });
16495
16496 cx.emit(EditorEvent::InputHandled {
16497 utf16_range_to_replace: range_to_replace,
16498 text: text.into(),
16499 });
16500
16501 if let Some(ranges) = ranges_to_replace {
16502 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16503 }
16504
16505 let marked_ranges = {
16506 let snapshot = this.buffer.read(cx).read(cx);
16507 this.selections
16508 .disjoint_anchors()
16509 .iter()
16510 .map(|selection| {
16511 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16512 })
16513 .collect::<Vec<_>>()
16514 };
16515
16516 if text.is_empty() {
16517 this.unmark_text(window, cx);
16518 } else {
16519 this.highlight_text::<InputComposition>(
16520 marked_ranges.clone(),
16521 HighlightStyle {
16522 underline: Some(UnderlineStyle {
16523 thickness: px(1.),
16524 color: None,
16525 wavy: false,
16526 }),
16527 ..Default::default()
16528 },
16529 cx,
16530 );
16531 }
16532
16533 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16534 let use_autoclose = this.use_autoclose;
16535 let use_auto_surround = this.use_auto_surround;
16536 this.set_use_autoclose(false);
16537 this.set_use_auto_surround(false);
16538 this.handle_input(text, window, cx);
16539 this.set_use_autoclose(use_autoclose);
16540 this.set_use_auto_surround(use_auto_surround);
16541
16542 if let Some(new_selected_range) = new_selected_range_utf16 {
16543 let snapshot = this.buffer.read(cx).read(cx);
16544 let new_selected_ranges = marked_ranges
16545 .into_iter()
16546 .map(|marked_range| {
16547 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16548 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16549 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16550 snapshot.clip_offset_utf16(new_start, Bias::Left)
16551 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16552 })
16553 .collect::<Vec<_>>();
16554
16555 drop(snapshot);
16556 this.change_selections(None, window, cx, |selections| {
16557 selections.select_ranges(new_selected_ranges)
16558 });
16559 }
16560 });
16561
16562 self.ime_transaction = self.ime_transaction.or(transaction);
16563 if let Some(transaction) = self.ime_transaction {
16564 self.buffer.update(cx, |buffer, cx| {
16565 buffer.group_until_transaction(transaction, cx);
16566 });
16567 }
16568
16569 if self.text_highlights::<InputComposition>(cx).is_none() {
16570 self.ime_transaction.take();
16571 }
16572 }
16573
16574 fn bounds_for_range(
16575 &mut self,
16576 range_utf16: Range<usize>,
16577 element_bounds: gpui::Bounds<Pixels>,
16578 window: &mut Window,
16579 cx: &mut Context<Self>,
16580 ) -> Option<gpui::Bounds<Pixels>> {
16581 let text_layout_details = self.text_layout_details(window);
16582 let gpui::Size {
16583 width: em_width,
16584 height: line_height,
16585 } = self.character_size(window);
16586
16587 let snapshot = self.snapshot(window, cx);
16588 let scroll_position = snapshot.scroll_position();
16589 let scroll_left = scroll_position.x * em_width;
16590
16591 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16592 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16593 + self.gutter_dimensions.width
16594 + self.gutter_dimensions.margin;
16595 let y = line_height * (start.row().as_f32() - scroll_position.y);
16596
16597 Some(Bounds {
16598 origin: element_bounds.origin + point(x, y),
16599 size: size(em_width, line_height),
16600 })
16601 }
16602
16603 fn character_index_for_point(
16604 &mut self,
16605 point: gpui::Point<Pixels>,
16606 _window: &mut Window,
16607 _cx: &mut Context<Self>,
16608 ) -> Option<usize> {
16609 let position_map = self.last_position_map.as_ref()?;
16610 if !position_map.text_hitbox.contains(&point) {
16611 return None;
16612 }
16613 let display_point = position_map.point_for_position(point).previous_valid;
16614 let anchor = position_map
16615 .snapshot
16616 .display_point_to_anchor(display_point, Bias::Left);
16617 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16618 Some(utf16_offset.0)
16619 }
16620}
16621
16622trait SelectionExt {
16623 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16624 fn spanned_rows(
16625 &self,
16626 include_end_if_at_line_start: bool,
16627 map: &DisplaySnapshot,
16628 ) -> Range<MultiBufferRow>;
16629}
16630
16631impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16632 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16633 let start = self
16634 .start
16635 .to_point(&map.buffer_snapshot)
16636 .to_display_point(map);
16637 let end = self
16638 .end
16639 .to_point(&map.buffer_snapshot)
16640 .to_display_point(map);
16641 if self.reversed {
16642 end..start
16643 } else {
16644 start..end
16645 }
16646 }
16647
16648 fn spanned_rows(
16649 &self,
16650 include_end_if_at_line_start: bool,
16651 map: &DisplaySnapshot,
16652 ) -> Range<MultiBufferRow> {
16653 let start = self.start.to_point(&map.buffer_snapshot);
16654 let mut end = self.end.to_point(&map.buffer_snapshot);
16655 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16656 end.row -= 1;
16657 }
16658
16659 let buffer_start = map.prev_line_boundary(start).0;
16660 let buffer_end = map.next_line_boundary(end).0;
16661 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16662 }
16663}
16664
16665impl<T: InvalidationRegion> InvalidationStack<T> {
16666 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16667 where
16668 S: Clone + ToOffset,
16669 {
16670 while let Some(region) = self.last() {
16671 let all_selections_inside_invalidation_ranges =
16672 if selections.len() == region.ranges().len() {
16673 selections
16674 .iter()
16675 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16676 .all(|(selection, invalidation_range)| {
16677 let head = selection.head().to_offset(buffer);
16678 invalidation_range.start <= head && invalidation_range.end >= head
16679 })
16680 } else {
16681 false
16682 };
16683
16684 if all_selections_inside_invalidation_ranges {
16685 break;
16686 } else {
16687 self.pop();
16688 }
16689 }
16690 }
16691}
16692
16693impl<T> Default for InvalidationStack<T> {
16694 fn default() -> Self {
16695 Self(Default::default())
16696 }
16697}
16698
16699impl<T> Deref for InvalidationStack<T> {
16700 type Target = Vec<T>;
16701
16702 fn deref(&self) -> &Self::Target {
16703 &self.0
16704 }
16705}
16706
16707impl<T> DerefMut for InvalidationStack<T> {
16708 fn deref_mut(&mut self) -> &mut Self::Target {
16709 &mut self.0
16710 }
16711}
16712
16713impl InvalidationRegion for SnippetState {
16714 fn ranges(&self) -> &[Range<Anchor>] {
16715 &self.ranges[self.active_index]
16716 }
16717}
16718
16719pub fn diagnostic_block_renderer(
16720 diagnostic: Diagnostic,
16721 max_message_rows: Option<u8>,
16722 allow_closing: bool,
16723 _is_valid: bool,
16724) -> RenderBlock {
16725 let (text_without_backticks, code_ranges) =
16726 highlight_diagnostic_message(&diagnostic, max_message_rows);
16727
16728 Arc::new(move |cx: &mut BlockContext| {
16729 let group_id: SharedString = cx.block_id.to_string().into();
16730
16731 let mut text_style = cx.window.text_style().clone();
16732 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16733 let theme_settings = ThemeSettings::get_global(cx);
16734 text_style.font_family = theme_settings.buffer_font.family.clone();
16735 text_style.font_style = theme_settings.buffer_font.style;
16736 text_style.font_features = theme_settings.buffer_font.features.clone();
16737 text_style.font_weight = theme_settings.buffer_font.weight;
16738
16739 let multi_line_diagnostic = diagnostic.message.contains('\n');
16740
16741 let buttons = |diagnostic: &Diagnostic| {
16742 if multi_line_diagnostic {
16743 v_flex()
16744 } else {
16745 h_flex()
16746 }
16747 .when(allow_closing, |div| {
16748 div.children(diagnostic.is_primary.then(|| {
16749 IconButton::new("close-block", IconName::XCircle)
16750 .icon_color(Color::Muted)
16751 .size(ButtonSize::Compact)
16752 .style(ButtonStyle::Transparent)
16753 .visible_on_hover(group_id.clone())
16754 .on_click(move |_click, window, cx| {
16755 window.dispatch_action(Box::new(Cancel), cx)
16756 })
16757 .tooltip(|window, cx| {
16758 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16759 })
16760 }))
16761 })
16762 .child(
16763 IconButton::new("copy-block", IconName::Copy)
16764 .icon_color(Color::Muted)
16765 .size(ButtonSize::Compact)
16766 .style(ButtonStyle::Transparent)
16767 .visible_on_hover(group_id.clone())
16768 .on_click({
16769 let message = diagnostic.message.clone();
16770 move |_click, _, cx| {
16771 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16772 }
16773 })
16774 .tooltip(Tooltip::text("Copy diagnostic message")),
16775 )
16776 };
16777
16778 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16779 AvailableSpace::min_size(),
16780 cx.window,
16781 cx.app,
16782 );
16783
16784 h_flex()
16785 .id(cx.block_id)
16786 .group(group_id.clone())
16787 .relative()
16788 .size_full()
16789 .block_mouse_down()
16790 .pl(cx.gutter_dimensions.width)
16791 .w(cx.max_width - cx.gutter_dimensions.full_width())
16792 .child(
16793 div()
16794 .flex()
16795 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16796 .flex_shrink(),
16797 )
16798 .child(buttons(&diagnostic))
16799 .child(div().flex().flex_shrink_0().child(
16800 StyledText::new(text_without_backticks.clone()).with_highlights(
16801 &text_style,
16802 code_ranges.iter().map(|range| {
16803 (
16804 range.clone(),
16805 HighlightStyle {
16806 font_weight: Some(FontWeight::BOLD),
16807 ..Default::default()
16808 },
16809 )
16810 }),
16811 ),
16812 ))
16813 .into_any_element()
16814 })
16815}
16816
16817fn inline_completion_edit_text(
16818 current_snapshot: &BufferSnapshot,
16819 edits: &[(Range<Anchor>, String)],
16820 edit_preview: &EditPreview,
16821 include_deletions: bool,
16822 cx: &App,
16823) -> HighlightedText {
16824 let edits = edits
16825 .iter()
16826 .map(|(anchor, text)| {
16827 (
16828 anchor.start.text_anchor..anchor.end.text_anchor,
16829 text.clone(),
16830 )
16831 })
16832 .collect::<Vec<_>>();
16833
16834 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16835}
16836
16837pub fn highlight_diagnostic_message(
16838 diagnostic: &Diagnostic,
16839 mut max_message_rows: Option<u8>,
16840) -> (SharedString, Vec<Range<usize>>) {
16841 let mut text_without_backticks = String::new();
16842 let mut code_ranges = Vec::new();
16843
16844 if let Some(source) = &diagnostic.source {
16845 text_without_backticks.push_str(source);
16846 code_ranges.push(0..source.len());
16847 text_without_backticks.push_str(": ");
16848 }
16849
16850 let mut prev_offset = 0;
16851 let mut in_code_block = false;
16852 let has_row_limit = max_message_rows.is_some();
16853 let mut newline_indices = diagnostic
16854 .message
16855 .match_indices('\n')
16856 .filter(|_| has_row_limit)
16857 .map(|(ix, _)| ix)
16858 .fuse()
16859 .peekable();
16860
16861 for (quote_ix, _) in diagnostic
16862 .message
16863 .match_indices('`')
16864 .chain([(diagnostic.message.len(), "")])
16865 {
16866 let mut first_newline_ix = None;
16867 let mut last_newline_ix = None;
16868 while let Some(newline_ix) = newline_indices.peek() {
16869 if *newline_ix < quote_ix {
16870 if first_newline_ix.is_none() {
16871 first_newline_ix = Some(*newline_ix);
16872 }
16873 last_newline_ix = Some(*newline_ix);
16874
16875 if let Some(rows_left) = &mut max_message_rows {
16876 if *rows_left == 0 {
16877 break;
16878 } else {
16879 *rows_left -= 1;
16880 }
16881 }
16882 let _ = newline_indices.next();
16883 } else {
16884 break;
16885 }
16886 }
16887 let prev_len = text_without_backticks.len();
16888 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16889 text_without_backticks.push_str(new_text);
16890 if in_code_block {
16891 code_ranges.push(prev_len..text_without_backticks.len());
16892 }
16893 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16894 in_code_block = !in_code_block;
16895 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16896 text_without_backticks.push_str("...");
16897 break;
16898 }
16899 }
16900
16901 (text_without_backticks.into(), code_ranges)
16902}
16903
16904fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16905 match severity {
16906 DiagnosticSeverity::ERROR => colors.error,
16907 DiagnosticSeverity::WARNING => colors.warning,
16908 DiagnosticSeverity::INFORMATION => colors.info,
16909 DiagnosticSeverity::HINT => colors.info,
16910 _ => colors.ignored,
16911 }
16912}
16913
16914pub fn styled_runs_for_code_label<'a>(
16915 label: &'a CodeLabel,
16916 syntax_theme: &'a theme::SyntaxTheme,
16917) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16918 let fade_out = HighlightStyle {
16919 fade_out: Some(0.35),
16920 ..Default::default()
16921 };
16922
16923 let mut prev_end = label.filter_range.end;
16924 label
16925 .runs
16926 .iter()
16927 .enumerate()
16928 .flat_map(move |(ix, (range, highlight_id))| {
16929 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16930 style
16931 } else {
16932 return Default::default();
16933 };
16934 let mut muted_style = style;
16935 muted_style.highlight(fade_out);
16936
16937 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16938 if range.start >= label.filter_range.end {
16939 if range.start > prev_end {
16940 runs.push((prev_end..range.start, fade_out));
16941 }
16942 runs.push((range.clone(), muted_style));
16943 } else if range.end <= label.filter_range.end {
16944 runs.push((range.clone(), style));
16945 } else {
16946 runs.push((range.start..label.filter_range.end, style));
16947 runs.push((label.filter_range.end..range.end, muted_style));
16948 }
16949 prev_end = cmp::max(prev_end, range.end);
16950
16951 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16952 runs.push((prev_end..label.text.len(), fade_out));
16953 }
16954
16955 runs
16956 })
16957}
16958
16959pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16960 let mut prev_index = 0;
16961 let mut prev_codepoint: Option<char> = None;
16962 text.char_indices()
16963 .chain([(text.len(), '\0')])
16964 .filter_map(move |(index, codepoint)| {
16965 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16966 let is_boundary = index == text.len()
16967 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16968 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16969 if is_boundary {
16970 let chunk = &text[prev_index..index];
16971 prev_index = index;
16972 Some(chunk)
16973 } else {
16974 None
16975 }
16976 })
16977}
16978
16979pub trait RangeToAnchorExt: Sized {
16980 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16981
16982 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16983 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16984 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16985 }
16986}
16987
16988impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16989 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16990 let start_offset = self.start.to_offset(snapshot);
16991 let end_offset = self.end.to_offset(snapshot);
16992 if start_offset == end_offset {
16993 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16994 } else {
16995 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16996 }
16997 }
16998}
16999
17000pub trait RowExt {
17001 fn as_f32(&self) -> f32;
17002
17003 fn next_row(&self) -> Self;
17004
17005 fn previous_row(&self) -> Self;
17006
17007 fn minus(&self, other: Self) -> u32;
17008}
17009
17010impl RowExt for DisplayRow {
17011 fn as_f32(&self) -> f32 {
17012 self.0 as f32
17013 }
17014
17015 fn next_row(&self) -> Self {
17016 Self(self.0 + 1)
17017 }
17018
17019 fn previous_row(&self) -> Self {
17020 Self(self.0.saturating_sub(1))
17021 }
17022
17023 fn minus(&self, other: Self) -> u32 {
17024 self.0 - other.0
17025 }
17026}
17027
17028impl RowExt for MultiBufferRow {
17029 fn as_f32(&self) -> f32 {
17030 self.0 as f32
17031 }
17032
17033 fn next_row(&self) -> Self {
17034 Self(self.0 + 1)
17035 }
17036
17037 fn previous_row(&self) -> Self {
17038 Self(self.0.saturating_sub(1))
17039 }
17040
17041 fn minus(&self, other: Self) -> u32 {
17042 self.0 - other.0
17043 }
17044}
17045
17046trait RowRangeExt {
17047 type Row;
17048
17049 fn len(&self) -> usize;
17050
17051 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17052}
17053
17054impl RowRangeExt for Range<MultiBufferRow> {
17055 type Row = MultiBufferRow;
17056
17057 fn len(&self) -> usize {
17058 (self.end.0 - self.start.0) as usize
17059 }
17060
17061 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17062 (self.start.0..self.end.0).map(MultiBufferRow)
17063 }
17064}
17065
17066impl RowRangeExt for Range<DisplayRow> {
17067 type Row = DisplayRow;
17068
17069 fn len(&self) -> usize {
17070 (self.end.0 - self.start.0) as usize
17071 }
17072
17073 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17074 (self.start.0..self.end.0).map(DisplayRow)
17075 }
17076}
17077
17078/// If select range has more than one line, we
17079/// just point the cursor to range.start.
17080fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17081 if range.start.row == range.end.row {
17082 range
17083 } else {
17084 range.start..range.start
17085 }
17086}
17087pub struct KillRing(ClipboardItem);
17088impl Global for KillRing {}
17089
17090const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17091
17092fn all_edits_insertions_or_deletions(
17093 edits: &Vec<(Range<Anchor>, String)>,
17094 snapshot: &MultiBufferSnapshot,
17095) -> bool {
17096 let mut all_insertions = true;
17097 let mut all_deletions = true;
17098
17099 for (range, new_text) in edits.iter() {
17100 let range_is_empty = range.to_offset(&snapshot).is_empty();
17101 let text_is_empty = new_text.is_empty();
17102
17103 if range_is_empty != text_is_empty {
17104 if range_is_empty {
17105 all_deletions = false;
17106 } else {
17107 all_insertions = false;
17108 }
17109 } else {
17110 return false;
17111 }
17112
17113 if !all_insertions && !all_deletions {
17114 return false;
17115 }
17116 }
17117 all_insertions || all_deletions
17118}