1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
84 ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
85 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
86 InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
87 Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
88 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
89 WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
103 HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
104 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109use persistence::DB;
110pub use proposed_changes_editor::{
111 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
112};
113use similar::{ChangeTag, TextDiff};
114use std::iter::Peekable;
115use task::{ResolvedTask, TaskTemplate, TaskVariables};
116
117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
118pub use lsp::CompletionContext;
119use lsp::{
120 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
121 LanguageServerId, LanguageServerName,
122};
123
124use language::BufferSnapshot;
125use movement::TextLayoutDetails;
126pub use multi_buffer::{
127 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
128 ToOffset, ToPoint,
129};
130use multi_buffer::{
131 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
132 ToOffsetUtf16,
133};
134use project::{
135 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
136 project_settings::{GitGutterSetting, ProjectSettings},
137 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
138 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
139};
140use rand::prelude::*;
141use rpc::{proto::*, ErrorExt};
142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
143use selections_collection::{
144 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
145};
146use serde::{Deserialize, Serialize};
147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
148use smallvec::SmallVec;
149use snippet::Snippet;
150use std::{
151 any::TypeId,
152 borrow::Cow,
153 cell::RefCell,
154 cmp::{self, Ordering, Reverse},
155 mem,
156 num::NonZeroU32,
157 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
158 path::{Path, PathBuf},
159 rc::Rc,
160 sync::Arc,
161 time::{Duration, Instant},
162};
163pub use sum_tree::Bias;
164use sum_tree::TreeMap;
165use text::{BufferId, OffsetUtf16, Rope};
166use theme::{
167 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
168 ThemeColors, ThemeSettings,
169};
170use ui::{
171 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
172 Tooltip,
173};
174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
175use workspace::{
176 item::{ItemHandle, PreviewTabsSettings},
177 ItemId, RestoreOnStartupBehavior,
178};
179use workspace::{
180 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
181 WorkspaceSettings,
182};
183use workspace::{
184 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
185};
186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
187
188use crate::hover_links::{find_url, find_url_from_range};
189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
190
191pub const FILE_HEADER_HEIGHT: u32 = 2;
192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
196const MAX_LINE_LEN: usize = 1024;
197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
200#[doc(hidden)]
201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
202
203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
205
206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
208
209pub fn render_parsed_markdown(
210 element_id: impl Into<ElementId>,
211 parsed: &language::ParsedMarkdown,
212 editor_style: &EditorStyle,
213 workspace: Option<WeakEntity<Workspace>>,
214 cx: &mut App,
215) -> InteractiveText {
216 let code_span_background_color = cx
217 .theme()
218 .colors()
219 .editor_document_highlight_read_background;
220
221 let highlights = gpui::combine_highlights(
222 parsed.highlights.iter().filter_map(|(range, highlight)| {
223 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
224 Some((range.clone(), highlight))
225 }),
226 parsed
227 .regions
228 .iter()
229 .zip(&parsed.region_ranges)
230 .filter_map(|(region, range)| {
231 if region.code {
232 Some((
233 range.clone(),
234 HighlightStyle {
235 background_color: Some(code_span_background_color),
236 ..Default::default()
237 },
238 ))
239 } else {
240 None
241 }
242 }),
243 );
244
245 let mut links = Vec::new();
246 let mut link_ranges = Vec::new();
247 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
248 if let Some(link) = region.link.clone() {
249 links.push(link);
250 link_ranges.push(range.clone());
251 }
252 }
253
254 InteractiveText::new(
255 element_id,
256 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
257 )
258 .on_click(
259 link_ranges,
260 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
261 markdown::Link::Web { url } => cx.open_url(url),
262 markdown::Link::Path { path } => {
263 if let Some(workspace) = &workspace {
264 _ = workspace.update(cx, |workspace, cx| {
265 workspace
266 .open_abs_path(path.clone(), false, window, cx)
267 .detach();
268 });
269 }
270 }
271 },
272 )
273}
274
275#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
276pub enum InlayId {
277 InlineCompletion(usize),
278 Hint(usize),
279}
280
281impl InlayId {
282 fn id(&self) -> usize {
283 match self {
284 Self::InlineCompletion(id) => *id,
285 Self::Hint(id) => *id,
286 }
287 }
288}
289
290enum DocumentHighlightRead {}
291enum DocumentHighlightWrite {}
292enum InputComposition {}
293enum SelectedTextHighlight {}
294
295#[derive(Debug, Copy, Clone, PartialEq, Eq)]
296pub enum Navigated {
297 Yes,
298 No,
299}
300
301impl Navigated {
302 pub fn from_bool(yes: bool) -> Navigated {
303 if yes {
304 Navigated::Yes
305 } else {
306 Navigated::No
307 }
308 }
309}
310
311pub fn init_settings(cx: &mut App) {
312 EditorSettings::register(cx);
313}
314
315pub fn init(cx: &mut App) {
316 init_settings(cx);
317
318 workspace::register_project_item::<Editor>(cx);
319 workspace::FollowableViewRegistry::register::<Editor>(cx);
320 workspace::register_serializable_item::<Editor>(cx);
321
322 cx.observe_new(
323 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
324 workspace.register_action(Editor::new_file);
325 workspace.register_action(Editor::new_file_vertical);
326 workspace.register_action(Editor::new_file_horizontal);
327 workspace.register_action(Editor::cancel_language_server_work);
328 },
329 )
330 .detach();
331
332 cx.on_action(move |_: &workspace::NewFile, cx| {
333 let app_state = workspace::AppState::global(cx);
334 if let Some(app_state) = app_state.upgrade() {
335 workspace::open_new(
336 Default::default(),
337 app_state,
338 cx,
339 |workspace, window, cx| {
340 Editor::new_file(workspace, &Default::default(), window, cx)
341 },
342 )
343 .detach();
344 }
345 });
346 cx.on_action(move |_: &workspace::NewWindow, cx| {
347 let app_state = workspace::AppState::global(cx);
348 if let Some(app_state) = app_state.upgrade() {
349 workspace::open_new(
350 Default::default(),
351 app_state,
352 cx,
353 |workspace, window, cx| {
354 cx.activate(true);
355 Editor::new_file(workspace, &Default::default(), window, cx)
356 },
357 )
358 .detach();
359 }
360 });
361}
362
363pub struct SearchWithinRange;
364
365trait InvalidationRegion {
366 fn ranges(&self) -> &[Range<Anchor>];
367}
368
369#[derive(Clone, Debug, PartialEq)]
370pub enum SelectPhase {
371 Begin {
372 position: DisplayPoint,
373 add: bool,
374 click_count: usize,
375 },
376 BeginColumnar {
377 position: DisplayPoint,
378 reset: bool,
379 goal_column: u32,
380 },
381 Extend {
382 position: DisplayPoint,
383 click_count: usize,
384 },
385 Update {
386 position: DisplayPoint,
387 goal_column: u32,
388 scroll_delta: gpui::Point<f32>,
389 },
390 End,
391}
392
393#[derive(Clone, Debug)]
394pub enum SelectMode {
395 Character,
396 Word(Range<Anchor>),
397 Line(Range<Anchor>),
398 All,
399}
400
401#[derive(Copy, Clone, PartialEq, Eq, Debug)]
402pub enum EditorMode {
403 SingleLine { auto_width: bool },
404 AutoHeight { max_lines: usize },
405 Full,
406}
407
408#[derive(Copy, Clone, Debug)]
409pub enum SoftWrap {
410 /// Prefer not to wrap at all.
411 ///
412 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
413 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
414 GitDiff,
415 /// Prefer a single line generally, unless an overly long line is encountered.
416 None,
417 /// Soft wrap lines that exceed the editor width.
418 EditorWidth,
419 /// Soft wrap lines at the preferred line length.
420 Column(u32),
421 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
422 Bounded(u32),
423}
424
425#[derive(Clone)]
426pub struct EditorStyle {
427 pub background: Hsla,
428 pub local_player: PlayerColor,
429 pub text: TextStyle,
430 pub scrollbar_width: Pixels,
431 pub syntax: Arc<SyntaxTheme>,
432 pub status: StatusColors,
433 pub inlay_hints_style: HighlightStyle,
434 pub inline_completion_styles: InlineCompletionStyles,
435 pub unnecessary_code_fade: f32,
436}
437
438impl Default for EditorStyle {
439 fn default() -> Self {
440 Self {
441 background: Hsla::default(),
442 local_player: PlayerColor::default(),
443 text: TextStyle::default(),
444 scrollbar_width: Pixels::default(),
445 syntax: Default::default(),
446 // HACK: Status colors don't have a real default.
447 // We should look into removing the status colors from the editor
448 // style and retrieve them directly from the theme.
449 status: StatusColors::dark(),
450 inlay_hints_style: HighlightStyle::default(),
451 inline_completion_styles: InlineCompletionStyles {
452 insertion: HighlightStyle::default(),
453 whitespace: HighlightStyle::default(),
454 },
455 unnecessary_code_fade: Default::default(),
456 }
457 }
458}
459
460pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
461 let show_background = language_settings::language_settings(None, None, cx)
462 .inlay_hints
463 .show_background;
464
465 HighlightStyle {
466 color: Some(cx.theme().status().hint),
467 background_color: show_background.then(|| cx.theme().status().hint_background),
468 ..HighlightStyle::default()
469 }
470}
471
472pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
473 InlineCompletionStyles {
474 insertion: HighlightStyle {
475 color: Some(cx.theme().status().predictive),
476 ..HighlightStyle::default()
477 },
478 whitespace: HighlightStyle {
479 background_color: Some(cx.theme().status().created_background),
480 ..HighlightStyle::default()
481 },
482 }
483}
484
485type CompletionId = usize;
486
487pub(crate) enum EditDisplayMode {
488 TabAccept,
489 DiffPopover,
490 Inline,
491}
492
493enum InlineCompletion {
494 Edit {
495 edits: Vec<(Range<Anchor>, String)>,
496 edit_preview: Option<EditPreview>,
497 display_mode: EditDisplayMode,
498 snapshot: BufferSnapshot,
499 },
500 Move {
501 target: Anchor,
502 snapshot: BufferSnapshot,
503 },
504}
505
506struct InlineCompletionState {
507 inlay_ids: Vec<InlayId>,
508 completion: InlineCompletion,
509 completion_id: Option<SharedString>,
510 invalidation_range: Range<Anchor>,
511}
512
513enum EditPredictionSettings {
514 Disabled,
515 Enabled {
516 show_in_menu: bool,
517 preview_requires_modifier: bool,
518 },
519}
520
521enum InlineCompletionHighlight {}
522
523pub enum MenuInlineCompletionsPolicy {
524 Never,
525 ByProvider,
526}
527
528pub enum EditPredictionPreview {
529 /// Modifier is not pressed
530 Inactive,
531 /// Modifier pressed
532 Active {
533 previous_scroll_position: Option<ScrollAnchor>,
534 },
535}
536
537#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
538struct EditorActionId(usize);
539
540impl EditorActionId {
541 pub fn post_inc(&mut self) -> Self {
542 let answer = self.0;
543
544 *self = Self(answer + 1);
545
546 Self(answer)
547 }
548}
549
550// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
551// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
552
553type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
554type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
555
556#[derive(Default)]
557struct ScrollbarMarkerState {
558 scrollbar_size: Size<Pixels>,
559 dirty: bool,
560 markers: Arc<[PaintQuad]>,
561 pending_refresh: Option<Task<Result<()>>>,
562}
563
564impl ScrollbarMarkerState {
565 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
566 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
567 }
568}
569
570#[derive(Clone, Debug)]
571struct RunnableTasks {
572 templates: Vec<(TaskSourceKind, TaskTemplate)>,
573 offset: MultiBufferOffset,
574 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
575 column: u32,
576 // Values of all named captures, including those starting with '_'
577 extra_variables: HashMap<String, String>,
578 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
579 context_range: Range<BufferOffset>,
580}
581
582impl RunnableTasks {
583 fn resolve<'a>(
584 &'a self,
585 cx: &'a task::TaskContext,
586 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
587 self.templates.iter().filter_map(|(kind, template)| {
588 template
589 .resolve_task(&kind.to_id_base(), cx)
590 .map(|task| (kind.clone(), task))
591 })
592 }
593}
594
595#[derive(Clone)]
596struct ResolvedTasks {
597 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
598 position: Anchor,
599}
600#[derive(Copy, Clone, Debug)]
601struct MultiBufferOffset(usize);
602#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
603struct BufferOffset(usize);
604
605// Addons allow storing per-editor state in other crates (e.g. Vim)
606pub trait Addon: 'static {
607 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
608
609 fn render_buffer_header_controls(
610 &self,
611 _: &ExcerptInfo,
612 _: &Window,
613 _: &App,
614 ) -> Option<AnyElement> {
615 None
616 }
617
618 fn to_any(&self) -> &dyn std::any::Any;
619}
620
621#[derive(Debug, Copy, Clone, PartialEq, Eq)]
622pub enum IsVimMode {
623 Yes,
624 No,
625}
626
627/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
628///
629/// See the [module level documentation](self) for more information.
630pub struct Editor {
631 focus_handle: FocusHandle,
632 last_focused_descendant: Option<WeakFocusHandle>,
633 /// The text buffer being edited
634 buffer: Entity<MultiBuffer>,
635 /// Map of how text in the buffer should be displayed.
636 /// Handles soft wraps, folds, fake inlay text insertions, etc.
637 pub display_map: Entity<DisplayMap>,
638 pub selections: SelectionsCollection,
639 pub scroll_manager: ScrollManager,
640 /// When inline assist editors are linked, they all render cursors because
641 /// typing enters text into each of them, even the ones that aren't focused.
642 pub(crate) show_cursor_when_unfocused: bool,
643 columnar_selection_tail: Option<Anchor>,
644 add_selections_state: Option<AddSelectionsState>,
645 select_next_state: Option<SelectNextState>,
646 select_prev_state: Option<SelectNextState>,
647 selection_history: SelectionHistory,
648 autoclose_regions: Vec<AutocloseRegion>,
649 snippet_stack: InvalidationStack<SnippetState>,
650 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
651 ime_transaction: Option<TransactionId>,
652 active_diagnostics: Option<ActiveDiagnosticGroup>,
653 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
654
655 // TODO: make this a access method
656 pub project: Option<Entity<Project>>,
657 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
658 completion_provider: Option<Box<dyn CompletionProvider>>,
659 collaboration_hub: Option<Box<dyn CollaborationHub>>,
660 blink_manager: Entity<BlinkManager>,
661 show_cursor_names: bool,
662 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
663 pub show_local_selections: bool,
664 mode: EditorMode,
665 show_breadcrumbs: bool,
666 show_gutter: bool,
667 show_scrollbars: bool,
668 show_line_numbers: Option<bool>,
669 use_relative_line_numbers: Option<bool>,
670 show_git_diff_gutter: Option<bool>,
671 show_code_actions: Option<bool>,
672 show_runnables: Option<bool>,
673 show_wrap_guides: Option<bool>,
674 show_indent_guides: Option<bool>,
675 placeholder_text: Option<Arc<str>>,
676 highlight_order: usize,
677 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
678 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
679 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
680 scrollbar_marker_state: ScrollbarMarkerState,
681 active_indent_guides_state: ActiveIndentGuidesState,
682 nav_history: Option<ItemNavHistory>,
683 context_menu: RefCell<Option<CodeContextMenu>>,
684 mouse_context_menu: Option<MouseContextMenu>,
685 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
686 signature_help_state: SignatureHelpState,
687 auto_signature_help: Option<bool>,
688 find_all_references_task_sources: Vec<Anchor>,
689 next_completion_id: CompletionId,
690 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
691 code_actions_task: Option<Task<Result<()>>>,
692 selection_highlight_task: Option<Task<()>>,
693 document_highlights_task: Option<Task<()>>,
694 linked_editing_range_task: Option<Task<Option<()>>>,
695 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
696 pending_rename: Option<RenameState>,
697 searchable: bool,
698 cursor_shape: CursorShape,
699 current_line_highlight: Option<CurrentLineHighlight>,
700 collapse_matches: bool,
701 autoindent_mode: Option<AutoindentMode>,
702 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
703 input_enabled: bool,
704 use_modal_editing: bool,
705 read_only: bool,
706 leader_peer_id: Option<PeerId>,
707 remote_id: Option<ViewId>,
708 hover_state: HoverState,
709 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
710 gutter_hovered: bool,
711 hovered_link_state: Option<HoveredLinkState>,
712 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
713 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
714 active_inline_completion: Option<InlineCompletionState>,
715 /// Used to prevent flickering as the user types while the menu is open
716 stale_inline_completion_in_menu: Option<InlineCompletionState>,
717 edit_prediction_settings: EditPredictionSettings,
718 inline_completions_hidden_for_vim_mode: bool,
719 show_inline_completions_override: Option<bool>,
720 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
721 edit_prediction_preview: EditPredictionPreview,
722 edit_prediction_cursor_on_leading_whitespace: bool,
723 edit_prediction_requires_modifier_in_leading_space: bool,
724 inlay_hint_cache: InlayHintCache,
725 next_inlay_id: usize,
726 _subscriptions: Vec<Subscription>,
727 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
728 gutter_dimensions: GutterDimensions,
729 style: Option<EditorStyle>,
730 text_style_refinement: Option<TextStyleRefinement>,
731 next_editor_action_id: EditorActionId,
732 editor_actions:
733 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
734 use_autoclose: bool,
735 use_auto_surround: bool,
736 auto_replace_emoji_shortcode: bool,
737 show_git_blame_gutter: bool,
738 show_git_blame_inline: bool,
739 show_git_blame_inline_delay_task: Option<Task<()>>,
740 distinguish_unstaged_diff_hunks: bool,
741 git_blame_inline_enabled: bool,
742 serialize_dirty_buffers: bool,
743 show_selection_menu: Option<bool>,
744 blame: Option<Entity<GitBlame>>,
745 blame_subscription: Option<Subscription>,
746 custom_context_menu: Option<
747 Box<
748 dyn 'static
749 + Fn(
750 &mut Self,
751 DisplayPoint,
752 &mut Window,
753 &mut Context<Self>,
754 ) -> Option<Entity<ui::ContextMenu>>,
755 >,
756 >,
757 last_bounds: Option<Bounds<Pixels>>,
758 last_position_map: Option<Rc<PositionMap>>,
759 expect_bounds_change: Option<Bounds<Pixels>>,
760 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
761 tasks_update_task: Option<Task<()>>,
762 in_project_search: bool,
763 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
764 breadcrumb_header: Option<String>,
765 focused_block: Option<FocusedBlock>,
766 next_scroll_position: NextScrollCursorCenterTopBottom,
767 addons: HashMap<TypeId, Box<dyn Addon>>,
768 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
769 load_diff_task: Option<Shared<Task<()>>>,
770 selection_mark_mode: bool,
771 toggle_fold_multiple_buffers: Task<()>,
772 _scroll_cursor_center_top_bottom_task: Task<()>,
773 serialize_selections: Task<()>,
774}
775
776#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
777enum NextScrollCursorCenterTopBottom {
778 #[default]
779 Center,
780 Top,
781 Bottom,
782}
783
784impl NextScrollCursorCenterTopBottom {
785 fn next(&self) -> Self {
786 match self {
787 Self::Center => Self::Top,
788 Self::Top => Self::Bottom,
789 Self::Bottom => Self::Center,
790 }
791 }
792}
793
794#[derive(Clone)]
795pub struct EditorSnapshot {
796 pub mode: EditorMode,
797 show_gutter: bool,
798 show_line_numbers: Option<bool>,
799 show_git_diff_gutter: Option<bool>,
800 show_code_actions: Option<bool>,
801 show_runnables: Option<bool>,
802 git_blame_gutter_max_author_length: Option<usize>,
803 pub display_snapshot: DisplaySnapshot,
804 pub placeholder_text: Option<Arc<str>>,
805 is_focused: bool,
806 scroll_anchor: ScrollAnchor,
807 ongoing_scroll: OngoingScroll,
808 current_line_highlight: CurrentLineHighlight,
809 gutter_hovered: bool,
810}
811
812const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
813
814#[derive(Default, Debug, Clone, Copy)]
815pub struct GutterDimensions {
816 pub left_padding: Pixels,
817 pub right_padding: Pixels,
818 pub width: Pixels,
819 pub margin: Pixels,
820 pub git_blame_entries_width: Option<Pixels>,
821}
822
823impl GutterDimensions {
824 /// The full width of the space taken up by the gutter.
825 pub fn full_width(&self) -> Pixels {
826 self.margin + self.width
827 }
828
829 /// The width of the space reserved for the fold indicators,
830 /// use alongside 'justify_end' and `gutter_width` to
831 /// right align content with the line numbers
832 pub fn fold_area_width(&self) -> Pixels {
833 self.margin + self.right_padding
834 }
835}
836
837#[derive(Debug)]
838pub struct RemoteSelection {
839 pub replica_id: ReplicaId,
840 pub selection: Selection<Anchor>,
841 pub cursor_shape: CursorShape,
842 pub peer_id: PeerId,
843 pub line_mode: bool,
844 pub participant_index: Option<ParticipantIndex>,
845 pub user_name: Option<SharedString>,
846}
847
848#[derive(Clone, Debug)]
849struct SelectionHistoryEntry {
850 selections: Arc<[Selection<Anchor>]>,
851 select_next_state: Option<SelectNextState>,
852 select_prev_state: Option<SelectNextState>,
853 add_selections_state: Option<AddSelectionsState>,
854}
855
856enum SelectionHistoryMode {
857 Normal,
858 Undoing,
859 Redoing,
860}
861
862#[derive(Clone, PartialEq, Eq, Hash)]
863struct HoveredCursor {
864 replica_id: u16,
865 selection_id: usize,
866}
867
868impl Default for SelectionHistoryMode {
869 fn default() -> Self {
870 Self::Normal
871 }
872}
873
874#[derive(Default)]
875struct SelectionHistory {
876 #[allow(clippy::type_complexity)]
877 selections_by_transaction:
878 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
879 mode: SelectionHistoryMode,
880 undo_stack: VecDeque<SelectionHistoryEntry>,
881 redo_stack: VecDeque<SelectionHistoryEntry>,
882}
883
884impl SelectionHistory {
885 fn insert_transaction(
886 &mut self,
887 transaction_id: TransactionId,
888 selections: Arc<[Selection<Anchor>]>,
889 ) {
890 self.selections_by_transaction
891 .insert(transaction_id, (selections, None));
892 }
893
894 #[allow(clippy::type_complexity)]
895 fn transaction(
896 &self,
897 transaction_id: TransactionId,
898 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
899 self.selections_by_transaction.get(&transaction_id)
900 }
901
902 #[allow(clippy::type_complexity)]
903 fn transaction_mut(
904 &mut self,
905 transaction_id: TransactionId,
906 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
907 self.selections_by_transaction.get_mut(&transaction_id)
908 }
909
910 fn push(&mut self, entry: SelectionHistoryEntry) {
911 if !entry.selections.is_empty() {
912 match self.mode {
913 SelectionHistoryMode::Normal => {
914 self.push_undo(entry);
915 self.redo_stack.clear();
916 }
917 SelectionHistoryMode::Undoing => self.push_redo(entry),
918 SelectionHistoryMode::Redoing => self.push_undo(entry),
919 }
920 }
921 }
922
923 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
924 if self
925 .undo_stack
926 .back()
927 .map_or(true, |e| e.selections != entry.selections)
928 {
929 self.undo_stack.push_back(entry);
930 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
931 self.undo_stack.pop_front();
932 }
933 }
934 }
935
936 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
937 if self
938 .redo_stack
939 .back()
940 .map_or(true, |e| e.selections != entry.selections)
941 {
942 self.redo_stack.push_back(entry);
943 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
944 self.redo_stack.pop_front();
945 }
946 }
947 }
948}
949
950struct RowHighlight {
951 index: usize,
952 range: Range<Anchor>,
953 color: Hsla,
954 should_autoscroll: bool,
955}
956
957#[derive(Clone, Debug)]
958struct AddSelectionsState {
959 above: bool,
960 stack: Vec<usize>,
961}
962
963#[derive(Clone)]
964struct SelectNextState {
965 query: AhoCorasick,
966 wordwise: bool,
967 done: bool,
968}
969
970impl std::fmt::Debug for SelectNextState {
971 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
972 f.debug_struct(std::any::type_name::<Self>())
973 .field("wordwise", &self.wordwise)
974 .field("done", &self.done)
975 .finish()
976 }
977}
978
979#[derive(Debug)]
980struct AutocloseRegion {
981 selection_id: usize,
982 range: Range<Anchor>,
983 pair: BracketPair,
984}
985
986#[derive(Debug)]
987struct SnippetState {
988 ranges: Vec<Vec<Range<Anchor>>>,
989 active_index: usize,
990 choices: Vec<Option<Vec<String>>>,
991}
992
993#[doc(hidden)]
994pub struct RenameState {
995 pub range: Range<Anchor>,
996 pub old_name: Arc<str>,
997 pub editor: Entity<Editor>,
998 block_id: CustomBlockId,
999}
1000
1001struct InvalidationStack<T>(Vec<T>);
1002
1003struct RegisteredInlineCompletionProvider {
1004 provider: Arc<dyn InlineCompletionProviderHandle>,
1005 _subscription: Subscription,
1006}
1007
1008#[derive(Debug)]
1009struct ActiveDiagnosticGroup {
1010 primary_range: Range<Anchor>,
1011 primary_message: String,
1012 group_id: usize,
1013 blocks: HashMap<CustomBlockId, Diagnostic>,
1014 is_valid: bool,
1015}
1016
1017#[derive(Serialize, Deserialize, Clone, Debug)]
1018pub struct ClipboardSelection {
1019 pub len: usize,
1020 pub is_entire_line: bool,
1021 pub first_line_indent: u32,
1022}
1023
1024#[derive(Debug)]
1025pub(crate) struct NavigationData {
1026 cursor_anchor: Anchor,
1027 cursor_position: Point,
1028 scroll_anchor: ScrollAnchor,
1029 scroll_top_row: u32,
1030}
1031
1032#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1033pub enum GotoDefinitionKind {
1034 Symbol,
1035 Declaration,
1036 Type,
1037 Implementation,
1038}
1039
1040#[derive(Debug, Clone)]
1041enum InlayHintRefreshReason {
1042 Toggle(bool),
1043 SettingsChange(InlayHintSettings),
1044 NewLinesShown,
1045 BufferEdited(HashSet<Arc<Language>>),
1046 RefreshRequested,
1047 ExcerptsRemoved(Vec<ExcerptId>),
1048}
1049
1050impl InlayHintRefreshReason {
1051 fn description(&self) -> &'static str {
1052 match self {
1053 Self::Toggle(_) => "toggle",
1054 Self::SettingsChange(_) => "settings change",
1055 Self::NewLinesShown => "new lines shown",
1056 Self::BufferEdited(_) => "buffer edited",
1057 Self::RefreshRequested => "refresh requested",
1058 Self::ExcerptsRemoved(_) => "excerpts removed",
1059 }
1060 }
1061}
1062
1063pub enum FormatTarget {
1064 Buffers,
1065 Ranges(Vec<Range<MultiBufferPoint>>),
1066}
1067
1068pub(crate) struct FocusedBlock {
1069 id: BlockId,
1070 focus_handle: WeakFocusHandle,
1071}
1072
1073#[derive(Clone)]
1074enum JumpData {
1075 MultiBufferRow {
1076 row: MultiBufferRow,
1077 line_offset_from_top: u32,
1078 },
1079 MultiBufferPoint {
1080 excerpt_id: ExcerptId,
1081 position: Point,
1082 anchor: text::Anchor,
1083 line_offset_from_top: u32,
1084 },
1085}
1086
1087pub enum MultibufferSelectionMode {
1088 First,
1089 All,
1090}
1091
1092impl Editor {
1093 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1094 let buffer = cx.new(|cx| Buffer::local("", cx));
1095 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1096 Self::new(
1097 EditorMode::SingleLine { auto_width: false },
1098 buffer,
1099 None,
1100 false,
1101 window,
1102 cx,
1103 )
1104 }
1105
1106 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1107 let buffer = cx.new(|cx| Buffer::local("", cx));
1108 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1109 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1110 }
1111
1112 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1113 let buffer = cx.new(|cx| Buffer::local("", cx));
1114 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1115 Self::new(
1116 EditorMode::SingleLine { auto_width: true },
1117 buffer,
1118 None,
1119 false,
1120 window,
1121 cx,
1122 )
1123 }
1124
1125 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1126 let buffer = cx.new(|cx| Buffer::local("", cx));
1127 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1128 Self::new(
1129 EditorMode::AutoHeight { max_lines },
1130 buffer,
1131 None,
1132 false,
1133 window,
1134 cx,
1135 )
1136 }
1137
1138 pub fn for_buffer(
1139 buffer: Entity<Buffer>,
1140 project: Option<Entity<Project>>,
1141 window: &mut Window,
1142 cx: &mut Context<Self>,
1143 ) -> Self {
1144 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1145 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1146 }
1147
1148 pub fn for_multibuffer(
1149 buffer: Entity<MultiBuffer>,
1150 project: Option<Entity<Project>>,
1151 show_excerpt_controls: bool,
1152 window: &mut Window,
1153 cx: &mut Context<Self>,
1154 ) -> Self {
1155 Self::new(
1156 EditorMode::Full,
1157 buffer,
1158 project,
1159 show_excerpt_controls,
1160 window,
1161 cx,
1162 )
1163 }
1164
1165 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1166 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1167 let mut clone = Self::new(
1168 self.mode,
1169 self.buffer.clone(),
1170 self.project.clone(),
1171 show_excerpt_controls,
1172 window,
1173 cx,
1174 );
1175 self.display_map.update(cx, |display_map, cx| {
1176 let snapshot = display_map.snapshot(cx);
1177 clone.display_map.update(cx, |display_map, cx| {
1178 display_map.set_state(&snapshot, cx);
1179 });
1180 });
1181 clone.selections.clone_state(&self.selections);
1182 clone.scroll_manager.clone_state(&self.scroll_manager);
1183 clone.searchable = self.searchable;
1184 clone
1185 }
1186
1187 pub fn new(
1188 mode: EditorMode,
1189 buffer: Entity<MultiBuffer>,
1190 project: Option<Entity<Project>>,
1191 show_excerpt_controls: bool,
1192 window: &mut Window,
1193 cx: &mut Context<Self>,
1194 ) -> Self {
1195 let style = window.text_style();
1196 let font_size = style.font_size.to_pixels(window.rem_size());
1197 let editor = cx.entity().downgrade();
1198 let fold_placeholder = FoldPlaceholder {
1199 constrain_width: true,
1200 render: Arc::new(move |fold_id, fold_range, _, cx| {
1201 let editor = editor.clone();
1202 div()
1203 .id(fold_id)
1204 .bg(cx.theme().colors().ghost_element_background)
1205 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1206 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1207 .rounded_sm()
1208 .size_full()
1209 .cursor_pointer()
1210 .child("⋯")
1211 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1212 .on_click(move |_, _window, cx| {
1213 editor
1214 .update(cx, |editor, cx| {
1215 editor.unfold_ranges(
1216 &[fold_range.start..fold_range.end],
1217 true,
1218 false,
1219 cx,
1220 );
1221 cx.stop_propagation();
1222 })
1223 .ok();
1224 })
1225 .into_any()
1226 }),
1227 merge_adjacent: true,
1228 ..Default::default()
1229 };
1230 let display_map = cx.new(|cx| {
1231 DisplayMap::new(
1232 buffer.clone(),
1233 style.font(),
1234 font_size,
1235 None,
1236 show_excerpt_controls,
1237 FILE_HEADER_HEIGHT,
1238 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1239 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1240 fold_placeholder,
1241 cx,
1242 )
1243 });
1244
1245 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1246
1247 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1248
1249 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1250 .then(|| language_settings::SoftWrap::None);
1251
1252 let mut project_subscriptions = Vec::new();
1253 if mode == EditorMode::Full {
1254 if let Some(project) = project.as_ref() {
1255 if buffer.read(cx).is_singleton() {
1256 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1257 cx.emit(EditorEvent::TitleChanged);
1258 }));
1259 }
1260 project_subscriptions.push(cx.subscribe_in(
1261 project,
1262 window,
1263 |editor, _, event, window, cx| {
1264 if let project::Event::RefreshInlayHints = event {
1265 editor
1266 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1267 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1268 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1269 let focus_handle = editor.focus_handle(cx);
1270 if focus_handle.is_focused(window) {
1271 let snapshot = buffer.read(cx).snapshot();
1272 for (range, snippet) in snippet_edits {
1273 let editor_range =
1274 language::range_from_lsp(*range).to_offset(&snapshot);
1275 editor
1276 .insert_snippet(
1277 &[editor_range],
1278 snippet.clone(),
1279 window,
1280 cx,
1281 )
1282 .ok();
1283 }
1284 }
1285 }
1286 }
1287 },
1288 ));
1289 if let Some(task_inventory) = project
1290 .read(cx)
1291 .task_store()
1292 .read(cx)
1293 .task_inventory()
1294 .cloned()
1295 {
1296 project_subscriptions.push(cx.observe_in(
1297 &task_inventory,
1298 window,
1299 |editor, _, window, cx| {
1300 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1301 },
1302 ));
1303 }
1304 }
1305 }
1306
1307 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1308
1309 let inlay_hint_settings =
1310 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1311 let focus_handle = cx.focus_handle();
1312 cx.on_focus(&focus_handle, window, Self::handle_focus)
1313 .detach();
1314 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1315 .detach();
1316 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1317 .detach();
1318 cx.on_blur(&focus_handle, window, Self::handle_blur)
1319 .detach();
1320
1321 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1322 Some(false)
1323 } else {
1324 None
1325 };
1326
1327 let mut code_action_providers = Vec::new();
1328 let mut load_uncommitted_diff = None;
1329 if let Some(project) = project.clone() {
1330 load_uncommitted_diff = Some(
1331 get_uncommitted_diff_for_buffer(
1332 &project,
1333 buffer.read(cx).all_buffers(),
1334 buffer.clone(),
1335 cx,
1336 )
1337 .shared(),
1338 );
1339 code_action_providers.push(Rc::new(project) as Rc<_>);
1340 }
1341
1342 let mut this = Self {
1343 focus_handle,
1344 show_cursor_when_unfocused: false,
1345 last_focused_descendant: None,
1346 buffer: buffer.clone(),
1347 display_map: display_map.clone(),
1348 selections,
1349 scroll_manager: ScrollManager::new(cx),
1350 columnar_selection_tail: None,
1351 add_selections_state: None,
1352 select_next_state: None,
1353 select_prev_state: None,
1354 selection_history: Default::default(),
1355 autoclose_regions: Default::default(),
1356 snippet_stack: Default::default(),
1357 select_larger_syntax_node_stack: Vec::new(),
1358 ime_transaction: Default::default(),
1359 active_diagnostics: None,
1360 soft_wrap_mode_override,
1361 completion_provider: project.clone().map(|project| Box::new(project) as _),
1362 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1363 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1364 project,
1365 blink_manager: blink_manager.clone(),
1366 show_local_selections: true,
1367 show_scrollbars: true,
1368 mode,
1369 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1370 show_gutter: mode == EditorMode::Full,
1371 show_line_numbers: None,
1372 use_relative_line_numbers: None,
1373 show_git_diff_gutter: None,
1374 show_code_actions: None,
1375 show_runnables: None,
1376 show_wrap_guides: None,
1377 show_indent_guides,
1378 placeholder_text: None,
1379 highlight_order: 0,
1380 highlighted_rows: HashMap::default(),
1381 background_highlights: Default::default(),
1382 gutter_highlights: TreeMap::default(),
1383 scrollbar_marker_state: ScrollbarMarkerState::default(),
1384 active_indent_guides_state: ActiveIndentGuidesState::default(),
1385 nav_history: None,
1386 context_menu: RefCell::new(None),
1387 mouse_context_menu: None,
1388 completion_tasks: Default::default(),
1389 signature_help_state: SignatureHelpState::default(),
1390 auto_signature_help: None,
1391 find_all_references_task_sources: Vec::new(),
1392 next_completion_id: 0,
1393 next_inlay_id: 0,
1394 code_action_providers,
1395 available_code_actions: Default::default(),
1396 code_actions_task: Default::default(),
1397 selection_highlight_task: Default::default(),
1398 document_highlights_task: Default::default(),
1399 linked_editing_range_task: Default::default(),
1400 pending_rename: Default::default(),
1401 searchable: true,
1402 cursor_shape: EditorSettings::get_global(cx)
1403 .cursor_shape
1404 .unwrap_or_default(),
1405 current_line_highlight: None,
1406 autoindent_mode: Some(AutoindentMode::EachLine),
1407 collapse_matches: false,
1408 workspace: None,
1409 input_enabled: true,
1410 use_modal_editing: mode == EditorMode::Full,
1411 read_only: false,
1412 use_autoclose: true,
1413 use_auto_surround: true,
1414 auto_replace_emoji_shortcode: false,
1415 leader_peer_id: None,
1416 remote_id: None,
1417 hover_state: Default::default(),
1418 pending_mouse_down: None,
1419 hovered_link_state: Default::default(),
1420 edit_prediction_provider: None,
1421 active_inline_completion: None,
1422 stale_inline_completion_in_menu: None,
1423 edit_prediction_preview: EditPredictionPreview::Inactive,
1424 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1425
1426 gutter_hovered: false,
1427 pixel_position_of_newest_cursor: None,
1428 last_bounds: None,
1429 last_position_map: None,
1430 expect_bounds_change: None,
1431 gutter_dimensions: GutterDimensions::default(),
1432 style: None,
1433 show_cursor_names: false,
1434 hovered_cursors: Default::default(),
1435 next_editor_action_id: EditorActionId::default(),
1436 editor_actions: Rc::default(),
1437 inline_completions_hidden_for_vim_mode: false,
1438 show_inline_completions_override: None,
1439 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1440 edit_prediction_settings: EditPredictionSettings::Disabled,
1441 edit_prediction_cursor_on_leading_whitespace: false,
1442 edit_prediction_requires_modifier_in_leading_space: true,
1443 custom_context_menu: None,
1444 show_git_blame_gutter: false,
1445 show_git_blame_inline: false,
1446 distinguish_unstaged_diff_hunks: false,
1447 show_selection_menu: None,
1448 show_git_blame_inline_delay_task: None,
1449 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1450 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1451 .session
1452 .restore_unsaved_buffers,
1453 blame: None,
1454 blame_subscription: None,
1455 tasks: Default::default(),
1456 _subscriptions: vec![
1457 cx.observe(&buffer, Self::on_buffer_changed),
1458 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1459 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1460 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1461 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1462 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1463 cx.observe_window_activation(window, |editor, window, cx| {
1464 let active = window.is_window_active();
1465 editor.blink_manager.update(cx, |blink_manager, cx| {
1466 if active {
1467 blink_manager.enable(cx);
1468 } else {
1469 blink_manager.disable(cx);
1470 }
1471 });
1472 }),
1473 ],
1474 tasks_update_task: None,
1475 linked_edit_ranges: Default::default(),
1476 in_project_search: false,
1477 previous_search_ranges: None,
1478 breadcrumb_header: None,
1479 focused_block: None,
1480 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1481 addons: HashMap::default(),
1482 registered_buffers: HashMap::default(),
1483 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1484 selection_mark_mode: false,
1485 toggle_fold_multiple_buffers: Task::ready(()),
1486 serialize_selections: Task::ready(()),
1487 text_style_refinement: None,
1488 load_diff_task: load_uncommitted_diff,
1489 };
1490 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1491 this._subscriptions.extend(project_subscriptions);
1492
1493 this.end_selection(window, cx);
1494 this.scroll_manager.show_scrollbar(window, cx);
1495
1496 if mode == EditorMode::Full {
1497 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1498 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1499
1500 if this.git_blame_inline_enabled {
1501 this.git_blame_inline_enabled = true;
1502 this.start_git_blame_inline(false, window, cx);
1503 }
1504
1505 if let Some(buffer) = buffer.read(cx).as_singleton() {
1506 if let Some(project) = this.project.as_ref() {
1507 let handle = project.update(cx, |project, cx| {
1508 project.register_buffer_with_language_servers(&buffer, cx)
1509 });
1510 this.registered_buffers
1511 .insert(buffer.read(cx).remote_id(), handle);
1512 }
1513 }
1514 }
1515
1516 this.report_editor_event("Editor Opened", None, cx);
1517 this
1518 }
1519
1520 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1521 self.mouse_context_menu
1522 .as_ref()
1523 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1524 }
1525
1526 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1527 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1528 }
1529
1530 fn key_context_internal(
1531 &self,
1532 has_active_edit_prediction: bool,
1533 window: &Window,
1534 cx: &App,
1535 ) -> KeyContext {
1536 let mut key_context = KeyContext::new_with_defaults();
1537 key_context.add("Editor");
1538 let mode = match self.mode {
1539 EditorMode::SingleLine { .. } => "single_line",
1540 EditorMode::AutoHeight { .. } => "auto_height",
1541 EditorMode::Full => "full",
1542 };
1543
1544 if EditorSettings::jupyter_enabled(cx) {
1545 key_context.add("jupyter");
1546 }
1547
1548 key_context.set("mode", mode);
1549 if self.pending_rename.is_some() {
1550 key_context.add("renaming");
1551 }
1552
1553 match self.context_menu.borrow().as_ref() {
1554 Some(CodeContextMenu::Completions(_)) => {
1555 key_context.add("menu");
1556 key_context.add("showing_completions");
1557 }
1558 Some(CodeContextMenu::CodeActions(_)) => {
1559 key_context.add("menu");
1560 key_context.add("showing_code_actions")
1561 }
1562 None => {}
1563 }
1564
1565 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1566 if !self.focus_handle(cx).contains_focused(window, cx)
1567 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1568 {
1569 for addon in self.addons.values() {
1570 addon.extend_key_context(&mut key_context, cx)
1571 }
1572 }
1573
1574 if let Some(extension) = self
1575 .buffer
1576 .read(cx)
1577 .as_singleton()
1578 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1579 {
1580 key_context.set("extension", extension.to_string());
1581 }
1582
1583 if has_active_edit_prediction {
1584 if self.edit_prediction_in_conflict() {
1585 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1586 } else {
1587 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1588 key_context.add("copilot_suggestion");
1589 }
1590 }
1591
1592 if self.selection_mark_mode {
1593 key_context.add("selection_mode");
1594 }
1595
1596 key_context
1597 }
1598
1599 pub fn edit_prediction_in_conflict(&self) -> bool {
1600 if !self.show_edit_predictions_in_menu() {
1601 return false;
1602 }
1603
1604 let showing_completions = self
1605 .context_menu
1606 .borrow()
1607 .as_ref()
1608 .map_or(false, |context| {
1609 matches!(context, CodeContextMenu::Completions(_))
1610 });
1611
1612 showing_completions
1613 || self.edit_prediction_requires_modifier()
1614 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1615 // bindings to insert tab characters.
1616 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1617 }
1618
1619 pub fn accept_edit_prediction_keybind(
1620 &self,
1621 window: &Window,
1622 cx: &App,
1623 ) -> AcceptEditPredictionBinding {
1624 let key_context = self.key_context_internal(true, window, cx);
1625 let in_conflict = self.edit_prediction_in_conflict();
1626
1627 AcceptEditPredictionBinding(
1628 window
1629 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1630 .into_iter()
1631 .filter(|binding| {
1632 !in_conflict
1633 || binding
1634 .keystrokes()
1635 .first()
1636 .map_or(false, |keystroke| keystroke.modifiers.modified())
1637 })
1638 .rev()
1639 .min_by_key(|binding| {
1640 binding
1641 .keystrokes()
1642 .first()
1643 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1644 }),
1645 )
1646 }
1647
1648 pub fn new_file(
1649 workspace: &mut Workspace,
1650 _: &workspace::NewFile,
1651 window: &mut Window,
1652 cx: &mut Context<Workspace>,
1653 ) {
1654 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1655 "Failed to create buffer",
1656 window,
1657 cx,
1658 |e, _, _| match e.error_code() {
1659 ErrorCode::RemoteUpgradeRequired => Some(format!(
1660 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1661 e.error_tag("required").unwrap_or("the latest version")
1662 )),
1663 _ => None,
1664 },
1665 );
1666 }
1667
1668 pub fn new_in_workspace(
1669 workspace: &mut Workspace,
1670 window: &mut Window,
1671 cx: &mut Context<Workspace>,
1672 ) -> Task<Result<Entity<Editor>>> {
1673 let project = workspace.project().clone();
1674 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1675
1676 cx.spawn_in(window, |workspace, mut cx| async move {
1677 let buffer = create.await?;
1678 workspace.update_in(&mut cx, |workspace, window, cx| {
1679 let editor =
1680 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1681 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1682 editor
1683 })
1684 })
1685 }
1686
1687 fn new_file_vertical(
1688 workspace: &mut Workspace,
1689 _: &workspace::NewFileSplitVertical,
1690 window: &mut Window,
1691 cx: &mut Context<Workspace>,
1692 ) {
1693 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1694 }
1695
1696 fn new_file_horizontal(
1697 workspace: &mut Workspace,
1698 _: &workspace::NewFileSplitHorizontal,
1699 window: &mut Window,
1700 cx: &mut Context<Workspace>,
1701 ) {
1702 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1703 }
1704
1705 fn new_file_in_direction(
1706 workspace: &mut Workspace,
1707 direction: SplitDirection,
1708 window: &mut Window,
1709 cx: &mut Context<Workspace>,
1710 ) {
1711 let project = workspace.project().clone();
1712 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1713
1714 cx.spawn_in(window, |workspace, mut cx| async move {
1715 let buffer = create.await?;
1716 workspace.update_in(&mut cx, move |workspace, window, cx| {
1717 workspace.split_item(
1718 direction,
1719 Box::new(
1720 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1721 ),
1722 window,
1723 cx,
1724 )
1725 })?;
1726 anyhow::Ok(())
1727 })
1728 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1729 match e.error_code() {
1730 ErrorCode::RemoteUpgradeRequired => Some(format!(
1731 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1732 e.error_tag("required").unwrap_or("the latest version")
1733 )),
1734 _ => None,
1735 }
1736 });
1737 }
1738
1739 pub fn leader_peer_id(&self) -> Option<PeerId> {
1740 self.leader_peer_id
1741 }
1742
1743 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1744 &self.buffer
1745 }
1746
1747 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1748 self.workspace.as_ref()?.0.upgrade()
1749 }
1750
1751 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1752 self.buffer().read(cx).title(cx)
1753 }
1754
1755 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1756 let git_blame_gutter_max_author_length = self
1757 .render_git_blame_gutter(cx)
1758 .then(|| {
1759 if let Some(blame) = self.blame.as_ref() {
1760 let max_author_length =
1761 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1762 Some(max_author_length)
1763 } else {
1764 None
1765 }
1766 })
1767 .flatten();
1768
1769 EditorSnapshot {
1770 mode: self.mode,
1771 show_gutter: self.show_gutter,
1772 show_line_numbers: self.show_line_numbers,
1773 show_git_diff_gutter: self.show_git_diff_gutter,
1774 show_code_actions: self.show_code_actions,
1775 show_runnables: self.show_runnables,
1776 git_blame_gutter_max_author_length,
1777 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1778 scroll_anchor: self.scroll_manager.anchor(),
1779 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1780 placeholder_text: self.placeholder_text.clone(),
1781 is_focused: self.focus_handle.is_focused(window),
1782 current_line_highlight: self
1783 .current_line_highlight
1784 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1785 gutter_hovered: self.gutter_hovered,
1786 }
1787 }
1788
1789 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1790 self.buffer.read(cx).language_at(point, cx)
1791 }
1792
1793 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1794 self.buffer.read(cx).read(cx).file_at(point).cloned()
1795 }
1796
1797 pub fn active_excerpt(
1798 &self,
1799 cx: &App,
1800 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1801 self.buffer
1802 .read(cx)
1803 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1804 }
1805
1806 pub fn mode(&self) -> EditorMode {
1807 self.mode
1808 }
1809
1810 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1811 self.collaboration_hub.as_deref()
1812 }
1813
1814 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1815 self.collaboration_hub = Some(hub);
1816 }
1817
1818 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1819 self.in_project_search = in_project_search;
1820 }
1821
1822 pub fn set_custom_context_menu(
1823 &mut self,
1824 f: impl 'static
1825 + Fn(
1826 &mut Self,
1827 DisplayPoint,
1828 &mut Window,
1829 &mut Context<Self>,
1830 ) -> Option<Entity<ui::ContextMenu>>,
1831 ) {
1832 self.custom_context_menu = Some(Box::new(f))
1833 }
1834
1835 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1836 self.completion_provider = provider;
1837 }
1838
1839 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1840 self.semantics_provider.clone()
1841 }
1842
1843 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1844 self.semantics_provider = provider;
1845 }
1846
1847 pub fn set_edit_prediction_provider<T>(
1848 &mut self,
1849 provider: Option<Entity<T>>,
1850 window: &mut Window,
1851 cx: &mut Context<Self>,
1852 ) where
1853 T: EditPredictionProvider,
1854 {
1855 self.edit_prediction_provider =
1856 provider.map(|provider| RegisteredInlineCompletionProvider {
1857 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1858 if this.focus_handle.is_focused(window) {
1859 this.update_visible_inline_completion(window, cx);
1860 }
1861 }),
1862 provider: Arc::new(provider),
1863 });
1864 self.refresh_inline_completion(false, false, window, cx);
1865 }
1866
1867 pub fn placeholder_text(&self) -> Option<&str> {
1868 self.placeholder_text.as_deref()
1869 }
1870
1871 pub fn set_placeholder_text(
1872 &mut self,
1873 placeholder_text: impl Into<Arc<str>>,
1874 cx: &mut Context<Self>,
1875 ) {
1876 let placeholder_text = Some(placeholder_text.into());
1877 if self.placeholder_text != placeholder_text {
1878 self.placeholder_text = placeholder_text;
1879 cx.notify();
1880 }
1881 }
1882
1883 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1884 self.cursor_shape = cursor_shape;
1885
1886 // Disrupt blink for immediate user feedback that the cursor shape has changed
1887 self.blink_manager.update(cx, BlinkManager::show_cursor);
1888
1889 cx.notify();
1890 }
1891
1892 pub fn set_current_line_highlight(
1893 &mut self,
1894 current_line_highlight: Option<CurrentLineHighlight>,
1895 ) {
1896 self.current_line_highlight = current_line_highlight;
1897 }
1898
1899 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1900 self.collapse_matches = collapse_matches;
1901 }
1902
1903 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1904 let buffers = self.buffer.read(cx).all_buffers();
1905 let Some(project) = self.project.as_ref() else {
1906 return;
1907 };
1908 project.update(cx, |project, cx| {
1909 for buffer in buffers {
1910 self.registered_buffers
1911 .entry(buffer.read(cx).remote_id())
1912 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1913 }
1914 })
1915 }
1916
1917 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1918 if self.collapse_matches {
1919 return range.start..range.start;
1920 }
1921 range.clone()
1922 }
1923
1924 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1925 if self.display_map.read(cx).clip_at_line_ends != clip {
1926 self.display_map
1927 .update(cx, |map, _| map.clip_at_line_ends = clip);
1928 }
1929 }
1930
1931 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1932 self.input_enabled = input_enabled;
1933 }
1934
1935 pub fn set_inline_completions_hidden_for_vim_mode(
1936 &mut self,
1937 hidden: bool,
1938 window: &mut Window,
1939 cx: &mut Context<Self>,
1940 ) {
1941 if hidden != self.inline_completions_hidden_for_vim_mode {
1942 self.inline_completions_hidden_for_vim_mode = hidden;
1943 if hidden {
1944 self.update_visible_inline_completion(window, cx);
1945 } else {
1946 self.refresh_inline_completion(true, false, window, cx);
1947 }
1948 }
1949 }
1950
1951 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1952 self.menu_inline_completions_policy = value;
1953 }
1954
1955 pub fn set_autoindent(&mut self, autoindent: bool) {
1956 if autoindent {
1957 self.autoindent_mode = Some(AutoindentMode::EachLine);
1958 } else {
1959 self.autoindent_mode = None;
1960 }
1961 }
1962
1963 pub fn read_only(&self, cx: &App) -> bool {
1964 self.read_only || self.buffer.read(cx).read_only()
1965 }
1966
1967 pub fn set_read_only(&mut self, read_only: bool) {
1968 self.read_only = read_only;
1969 }
1970
1971 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1972 self.use_autoclose = autoclose;
1973 }
1974
1975 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1976 self.use_auto_surround = auto_surround;
1977 }
1978
1979 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1980 self.auto_replace_emoji_shortcode = auto_replace;
1981 }
1982
1983 pub fn toggle_inline_completions(
1984 &mut self,
1985 _: &ToggleEditPrediction,
1986 window: &mut Window,
1987 cx: &mut Context<Self>,
1988 ) {
1989 if self.show_inline_completions_override.is_some() {
1990 self.set_show_edit_predictions(None, window, cx);
1991 } else {
1992 let show_edit_predictions = !self.edit_predictions_enabled();
1993 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1994 }
1995 }
1996
1997 pub fn set_show_edit_predictions(
1998 &mut self,
1999 show_edit_predictions: Option<bool>,
2000 window: &mut Window,
2001 cx: &mut Context<Self>,
2002 ) {
2003 self.show_inline_completions_override = show_edit_predictions;
2004 self.refresh_inline_completion(false, true, window, cx);
2005 }
2006
2007 fn inline_completions_disabled_in_scope(
2008 &self,
2009 buffer: &Entity<Buffer>,
2010 buffer_position: language::Anchor,
2011 cx: &App,
2012 ) -> bool {
2013 let snapshot = buffer.read(cx).snapshot();
2014 let settings = snapshot.settings_at(buffer_position, cx);
2015
2016 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2017 return false;
2018 };
2019
2020 scope.override_name().map_or(false, |scope_name| {
2021 settings
2022 .edit_predictions_disabled_in
2023 .iter()
2024 .any(|s| s == scope_name)
2025 })
2026 }
2027
2028 pub fn set_use_modal_editing(&mut self, to: bool) {
2029 self.use_modal_editing = to;
2030 }
2031
2032 pub fn use_modal_editing(&self) -> bool {
2033 self.use_modal_editing
2034 }
2035
2036 fn selections_did_change(
2037 &mut self,
2038 local: bool,
2039 old_cursor_position: &Anchor,
2040 show_completions: bool,
2041 window: &mut Window,
2042 cx: &mut Context<Self>,
2043 ) {
2044 window.invalidate_character_coordinates();
2045
2046 // Copy selections to primary selection buffer
2047 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2048 if local {
2049 let selections = self.selections.all::<usize>(cx);
2050 let buffer_handle = self.buffer.read(cx).read(cx);
2051
2052 let mut text = String::new();
2053 for (index, selection) in selections.iter().enumerate() {
2054 let text_for_selection = buffer_handle
2055 .text_for_range(selection.start..selection.end)
2056 .collect::<String>();
2057
2058 text.push_str(&text_for_selection);
2059 if index != selections.len() - 1 {
2060 text.push('\n');
2061 }
2062 }
2063
2064 if !text.is_empty() {
2065 cx.write_to_primary(ClipboardItem::new_string(text));
2066 }
2067 }
2068
2069 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2070 self.buffer.update(cx, |buffer, cx| {
2071 buffer.set_active_selections(
2072 &self.selections.disjoint_anchors(),
2073 self.selections.line_mode,
2074 self.cursor_shape,
2075 cx,
2076 )
2077 });
2078 }
2079 let display_map = self
2080 .display_map
2081 .update(cx, |display_map, cx| display_map.snapshot(cx));
2082 let buffer = &display_map.buffer_snapshot;
2083 self.add_selections_state = None;
2084 self.select_next_state = None;
2085 self.select_prev_state = None;
2086 self.select_larger_syntax_node_stack.clear();
2087 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2088 self.snippet_stack
2089 .invalidate(&self.selections.disjoint_anchors(), buffer);
2090 self.take_rename(false, window, cx);
2091
2092 let new_cursor_position = self.selections.newest_anchor().head();
2093
2094 self.push_to_nav_history(
2095 *old_cursor_position,
2096 Some(new_cursor_position.to_point(buffer)),
2097 cx,
2098 );
2099
2100 if local {
2101 let new_cursor_position = self.selections.newest_anchor().head();
2102 let mut context_menu = self.context_menu.borrow_mut();
2103 let completion_menu = match context_menu.as_ref() {
2104 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2105 _ => {
2106 *context_menu = None;
2107 None
2108 }
2109 };
2110 if let Some(buffer_id) = new_cursor_position.buffer_id {
2111 if !self.registered_buffers.contains_key(&buffer_id) {
2112 if let Some(project) = self.project.as_ref() {
2113 project.update(cx, |project, cx| {
2114 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2115 return;
2116 };
2117 self.registered_buffers.insert(
2118 buffer_id,
2119 project.register_buffer_with_language_servers(&buffer, cx),
2120 );
2121 })
2122 }
2123 }
2124 }
2125
2126 if let Some(completion_menu) = completion_menu {
2127 let cursor_position = new_cursor_position.to_offset(buffer);
2128 let (word_range, kind) =
2129 buffer.surrounding_word(completion_menu.initial_position, true);
2130 if kind == Some(CharKind::Word)
2131 && word_range.to_inclusive().contains(&cursor_position)
2132 {
2133 let mut completion_menu = completion_menu.clone();
2134 drop(context_menu);
2135
2136 let query = Self::completion_query(buffer, cursor_position);
2137 cx.spawn(move |this, mut cx| async move {
2138 completion_menu
2139 .filter(query.as_deref(), cx.background_executor().clone())
2140 .await;
2141
2142 this.update(&mut cx, |this, cx| {
2143 let mut context_menu = this.context_menu.borrow_mut();
2144 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2145 else {
2146 return;
2147 };
2148
2149 if menu.id > completion_menu.id {
2150 return;
2151 }
2152
2153 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2154 drop(context_menu);
2155 cx.notify();
2156 })
2157 })
2158 .detach();
2159
2160 if show_completions {
2161 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2162 }
2163 } else {
2164 drop(context_menu);
2165 self.hide_context_menu(window, cx);
2166 }
2167 } else {
2168 drop(context_menu);
2169 }
2170
2171 hide_hover(self, cx);
2172
2173 if old_cursor_position.to_display_point(&display_map).row()
2174 != new_cursor_position.to_display_point(&display_map).row()
2175 {
2176 self.available_code_actions.take();
2177 }
2178 self.refresh_code_actions(window, cx);
2179 self.refresh_document_highlights(cx);
2180 self.refresh_selected_text_highlights(window, cx);
2181 refresh_matching_bracket_highlights(self, window, cx);
2182 self.update_visible_inline_completion(window, cx);
2183 self.edit_prediction_requires_modifier_in_leading_space = true;
2184 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2185 if self.git_blame_inline_enabled {
2186 self.start_inline_blame_timer(window, cx);
2187 }
2188 }
2189
2190 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2191 cx.emit(EditorEvent::SelectionsChanged { local });
2192
2193 let selections = &self.selections.disjoint;
2194 if selections.len() == 1 {
2195 cx.emit(SearchEvent::ActiveMatchChanged)
2196 }
2197 if local
2198 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2199 {
2200 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2201 let background_executor = cx.background_executor().clone();
2202 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2203 let snapshot = self.buffer().read(cx).snapshot(cx);
2204 let selections = selections.clone();
2205 self.serialize_selections = cx.background_spawn(async move {
2206 background_executor.timer(Duration::from_millis(100)).await;
2207 let selections = selections
2208 .iter()
2209 .map(|selection| {
2210 (
2211 selection.start.to_offset(&snapshot),
2212 selection.end.to_offset(&snapshot),
2213 )
2214 })
2215 .collect();
2216 DB.save_editor_selections(editor_id, workspace_id, selections)
2217 .await
2218 .context("persisting editor selections")
2219 .log_err();
2220 });
2221 }
2222 }
2223
2224 cx.notify();
2225 }
2226
2227 pub fn change_selections<R>(
2228 &mut self,
2229 autoscroll: Option<Autoscroll>,
2230 window: &mut Window,
2231 cx: &mut Context<Self>,
2232 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2233 ) -> R {
2234 self.change_selections_inner(autoscroll, true, window, cx, change)
2235 }
2236
2237 fn change_selections_inner<R>(
2238 &mut self,
2239 autoscroll: Option<Autoscroll>,
2240 request_completions: bool,
2241 window: &mut Window,
2242 cx: &mut Context<Self>,
2243 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2244 ) -> R {
2245 let old_cursor_position = self.selections.newest_anchor().head();
2246 self.push_to_selection_history();
2247
2248 let (changed, result) = self.selections.change_with(cx, change);
2249
2250 if changed {
2251 if let Some(autoscroll) = autoscroll {
2252 self.request_autoscroll(autoscroll, cx);
2253 }
2254 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2255
2256 if self.should_open_signature_help_automatically(
2257 &old_cursor_position,
2258 self.signature_help_state.backspace_pressed(),
2259 cx,
2260 ) {
2261 self.show_signature_help(&ShowSignatureHelp, window, cx);
2262 }
2263 self.signature_help_state.set_backspace_pressed(false);
2264 }
2265
2266 result
2267 }
2268
2269 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2270 where
2271 I: IntoIterator<Item = (Range<S>, T)>,
2272 S: ToOffset,
2273 T: Into<Arc<str>>,
2274 {
2275 if self.read_only(cx) {
2276 return;
2277 }
2278
2279 self.buffer
2280 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2281 }
2282
2283 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2284 where
2285 I: IntoIterator<Item = (Range<S>, T)>,
2286 S: ToOffset,
2287 T: Into<Arc<str>>,
2288 {
2289 if self.read_only(cx) {
2290 return;
2291 }
2292
2293 self.buffer.update(cx, |buffer, cx| {
2294 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2295 });
2296 }
2297
2298 pub fn edit_with_block_indent<I, S, T>(
2299 &mut self,
2300 edits: I,
2301 original_indent_columns: Vec<u32>,
2302 cx: &mut Context<Self>,
2303 ) where
2304 I: IntoIterator<Item = (Range<S>, T)>,
2305 S: ToOffset,
2306 T: Into<Arc<str>>,
2307 {
2308 if self.read_only(cx) {
2309 return;
2310 }
2311
2312 self.buffer.update(cx, |buffer, cx| {
2313 buffer.edit(
2314 edits,
2315 Some(AutoindentMode::Block {
2316 original_indent_columns,
2317 }),
2318 cx,
2319 )
2320 });
2321 }
2322
2323 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2324 self.hide_context_menu(window, cx);
2325
2326 match phase {
2327 SelectPhase::Begin {
2328 position,
2329 add,
2330 click_count,
2331 } => self.begin_selection(position, add, click_count, window, cx),
2332 SelectPhase::BeginColumnar {
2333 position,
2334 goal_column,
2335 reset,
2336 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2337 SelectPhase::Extend {
2338 position,
2339 click_count,
2340 } => self.extend_selection(position, click_count, window, cx),
2341 SelectPhase::Update {
2342 position,
2343 goal_column,
2344 scroll_delta,
2345 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2346 SelectPhase::End => self.end_selection(window, cx),
2347 }
2348 }
2349
2350 fn extend_selection(
2351 &mut self,
2352 position: DisplayPoint,
2353 click_count: usize,
2354 window: &mut Window,
2355 cx: &mut Context<Self>,
2356 ) {
2357 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2358 let tail = self.selections.newest::<usize>(cx).tail();
2359 self.begin_selection(position, false, click_count, window, cx);
2360
2361 let position = position.to_offset(&display_map, Bias::Left);
2362 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2363
2364 let mut pending_selection = self
2365 .selections
2366 .pending_anchor()
2367 .expect("extend_selection not called with pending selection");
2368 if position >= tail {
2369 pending_selection.start = tail_anchor;
2370 } else {
2371 pending_selection.end = tail_anchor;
2372 pending_selection.reversed = true;
2373 }
2374
2375 let mut pending_mode = self.selections.pending_mode().unwrap();
2376 match &mut pending_mode {
2377 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2378 _ => {}
2379 }
2380
2381 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2382 s.set_pending(pending_selection, pending_mode)
2383 });
2384 }
2385
2386 fn begin_selection(
2387 &mut self,
2388 position: DisplayPoint,
2389 add: bool,
2390 click_count: usize,
2391 window: &mut Window,
2392 cx: &mut Context<Self>,
2393 ) {
2394 if !self.focus_handle.is_focused(window) {
2395 self.last_focused_descendant = None;
2396 window.focus(&self.focus_handle);
2397 }
2398
2399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2400 let buffer = &display_map.buffer_snapshot;
2401 let newest_selection = self.selections.newest_anchor().clone();
2402 let position = display_map.clip_point(position, Bias::Left);
2403
2404 let start;
2405 let end;
2406 let mode;
2407 let mut auto_scroll;
2408 match click_count {
2409 1 => {
2410 start = buffer.anchor_before(position.to_point(&display_map));
2411 end = start;
2412 mode = SelectMode::Character;
2413 auto_scroll = true;
2414 }
2415 2 => {
2416 let range = movement::surrounding_word(&display_map, position);
2417 start = buffer.anchor_before(range.start.to_point(&display_map));
2418 end = buffer.anchor_before(range.end.to_point(&display_map));
2419 mode = SelectMode::Word(start..end);
2420 auto_scroll = true;
2421 }
2422 3 => {
2423 let position = display_map
2424 .clip_point(position, Bias::Left)
2425 .to_point(&display_map);
2426 let line_start = display_map.prev_line_boundary(position).0;
2427 let next_line_start = buffer.clip_point(
2428 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2429 Bias::Left,
2430 );
2431 start = buffer.anchor_before(line_start);
2432 end = buffer.anchor_before(next_line_start);
2433 mode = SelectMode::Line(start..end);
2434 auto_scroll = true;
2435 }
2436 _ => {
2437 start = buffer.anchor_before(0);
2438 end = buffer.anchor_before(buffer.len());
2439 mode = SelectMode::All;
2440 auto_scroll = false;
2441 }
2442 }
2443 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2444
2445 let point_to_delete: Option<usize> = {
2446 let selected_points: Vec<Selection<Point>> =
2447 self.selections.disjoint_in_range(start..end, cx);
2448
2449 if !add || click_count > 1 {
2450 None
2451 } else if !selected_points.is_empty() {
2452 Some(selected_points[0].id)
2453 } else {
2454 let clicked_point_already_selected =
2455 self.selections.disjoint.iter().find(|selection| {
2456 selection.start.to_point(buffer) == start.to_point(buffer)
2457 || selection.end.to_point(buffer) == end.to_point(buffer)
2458 });
2459
2460 clicked_point_already_selected.map(|selection| selection.id)
2461 }
2462 };
2463
2464 let selections_count = self.selections.count();
2465
2466 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2467 if let Some(point_to_delete) = point_to_delete {
2468 s.delete(point_to_delete);
2469
2470 if selections_count == 1 {
2471 s.set_pending_anchor_range(start..end, mode);
2472 }
2473 } else {
2474 if !add {
2475 s.clear_disjoint();
2476 } else if click_count > 1 {
2477 s.delete(newest_selection.id)
2478 }
2479
2480 s.set_pending_anchor_range(start..end, mode);
2481 }
2482 });
2483 }
2484
2485 fn begin_columnar_selection(
2486 &mut self,
2487 position: DisplayPoint,
2488 goal_column: u32,
2489 reset: bool,
2490 window: &mut Window,
2491 cx: &mut Context<Self>,
2492 ) {
2493 if !self.focus_handle.is_focused(window) {
2494 self.last_focused_descendant = None;
2495 window.focus(&self.focus_handle);
2496 }
2497
2498 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2499
2500 if reset {
2501 let pointer_position = display_map
2502 .buffer_snapshot
2503 .anchor_before(position.to_point(&display_map));
2504
2505 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2506 s.clear_disjoint();
2507 s.set_pending_anchor_range(
2508 pointer_position..pointer_position,
2509 SelectMode::Character,
2510 );
2511 });
2512 }
2513
2514 let tail = self.selections.newest::<Point>(cx).tail();
2515 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2516
2517 if !reset {
2518 self.select_columns(
2519 tail.to_display_point(&display_map),
2520 position,
2521 goal_column,
2522 &display_map,
2523 window,
2524 cx,
2525 );
2526 }
2527 }
2528
2529 fn update_selection(
2530 &mut self,
2531 position: DisplayPoint,
2532 goal_column: u32,
2533 scroll_delta: gpui::Point<f32>,
2534 window: &mut Window,
2535 cx: &mut Context<Self>,
2536 ) {
2537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2538
2539 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2540 let tail = tail.to_display_point(&display_map);
2541 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2542 } else if let Some(mut pending) = self.selections.pending_anchor() {
2543 let buffer = self.buffer.read(cx).snapshot(cx);
2544 let head;
2545 let tail;
2546 let mode = self.selections.pending_mode().unwrap();
2547 match &mode {
2548 SelectMode::Character => {
2549 head = position.to_point(&display_map);
2550 tail = pending.tail().to_point(&buffer);
2551 }
2552 SelectMode::Word(original_range) => {
2553 let original_display_range = original_range.start.to_display_point(&display_map)
2554 ..original_range.end.to_display_point(&display_map);
2555 let original_buffer_range = original_display_range.start.to_point(&display_map)
2556 ..original_display_range.end.to_point(&display_map);
2557 if movement::is_inside_word(&display_map, position)
2558 || original_display_range.contains(&position)
2559 {
2560 let word_range = movement::surrounding_word(&display_map, position);
2561 if word_range.start < original_display_range.start {
2562 head = word_range.start.to_point(&display_map);
2563 } else {
2564 head = word_range.end.to_point(&display_map);
2565 }
2566 } else {
2567 head = position.to_point(&display_map);
2568 }
2569
2570 if head <= original_buffer_range.start {
2571 tail = original_buffer_range.end;
2572 } else {
2573 tail = original_buffer_range.start;
2574 }
2575 }
2576 SelectMode::Line(original_range) => {
2577 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2578
2579 let position = display_map
2580 .clip_point(position, Bias::Left)
2581 .to_point(&display_map);
2582 let line_start = display_map.prev_line_boundary(position).0;
2583 let next_line_start = buffer.clip_point(
2584 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2585 Bias::Left,
2586 );
2587
2588 if line_start < original_range.start {
2589 head = line_start
2590 } else {
2591 head = next_line_start
2592 }
2593
2594 if head <= original_range.start {
2595 tail = original_range.end;
2596 } else {
2597 tail = original_range.start;
2598 }
2599 }
2600 SelectMode::All => {
2601 return;
2602 }
2603 };
2604
2605 if head < tail {
2606 pending.start = buffer.anchor_before(head);
2607 pending.end = buffer.anchor_before(tail);
2608 pending.reversed = true;
2609 } else {
2610 pending.start = buffer.anchor_before(tail);
2611 pending.end = buffer.anchor_before(head);
2612 pending.reversed = false;
2613 }
2614
2615 self.change_selections(None, window, cx, |s| {
2616 s.set_pending(pending, mode);
2617 });
2618 } else {
2619 log::error!("update_selection dispatched with no pending selection");
2620 return;
2621 }
2622
2623 self.apply_scroll_delta(scroll_delta, window, cx);
2624 cx.notify();
2625 }
2626
2627 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2628 self.columnar_selection_tail.take();
2629 if self.selections.pending_anchor().is_some() {
2630 let selections = self.selections.all::<usize>(cx);
2631 self.change_selections(None, window, cx, |s| {
2632 s.select(selections);
2633 s.clear_pending();
2634 });
2635 }
2636 }
2637
2638 fn select_columns(
2639 &mut self,
2640 tail: DisplayPoint,
2641 head: DisplayPoint,
2642 goal_column: u32,
2643 display_map: &DisplaySnapshot,
2644 window: &mut Window,
2645 cx: &mut Context<Self>,
2646 ) {
2647 let start_row = cmp::min(tail.row(), head.row());
2648 let end_row = cmp::max(tail.row(), head.row());
2649 let start_column = cmp::min(tail.column(), goal_column);
2650 let end_column = cmp::max(tail.column(), goal_column);
2651 let reversed = start_column < tail.column();
2652
2653 let selection_ranges = (start_row.0..=end_row.0)
2654 .map(DisplayRow)
2655 .filter_map(|row| {
2656 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2657 let start = display_map
2658 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2659 .to_point(display_map);
2660 let end = display_map
2661 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2662 .to_point(display_map);
2663 if reversed {
2664 Some(end..start)
2665 } else {
2666 Some(start..end)
2667 }
2668 } else {
2669 None
2670 }
2671 })
2672 .collect::<Vec<_>>();
2673
2674 self.change_selections(None, window, cx, |s| {
2675 s.select_ranges(selection_ranges);
2676 });
2677 cx.notify();
2678 }
2679
2680 pub fn has_pending_nonempty_selection(&self) -> bool {
2681 let pending_nonempty_selection = match self.selections.pending_anchor() {
2682 Some(Selection { start, end, .. }) => start != end,
2683 None => false,
2684 };
2685
2686 pending_nonempty_selection
2687 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2688 }
2689
2690 pub fn has_pending_selection(&self) -> bool {
2691 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2692 }
2693
2694 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2695 self.selection_mark_mode = false;
2696
2697 if self.clear_expanded_diff_hunks(cx) {
2698 cx.notify();
2699 return;
2700 }
2701 if self.dismiss_menus_and_popups(true, window, cx) {
2702 return;
2703 }
2704
2705 if self.mode == EditorMode::Full
2706 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2707 {
2708 return;
2709 }
2710
2711 cx.propagate();
2712 }
2713
2714 pub fn dismiss_menus_and_popups(
2715 &mut self,
2716 is_user_requested: bool,
2717 window: &mut Window,
2718 cx: &mut Context<Self>,
2719 ) -> bool {
2720 if self.take_rename(false, window, cx).is_some() {
2721 return true;
2722 }
2723
2724 if hide_hover(self, cx) {
2725 return true;
2726 }
2727
2728 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2729 return true;
2730 }
2731
2732 if self.hide_context_menu(window, cx).is_some() {
2733 return true;
2734 }
2735
2736 if self.mouse_context_menu.take().is_some() {
2737 return true;
2738 }
2739
2740 if is_user_requested && self.discard_inline_completion(true, cx) {
2741 return true;
2742 }
2743
2744 if self.snippet_stack.pop().is_some() {
2745 return true;
2746 }
2747
2748 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2749 self.dismiss_diagnostics(cx);
2750 return true;
2751 }
2752
2753 false
2754 }
2755
2756 fn linked_editing_ranges_for(
2757 &self,
2758 selection: Range<text::Anchor>,
2759 cx: &App,
2760 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2761 if self.linked_edit_ranges.is_empty() {
2762 return None;
2763 }
2764 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2765 selection.end.buffer_id.and_then(|end_buffer_id| {
2766 if selection.start.buffer_id != Some(end_buffer_id) {
2767 return None;
2768 }
2769 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2770 let snapshot = buffer.read(cx).snapshot();
2771 self.linked_edit_ranges
2772 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2773 .map(|ranges| (ranges, snapshot, buffer))
2774 })?;
2775 use text::ToOffset as TO;
2776 // find offset from the start of current range to current cursor position
2777 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2778
2779 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2780 let start_difference = start_offset - start_byte_offset;
2781 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2782 let end_difference = end_offset - start_byte_offset;
2783 // Current range has associated linked ranges.
2784 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2785 for range in linked_ranges.iter() {
2786 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2787 let end_offset = start_offset + end_difference;
2788 let start_offset = start_offset + start_difference;
2789 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2790 continue;
2791 }
2792 if self.selections.disjoint_anchor_ranges().any(|s| {
2793 if s.start.buffer_id != selection.start.buffer_id
2794 || s.end.buffer_id != selection.end.buffer_id
2795 {
2796 return false;
2797 }
2798 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2799 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2800 }) {
2801 continue;
2802 }
2803 let start = buffer_snapshot.anchor_after(start_offset);
2804 let end = buffer_snapshot.anchor_after(end_offset);
2805 linked_edits
2806 .entry(buffer.clone())
2807 .or_default()
2808 .push(start..end);
2809 }
2810 Some(linked_edits)
2811 }
2812
2813 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2814 let text: Arc<str> = text.into();
2815
2816 if self.read_only(cx) {
2817 return;
2818 }
2819
2820 let selections = self.selections.all_adjusted(cx);
2821 let mut bracket_inserted = false;
2822 let mut edits = Vec::new();
2823 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2824 let mut new_selections = Vec::with_capacity(selections.len());
2825 let mut new_autoclose_regions = Vec::new();
2826 let snapshot = self.buffer.read(cx).read(cx);
2827
2828 for (selection, autoclose_region) in
2829 self.selections_with_autoclose_regions(selections, &snapshot)
2830 {
2831 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2832 // Determine if the inserted text matches the opening or closing
2833 // bracket of any of this language's bracket pairs.
2834 let mut bracket_pair = None;
2835 let mut is_bracket_pair_start = false;
2836 let mut is_bracket_pair_end = false;
2837 if !text.is_empty() {
2838 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2839 // and they are removing the character that triggered IME popup.
2840 for (pair, enabled) in scope.brackets() {
2841 if !pair.close && !pair.surround {
2842 continue;
2843 }
2844
2845 if enabled && pair.start.ends_with(text.as_ref()) {
2846 let prefix_len = pair.start.len() - text.len();
2847 let preceding_text_matches_prefix = prefix_len == 0
2848 || (selection.start.column >= (prefix_len as u32)
2849 && snapshot.contains_str_at(
2850 Point::new(
2851 selection.start.row,
2852 selection.start.column - (prefix_len as u32),
2853 ),
2854 &pair.start[..prefix_len],
2855 ));
2856 if preceding_text_matches_prefix {
2857 bracket_pair = Some(pair.clone());
2858 is_bracket_pair_start = true;
2859 break;
2860 }
2861 }
2862 if pair.end.as_str() == text.as_ref() {
2863 bracket_pair = Some(pair.clone());
2864 is_bracket_pair_end = true;
2865 break;
2866 }
2867 }
2868 }
2869
2870 if let Some(bracket_pair) = bracket_pair {
2871 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2872 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2873 let auto_surround =
2874 self.use_auto_surround && snapshot_settings.use_auto_surround;
2875 if selection.is_empty() {
2876 if is_bracket_pair_start {
2877 // If the inserted text is a suffix of an opening bracket and the
2878 // selection is preceded by the rest of the opening bracket, then
2879 // insert the closing bracket.
2880 let following_text_allows_autoclose = snapshot
2881 .chars_at(selection.start)
2882 .next()
2883 .map_or(true, |c| scope.should_autoclose_before(c));
2884
2885 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2886 && bracket_pair.start.len() == 1
2887 {
2888 let target = bracket_pair.start.chars().next().unwrap();
2889 let current_line_count = snapshot
2890 .reversed_chars_at(selection.start)
2891 .take_while(|&c| c != '\n')
2892 .filter(|&c| c == target)
2893 .count();
2894 current_line_count % 2 == 1
2895 } else {
2896 false
2897 };
2898
2899 if autoclose
2900 && bracket_pair.close
2901 && following_text_allows_autoclose
2902 && !is_closing_quote
2903 {
2904 let anchor = snapshot.anchor_before(selection.end);
2905 new_selections.push((selection.map(|_| anchor), text.len()));
2906 new_autoclose_regions.push((
2907 anchor,
2908 text.len(),
2909 selection.id,
2910 bracket_pair.clone(),
2911 ));
2912 edits.push((
2913 selection.range(),
2914 format!("{}{}", text, bracket_pair.end).into(),
2915 ));
2916 bracket_inserted = true;
2917 continue;
2918 }
2919 }
2920
2921 if let Some(region) = autoclose_region {
2922 // If the selection is followed by an auto-inserted closing bracket,
2923 // then don't insert that closing bracket again; just move the selection
2924 // past the closing bracket.
2925 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2926 && text.as_ref() == region.pair.end.as_str();
2927 if should_skip {
2928 let anchor = snapshot.anchor_after(selection.end);
2929 new_selections
2930 .push((selection.map(|_| anchor), region.pair.end.len()));
2931 continue;
2932 }
2933 }
2934
2935 let always_treat_brackets_as_autoclosed = snapshot
2936 .settings_at(selection.start, cx)
2937 .always_treat_brackets_as_autoclosed;
2938 if always_treat_brackets_as_autoclosed
2939 && is_bracket_pair_end
2940 && snapshot.contains_str_at(selection.end, text.as_ref())
2941 {
2942 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2943 // and the inserted text is a closing bracket and the selection is followed
2944 // by the closing bracket then move the selection past the closing bracket.
2945 let anchor = snapshot.anchor_after(selection.end);
2946 new_selections.push((selection.map(|_| anchor), text.len()));
2947 continue;
2948 }
2949 }
2950 // If an opening bracket is 1 character long and is typed while
2951 // text is selected, then surround that text with the bracket pair.
2952 else if auto_surround
2953 && bracket_pair.surround
2954 && is_bracket_pair_start
2955 && bracket_pair.start.chars().count() == 1
2956 {
2957 edits.push((selection.start..selection.start, text.clone()));
2958 edits.push((
2959 selection.end..selection.end,
2960 bracket_pair.end.as_str().into(),
2961 ));
2962 bracket_inserted = true;
2963 new_selections.push((
2964 Selection {
2965 id: selection.id,
2966 start: snapshot.anchor_after(selection.start),
2967 end: snapshot.anchor_before(selection.end),
2968 reversed: selection.reversed,
2969 goal: selection.goal,
2970 },
2971 0,
2972 ));
2973 continue;
2974 }
2975 }
2976 }
2977
2978 if self.auto_replace_emoji_shortcode
2979 && selection.is_empty()
2980 && text.as_ref().ends_with(':')
2981 {
2982 if let Some(possible_emoji_short_code) =
2983 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2984 {
2985 if !possible_emoji_short_code.is_empty() {
2986 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2987 let emoji_shortcode_start = Point::new(
2988 selection.start.row,
2989 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2990 );
2991
2992 // Remove shortcode from buffer
2993 edits.push((
2994 emoji_shortcode_start..selection.start,
2995 "".to_string().into(),
2996 ));
2997 new_selections.push((
2998 Selection {
2999 id: selection.id,
3000 start: snapshot.anchor_after(emoji_shortcode_start),
3001 end: snapshot.anchor_before(selection.start),
3002 reversed: selection.reversed,
3003 goal: selection.goal,
3004 },
3005 0,
3006 ));
3007
3008 // Insert emoji
3009 let selection_start_anchor = snapshot.anchor_after(selection.start);
3010 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3011 edits.push((selection.start..selection.end, emoji.to_string().into()));
3012
3013 continue;
3014 }
3015 }
3016 }
3017 }
3018
3019 // If not handling any auto-close operation, then just replace the selected
3020 // text with the given input and move the selection to the end of the
3021 // newly inserted text.
3022 let anchor = snapshot.anchor_after(selection.end);
3023 if !self.linked_edit_ranges.is_empty() {
3024 let start_anchor = snapshot.anchor_before(selection.start);
3025
3026 let is_word_char = text.chars().next().map_or(true, |char| {
3027 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3028 classifier.is_word(char)
3029 });
3030
3031 if is_word_char {
3032 if let Some(ranges) = self
3033 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3034 {
3035 for (buffer, edits) in ranges {
3036 linked_edits
3037 .entry(buffer.clone())
3038 .or_default()
3039 .extend(edits.into_iter().map(|range| (range, text.clone())));
3040 }
3041 }
3042 }
3043 }
3044
3045 new_selections.push((selection.map(|_| anchor), 0));
3046 edits.push((selection.start..selection.end, text.clone()));
3047 }
3048
3049 drop(snapshot);
3050
3051 self.transact(window, cx, |this, window, cx| {
3052 this.buffer.update(cx, |buffer, cx| {
3053 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3054 });
3055 for (buffer, edits) in linked_edits {
3056 buffer.update(cx, |buffer, cx| {
3057 let snapshot = buffer.snapshot();
3058 let edits = edits
3059 .into_iter()
3060 .map(|(range, text)| {
3061 use text::ToPoint as TP;
3062 let end_point = TP::to_point(&range.end, &snapshot);
3063 let start_point = TP::to_point(&range.start, &snapshot);
3064 (start_point..end_point, text)
3065 })
3066 .sorted_by_key(|(range, _)| range.start)
3067 .collect::<Vec<_>>();
3068 buffer.edit(edits, None, cx);
3069 })
3070 }
3071 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3072 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3073 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3074 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3075 .zip(new_selection_deltas)
3076 .map(|(selection, delta)| Selection {
3077 id: selection.id,
3078 start: selection.start + delta,
3079 end: selection.end + delta,
3080 reversed: selection.reversed,
3081 goal: SelectionGoal::None,
3082 })
3083 .collect::<Vec<_>>();
3084
3085 let mut i = 0;
3086 for (position, delta, selection_id, pair) in new_autoclose_regions {
3087 let position = position.to_offset(&map.buffer_snapshot) + delta;
3088 let start = map.buffer_snapshot.anchor_before(position);
3089 let end = map.buffer_snapshot.anchor_after(position);
3090 while let Some(existing_state) = this.autoclose_regions.get(i) {
3091 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3092 Ordering::Less => i += 1,
3093 Ordering::Greater => break,
3094 Ordering::Equal => {
3095 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3096 Ordering::Less => i += 1,
3097 Ordering::Equal => break,
3098 Ordering::Greater => break,
3099 }
3100 }
3101 }
3102 }
3103 this.autoclose_regions.insert(
3104 i,
3105 AutocloseRegion {
3106 selection_id,
3107 range: start..end,
3108 pair,
3109 },
3110 );
3111 }
3112
3113 let had_active_inline_completion = this.has_active_inline_completion();
3114 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3115 s.select(new_selections)
3116 });
3117
3118 if !bracket_inserted {
3119 if let Some(on_type_format_task) =
3120 this.trigger_on_type_formatting(text.to_string(), window, cx)
3121 {
3122 on_type_format_task.detach_and_log_err(cx);
3123 }
3124 }
3125
3126 let editor_settings = EditorSettings::get_global(cx);
3127 if bracket_inserted
3128 && (editor_settings.auto_signature_help
3129 || editor_settings.show_signature_help_after_edits)
3130 {
3131 this.show_signature_help(&ShowSignatureHelp, window, cx);
3132 }
3133
3134 let trigger_in_words =
3135 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3136 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3137 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3138 this.refresh_inline_completion(true, false, window, cx);
3139 });
3140 }
3141
3142 fn find_possible_emoji_shortcode_at_position(
3143 snapshot: &MultiBufferSnapshot,
3144 position: Point,
3145 ) -> Option<String> {
3146 let mut chars = Vec::new();
3147 let mut found_colon = false;
3148 for char in snapshot.reversed_chars_at(position).take(100) {
3149 // Found a possible emoji shortcode in the middle of the buffer
3150 if found_colon {
3151 if char.is_whitespace() {
3152 chars.reverse();
3153 return Some(chars.iter().collect());
3154 }
3155 // If the previous character is not a whitespace, we are in the middle of a word
3156 // and we only want to complete the shortcode if the word is made up of other emojis
3157 let mut containing_word = String::new();
3158 for ch in snapshot
3159 .reversed_chars_at(position)
3160 .skip(chars.len() + 1)
3161 .take(100)
3162 {
3163 if ch.is_whitespace() {
3164 break;
3165 }
3166 containing_word.push(ch);
3167 }
3168 let containing_word = containing_word.chars().rev().collect::<String>();
3169 if util::word_consists_of_emojis(containing_word.as_str()) {
3170 chars.reverse();
3171 return Some(chars.iter().collect());
3172 }
3173 }
3174
3175 if char.is_whitespace() || !char.is_ascii() {
3176 return None;
3177 }
3178 if char == ':' {
3179 found_colon = true;
3180 } else {
3181 chars.push(char);
3182 }
3183 }
3184 // Found a possible emoji shortcode at the beginning of the buffer
3185 chars.reverse();
3186 Some(chars.iter().collect())
3187 }
3188
3189 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3190 self.transact(window, cx, |this, window, cx| {
3191 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3192 let selections = this.selections.all::<usize>(cx);
3193 let multi_buffer = this.buffer.read(cx);
3194 let buffer = multi_buffer.snapshot(cx);
3195 selections
3196 .iter()
3197 .map(|selection| {
3198 let start_point = selection.start.to_point(&buffer);
3199 let mut indent =
3200 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3201 indent.len = cmp::min(indent.len, start_point.column);
3202 let start = selection.start;
3203 let end = selection.end;
3204 let selection_is_empty = start == end;
3205 let language_scope = buffer.language_scope_at(start);
3206 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3207 &language_scope
3208 {
3209 let leading_whitespace_len = buffer
3210 .reversed_chars_at(start)
3211 .take_while(|c| c.is_whitespace() && *c != '\n')
3212 .map(|c| c.len_utf8())
3213 .sum::<usize>();
3214
3215 let trailing_whitespace_len = buffer
3216 .chars_at(end)
3217 .take_while(|c| c.is_whitespace() && *c != '\n')
3218 .map(|c| c.len_utf8())
3219 .sum::<usize>();
3220
3221 let insert_extra_newline =
3222 language.brackets().any(|(pair, enabled)| {
3223 let pair_start = pair.start.trim_end();
3224 let pair_end = pair.end.trim_start();
3225
3226 enabled
3227 && pair.newline
3228 && buffer.contains_str_at(
3229 end + trailing_whitespace_len,
3230 pair_end,
3231 )
3232 && buffer.contains_str_at(
3233 (start - leading_whitespace_len)
3234 .saturating_sub(pair_start.len()),
3235 pair_start,
3236 )
3237 });
3238
3239 // Comment extension on newline is allowed only for cursor selections
3240 let comment_delimiter = maybe!({
3241 if !selection_is_empty {
3242 return None;
3243 }
3244
3245 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3246 return None;
3247 }
3248
3249 let delimiters = language.line_comment_prefixes();
3250 let max_len_of_delimiter =
3251 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3252 let (snapshot, range) =
3253 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3254
3255 let mut index_of_first_non_whitespace = 0;
3256 let comment_candidate = snapshot
3257 .chars_for_range(range)
3258 .skip_while(|c| {
3259 let should_skip = c.is_whitespace();
3260 if should_skip {
3261 index_of_first_non_whitespace += 1;
3262 }
3263 should_skip
3264 })
3265 .take(max_len_of_delimiter)
3266 .collect::<String>();
3267 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3268 comment_candidate.starts_with(comment_prefix.as_ref())
3269 })?;
3270 let cursor_is_placed_after_comment_marker =
3271 index_of_first_non_whitespace + comment_prefix.len()
3272 <= start_point.column as usize;
3273 if cursor_is_placed_after_comment_marker {
3274 Some(comment_prefix.clone())
3275 } else {
3276 None
3277 }
3278 });
3279 (comment_delimiter, insert_extra_newline)
3280 } else {
3281 (None, false)
3282 };
3283
3284 let capacity_for_delimiter = comment_delimiter
3285 .as_deref()
3286 .map(str::len)
3287 .unwrap_or_default();
3288 let mut new_text =
3289 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3290 new_text.push('\n');
3291 new_text.extend(indent.chars());
3292 if let Some(delimiter) = &comment_delimiter {
3293 new_text.push_str(delimiter);
3294 }
3295 if insert_extra_newline {
3296 new_text = new_text.repeat(2);
3297 }
3298
3299 let anchor = buffer.anchor_after(end);
3300 let new_selection = selection.map(|_| anchor);
3301 (
3302 (start..end, new_text),
3303 (insert_extra_newline, new_selection),
3304 )
3305 })
3306 .unzip()
3307 };
3308
3309 this.edit_with_autoindent(edits, cx);
3310 let buffer = this.buffer.read(cx).snapshot(cx);
3311 let new_selections = selection_fixup_info
3312 .into_iter()
3313 .map(|(extra_newline_inserted, new_selection)| {
3314 let mut cursor = new_selection.end.to_point(&buffer);
3315 if extra_newline_inserted {
3316 cursor.row -= 1;
3317 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3318 }
3319 new_selection.map(|_| cursor)
3320 })
3321 .collect();
3322
3323 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3324 s.select(new_selections)
3325 });
3326 this.refresh_inline_completion(true, false, window, cx);
3327 });
3328 }
3329
3330 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3331 let buffer = self.buffer.read(cx);
3332 let snapshot = buffer.snapshot(cx);
3333
3334 let mut edits = Vec::new();
3335 let mut rows = Vec::new();
3336
3337 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3338 let cursor = selection.head();
3339 let row = cursor.row;
3340
3341 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3342
3343 let newline = "\n".to_string();
3344 edits.push((start_of_line..start_of_line, newline));
3345
3346 rows.push(row + rows_inserted as u32);
3347 }
3348
3349 self.transact(window, cx, |editor, window, cx| {
3350 editor.edit(edits, cx);
3351
3352 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3353 let mut index = 0;
3354 s.move_cursors_with(|map, _, _| {
3355 let row = rows[index];
3356 index += 1;
3357
3358 let point = Point::new(row, 0);
3359 let boundary = map.next_line_boundary(point).1;
3360 let clipped = map.clip_point(boundary, Bias::Left);
3361
3362 (clipped, SelectionGoal::None)
3363 });
3364 });
3365
3366 let mut indent_edits = Vec::new();
3367 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3368 for row in rows {
3369 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3370 for (row, indent) in indents {
3371 if indent.len == 0 {
3372 continue;
3373 }
3374
3375 let text = match indent.kind {
3376 IndentKind::Space => " ".repeat(indent.len as usize),
3377 IndentKind::Tab => "\t".repeat(indent.len as usize),
3378 };
3379 let point = Point::new(row.0, 0);
3380 indent_edits.push((point..point, text));
3381 }
3382 }
3383 editor.edit(indent_edits, cx);
3384 });
3385 }
3386
3387 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3388 let buffer = self.buffer.read(cx);
3389 let snapshot = buffer.snapshot(cx);
3390
3391 let mut edits = Vec::new();
3392 let mut rows = Vec::new();
3393 let mut rows_inserted = 0;
3394
3395 for selection in self.selections.all_adjusted(cx) {
3396 let cursor = selection.head();
3397 let row = cursor.row;
3398
3399 let point = Point::new(row + 1, 0);
3400 let start_of_line = snapshot.clip_point(point, Bias::Left);
3401
3402 let newline = "\n".to_string();
3403 edits.push((start_of_line..start_of_line, newline));
3404
3405 rows_inserted += 1;
3406 rows.push(row + rows_inserted);
3407 }
3408
3409 self.transact(window, cx, |editor, window, cx| {
3410 editor.edit(edits, cx);
3411
3412 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3413 let mut index = 0;
3414 s.move_cursors_with(|map, _, _| {
3415 let row = rows[index];
3416 index += 1;
3417
3418 let point = Point::new(row, 0);
3419 let boundary = map.next_line_boundary(point).1;
3420 let clipped = map.clip_point(boundary, Bias::Left);
3421
3422 (clipped, SelectionGoal::None)
3423 });
3424 });
3425
3426 let mut indent_edits = Vec::new();
3427 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3428 for row in rows {
3429 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3430 for (row, indent) in indents {
3431 if indent.len == 0 {
3432 continue;
3433 }
3434
3435 let text = match indent.kind {
3436 IndentKind::Space => " ".repeat(indent.len as usize),
3437 IndentKind::Tab => "\t".repeat(indent.len as usize),
3438 };
3439 let point = Point::new(row.0, 0);
3440 indent_edits.push((point..point, text));
3441 }
3442 }
3443 editor.edit(indent_edits, cx);
3444 });
3445 }
3446
3447 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3448 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3449 original_indent_columns: Vec::new(),
3450 });
3451 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3452 }
3453
3454 fn insert_with_autoindent_mode(
3455 &mut self,
3456 text: &str,
3457 autoindent_mode: Option<AutoindentMode>,
3458 window: &mut Window,
3459 cx: &mut Context<Self>,
3460 ) {
3461 if self.read_only(cx) {
3462 return;
3463 }
3464
3465 let text: Arc<str> = text.into();
3466 self.transact(window, cx, |this, window, cx| {
3467 let old_selections = this.selections.all_adjusted(cx);
3468 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3469 let anchors = {
3470 let snapshot = buffer.read(cx);
3471 old_selections
3472 .iter()
3473 .map(|s| {
3474 let anchor = snapshot.anchor_after(s.head());
3475 s.map(|_| anchor)
3476 })
3477 .collect::<Vec<_>>()
3478 };
3479 buffer.edit(
3480 old_selections
3481 .iter()
3482 .map(|s| (s.start..s.end, text.clone())),
3483 autoindent_mode,
3484 cx,
3485 );
3486 anchors
3487 });
3488
3489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3490 s.select_anchors(selection_anchors);
3491 });
3492
3493 cx.notify();
3494 });
3495 }
3496
3497 fn trigger_completion_on_input(
3498 &mut self,
3499 text: &str,
3500 trigger_in_words: bool,
3501 window: &mut Window,
3502 cx: &mut Context<Self>,
3503 ) {
3504 if self.is_completion_trigger(text, trigger_in_words, cx) {
3505 self.show_completions(
3506 &ShowCompletions {
3507 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3508 },
3509 window,
3510 cx,
3511 );
3512 } else {
3513 self.hide_context_menu(window, cx);
3514 }
3515 }
3516
3517 fn is_completion_trigger(
3518 &self,
3519 text: &str,
3520 trigger_in_words: bool,
3521 cx: &mut Context<Self>,
3522 ) -> bool {
3523 let position = self.selections.newest_anchor().head();
3524 let multibuffer = self.buffer.read(cx);
3525 let Some(buffer) = position
3526 .buffer_id
3527 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3528 else {
3529 return false;
3530 };
3531
3532 if let Some(completion_provider) = &self.completion_provider {
3533 completion_provider.is_completion_trigger(
3534 &buffer,
3535 position.text_anchor,
3536 text,
3537 trigger_in_words,
3538 cx,
3539 )
3540 } else {
3541 false
3542 }
3543 }
3544
3545 /// If any empty selections is touching the start of its innermost containing autoclose
3546 /// region, expand it to select the brackets.
3547 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3548 let selections = self.selections.all::<usize>(cx);
3549 let buffer = self.buffer.read(cx).read(cx);
3550 let new_selections = self
3551 .selections_with_autoclose_regions(selections, &buffer)
3552 .map(|(mut selection, region)| {
3553 if !selection.is_empty() {
3554 return selection;
3555 }
3556
3557 if let Some(region) = region {
3558 let mut range = region.range.to_offset(&buffer);
3559 if selection.start == range.start && range.start >= region.pair.start.len() {
3560 range.start -= region.pair.start.len();
3561 if buffer.contains_str_at(range.start, ®ion.pair.start)
3562 && buffer.contains_str_at(range.end, ®ion.pair.end)
3563 {
3564 range.end += region.pair.end.len();
3565 selection.start = range.start;
3566 selection.end = range.end;
3567
3568 return selection;
3569 }
3570 }
3571 }
3572
3573 let always_treat_brackets_as_autoclosed = buffer
3574 .settings_at(selection.start, cx)
3575 .always_treat_brackets_as_autoclosed;
3576
3577 if !always_treat_brackets_as_autoclosed {
3578 return selection;
3579 }
3580
3581 if let Some(scope) = buffer.language_scope_at(selection.start) {
3582 for (pair, enabled) in scope.brackets() {
3583 if !enabled || !pair.close {
3584 continue;
3585 }
3586
3587 if buffer.contains_str_at(selection.start, &pair.end) {
3588 let pair_start_len = pair.start.len();
3589 if buffer.contains_str_at(
3590 selection.start.saturating_sub(pair_start_len),
3591 &pair.start,
3592 ) {
3593 selection.start -= pair_start_len;
3594 selection.end += pair.end.len();
3595
3596 return selection;
3597 }
3598 }
3599 }
3600 }
3601
3602 selection
3603 })
3604 .collect();
3605
3606 drop(buffer);
3607 self.change_selections(None, window, cx, |selections| {
3608 selections.select(new_selections)
3609 });
3610 }
3611
3612 /// Iterate the given selections, and for each one, find the smallest surrounding
3613 /// autoclose region. This uses the ordering of the selections and the autoclose
3614 /// regions to avoid repeated comparisons.
3615 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3616 &'a self,
3617 selections: impl IntoIterator<Item = Selection<D>>,
3618 buffer: &'a MultiBufferSnapshot,
3619 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3620 let mut i = 0;
3621 let mut regions = self.autoclose_regions.as_slice();
3622 selections.into_iter().map(move |selection| {
3623 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3624
3625 let mut enclosing = None;
3626 while let Some(pair_state) = regions.get(i) {
3627 if pair_state.range.end.to_offset(buffer) < range.start {
3628 regions = ®ions[i + 1..];
3629 i = 0;
3630 } else if pair_state.range.start.to_offset(buffer) > range.end {
3631 break;
3632 } else {
3633 if pair_state.selection_id == selection.id {
3634 enclosing = Some(pair_state);
3635 }
3636 i += 1;
3637 }
3638 }
3639
3640 (selection, enclosing)
3641 })
3642 }
3643
3644 /// Remove any autoclose regions that no longer contain their selection.
3645 fn invalidate_autoclose_regions(
3646 &mut self,
3647 mut selections: &[Selection<Anchor>],
3648 buffer: &MultiBufferSnapshot,
3649 ) {
3650 self.autoclose_regions.retain(|state| {
3651 let mut i = 0;
3652 while let Some(selection) = selections.get(i) {
3653 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3654 selections = &selections[1..];
3655 continue;
3656 }
3657 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3658 break;
3659 }
3660 if selection.id == state.selection_id {
3661 return true;
3662 } else {
3663 i += 1;
3664 }
3665 }
3666 false
3667 });
3668 }
3669
3670 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3671 let offset = position.to_offset(buffer);
3672 let (word_range, kind) = buffer.surrounding_word(offset, true);
3673 if offset > word_range.start && kind == Some(CharKind::Word) {
3674 Some(
3675 buffer
3676 .text_for_range(word_range.start..offset)
3677 .collect::<String>(),
3678 )
3679 } else {
3680 None
3681 }
3682 }
3683
3684 pub fn toggle_inlay_hints(
3685 &mut self,
3686 _: &ToggleInlayHints,
3687 _: &mut Window,
3688 cx: &mut Context<Self>,
3689 ) {
3690 self.refresh_inlay_hints(
3691 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3692 cx,
3693 );
3694 }
3695
3696 pub fn inlay_hints_enabled(&self) -> bool {
3697 self.inlay_hint_cache.enabled
3698 }
3699
3700 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3701 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3702 return;
3703 }
3704
3705 let reason_description = reason.description();
3706 let ignore_debounce = matches!(
3707 reason,
3708 InlayHintRefreshReason::SettingsChange(_)
3709 | InlayHintRefreshReason::Toggle(_)
3710 | InlayHintRefreshReason::ExcerptsRemoved(_)
3711 );
3712 let (invalidate_cache, required_languages) = match reason {
3713 InlayHintRefreshReason::Toggle(enabled) => {
3714 self.inlay_hint_cache.enabled = enabled;
3715 if enabled {
3716 (InvalidationStrategy::RefreshRequested, None)
3717 } else {
3718 self.inlay_hint_cache.clear();
3719 self.splice_inlays(
3720 &self
3721 .visible_inlay_hints(cx)
3722 .iter()
3723 .map(|inlay| inlay.id)
3724 .collect::<Vec<InlayId>>(),
3725 Vec::new(),
3726 cx,
3727 );
3728 return;
3729 }
3730 }
3731 InlayHintRefreshReason::SettingsChange(new_settings) => {
3732 match self.inlay_hint_cache.update_settings(
3733 &self.buffer,
3734 new_settings,
3735 self.visible_inlay_hints(cx),
3736 cx,
3737 ) {
3738 ControlFlow::Break(Some(InlaySplice {
3739 to_remove,
3740 to_insert,
3741 })) => {
3742 self.splice_inlays(&to_remove, to_insert, cx);
3743 return;
3744 }
3745 ControlFlow::Break(None) => return,
3746 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3747 }
3748 }
3749 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3750 if let Some(InlaySplice {
3751 to_remove,
3752 to_insert,
3753 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3754 {
3755 self.splice_inlays(&to_remove, to_insert, cx);
3756 }
3757 return;
3758 }
3759 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3760 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3761 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3762 }
3763 InlayHintRefreshReason::RefreshRequested => {
3764 (InvalidationStrategy::RefreshRequested, None)
3765 }
3766 };
3767
3768 if let Some(InlaySplice {
3769 to_remove,
3770 to_insert,
3771 }) = self.inlay_hint_cache.spawn_hint_refresh(
3772 reason_description,
3773 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3774 invalidate_cache,
3775 ignore_debounce,
3776 cx,
3777 ) {
3778 self.splice_inlays(&to_remove, to_insert, cx);
3779 }
3780 }
3781
3782 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3783 self.display_map
3784 .read(cx)
3785 .current_inlays()
3786 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3787 .cloned()
3788 .collect()
3789 }
3790
3791 pub fn excerpts_for_inlay_hints_query(
3792 &self,
3793 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3794 cx: &mut Context<Editor>,
3795 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3796 let Some(project) = self.project.as_ref() else {
3797 return HashMap::default();
3798 };
3799 let project = project.read(cx);
3800 let multi_buffer = self.buffer().read(cx);
3801 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3802 let multi_buffer_visible_start = self
3803 .scroll_manager
3804 .anchor()
3805 .anchor
3806 .to_point(&multi_buffer_snapshot);
3807 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3808 multi_buffer_visible_start
3809 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3810 Bias::Left,
3811 );
3812 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3813 multi_buffer_snapshot
3814 .range_to_buffer_ranges(multi_buffer_visible_range)
3815 .into_iter()
3816 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3817 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3818 let buffer_file = project::File::from_dyn(buffer.file())?;
3819 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3820 let worktree_entry = buffer_worktree
3821 .read(cx)
3822 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3823 if worktree_entry.is_ignored {
3824 return None;
3825 }
3826
3827 let language = buffer.language()?;
3828 if let Some(restrict_to_languages) = restrict_to_languages {
3829 if !restrict_to_languages.contains(language) {
3830 return None;
3831 }
3832 }
3833 Some((
3834 excerpt_id,
3835 (
3836 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3837 buffer.version().clone(),
3838 excerpt_visible_range,
3839 ),
3840 ))
3841 })
3842 .collect()
3843 }
3844
3845 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3846 TextLayoutDetails {
3847 text_system: window.text_system().clone(),
3848 editor_style: self.style.clone().unwrap(),
3849 rem_size: window.rem_size(),
3850 scroll_anchor: self.scroll_manager.anchor(),
3851 visible_rows: self.visible_line_count(),
3852 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3853 }
3854 }
3855
3856 pub fn splice_inlays(
3857 &self,
3858 to_remove: &[InlayId],
3859 to_insert: Vec<Inlay>,
3860 cx: &mut Context<Self>,
3861 ) {
3862 self.display_map.update(cx, |display_map, cx| {
3863 display_map.splice_inlays(to_remove, to_insert, cx)
3864 });
3865 cx.notify();
3866 }
3867
3868 fn trigger_on_type_formatting(
3869 &self,
3870 input: String,
3871 window: &mut Window,
3872 cx: &mut Context<Self>,
3873 ) -> Option<Task<Result<()>>> {
3874 if input.len() != 1 {
3875 return None;
3876 }
3877
3878 let project = self.project.as_ref()?;
3879 let position = self.selections.newest_anchor().head();
3880 let (buffer, buffer_position) = self
3881 .buffer
3882 .read(cx)
3883 .text_anchor_for_position(position, cx)?;
3884
3885 let settings = language_settings::language_settings(
3886 buffer
3887 .read(cx)
3888 .language_at(buffer_position)
3889 .map(|l| l.name()),
3890 buffer.read(cx).file(),
3891 cx,
3892 );
3893 if !settings.use_on_type_format {
3894 return None;
3895 }
3896
3897 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3898 // hence we do LSP request & edit on host side only — add formats to host's history.
3899 let push_to_lsp_host_history = true;
3900 // If this is not the host, append its history with new edits.
3901 let push_to_client_history = project.read(cx).is_via_collab();
3902
3903 let on_type_formatting = project.update(cx, |project, cx| {
3904 project.on_type_format(
3905 buffer.clone(),
3906 buffer_position,
3907 input,
3908 push_to_lsp_host_history,
3909 cx,
3910 )
3911 });
3912 Some(cx.spawn_in(window, |editor, mut cx| async move {
3913 if let Some(transaction) = on_type_formatting.await? {
3914 if push_to_client_history {
3915 buffer
3916 .update(&mut cx, |buffer, _| {
3917 buffer.push_transaction(transaction, Instant::now());
3918 })
3919 .ok();
3920 }
3921 editor.update(&mut cx, |editor, cx| {
3922 editor.refresh_document_highlights(cx);
3923 })?;
3924 }
3925 Ok(())
3926 }))
3927 }
3928
3929 pub fn show_completions(
3930 &mut self,
3931 options: &ShowCompletions,
3932 window: &mut Window,
3933 cx: &mut Context<Self>,
3934 ) {
3935 if self.pending_rename.is_some() {
3936 return;
3937 }
3938
3939 let Some(provider) = self.completion_provider.as_ref() else {
3940 return;
3941 };
3942
3943 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3944 return;
3945 }
3946
3947 let position = self.selections.newest_anchor().head();
3948 if position.diff_base_anchor.is_some() {
3949 return;
3950 }
3951 let (buffer, buffer_position) =
3952 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3953 output
3954 } else {
3955 return;
3956 };
3957 let show_completion_documentation = buffer
3958 .read(cx)
3959 .snapshot()
3960 .settings_at(buffer_position, cx)
3961 .show_completion_documentation;
3962
3963 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3964
3965 let trigger_kind = match &options.trigger {
3966 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3967 CompletionTriggerKind::TRIGGER_CHARACTER
3968 }
3969 _ => CompletionTriggerKind::INVOKED,
3970 };
3971 let completion_context = CompletionContext {
3972 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3973 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3974 Some(String::from(trigger))
3975 } else {
3976 None
3977 }
3978 }),
3979 trigger_kind,
3980 };
3981 let completions =
3982 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3983 let sort_completions = provider.sort_completions();
3984
3985 let id = post_inc(&mut self.next_completion_id);
3986 let task = cx.spawn_in(window, |editor, mut cx| {
3987 async move {
3988 editor.update(&mut cx, |this, _| {
3989 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3990 })?;
3991 let completions = completions.await.log_err();
3992 let menu = if let Some(completions) = completions {
3993 let mut menu = CompletionsMenu::new(
3994 id,
3995 sort_completions,
3996 show_completion_documentation,
3997 position,
3998 buffer.clone(),
3999 completions.into(),
4000 );
4001
4002 menu.filter(query.as_deref(), cx.background_executor().clone())
4003 .await;
4004
4005 menu.visible().then_some(menu)
4006 } else {
4007 None
4008 };
4009
4010 editor.update_in(&mut cx, |editor, window, cx| {
4011 match editor.context_menu.borrow().as_ref() {
4012 None => {}
4013 Some(CodeContextMenu::Completions(prev_menu)) => {
4014 if prev_menu.id > id {
4015 return;
4016 }
4017 }
4018 _ => return,
4019 }
4020
4021 if editor.focus_handle.is_focused(window) && menu.is_some() {
4022 let mut menu = menu.unwrap();
4023 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4024
4025 *editor.context_menu.borrow_mut() =
4026 Some(CodeContextMenu::Completions(menu));
4027
4028 if editor.show_edit_predictions_in_menu() {
4029 editor.update_visible_inline_completion(window, cx);
4030 } else {
4031 editor.discard_inline_completion(false, cx);
4032 }
4033
4034 cx.notify();
4035 } else if editor.completion_tasks.len() <= 1 {
4036 // If there are no more completion tasks and the last menu was
4037 // empty, we should hide it.
4038 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4039 // If it was already hidden and we don't show inline
4040 // completions in the menu, we should also show the
4041 // inline-completion when available.
4042 if was_hidden && editor.show_edit_predictions_in_menu() {
4043 editor.update_visible_inline_completion(window, cx);
4044 }
4045 }
4046 })?;
4047
4048 Ok::<_, anyhow::Error>(())
4049 }
4050 .log_err()
4051 });
4052
4053 self.completion_tasks.push((id, task));
4054 }
4055
4056 pub fn confirm_completion(
4057 &mut self,
4058 action: &ConfirmCompletion,
4059 window: &mut Window,
4060 cx: &mut Context<Self>,
4061 ) -> Option<Task<Result<()>>> {
4062 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4063 }
4064
4065 pub fn compose_completion(
4066 &mut self,
4067 action: &ComposeCompletion,
4068 window: &mut Window,
4069 cx: &mut Context<Self>,
4070 ) -> Option<Task<Result<()>>> {
4071 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4072 }
4073
4074 fn do_completion(
4075 &mut self,
4076 item_ix: Option<usize>,
4077 intent: CompletionIntent,
4078 window: &mut Window,
4079 cx: &mut Context<Editor>,
4080 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4081 use language::ToOffset as _;
4082
4083 let completions_menu =
4084 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4085 menu
4086 } else {
4087 return None;
4088 };
4089
4090 let entries = completions_menu.entries.borrow();
4091 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4092 if self.show_edit_predictions_in_menu() {
4093 self.discard_inline_completion(true, cx);
4094 }
4095 let candidate_id = mat.candidate_id;
4096 drop(entries);
4097
4098 let buffer_handle = completions_menu.buffer;
4099 let completion = completions_menu
4100 .completions
4101 .borrow()
4102 .get(candidate_id)?
4103 .clone();
4104 cx.stop_propagation();
4105
4106 let snippet;
4107 let text;
4108
4109 if completion.is_snippet() {
4110 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4111 text = snippet.as_ref().unwrap().text.clone();
4112 } else {
4113 snippet = None;
4114 text = completion.new_text.clone();
4115 };
4116 let selections = self.selections.all::<usize>(cx);
4117 let buffer = buffer_handle.read(cx);
4118 let old_range = completion.old_range.to_offset(buffer);
4119 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4120
4121 let newest_selection = self.selections.newest_anchor();
4122 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4123 return None;
4124 }
4125
4126 let lookbehind = newest_selection
4127 .start
4128 .text_anchor
4129 .to_offset(buffer)
4130 .saturating_sub(old_range.start);
4131 let lookahead = old_range
4132 .end
4133 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4134 let mut common_prefix_len = old_text
4135 .bytes()
4136 .zip(text.bytes())
4137 .take_while(|(a, b)| a == b)
4138 .count();
4139
4140 let snapshot = self.buffer.read(cx).snapshot(cx);
4141 let mut range_to_replace: Option<Range<isize>> = None;
4142 let mut ranges = Vec::new();
4143 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4144 for selection in &selections {
4145 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4146 let start = selection.start.saturating_sub(lookbehind);
4147 let end = selection.end + lookahead;
4148 if selection.id == newest_selection.id {
4149 range_to_replace = Some(
4150 ((start + common_prefix_len) as isize - selection.start as isize)
4151 ..(end as isize - selection.start as isize),
4152 );
4153 }
4154 ranges.push(start + common_prefix_len..end);
4155 } else {
4156 common_prefix_len = 0;
4157 ranges.clear();
4158 ranges.extend(selections.iter().map(|s| {
4159 if s.id == newest_selection.id {
4160 range_to_replace = Some(
4161 old_range.start.to_offset_utf16(&snapshot).0 as isize
4162 - selection.start as isize
4163 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4164 - selection.start as isize,
4165 );
4166 old_range.clone()
4167 } else {
4168 s.start..s.end
4169 }
4170 }));
4171 break;
4172 }
4173 if !self.linked_edit_ranges.is_empty() {
4174 let start_anchor = snapshot.anchor_before(selection.head());
4175 let end_anchor = snapshot.anchor_after(selection.tail());
4176 if let Some(ranges) = self
4177 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4178 {
4179 for (buffer, edits) in ranges {
4180 linked_edits.entry(buffer.clone()).or_default().extend(
4181 edits
4182 .into_iter()
4183 .map(|range| (range, text[common_prefix_len..].to_owned())),
4184 );
4185 }
4186 }
4187 }
4188 }
4189 let text = &text[common_prefix_len..];
4190
4191 cx.emit(EditorEvent::InputHandled {
4192 utf16_range_to_replace: range_to_replace,
4193 text: text.into(),
4194 });
4195
4196 self.transact(window, cx, |this, window, cx| {
4197 if let Some(mut snippet) = snippet {
4198 snippet.text = text.to_string();
4199 for tabstop in snippet
4200 .tabstops
4201 .iter_mut()
4202 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4203 {
4204 tabstop.start -= common_prefix_len as isize;
4205 tabstop.end -= common_prefix_len as isize;
4206 }
4207
4208 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4209 } else {
4210 this.buffer.update(cx, |buffer, cx| {
4211 buffer.edit(
4212 ranges.iter().map(|range| (range.clone(), text)),
4213 this.autoindent_mode.clone(),
4214 cx,
4215 );
4216 });
4217 }
4218 for (buffer, edits) in linked_edits {
4219 buffer.update(cx, |buffer, cx| {
4220 let snapshot = buffer.snapshot();
4221 let edits = edits
4222 .into_iter()
4223 .map(|(range, text)| {
4224 use text::ToPoint as TP;
4225 let end_point = TP::to_point(&range.end, &snapshot);
4226 let start_point = TP::to_point(&range.start, &snapshot);
4227 (start_point..end_point, text)
4228 })
4229 .sorted_by_key(|(range, _)| range.start)
4230 .collect::<Vec<_>>();
4231 buffer.edit(edits, None, cx);
4232 })
4233 }
4234
4235 this.refresh_inline_completion(true, false, window, cx);
4236 });
4237
4238 let show_new_completions_on_confirm = completion
4239 .confirm
4240 .as_ref()
4241 .map_or(false, |confirm| confirm(intent, window, cx));
4242 if show_new_completions_on_confirm {
4243 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4244 }
4245
4246 let provider = self.completion_provider.as_ref()?;
4247 drop(completion);
4248 let apply_edits = provider.apply_additional_edits_for_completion(
4249 buffer_handle,
4250 completions_menu.completions.clone(),
4251 candidate_id,
4252 true,
4253 cx,
4254 );
4255
4256 let editor_settings = EditorSettings::get_global(cx);
4257 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4258 // After the code completion is finished, users often want to know what signatures are needed.
4259 // so we should automatically call signature_help
4260 self.show_signature_help(&ShowSignatureHelp, window, cx);
4261 }
4262
4263 Some(cx.foreground_executor().spawn(async move {
4264 apply_edits.await?;
4265 Ok(())
4266 }))
4267 }
4268
4269 pub fn toggle_code_actions(
4270 &mut self,
4271 action: &ToggleCodeActions,
4272 window: &mut Window,
4273 cx: &mut Context<Self>,
4274 ) {
4275 let mut context_menu = self.context_menu.borrow_mut();
4276 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4277 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4278 // Toggle if we're selecting the same one
4279 *context_menu = None;
4280 cx.notify();
4281 return;
4282 } else {
4283 // Otherwise, clear it and start a new one
4284 *context_menu = None;
4285 cx.notify();
4286 }
4287 }
4288 drop(context_menu);
4289 let snapshot = self.snapshot(window, cx);
4290 let deployed_from_indicator = action.deployed_from_indicator;
4291 let mut task = self.code_actions_task.take();
4292 let action = action.clone();
4293 cx.spawn_in(window, |editor, mut cx| async move {
4294 while let Some(prev_task) = task {
4295 prev_task.await.log_err();
4296 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4297 }
4298
4299 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4300 if editor.focus_handle.is_focused(window) {
4301 let multibuffer_point = action
4302 .deployed_from_indicator
4303 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4304 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4305 let (buffer, buffer_row) = snapshot
4306 .buffer_snapshot
4307 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4308 .and_then(|(buffer_snapshot, range)| {
4309 editor
4310 .buffer
4311 .read(cx)
4312 .buffer(buffer_snapshot.remote_id())
4313 .map(|buffer| (buffer, range.start.row))
4314 })?;
4315 let (_, code_actions) = editor
4316 .available_code_actions
4317 .clone()
4318 .and_then(|(location, code_actions)| {
4319 let snapshot = location.buffer.read(cx).snapshot();
4320 let point_range = location.range.to_point(&snapshot);
4321 let point_range = point_range.start.row..=point_range.end.row;
4322 if point_range.contains(&buffer_row) {
4323 Some((location, code_actions))
4324 } else {
4325 None
4326 }
4327 })
4328 .unzip();
4329 let buffer_id = buffer.read(cx).remote_id();
4330 let tasks = editor
4331 .tasks
4332 .get(&(buffer_id, buffer_row))
4333 .map(|t| Arc::new(t.to_owned()));
4334 if tasks.is_none() && code_actions.is_none() {
4335 return None;
4336 }
4337
4338 editor.completion_tasks.clear();
4339 editor.discard_inline_completion(false, cx);
4340 let task_context =
4341 tasks
4342 .as_ref()
4343 .zip(editor.project.clone())
4344 .map(|(tasks, project)| {
4345 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4346 });
4347
4348 Some(cx.spawn_in(window, |editor, mut cx| async move {
4349 let task_context = match task_context {
4350 Some(task_context) => task_context.await,
4351 None => None,
4352 };
4353 let resolved_tasks =
4354 tasks.zip(task_context).map(|(tasks, task_context)| {
4355 Rc::new(ResolvedTasks {
4356 templates: tasks.resolve(&task_context).collect(),
4357 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4358 multibuffer_point.row,
4359 tasks.column,
4360 )),
4361 })
4362 });
4363 let spawn_straight_away = resolved_tasks
4364 .as_ref()
4365 .map_or(false, |tasks| tasks.templates.len() == 1)
4366 && code_actions
4367 .as_ref()
4368 .map_or(true, |actions| actions.is_empty());
4369 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4370 *editor.context_menu.borrow_mut() =
4371 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4372 buffer,
4373 actions: CodeActionContents {
4374 tasks: resolved_tasks,
4375 actions: code_actions,
4376 },
4377 selected_item: Default::default(),
4378 scroll_handle: UniformListScrollHandle::default(),
4379 deployed_from_indicator,
4380 }));
4381 if spawn_straight_away {
4382 if let Some(task) = editor.confirm_code_action(
4383 &ConfirmCodeAction { item_ix: Some(0) },
4384 window,
4385 cx,
4386 ) {
4387 cx.notify();
4388 return task;
4389 }
4390 }
4391 cx.notify();
4392 Task::ready(Ok(()))
4393 }) {
4394 task.await
4395 } else {
4396 Ok(())
4397 }
4398 }))
4399 } else {
4400 Some(Task::ready(Ok(())))
4401 }
4402 })?;
4403 if let Some(task) = spawned_test_task {
4404 task.await?;
4405 }
4406
4407 Ok::<_, anyhow::Error>(())
4408 })
4409 .detach_and_log_err(cx);
4410 }
4411
4412 pub fn confirm_code_action(
4413 &mut self,
4414 action: &ConfirmCodeAction,
4415 window: &mut Window,
4416 cx: &mut Context<Self>,
4417 ) -> Option<Task<Result<()>>> {
4418 let actions_menu =
4419 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4420 menu
4421 } else {
4422 return None;
4423 };
4424 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4425 let action = actions_menu.actions.get(action_ix)?;
4426 let title = action.label();
4427 let buffer = actions_menu.buffer;
4428 let workspace = self.workspace()?;
4429
4430 match action {
4431 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4432 workspace.update(cx, |workspace, cx| {
4433 workspace::tasks::schedule_resolved_task(
4434 workspace,
4435 task_source_kind,
4436 resolved_task,
4437 false,
4438 cx,
4439 );
4440
4441 Some(Task::ready(Ok(())))
4442 })
4443 }
4444 CodeActionsItem::CodeAction {
4445 excerpt_id,
4446 action,
4447 provider,
4448 } => {
4449 let apply_code_action =
4450 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4451 let workspace = workspace.downgrade();
4452 Some(cx.spawn_in(window, |editor, cx| async move {
4453 let project_transaction = apply_code_action.await?;
4454 Self::open_project_transaction(
4455 &editor,
4456 workspace,
4457 project_transaction,
4458 title,
4459 cx,
4460 )
4461 .await
4462 }))
4463 }
4464 }
4465 }
4466
4467 pub async fn open_project_transaction(
4468 this: &WeakEntity<Editor>,
4469 workspace: WeakEntity<Workspace>,
4470 transaction: ProjectTransaction,
4471 title: String,
4472 mut cx: AsyncWindowContext,
4473 ) -> Result<()> {
4474 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4475 cx.update(|_, cx| {
4476 entries.sort_unstable_by_key(|(buffer, _)| {
4477 buffer.read(cx).file().map(|f| f.path().clone())
4478 });
4479 })?;
4480
4481 // If the project transaction's edits are all contained within this editor, then
4482 // avoid opening a new editor to display them.
4483
4484 if let Some((buffer, transaction)) = entries.first() {
4485 if entries.len() == 1 {
4486 let excerpt = this.update(&mut cx, |editor, cx| {
4487 editor
4488 .buffer()
4489 .read(cx)
4490 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4491 })?;
4492 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4493 if excerpted_buffer == *buffer {
4494 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4495 let excerpt_range = excerpt_range.to_offset(buffer);
4496 buffer
4497 .edited_ranges_for_transaction::<usize>(transaction)
4498 .all(|range| {
4499 excerpt_range.start <= range.start
4500 && excerpt_range.end >= range.end
4501 })
4502 })?;
4503
4504 if all_edits_within_excerpt {
4505 return Ok(());
4506 }
4507 }
4508 }
4509 }
4510 } else {
4511 return Ok(());
4512 }
4513
4514 let mut ranges_to_highlight = Vec::new();
4515 let excerpt_buffer = cx.new(|cx| {
4516 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4517 for (buffer_handle, transaction) in &entries {
4518 let buffer = buffer_handle.read(cx);
4519 ranges_to_highlight.extend(
4520 multibuffer.push_excerpts_with_context_lines(
4521 buffer_handle.clone(),
4522 buffer
4523 .edited_ranges_for_transaction::<usize>(transaction)
4524 .collect(),
4525 DEFAULT_MULTIBUFFER_CONTEXT,
4526 cx,
4527 ),
4528 );
4529 }
4530 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4531 multibuffer
4532 })?;
4533
4534 workspace.update_in(&mut cx, |workspace, window, cx| {
4535 let project = workspace.project().clone();
4536 let editor = cx
4537 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4538 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4539 editor.update(cx, |editor, cx| {
4540 editor.highlight_background::<Self>(
4541 &ranges_to_highlight,
4542 |theme| theme.editor_highlighted_line_background,
4543 cx,
4544 );
4545 });
4546 })?;
4547
4548 Ok(())
4549 }
4550
4551 pub fn clear_code_action_providers(&mut self) {
4552 self.code_action_providers.clear();
4553 self.available_code_actions.take();
4554 }
4555
4556 pub fn add_code_action_provider(
4557 &mut self,
4558 provider: Rc<dyn CodeActionProvider>,
4559 window: &mut Window,
4560 cx: &mut Context<Self>,
4561 ) {
4562 if self
4563 .code_action_providers
4564 .iter()
4565 .any(|existing_provider| existing_provider.id() == provider.id())
4566 {
4567 return;
4568 }
4569
4570 self.code_action_providers.push(provider);
4571 self.refresh_code_actions(window, cx);
4572 }
4573
4574 pub fn remove_code_action_provider(
4575 &mut self,
4576 id: Arc<str>,
4577 window: &mut Window,
4578 cx: &mut Context<Self>,
4579 ) {
4580 self.code_action_providers
4581 .retain(|provider| provider.id() != id);
4582 self.refresh_code_actions(window, cx);
4583 }
4584
4585 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4586 let buffer = self.buffer.read(cx);
4587 let newest_selection = self.selections.newest_anchor().clone();
4588 if newest_selection.head().diff_base_anchor.is_some() {
4589 return None;
4590 }
4591 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4592 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4593 if start_buffer != end_buffer {
4594 return None;
4595 }
4596
4597 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4598 cx.background_executor()
4599 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4600 .await;
4601
4602 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4603 let providers = this.code_action_providers.clone();
4604 let tasks = this
4605 .code_action_providers
4606 .iter()
4607 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4608 .collect::<Vec<_>>();
4609 (providers, tasks)
4610 })?;
4611
4612 let mut actions = Vec::new();
4613 for (provider, provider_actions) in
4614 providers.into_iter().zip(future::join_all(tasks).await)
4615 {
4616 if let Some(provider_actions) = provider_actions.log_err() {
4617 actions.extend(provider_actions.into_iter().map(|action| {
4618 AvailableCodeAction {
4619 excerpt_id: newest_selection.start.excerpt_id,
4620 action,
4621 provider: provider.clone(),
4622 }
4623 }));
4624 }
4625 }
4626
4627 this.update(&mut cx, |this, cx| {
4628 this.available_code_actions = if actions.is_empty() {
4629 None
4630 } else {
4631 Some((
4632 Location {
4633 buffer: start_buffer,
4634 range: start..end,
4635 },
4636 actions.into(),
4637 ))
4638 };
4639 cx.notify();
4640 })
4641 }));
4642 None
4643 }
4644
4645 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4646 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4647 self.show_git_blame_inline = false;
4648
4649 self.show_git_blame_inline_delay_task =
4650 Some(cx.spawn_in(window, |this, mut cx| async move {
4651 cx.background_executor().timer(delay).await;
4652
4653 this.update(&mut cx, |this, cx| {
4654 this.show_git_blame_inline = true;
4655 cx.notify();
4656 })
4657 .log_err();
4658 }));
4659 }
4660 }
4661
4662 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4663 if self.pending_rename.is_some() {
4664 return None;
4665 }
4666
4667 let provider = self.semantics_provider.clone()?;
4668 let buffer = self.buffer.read(cx);
4669 let newest_selection = self.selections.newest_anchor().clone();
4670 let cursor_position = newest_selection.head();
4671 let (cursor_buffer, cursor_buffer_position) =
4672 buffer.text_anchor_for_position(cursor_position, cx)?;
4673 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4674 if cursor_buffer != tail_buffer {
4675 return None;
4676 }
4677 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4678 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4679 cx.background_executor()
4680 .timer(Duration::from_millis(debounce))
4681 .await;
4682
4683 let highlights = if let Some(highlights) = cx
4684 .update(|cx| {
4685 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4686 })
4687 .ok()
4688 .flatten()
4689 {
4690 highlights.await.log_err()
4691 } else {
4692 None
4693 };
4694
4695 if let Some(highlights) = highlights {
4696 this.update(&mut cx, |this, cx| {
4697 if this.pending_rename.is_some() {
4698 return;
4699 }
4700
4701 let buffer_id = cursor_position.buffer_id;
4702 let buffer = this.buffer.read(cx);
4703 if !buffer
4704 .text_anchor_for_position(cursor_position, cx)
4705 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4706 {
4707 return;
4708 }
4709
4710 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4711 let mut write_ranges = Vec::new();
4712 let mut read_ranges = Vec::new();
4713 for highlight in highlights {
4714 for (excerpt_id, excerpt_range) in
4715 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4716 {
4717 let start = highlight
4718 .range
4719 .start
4720 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4721 let end = highlight
4722 .range
4723 .end
4724 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4725 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4726 continue;
4727 }
4728
4729 let range = Anchor {
4730 buffer_id,
4731 excerpt_id,
4732 text_anchor: start,
4733 diff_base_anchor: None,
4734 }..Anchor {
4735 buffer_id,
4736 excerpt_id,
4737 text_anchor: end,
4738 diff_base_anchor: None,
4739 };
4740 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4741 write_ranges.push(range);
4742 } else {
4743 read_ranges.push(range);
4744 }
4745 }
4746 }
4747
4748 this.highlight_background::<DocumentHighlightRead>(
4749 &read_ranges,
4750 |theme| theme.editor_document_highlight_read_background,
4751 cx,
4752 );
4753 this.highlight_background::<DocumentHighlightWrite>(
4754 &write_ranges,
4755 |theme| theme.editor_document_highlight_write_background,
4756 cx,
4757 );
4758 cx.notify();
4759 })
4760 .log_err();
4761 }
4762 }));
4763 None
4764 }
4765
4766 pub fn refresh_selected_text_highlights(
4767 &mut self,
4768 window: &mut Window,
4769 cx: &mut Context<Editor>,
4770 ) {
4771 self.selection_highlight_task.take();
4772 if !EditorSettings::get_global(cx).selection_highlight {
4773 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4774 return;
4775 }
4776 if self.selections.count() != 1 || self.selections.line_mode {
4777 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4778 return;
4779 }
4780 let selection = self.selections.newest::<Point>(cx);
4781 if selection.is_empty() || selection.start.row != selection.end.row {
4782 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4783 return;
4784 }
4785 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4786 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4787 cx.background_executor()
4788 .timer(Duration::from_millis(debounce))
4789 .await;
4790 let Some(matches_task) = editor
4791 .read_with(&mut cx, |editor, cx| {
4792 let buffer = editor.buffer().read(cx).snapshot(cx);
4793 cx.background_executor().spawn(async move {
4794 let mut ranges = Vec::new();
4795 let buffer_ranges =
4796 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
4797 let query = buffer.text_for_range(selection.range()).collect::<String>();
4798 for range in buffer_ranges {
4799 for (search_buffer, search_range, excerpt_id) in
4800 buffer.range_to_buffer_ranges(range)
4801 {
4802 ranges.extend(
4803 project::search::SearchQuery::text(
4804 query.clone(),
4805 false,
4806 false,
4807 false,
4808 Default::default(),
4809 Default::default(),
4810 None,
4811 )
4812 .unwrap()
4813 .search(search_buffer, Some(search_range.clone()))
4814 .await
4815 .into_iter()
4816 .map(|match_range| {
4817 let start = search_buffer
4818 .anchor_after(search_range.start + match_range.start);
4819 let end = search_buffer
4820 .anchor_before(search_range.start + match_range.end);
4821 Anchor::range_in_buffer(
4822 excerpt_id,
4823 search_buffer.remote_id(),
4824 start..end,
4825 )
4826 }),
4827 );
4828 }
4829 }
4830 ranges
4831 })
4832 })
4833 .log_err()
4834 else {
4835 return;
4836 };
4837 let matches = matches_task.await;
4838 editor
4839 .update_in(&mut cx, |editor, _, cx| {
4840 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4841 if !matches.is_empty() {
4842 editor.highlight_background::<SelectedTextHighlight>(
4843 &matches,
4844 |theme| theme.editor_document_highlight_bracket_background,
4845 cx,
4846 )
4847 }
4848 })
4849 .log_err();
4850 }));
4851 }
4852
4853 pub fn refresh_inline_completion(
4854 &mut self,
4855 debounce: bool,
4856 user_requested: bool,
4857 window: &mut Window,
4858 cx: &mut Context<Self>,
4859 ) -> Option<()> {
4860 let provider = self.edit_prediction_provider()?;
4861 let cursor = self.selections.newest_anchor().head();
4862 let (buffer, cursor_buffer_position) =
4863 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4864
4865 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4866 self.discard_inline_completion(false, cx);
4867 return None;
4868 }
4869
4870 if !user_requested
4871 && (!self.should_show_edit_predictions()
4872 || !self.is_focused(window)
4873 || buffer.read(cx).is_empty())
4874 {
4875 self.discard_inline_completion(false, cx);
4876 return None;
4877 }
4878
4879 self.update_visible_inline_completion(window, cx);
4880 provider.refresh(
4881 self.project.clone(),
4882 buffer,
4883 cursor_buffer_position,
4884 debounce,
4885 cx,
4886 );
4887 Some(())
4888 }
4889
4890 fn show_edit_predictions_in_menu(&self) -> bool {
4891 match self.edit_prediction_settings {
4892 EditPredictionSettings::Disabled => false,
4893 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4894 }
4895 }
4896
4897 pub fn edit_predictions_enabled(&self) -> bool {
4898 match self.edit_prediction_settings {
4899 EditPredictionSettings::Disabled => false,
4900 EditPredictionSettings::Enabled { .. } => true,
4901 }
4902 }
4903
4904 fn edit_prediction_requires_modifier(&self) -> bool {
4905 match self.edit_prediction_settings {
4906 EditPredictionSettings::Disabled => false,
4907 EditPredictionSettings::Enabled {
4908 preview_requires_modifier,
4909 ..
4910 } => preview_requires_modifier,
4911 }
4912 }
4913
4914 fn edit_prediction_settings_at_position(
4915 &self,
4916 buffer: &Entity<Buffer>,
4917 buffer_position: language::Anchor,
4918 cx: &App,
4919 ) -> EditPredictionSettings {
4920 if self.mode != EditorMode::Full
4921 || !self.show_inline_completions_override.unwrap_or(true)
4922 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4923 {
4924 return EditPredictionSettings::Disabled;
4925 }
4926
4927 let buffer = buffer.read(cx);
4928
4929 let file = buffer.file();
4930
4931 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4932 return EditPredictionSettings::Disabled;
4933 };
4934
4935 let by_provider = matches!(
4936 self.menu_inline_completions_policy,
4937 MenuInlineCompletionsPolicy::ByProvider
4938 );
4939
4940 let show_in_menu = by_provider
4941 && self
4942 .edit_prediction_provider
4943 .as_ref()
4944 .map_or(false, |provider| {
4945 provider.provider.show_completions_in_menu()
4946 });
4947
4948 let preview_requires_modifier =
4949 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4950
4951 EditPredictionSettings::Enabled {
4952 show_in_menu,
4953 preview_requires_modifier,
4954 }
4955 }
4956
4957 fn should_show_edit_predictions(&self) -> bool {
4958 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4959 }
4960
4961 pub fn edit_prediction_preview_is_active(&self) -> bool {
4962 matches!(
4963 self.edit_prediction_preview,
4964 EditPredictionPreview::Active { .. }
4965 )
4966 }
4967
4968 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4969 let cursor = self.selections.newest_anchor().head();
4970 if let Some((buffer, cursor_position)) =
4971 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4972 {
4973 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4974 } else {
4975 false
4976 }
4977 }
4978
4979 fn inline_completions_enabled_in_buffer(
4980 &self,
4981 buffer: &Entity<Buffer>,
4982 buffer_position: language::Anchor,
4983 cx: &App,
4984 ) -> bool {
4985 maybe!({
4986 let provider = self.edit_prediction_provider()?;
4987 if !provider.is_enabled(&buffer, buffer_position, cx) {
4988 return Some(false);
4989 }
4990 let buffer = buffer.read(cx);
4991 let Some(file) = buffer.file() else {
4992 return Some(true);
4993 };
4994 let settings = all_language_settings(Some(file), cx);
4995 Some(settings.inline_completions_enabled_for_path(file.path()))
4996 })
4997 .unwrap_or(false)
4998 }
4999
5000 fn cycle_inline_completion(
5001 &mut self,
5002 direction: Direction,
5003 window: &mut Window,
5004 cx: &mut Context<Self>,
5005 ) -> Option<()> {
5006 let provider = self.edit_prediction_provider()?;
5007 let cursor = self.selections.newest_anchor().head();
5008 let (buffer, cursor_buffer_position) =
5009 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5010 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5011 return None;
5012 }
5013
5014 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5015 self.update_visible_inline_completion(window, cx);
5016
5017 Some(())
5018 }
5019
5020 pub fn show_inline_completion(
5021 &mut self,
5022 _: &ShowEditPrediction,
5023 window: &mut Window,
5024 cx: &mut Context<Self>,
5025 ) {
5026 if !self.has_active_inline_completion() {
5027 self.refresh_inline_completion(false, true, window, cx);
5028 return;
5029 }
5030
5031 self.update_visible_inline_completion(window, cx);
5032 }
5033
5034 pub fn display_cursor_names(
5035 &mut self,
5036 _: &DisplayCursorNames,
5037 window: &mut Window,
5038 cx: &mut Context<Self>,
5039 ) {
5040 self.show_cursor_names(window, cx);
5041 }
5042
5043 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5044 self.show_cursor_names = true;
5045 cx.notify();
5046 cx.spawn_in(window, |this, mut cx| async move {
5047 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5048 this.update(&mut cx, |this, cx| {
5049 this.show_cursor_names = false;
5050 cx.notify()
5051 })
5052 .ok()
5053 })
5054 .detach();
5055 }
5056
5057 pub fn next_edit_prediction(
5058 &mut self,
5059 _: &NextEditPrediction,
5060 window: &mut Window,
5061 cx: &mut Context<Self>,
5062 ) {
5063 if self.has_active_inline_completion() {
5064 self.cycle_inline_completion(Direction::Next, window, cx);
5065 } else {
5066 let is_copilot_disabled = self
5067 .refresh_inline_completion(false, true, window, cx)
5068 .is_none();
5069 if is_copilot_disabled {
5070 cx.propagate();
5071 }
5072 }
5073 }
5074
5075 pub fn previous_edit_prediction(
5076 &mut self,
5077 _: &PreviousEditPrediction,
5078 window: &mut Window,
5079 cx: &mut Context<Self>,
5080 ) {
5081 if self.has_active_inline_completion() {
5082 self.cycle_inline_completion(Direction::Prev, window, cx);
5083 } else {
5084 let is_copilot_disabled = self
5085 .refresh_inline_completion(false, true, window, cx)
5086 .is_none();
5087 if is_copilot_disabled {
5088 cx.propagate();
5089 }
5090 }
5091 }
5092
5093 pub fn accept_edit_prediction(
5094 &mut self,
5095 _: &AcceptEditPrediction,
5096 window: &mut Window,
5097 cx: &mut Context<Self>,
5098 ) {
5099 if self.show_edit_predictions_in_menu() {
5100 self.hide_context_menu(window, cx);
5101 }
5102
5103 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5104 return;
5105 };
5106
5107 self.report_inline_completion_event(
5108 active_inline_completion.completion_id.clone(),
5109 true,
5110 cx,
5111 );
5112
5113 match &active_inline_completion.completion {
5114 InlineCompletion::Move { target, .. } => {
5115 let target = *target;
5116
5117 if let Some(position_map) = &self.last_position_map {
5118 if position_map
5119 .visible_row_range
5120 .contains(&target.to_display_point(&position_map.snapshot).row())
5121 || !self.edit_prediction_requires_modifier()
5122 {
5123 // Note that this is also done in vim's handler of the Tab action.
5124 self.change_selections(
5125 Some(Autoscroll::newest()),
5126 window,
5127 cx,
5128 |selections| {
5129 selections.select_anchor_ranges([target..target]);
5130 },
5131 );
5132 self.clear_row_highlights::<EditPredictionPreview>();
5133
5134 self.edit_prediction_preview = EditPredictionPreview::Active {
5135 previous_scroll_position: None,
5136 };
5137 } else {
5138 self.edit_prediction_preview = EditPredictionPreview::Active {
5139 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5140 };
5141 self.highlight_rows::<EditPredictionPreview>(
5142 target..target,
5143 cx.theme().colors().editor_highlighted_line_background,
5144 true,
5145 cx,
5146 );
5147 self.request_autoscroll(Autoscroll::fit(), cx);
5148 }
5149 }
5150 }
5151 InlineCompletion::Edit { edits, .. } => {
5152 if let Some(provider) = self.edit_prediction_provider() {
5153 provider.accept(cx);
5154 }
5155
5156 let snapshot = self.buffer.read(cx).snapshot(cx);
5157 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5158
5159 self.buffer.update(cx, |buffer, cx| {
5160 buffer.edit(edits.iter().cloned(), None, cx)
5161 });
5162
5163 self.change_selections(None, window, cx, |s| {
5164 s.select_anchor_ranges([last_edit_end..last_edit_end])
5165 });
5166
5167 self.update_visible_inline_completion(window, cx);
5168 if self.active_inline_completion.is_none() {
5169 self.refresh_inline_completion(true, true, window, cx);
5170 }
5171
5172 cx.notify();
5173 }
5174 }
5175
5176 self.edit_prediction_requires_modifier_in_leading_space = false;
5177 }
5178
5179 pub fn accept_partial_inline_completion(
5180 &mut self,
5181 _: &AcceptPartialEditPrediction,
5182 window: &mut Window,
5183 cx: &mut Context<Self>,
5184 ) {
5185 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5186 return;
5187 };
5188 if self.selections.count() != 1 {
5189 return;
5190 }
5191
5192 self.report_inline_completion_event(
5193 active_inline_completion.completion_id.clone(),
5194 true,
5195 cx,
5196 );
5197
5198 match &active_inline_completion.completion {
5199 InlineCompletion::Move { target, .. } => {
5200 let target = *target;
5201 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5202 selections.select_anchor_ranges([target..target]);
5203 });
5204 }
5205 InlineCompletion::Edit { edits, .. } => {
5206 // Find an insertion that starts at the cursor position.
5207 let snapshot = self.buffer.read(cx).snapshot(cx);
5208 let cursor_offset = self.selections.newest::<usize>(cx).head();
5209 let insertion = edits.iter().find_map(|(range, text)| {
5210 let range = range.to_offset(&snapshot);
5211 if range.is_empty() && range.start == cursor_offset {
5212 Some(text)
5213 } else {
5214 None
5215 }
5216 });
5217
5218 if let Some(text) = insertion {
5219 let mut partial_completion = text
5220 .chars()
5221 .by_ref()
5222 .take_while(|c| c.is_alphabetic())
5223 .collect::<String>();
5224 if partial_completion.is_empty() {
5225 partial_completion = text
5226 .chars()
5227 .by_ref()
5228 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5229 .collect::<String>();
5230 }
5231
5232 cx.emit(EditorEvent::InputHandled {
5233 utf16_range_to_replace: None,
5234 text: partial_completion.clone().into(),
5235 });
5236
5237 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5238
5239 self.refresh_inline_completion(true, true, window, cx);
5240 cx.notify();
5241 } else {
5242 self.accept_edit_prediction(&Default::default(), window, cx);
5243 }
5244 }
5245 }
5246 }
5247
5248 fn discard_inline_completion(
5249 &mut self,
5250 should_report_inline_completion_event: bool,
5251 cx: &mut Context<Self>,
5252 ) -> bool {
5253 if should_report_inline_completion_event {
5254 let completion_id = self
5255 .active_inline_completion
5256 .as_ref()
5257 .and_then(|active_completion| active_completion.completion_id.clone());
5258
5259 self.report_inline_completion_event(completion_id, false, cx);
5260 }
5261
5262 if let Some(provider) = self.edit_prediction_provider() {
5263 provider.discard(cx);
5264 }
5265
5266 self.take_active_inline_completion(cx)
5267 }
5268
5269 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5270 let Some(provider) = self.edit_prediction_provider() else {
5271 return;
5272 };
5273
5274 let Some((_, buffer, _)) = self
5275 .buffer
5276 .read(cx)
5277 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5278 else {
5279 return;
5280 };
5281
5282 let extension = buffer
5283 .read(cx)
5284 .file()
5285 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5286
5287 let event_type = match accepted {
5288 true => "Edit Prediction Accepted",
5289 false => "Edit Prediction Discarded",
5290 };
5291 telemetry::event!(
5292 event_type,
5293 provider = provider.name(),
5294 prediction_id = id,
5295 suggestion_accepted = accepted,
5296 file_extension = extension,
5297 );
5298 }
5299
5300 pub fn has_active_inline_completion(&self) -> bool {
5301 self.active_inline_completion.is_some()
5302 }
5303
5304 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5305 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5306 return false;
5307 };
5308
5309 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5310 self.clear_highlights::<InlineCompletionHighlight>(cx);
5311 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5312 true
5313 }
5314
5315 /// Returns true when we're displaying the edit prediction popover below the cursor
5316 /// like we are not previewing and the LSP autocomplete menu is visible
5317 /// or we are in `when_holding_modifier` mode.
5318 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5319 if self.edit_prediction_preview_is_active()
5320 || !self.show_edit_predictions_in_menu()
5321 || !self.edit_predictions_enabled()
5322 {
5323 return false;
5324 }
5325
5326 if self.has_visible_completions_menu() {
5327 return true;
5328 }
5329
5330 has_completion && self.edit_prediction_requires_modifier()
5331 }
5332
5333 fn handle_modifiers_changed(
5334 &mut self,
5335 modifiers: Modifiers,
5336 position_map: &PositionMap,
5337 window: &mut Window,
5338 cx: &mut Context<Self>,
5339 ) {
5340 if self.show_edit_predictions_in_menu() {
5341 self.update_edit_prediction_preview(&modifiers, window, cx);
5342 }
5343
5344 let mouse_position = window.mouse_position();
5345 if !position_map.text_hitbox.is_hovered(window) {
5346 return;
5347 }
5348
5349 self.update_hovered_link(
5350 position_map.point_for_position(mouse_position),
5351 &position_map.snapshot,
5352 modifiers,
5353 window,
5354 cx,
5355 )
5356 }
5357
5358 fn update_edit_prediction_preview(
5359 &mut self,
5360 modifiers: &Modifiers,
5361 window: &mut Window,
5362 cx: &mut Context<Self>,
5363 ) {
5364 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5365 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5366 return;
5367 };
5368
5369 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5370 if matches!(
5371 self.edit_prediction_preview,
5372 EditPredictionPreview::Inactive
5373 ) {
5374 self.edit_prediction_preview = EditPredictionPreview::Active {
5375 previous_scroll_position: None,
5376 };
5377
5378 self.update_visible_inline_completion(window, cx);
5379 cx.notify();
5380 }
5381 } else if let EditPredictionPreview::Active {
5382 previous_scroll_position,
5383 } = self.edit_prediction_preview
5384 {
5385 if let (Some(previous_scroll_position), Some(position_map)) =
5386 (previous_scroll_position, self.last_position_map.as_ref())
5387 {
5388 self.set_scroll_position(
5389 previous_scroll_position
5390 .scroll_position(&position_map.snapshot.display_snapshot),
5391 window,
5392 cx,
5393 );
5394 }
5395
5396 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5397 self.clear_row_highlights::<EditPredictionPreview>();
5398 self.update_visible_inline_completion(window, cx);
5399 cx.notify();
5400 }
5401 }
5402
5403 fn update_visible_inline_completion(
5404 &mut self,
5405 _window: &mut Window,
5406 cx: &mut Context<Self>,
5407 ) -> Option<()> {
5408 let selection = self.selections.newest_anchor();
5409 let cursor = selection.head();
5410 let multibuffer = self.buffer.read(cx).snapshot(cx);
5411 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5412 let excerpt_id = cursor.excerpt_id;
5413
5414 let show_in_menu = self.show_edit_predictions_in_menu();
5415 let completions_menu_has_precedence = !show_in_menu
5416 && (self.context_menu.borrow().is_some()
5417 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5418
5419 if completions_menu_has_precedence
5420 || !offset_selection.is_empty()
5421 || self
5422 .active_inline_completion
5423 .as_ref()
5424 .map_or(false, |completion| {
5425 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5426 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5427 !invalidation_range.contains(&offset_selection.head())
5428 })
5429 {
5430 self.discard_inline_completion(false, cx);
5431 return None;
5432 }
5433
5434 self.take_active_inline_completion(cx);
5435 let Some(provider) = self.edit_prediction_provider() else {
5436 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5437 return None;
5438 };
5439
5440 let (buffer, cursor_buffer_position) =
5441 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5442
5443 self.edit_prediction_settings =
5444 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5445
5446 self.edit_prediction_cursor_on_leading_whitespace =
5447 multibuffer.is_line_whitespace_upto(cursor);
5448
5449 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5450 let edits = inline_completion
5451 .edits
5452 .into_iter()
5453 .flat_map(|(range, new_text)| {
5454 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5455 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5456 Some((start..end, new_text))
5457 })
5458 .collect::<Vec<_>>();
5459 if edits.is_empty() {
5460 return None;
5461 }
5462
5463 let first_edit_start = edits.first().unwrap().0.start;
5464 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5465 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5466
5467 let last_edit_end = edits.last().unwrap().0.end;
5468 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5469 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5470
5471 let cursor_row = cursor.to_point(&multibuffer).row;
5472
5473 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5474
5475 let mut inlay_ids = Vec::new();
5476 let invalidation_row_range;
5477 let move_invalidation_row_range = if cursor_row < edit_start_row {
5478 Some(cursor_row..edit_end_row)
5479 } else if cursor_row > edit_end_row {
5480 Some(edit_start_row..cursor_row)
5481 } else {
5482 None
5483 };
5484 let is_move =
5485 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5486 let completion = if is_move {
5487 invalidation_row_range =
5488 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5489 let target = first_edit_start;
5490 InlineCompletion::Move { target, snapshot }
5491 } else {
5492 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5493 && !self.inline_completions_hidden_for_vim_mode;
5494
5495 if show_completions_in_buffer {
5496 if edits
5497 .iter()
5498 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5499 {
5500 let mut inlays = Vec::new();
5501 for (range, new_text) in &edits {
5502 let inlay = Inlay::inline_completion(
5503 post_inc(&mut self.next_inlay_id),
5504 range.start,
5505 new_text.as_str(),
5506 );
5507 inlay_ids.push(inlay.id);
5508 inlays.push(inlay);
5509 }
5510
5511 self.splice_inlays(&[], inlays, cx);
5512 } else {
5513 let background_color = cx.theme().status().deleted_background;
5514 self.highlight_text::<InlineCompletionHighlight>(
5515 edits.iter().map(|(range, _)| range.clone()).collect(),
5516 HighlightStyle {
5517 background_color: Some(background_color),
5518 ..Default::default()
5519 },
5520 cx,
5521 );
5522 }
5523 }
5524
5525 invalidation_row_range = edit_start_row..edit_end_row;
5526
5527 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5528 if provider.show_tab_accept_marker() {
5529 EditDisplayMode::TabAccept
5530 } else {
5531 EditDisplayMode::Inline
5532 }
5533 } else {
5534 EditDisplayMode::DiffPopover
5535 };
5536
5537 InlineCompletion::Edit {
5538 edits,
5539 edit_preview: inline_completion.edit_preview,
5540 display_mode,
5541 snapshot,
5542 }
5543 };
5544
5545 let invalidation_range = multibuffer
5546 .anchor_before(Point::new(invalidation_row_range.start, 0))
5547 ..multibuffer.anchor_after(Point::new(
5548 invalidation_row_range.end,
5549 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5550 ));
5551
5552 self.stale_inline_completion_in_menu = None;
5553 self.active_inline_completion = Some(InlineCompletionState {
5554 inlay_ids,
5555 completion,
5556 completion_id: inline_completion.id,
5557 invalidation_range,
5558 });
5559
5560 cx.notify();
5561
5562 Some(())
5563 }
5564
5565 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5566 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5567 }
5568
5569 fn render_code_actions_indicator(
5570 &self,
5571 _style: &EditorStyle,
5572 row: DisplayRow,
5573 is_active: bool,
5574 cx: &mut Context<Self>,
5575 ) -> Option<IconButton> {
5576 if self.available_code_actions.is_some() {
5577 Some(
5578 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5579 .shape(ui::IconButtonShape::Square)
5580 .icon_size(IconSize::XSmall)
5581 .icon_color(Color::Muted)
5582 .toggle_state(is_active)
5583 .tooltip({
5584 let focus_handle = self.focus_handle.clone();
5585 move |window, cx| {
5586 Tooltip::for_action_in(
5587 "Toggle Code Actions",
5588 &ToggleCodeActions {
5589 deployed_from_indicator: None,
5590 },
5591 &focus_handle,
5592 window,
5593 cx,
5594 )
5595 }
5596 })
5597 .on_click(cx.listener(move |editor, _e, window, cx| {
5598 window.focus(&editor.focus_handle(cx));
5599 editor.toggle_code_actions(
5600 &ToggleCodeActions {
5601 deployed_from_indicator: Some(row),
5602 },
5603 window,
5604 cx,
5605 );
5606 })),
5607 )
5608 } else {
5609 None
5610 }
5611 }
5612
5613 fn clear_tasks(&mut self) {
5614 self.tasks.clear()
5615 }
5616
5617 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5618 if self.tasks.insert(key, value).is_some() {
5619 // This case should hopefully be rare, but just in case...
5620 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5621 }
5622 }
5623
5624 fn build_tasks_context(
5625 project: &Entity<Project>,
5626 buffer: &Entity<Buffer>,
5627 buffer_row: u32,
5628 tasks: &Arc<RunnableTasks>,
5629 cx: &mut Context<Self>,
5630 ) -> Task<Option<task::TaskContext>> {
5631 let position = Point::new(buffer_row, tasks.column);
5632 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5633 let location = Location {
5634 buffer: buffer.clone(),
5635 range: range_start..range_start,
5636 };
5637 // Fill in the environmental variables from the tree-sitter captures
5638 let mut captured_task_variables = TaskVariables::default();
5639 for (capture_name, value) in tasks.extra_variables.clone() {
5640 captured_task_variables.insert(
5641 task::VariableName::Custom(capture_name.into()),
5642 value.clone(),
5643 );
5644 }
5645 project.update(cx, |project, cx| {
5646 project.task_store().update(cx, |task_store, cx| {
5647 task_store.task_context_for_location(captured_task_variables, location, cx)
5648 })
5649 })
5650 }
5651
5652 pub fn spawn_nearest_task(
5653 &mut self,
5654 action: &SpawnNearestTask,
5655 window: &mut Window,
5656 cx: &mut Context<Self>,
5657 ) {
5658 let Some((workspace, _)) = self.workspace.clone() else {
5659 return;
5660 };
5661 let Some(project) = self.project.clone() else {
5662 return;
5663 };
5664
5665 // Try to find a closest, enclosing node using tree-sitter that has a
5666 // task
5667 let Some((buffer, buffer_row, tasks)) = self
5668 .find_enclosing_node_task(cx)
5669 // Or find the task that's closest in row-distance.
5670 .or_else(|| self.find_closest_task(cx))
5671 else {
5672 return;
5673 };
5674
5675 let reveal_strategy = action.reveal;
5676 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5677 cx.spawn_in(window, |_, mut cx| async move {
5678 let context = task_context.await?;
5679 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5680
5681 let resolved = resolved_task.resolved.as_mut()?;
5682 resolved.reveal = reveal_strategy;
5683
5684 workspace
5685 .update(&mut cx, |workspace, cx| {
5686 workspace::tasks::schedule_resolved_task(
5687 workspace,
5688 task_source_kind,
5689 resolved_task,
5690 false,
5691 cx,
5692 );
5693 })
5694 .ok()
5695 })
5696 .detach();
5697 }
5698
5699 fn find_closest_task(
5700 &mut self,
5701 cx: &mut Context<Self>,
5702 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5703 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5704
5705 let ((buffer_id, row), tasks) = self
5706 .tasks
5707 .iter()
5708 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5709
5710 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5711 let tasks = Arc::new(tasks.to_owned());
5712 Some((buffer, *row, tasks))
5713 }
5714
5715 fn find_enclosing_node_task(
5716 &mut self,
5717 cx: &mut Context<Self>,
5718 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5719 let snapshot = self.buffer.read(cx).snapshot(cx);
5720 let offset = self.selections.newest::<usize>(cx).head();
5721 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5722 let buffer_id = excerpt.buffer().remote_id();
5723
5724 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5725 let mut cursor = layer.node().walk();
5726
5727 while cursor.goto_first_child_for_byte(offset).is_some() {
5728 if cursor.node().end_byte() == offset {
5729 cursor.goto_next_sibling();
5730 }
5731 }
5732
5733 // Ascend to the smallest ancestor that contains the range and has a task.
5734 loop {
5735 let node = cursor.node();
5736 let node_range = node.byte_range();
5737 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5738
5739 // Check if this node contains our offset
5740 if node_range.start <= offset && node_range.end >= offset {
5741 // If it contains offset, check for task
5742 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5743 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5744 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5745 }
5746 }
5747
5748 if !cursor.goto_parent() {
5749 break;
5750 }
5751 }
5752 None
5753 }
5754
5755 fn render_run_indicator(
5756 &self,
5757 _style: &EditorStyle,
5758 is_active: bool,
5759 row: DisplayRow,
5760 cx: &mut Context<Self>,
5761 ) -> IconButton {
5762 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5763 .shape(ui::IconButtonShape::Square)
5764 .icon_size(IconSize::XSmall)
5765 .icon_color(Color::Muted)
5766 .toggle_state(is_active)
5767 .on_click(cx.listener(move |editor, _e, window, cx| {
5768 window.focus(&editor.focus_handle(cx));
5769 editor.toggle_code_actions(
5770 &ToggleCodeActions {
5771 deployed_from_indicator: Some(row),
5772 },
5773 window,
5774 cx,
5775 );
5776 }))
5777 }
5778
5779 pub fn context_menu_visible(&self) -> bool {
5780 !self.edit_prediction_preview_is_active()
5781 && self
5782 .context_menu
5783 .borrow()
5784 .as_ref()
5785 .map_or(false, |menu| menu.visible())
5786 }
5787
5788 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5789 self.context_menu
5790 .borrow()
5791 .as_ref()
5792 .map(|menu| menu.origin())
5793 }
5794
5795 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5796 px(30.)
5797 }
5798
5799 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5800 if self.read_only(cx) {
5801 cx.theme().players().read_only()
5802 } else {
5803 self.style.as_ref().unwrap().local_player
5804 }
5805 }
5806
5807 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5808 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5809 let accept_keystroke = accept_binding.keystroke()?;
5810
5811 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5812
5813 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5814 Color::Accent
5815 } else {
5816 Color::Muted
5817 };
5818
5819 h_flex()
5820 .px_0p5()
5821 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5822 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5823 .text_size(TextSize::XSmall.rems(cx))
5824 .child(h_flex().children(ui::render_modifiers(
5825 &accept_keystroke.modifiers,
5826 PlatformStyle::platform(),
5827 Some(modifiers_color),
5828 Some(IconSize::XSmall.rems().into()),
5829 true,
5830 )))
5831 .when(is_platform_style_mac, |parent| {
5832 parent.child(accept_keystroke.key.clone())
5833 })
5834 .when(!is_platform_style_mac, |parent| {
5835 parent.child(
5836 Key::new(
5837 util::capitalize(&accept_keystroke.key),
5838 Some(Color::Default),
5839 )
5840 .size(Some(IconSize::XSmall.rems().into())),
5841 )
5842 })
5843 .into()
5844 }
5845
5846 fn render_edit_prediction_line_popover(
5847 &self,
5848 label: impl Into<SharedString>,
5849 icon: Option<IconName>,
5850 window: &mut Window,
5851 cx: &App,
5852 ) -> Option<Div> {
5853 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5854
5855 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5856
5857 let result = h_flex()
5858 .gap_1()
5859 .border_1()
5860 .rounded_lg()
5861 .shadow_sm()
5862 .bg(bg_color)
5863 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5864 .py_0p5()
5865 .pl_1()
5866 .pr(padding_right)
5867 .children(self.render_edit_prediction_accept_keybind(window, cx))
5868 .child(Label::new(label).size(LabelSize::Small))
5869 .when_some(icon, |element, icon| {
5870 element.child(
5871 div()
5872 .mt(px(1.5))
5873 .child(Icon::new(icon).size(IconSize::Small)),
5874 )
5875 });
5876
5877 Some(result)
5878 }
5879
5880 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5881 let accent_color = cx.theme().colors().text_accent;
5882 let editor_bg_color = cx.theme().colors().editor_background;
5883 editor_bg_color.blend(accent_color.opacity(0.1))
5884 }
5885
5886 fn render_edit_prediction_cursor_popover(
5887 &self,
5888 min_width: Pixels,
5889 max_width: Pixels,
5890 cursor_point: Point,
5891 style: &EditorStyle,
5892 accept_keystroke: Option<&gpui::Keystroke>,
5893 _window: &Window,
5894 cx: &mut Context<Editor>,
5895 ) -> Option<AnyElement> {
5896 let provider = self.edit_prediction_provider.as_ref()?;
5897
5898 if provider.provider.needs_terms_acceptance(cx) {
5899 return Some(
5900 h_flex()
5901 .min_w(min_width)
5902 .flex_1()
5903 .px_2()
5904 .py_1()
5905 .gap_3()
5906 .elevation_2(cx)
5907 .hover(|style| style.bg(cx.theme().colors().element_hover))
5908 .id("accept-terms")
5909 .cursor_pointer()
5910 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5911 .on_click(cx.listener(|this, _event, window, cx| {
5912 cx.stop_propagation();
5913 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5914 window.dispatch_action(
5915 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5916 cx,
5917 );
5918 }))
5919 .child(
5920 h_flex()
5921 .flex_1()
5922 .gap_2()
5923 .child(Icon::new(IconName::ZedPredict))
5924 .child(Label::new("Accept Terms of Service"))
5925 .child(div().w_full())
5926 .child(
5927 Icon::new(IconName::ArrowUpRight)
5928 .color(Color::Muted)
5929 .size(IconSize::Small),
5930 )
5931 .into_any_element(),
5932 )
5933 .into_any(),
5934 );
5935 }
5936
5937 let is_refreshing = provider.provider.is_refreshing(cx);
5938
5939 fn pending_completion_container() -> Div {
5940 h_flex()
5941 .h_full()
5942 .flex_1()
5943 .gap_2()
5944 .child(Icon::new(IconName::ZedPredict))
5945 }
5946
5947 let completion = match &self.active_inline_completion {
5948 Some(completion) => match &completion.completion {
5949 InlineCompletion::Move {
5950 target, snapshot, ..
5951 } if !self.has_visible_completions_menu() => {
5952 use text::ToPoint as _;
5953
5954 return Some(
5955 h_flex()
5956 .px_2()
5957 .py_1()
5958 .elevation_2(cx)
5959 .border_color(cx.theme().colors().border)
5960 .rounded_tl(px(0.))
5961 .gap_2()
5962 .child(
5963 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5964 Icon::new(IconName::ZedPredictDown)
5965 } else {
5966 Icon::new(IconName::ZedPredictUp)
5967 },
5968 )
5969 .child(Label::new("Hold").size(LabelSize::Small))
5970 .child(h_flex().children(ui::render_modifiers(
5971 &accept_keystroke?.modifiers,
5972 PlatformStyle::platform(),
5973 Some(Color::Default),
5974 Some(IconSize::Small.rems().into()),
5975 false,
5976 )))
5977 .into_any(),
5978 );
5979 }
5980 _ => self.render_edit_prediction_cursor_popover_preview(
5981 completion,
5982 cursor_point,
5983 style,
5984 cx,
5985 )?,
5986 },
5987
5988 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5989 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5990 stale_completion,
5991 cursor_point,
5992 style,
5993 cx,
5994 )?,
5995
5996 None => {
5997 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5998 }
5999 },
6000
6001 None => pending_completion_container().child(Label::new("No Prediction")),
6002 };
6003
6004 let completion = if is_refreshing {
6005 completion
6006 .with_animation(
6007 "loading-completion",
6008 Animation::new(Duration::from_secs(2))
6009 .repeat()
6010 .with_easing(pulsating_between(0.4, 0.8)),
6011 |label, delta| label.opacity(delta),
6012 )
6013 .into_any_element()
6014 } else {
6015 completion.into_any_element()
6016 };
6017
6018 let has_completion = self.active_inline_completion.is_some();
6019
6020 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6021 Some(
6022 h_flex()
6023 .min_w(min_width)
6024 .max_w(max_width)
6025 .flex_1()
6026 .elevation_2(cx)
6027 .border_color(cx.theme().colors().border)
6028 .child(
6029 div()
6030 .flex_1()
6031 .py_1()
6032 .px_2()
6033 .overflow_hidden()
6034 .child(completion),
6035 )
6036 .when_some(accept_keystroke, |el, accept_keystroke| {
6037 if !accept_keystroke.modifiers.modified() {
6038 return el;
6039 }
6040
6041 el.child(
6042 h_flex()
6043 .h_full()
6044 .border_l_1()
6045 .rounded_r_lg()
6046 .border_color(cx.theme().colors().border)
6047 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6048 .gap_1()
6049 .py_1()
6050 .px_2()
6051 .child(
6052 h_flex()
6053 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6054 .when(is_platform_style_mac, |parent| parent.gap_1())
6055 .child(h_flex().children(ui::render_modifiers(
6056 &accept_keystroke.modifiers,
6057 PlatformStyle::platform(),
6058 Some(if !has_completion {
6059 Color::Muted
6060 } else {
6061 Color::Default
6062 }),
6063 None,
6064 false,
6065 ))),
6066 )
6067 .child(Label::new("Preview").into_any_element())
6068 .opacity(if has_completion { 1.0 } else { 0.4 }),
6069 )
6070 })
6071 .into_any(),
6072 )
6073 }
6074
6075 fn render_edit_prediction_cursor_popover_preview(
6076 &self,
6077 completion: &InlineCompletionState,
6078 cursor_point: Point,
6079 style: &EditorStyle,
6080 cx: &mut Context<Editor>,
6081 ) -> Option<Div> {
6082 use text::ToPoint as _;
6083
6084 fn render_relative_row_jump(
6085 prefix: impl Into<String>,
6086 current_row: u32,
6087 target_row: u32,
6088 ) -> Div {
6089 let (row_diff, arrow) = if target_row < current_row {
6090 (current_row - target_row, IconName::ArrowUp)
6091 } else {
6092 (target_row - current_row, IconName::ArrowDown)
6093 };
6094
6095 h_flex()
6096 .child(
6097 Label::new(format!("{}{}", prefix.into(), row_diff))
6098 .color(Color::Muted)
6099 .size(LabelSize::Small),
6100 )
6101 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6102 }
6103
6104 match &completion.completion {
6105 InlineCompletion::Move {
6106 target, snapshot, ..
6107 } => Some(
6108 h_flex()
6109 .px_2()
6110 .gap_2()
6111 .flex_1()
6112 .child(
6113 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6114 Icon::new(IconName::ZedPredictDown)
6115 } else {
6116 Icon::new(IconName::ZedPredictUp)
6117 },
6118 )
6119 .child(Label::new("Jump to Edit")),
6120 ),
6121
6122 InlineCompletion::Edit {
6123 edits,
6124 edit_preview,
6125 snapshot,
6126 display_mode: _,
6127 } => {
6128 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6129
6130 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6131 &snapshot,
6132 &edits,
6133 edit_preview.as_ref()?,
6134 true,
6135 cx,
6136 )
6137 .first_line_preview();
6138
6139 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6140 .with_highlights(&style.text, highlighted_edits.highlights);
6141
6142 let preview = h_flex()
6143 .gap_1()
6144 .min_w_16()
6145 .child(styled_text)
6146 .when(has_more_lines, |parent| parent.child("…"));
6147
6148 let left = if first_edit_row != cursor_point.row {
6149 render_relative_row_jump("", cursor_point.row, first_edit_row)
6150 .into_any_element()
6151 } else {
6152 Icon::new(IconName::ZedPredict).into_any_element()
6153 };
6154
6155 Some(
6156 h_flex()
6157 .h_full()
6158 .flex_1()
6159 .gap_2()
6160 .pr_1()
6161 .overflow_x_hidden()
6162 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6163 .child(left)
6164 .child(preview),
6165 )
6166 }
6167 }
6168 }
6169
6170 fn render_context_menu(
6171 &self,
6172 style: &EditorStyle,
6173 max_height_in_lines: u32,
6174 y_flipped: bool,
6175 window: &mut Window,
6176 cx: &mut Context<Editor>,
6177 ) -> Option<AnyElement> {
6178 let menu = self.context_menu.borrow();
6179 let menu = menu.as_ref()?;
6180 if !menu.visible() {
6181 return None;
6182 };
6183 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6184 }
6185
6186 fn render_context_menu_aside(
6187 &self,
6188 style: &EditorStyle,
6189 max_size: Size<Pixels>,
6190 cx: &mut Context<Editor>,
6191 ) -> Option<AnyElement> {
6192 self.context_menu.borrow().as_ref().and_then(|menu| {
6193 if menu.visible() {
6194 menu.render_aside(
6195 style,
6196 max_size,
6197 self.workspace.as_ref().map(|(w, _)| w.clone()),
6198 cx,
6199 )
6200 } else {
6201 None
6202 }
6203 })
6204 }
6205
6206 fn hide_context_menu(
6207 &mut self,
6208 window: &mut Window,
6209 cx: &mut Context<Self>,
6210 ) -> Option<CodeContextMenu> {
6211 cx.notify();
6212 self.completion_tasks.clear();
6213 let context_menu = self.context_menu.borrow_mut().take();
6214 self.stale_inline_completion_in_menu.take();
6215 self.update_visible_inline_completion(window, cx);
6216 context_menu
6217 }
6218
6219 fn show_snippet_choices(
6220 &mut self,
6221 choices: &Vec<String>,
6222 selection: Range<Anchor>,
6223 cx: &mut Context<Self>,
6224 ) {
6225 if selection.start.buffer_id.is_none() {
6226 return;
6227 }
6228 let buffer_id = selection.start.buffer_id.unwrap();
6229 let buffer = self.buffer().read(cx).buffer(buffer_id);
6230 let id = post_inc(&mut self.next_completion_id);
6231
6232 if let Some(buffer) = buffer {
6233 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6234 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6235 ));
6236 }
6237 }
6238
6239 pub fn insert_snippet(
6240 &mut self,
6241 insertion_ranges: &[Range<usize>],
6242 snippet: Snippet,
6243 window: &mut Window,
6244 cx: &mut Context<Self>,
6245 ) -> Result<()> {
6246 struct Tabstop<T> {
6247 is_end_tabstop: bool,
6248 ranges: Vec<Range<T>>,
6249 choices: Option<Vec<String>>,
6250 }
6251
6252 let tabstops = self.buffer.update(cx, |buffer, cx| {
6253 let snippet_text: Arc<str> = snippet.text.clone().into();
6254 buffer.edit(
6255 insertion_ranges
6256 .iter()
6257 .cloned()
6258 .map(|range| (range, snippet_text.clone())),
6259 Some(AutoindentMode::EachLine),
6260 cx,
6261 );
6262
6263 let snapshot = &*buffer.read(cx);
6264 let snippet = &snippet;
6265 snippet
6266 .tabstops
6267 .iter()
6268 .map(|tabstop| {
6269 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6270 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6271 });
6272 let mut tabstop_ranges = tabstop
6273 .ranges
6274 .iter()
6275 .flat_map(|tabstop_range| {
6276 let mut delta = 0_isize;
6277 insertion_ranges.iter().map(move |insertion_range| {
6278 let insertion_start = insertion_range.start as isize + delta;
6279 delta +=
6280 snippet.text.len() as isize - insertion_range.len() as isize;
6281
6282 let start = ((insertion_start + tabstop_range.start) as usize)
6283 .min(snapshot.len());
6284 let end = ((insertion_start + tabstop_range.end) as usize)
6285 .min(snapshot.len());
6286 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6287 })
6288 })
6289 .collect::<Vec<_>>();
6290 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6291
6292 Tabstop {
6293 is_end_tabstop,
6294 ranges: tabstop_ranges,
6295 choices: tabstop.choices.clone(),
6296 }
6297 })
6298 .collect::<Vec<_>>()
6299 });
6300 if let Some(tabstop) = tabstops.first() {
6301 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6302 s.select_ranges(tabstop.ranges.iter().cloned());
6303 });
6304
6305 if let Some(choices) = &tabstop.choices {
6306 if let Some(selection) = tabstop.ranges.first() {
6307 self.show_snippet_choices(choices, selection.clone(), cx)
6308 }
6309 }
6310
6311 // If we're already at the last tabstop and it's at the end of the snippet,
6312 // we're done, we don't need to keep the state around.
6313 if !tabstop.is_end_tabstop {
6314 let choices = tabstops
6315 .iter()
6316 .map(|tabstop| tabstop.choices.clone())
6317 .collect();
6318
6319 let ranges = tabstops
6320 .into_iter()
6321 .map(|tabstop| tabstop.ranges)
6322 .collect::<Vec<_>>();
6323
6324 self.snippet_stack.push(SnippetState {
6325 active_index: 0,
6326 ranges,
6327 choices,
6328 });
6329 }
6330
6331 // Check whether the just-entered snippet ends with an auto-closable bracket.
6332 if self.autoclose_regions.is_empty() {
6333 let snapshot = self.buffer.read(cx).snapshot(cx);
6334 for selection in &mut self.selections.all::<Point>(cx) {
6335 let selection_head = selection.head();
6336 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6337 continue;
6338 };
6339
6340 let mut bracket_pair = None;
6341 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6342 let prev_chars = snapshot
6343 .reversed_chars_at(selection_head)
6344 .collect::<String>();
6345 for (pair, enabled) in scope.brackets() {
6346 if enabled
6347 && pair.close
6348 && prev_chars.starts_with(pair.start.as_str())
6349 && next_chars.starts_with(pair.end.as_str())
6350 {
6351 bracket_pair = Some(pair.clone());
6352 break;
6353 }
6354 }
6355 if let Some(pair) = bracket_pair {
6356 let start = snapshot.anchor_after(selection_head);
6357 let end = snapshot.anchor_after(selection_head);
6358 self.autoclose_regions.push(AutocloseRegion {
6359 selection_id: selection.id,
6360 range: start..end,
6361 pair,
6362 });
6363 }
6364 }
6365 }
6366 }
6367 Ok(())
6368 }
6369
6370 pub fn move_to_next_snippet_tabstop(
6371 &mut self,
6372 window: &mut Window,
6373 cx: &mut Context<Self>,
6374 ) -> bool {
6375 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6376 }
6377
6378 pub fn move_to_prev_snippet_tabstop(
6379 &mut self,
6380 window: &mut Window,
6381 cx: &mut Context<Self>,
6382 ) -> bool {
6383 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6384 }
6385
6386 pub fn move_to_snippet_tabstop(
6387 &mut self,
6388 bias: Bias,
6389 window: &mut Window,
6390 cx: &mut Context<Self>,
6391 ) -> bool {
6392 if let Some(mut snippet) = self.snippet_stack.pop() {
6393 match bias {
6394 Bias::Left => {
6395 if snippet.active_index > 0 {
6396 snippet.active_index -= 1;
6397 } else {
6398 self.snippet_stack.push(snippet);
6399 return false;
6400 }
6401 }
6402 Bias::Right => {
6403 if snippet.active_index + 1 < snippet.ranges.len() {
6404 snippet.active_index += 1;
6405 } else {
6406 self.snippet_stack.push(snippet);
6407 return false;
6408 }
6409 }
6410 }
6411 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6412 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6413 s.select_anchor_ranges(current_ranges.iter().cloned())
6414 });
6415
6416 if let Some(choices) = &snippet.choices[snippet.active_index] {
6417 if let Some(selection) = current_ranges.first() {
6418 self.show_snippet_choices(&choices, selection.clone(), cx);
6419 }
6420 }
6421
6422 // If snippet state is not at the last tabstop, push it back on the stack
6423 if snippet.active_index + 1 < snippet.ranges.len() {
6424 self.snippet_stack.push(snippet);
6425 }
6426 return true;
6427 }
6428 }
6429
6430 false
6431 }
6432
6433 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6434 self.transact(window, cx, |this, window, cx| {
6435 this.select_all(&SelectAll, window, cx);
6436 this.insert("", window, cx);
6437 });
6438 }
6439
6440 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6441 self.transact(window, cx, |this, window, cx| {
6442 this.select_autoclose_pair(window, cx);
6443 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6444 if !this.linked_edit_ranges.is_empty() {
6445 let selections = this.selections.all::<MultiBufferPoint>(cx);
6446 let snapshot = this.buffer.read(cx).snapshot(cx);
6447
6448 for selection in selections.iter() {
6449 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6450 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6451 if selection_start.buffer_id != selection_end.buffer_id {
6452 continue;
6453 }
6454 if let Some(ranges) =
6455 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6456 {
6457 for (buffer, entries) in ranges {
6458 linked_ranges.entry(buffer).or_default().extend(entries);
6459 }
6460 }
6461 }
6462 }
6463
6464 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6465 if !this.selections.line_mode {
6466 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6467 for selection in &mut selections {
6468 if selection.is_empty() {
6469 let old_head = selection.head();
6470 let mut new_head =
6471 movement::left(&display_map, old_head.to_display_point(&display_map))
6472 .to_point(&display_map);
6473 if let Some((buffer, line_buffer_range)) = display_map
6474 .buffer_snapshot
6475 .buffer_line_for_row(MultiBufferRow(old_head.row))
6476 {
6477 let indent_size =
6478 buffer.indent_size_for_line(line_buffer_range.start.row);
6479 let indent_len = match indent_size.kind {
6480 IndentKind::Space => {
6481 buffer.settings_at(line_buffer_range.start, cx).tab_size
6482 }
6483 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6484 };
6485 if old_head.column <= indent_size.len && old_head.column > 0 {
6486 let indent_len = indent_len.get();
6487 new_head = cmp::min(
6488 new_head,
6489 MultiBufferPoint::new(
6490 old_head.row,
6491 ((old_head.column - 1) / indent_len) * indent_len,
6492 ),
6493 );
6494 }
6495 }
6496
6497 selection.set_head(new_head, SelectionGoal::None);
6498 }
6499 }
6500 }
6501
6502 this.signature_help_state.set_backspace_pressed(true);
6503 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6504 s.select(selections)
6505 });
6506 this.insert("", window, cx);
6507 let empty_str: Arc<str> = Arc::from("");
6508 for (buffer, edits) in linked_ranges {
6509 let snapshot = buffer.read(cx).snapshot();
6510 use text::ToPoint as TP;
6511
6512 let edits = edits
6513 .into_iter()
6514 .map(|range| {
6515 let end_point = TP::to_point(&range.end, &snapshot);
6516 let mut start_point = TP::to_point(&range.start, &snapshot);
6517
6518 if end_point == start_point {
6519 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6520 .saturating_sub(1);
6521 start_point =
6522 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6523 };
6524
6525 (start_point..end_point, empty_str.clone())
6526 })
6527 .sorted_by_key(|(range, _)| range.start)
6528 .collect::<Vec<_>>();
6529 buffer.update(cx, |this, cx| {
6530 this.edit(edits, None, cx);
6531 })
6532 }
6533 this.refresh_inline_completion(true, false, window, cx);
6534 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6535 });
6536 }
6537
6538 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6539 self.transact(window, cx, |this, window, cx| {
6540 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6541 let line_mode = s.line_mode;
6542 s.move_with(|map, selection| {
6543 if selection.is_empty() && !line_mode {
6544 let cursor = movement::right(map, selection.head());
6545 selection.end = cursor;
6546 selection.reversed = true;
6547 selection.goal = SelectionGoal::None;
6548 }
6549 })
6550 });
6551 this.insert("", window, cx);
6552 this.refresh_inline_completion(true, false, window, cx);
6553 });
6554 }
6555
6556 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6557 if self.move_to_prev_snippet_tabstop(window, cx) {
6558 return;
6559 }
6560
6561 self.outdent(&Outdent, window, cx);
6562 }
6563
6564 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6565 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6566 return;
6567 }
6568
6569 let mut selections = self.selections.all_adjusted(cx);
6570 let buffer = self.buffer.read(cx);
6571 let snapshot = buffer.snapshot(cx);
6572 let rows_iter = selections.iter().map(|s| s.head().row);
6573 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6574
6575 let mut edits = Vec::new();
6576 let mut prev_edited_row = 0;
6577 let mut row_delta = 0;
6578 for selection in &mut selections {
6579 if selection.start.row != prev_edited_row {
6580 row_delta = 0;
6581 }
6582 prev_edited_row = selection.end.row;
6583
6584 // If the selection is non-empty, then increase the indentation of the selected lines.
6585 if !selection.is_empty() {
6586 row_delta =
6587 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6588 continue;
6589 }
6590
6591 // If the selection is empty and the cursor is in the leading whitespace before the
6592 // suggested indentation, then auto-indent the line.
6593 let cursor = selection.head();
6594 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6595 if let Some(suggested_indent) =
6596 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6597 {
6598 if cursor.column < suggested_indent.len
6599 && cursor.column <= current_indent.len
6600 && current_indent.len <= suggested_indent.len
6601 {
6602 selection.start = Point::new(cursor.row, suggested_indent.len);
6603 selection.end = selection.start;
6604 if row_delta == 0 {
6605 edits.extend(Buffer::edit_for_indent_size_adjustment(
6606 cursor.row,
6607 current_indent,
6608 suggested_indent,
6609 ));
6610 row_delta = suggested_indent.len - current_indent.len;
6611 }
6612 continue;
6613 }
6614 }
6615
6616 // Otherwise, insert a hard or soft tab.
6617 let settings = buffer.settings_at(cursor, cx);
6618 let tab_size = if settings.hard_tabs {
6619 IndentSize::tab()
6620 } else {
6621 let tab_size = settings.tab_size.get();
6622 let char_column = snapshot
6623 .text_for_range(Point::new(cursor.row, 0)..cursor)
6624 .flat_map(str::chars)
6625 .count()
6626 + row_delta as usize;
6627 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6628 IndentSize::spaces(chars_to_next_tab_stop)
6629 };
6630 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6631 selection.end = selection.start;
6632 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6633 row_delta += tab_size.len;
6634 }
6635
6636 self.transact(window, cx, |this, window, cx| {
6637 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6638 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6639 s.select(selections)
6640 });
6641 this.refresh_inline_completion(true, false, window, cx);
6642 });
6643 }
6644
6645 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6646 if self.read_only(cx) {
6647 return;
6648 }
6649 let mut selections = self.selections.all::<Point>(cx);
6650 let mut prev_edited_row = 0;
6651 let mut row_delta = 0;
6652 let mut edits = Vec::new();
6653 let buffer = self.buffer.read(cx);
6654 let snapshot = buffer.snapshot(cx);
6655 for selection in &mut selections {
6656 if selection.start.row != prev_edited_row {
6657 row_delta = 0;
6658 }
6659 prev_edited_row = selection.end.row;
6660
6661 row_delta =
6662 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6663 }
6664
6665 self.transact(window, cx, |this, window, cx| {
6666 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6667 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6668 s.select(selections)
6669 });
6670 });
6671 }
6672
6673 fn indent_selection(
6674 buffer: &MultiBuffer,
6675 snapshot: &MultiBufferSnapshot,
6676 selection: &mut Selection<Point>,
6677 edits: &mut Vec<(Range<Point>, String)>,
6678 delta_for_start_row: u32,
6679 cx: &App,
6680 ) -> u32 {
6681 let settings = buffer.settings_at(selection.start, cx);
6682 let tab_size = settings.tab_size.get();
6683 let indent_kind = if settings.hard_tabs {
6684 IndentKind::Tab
6685 } else {
6686 IndentKind::Space
6687 };
6688 let mut start_row = selection.start.row;
6689 let mut end_row = selection.end.row + 1;
6690
6691 // If a selection ends at the beginning of a line, don't indent
6692 // that last line.
6693 if selection.end.column == 0 && selection.end.row > selection.start.row {
6694 end_row -= 1;
6695 }
6696
6697 // Avoid re-indenting a row that has already been indented by a
6698 // previous selection, but still update this selection's column
6699 // to reflect that indentation.
6700 if delta_for_start_row > 0 {
6701 start_row += 1;
6702 selection.start.column += delta_for_start_row;
6703 if selection.end.row == selection.start.row {
6704 selection.end.column += delta_for_start_row;
6705 }
6706 }
6707
6708 let mut delta_for_end_row = 0;
6709 let has_multiple_rows = start_row + 1 != end_row;
6710 for row in start_row..end_row {
6711 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6712 let indent_delta = match (current_indent.kind, indent_kind) {
6713 (IndentKind::Space, IndentKind::Space) => {
6714 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6715 IndentSize::spaces(columns_to_next_tab_stop)
6716 }
6717 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6718 (_, IndentKind::Tab) => IndentSize::tab(),
6719 };
6720
6721 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6722 0
6723 } else {
6724 selection.start.column
6725 };
6726 let row_start = Point::new(row, start);
6727 edits.push((
6728 row_start..row_start,
6729 indent_delta.chars().collect::<String>(),
6730 ));
6731
6732 // Update this selection's endpoints to reflect the indentation.
6733 if row == selection.start.row {
6734 selection.start.column += indent_delta.len;
6735 }
6736 if row == selection.end.row {
6737 selection.end.column += indent_delta.len;
6738 delta_for_end_row = indent_delta.len;
6739 }
6740 }
6741
6742 if selection.start.row == selection.end.row {
6743 delta_for_start_row + delta_for_end_row
6744 } else {
6745 delta_for_end_row
6746 }
6747 }
6748
6749 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6750 if self.read_only(cx) {
6751 return;
6752 }
6753 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6754 let selections = self.selections.all::<Point>(cx);
6755 let mut deletion_ranges = Vec::new();
6756 let mut last_outdent = None;
6757 {
6758 let buffer = self.buffer.read(cx);
6759 let snapshot = buffer.snapshot(cx);
6760 for selection in &selections {
6761 let settings = buffer.settings_at(selection.start, cx);
6762 let tab_size = settings.tab_size.get();
6763 let mut rows = selection.spanned_rows(false, &display_map);
6764
6765 // Avoid re-outdenting a row that has already been outdented by a
6766 // previous selection.
6767 if let Some(last_row) = last_outdent {
6768 if last_row == rows.start {
6769 rows.start = rows.start.next_row();
6770 }
6771 }
6772 let has_multiple_rows = rows.len() > 1;
6773 for row in rows.iter_rows() {
6774 let indent_size = snapshot.indent_size_for_line(row);
6775 if indent_size.len > 0 {
6776 let deletion_len = match indent_size.kind {
6777 IndentKind::Space => {
6778 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6779 if columns_to_prev_tab_stop == 0 {
6780 tab_size
6781 } else {
6782 columns_to_prev_tab_stop
6783 }
6784 }
6785 IndentKind::Tab => 1,
6786 };
6787 let start = if has_multiple_rows
6788 || deletion_len > selection.start.column
6789 || indent_size.len < selection.start.column
6790 {
6791 0
6792 } else {
6793 selection.start.column - deletion_len
6794 };
6795 deletion_ranges.push(
6796 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6797 );
6798 last_outdent = Some(row);
6799 }
6800 }
6801 }
6802 }
6803
6804 self.transact(window, cx, |this, window, cx| {
6805 this.buffer.update(cx, |buffer, cx| {
6806 let empty_str: Arc<str> = Arc::default();
6807 buffer.edit(
6808 deletion_ranges
6809 .into_iter()
6810 .map(|range| (range, empty_str.clone())),
6811 None,
6812 cx,
6813 );
6814 });
6815 let selections = this.selections.all::<usize>(cx);
6816 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6817 s.select(selections)
6818 });
6819 });
6820 }
6821
6822 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6823 if self.read_only(cx) {
6824 return;
6825 }
6826 let selections = self
6827 .selections
6828 .all::<usize>(cx)
6829 .into_iter()
6830 .map(|s| s.range());
6831
6832 self.transact(window, cx, |this, window, cx| {
6833 this.buffer.update(cx, |buffer, cx| {
6834 buffer.autoindent_ranges(selections, cx);
6835 });
6836 let selections = this.selections.all::<usize>(cx);
6837 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6838 s.select(selections)
6839 });
6840 });
6841 }
6842
6843 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6845 let selections = self.selections.all::<Point>(cx);
6846
6847 let mut new_cursors = Vec::new();
6848 let mut edit_ranges = Vec::new();
6849 let mut selections = selections.iter().peekable();
6850 while let Some(selection) = selections.next() {
6851 let mut rows = selection.spanned_rows(false, &display_map);
6852 let goal_display_column = selection.head().to_display_point(&display_map).column();
6853
6854 // Accumulate contiguous regions of rows that we want to delete.
6855 while let Some(next_selection) = selections.peek() {
6856 let next_rows = next_selection.spanned_rows(false, &display_map);
6857 if next_rows.start <= rows.end {
6858 rows.end = next_rows.end;
6859 selections.next().unwrap();
6860 } else {
6861 break;
6862 }
6863 }
6864
6865 let buffer = &display_map.buffer_snapshot;
6866 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6867 let edit_end;
6868 let cursor_buffer_row;
6869 if buffer.max_point().row >= rows.end.0 {
6870 // If there's a line after the range, delete the \n from the end of the row range
6871 // and position the cursor on the next line.
6872 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6873 cursor_buffer_row = rows.end;
6874 } else {
6875 // If there isn't a line after the range, delete the \n from the line before the
6876 // start of the row range and position the cursor there.
6877 edit_start = edit_start.saturating_sub(1);
6878 edit_end = buffer.len();
6879 cursor_buffer_row = rows.start.previous_row();
6880 }
6881
6882 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6883 *cursor.column_mut() =
6884 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6885
6886 new_cursors.push((
6887 selection.id,
6888 buffer.anchor_after(cursor.to_point(&display_map)),
6889 ));
6890 edit_ranges.push(edit_start..edit_end);
6891 }
6892
6893 self.transact(window, cx, |this, window, cx| {
6894 let buffer = this.buffer.update(cx, |buffer, cx| {
6895 let empty_str: Arc<str> = Arc::default();
6896 buffer.edit(
6897 edit_ranges
6898 .into_iter()
6899 .map(|range| (range, empty_str.clone())),
6900 None,
6901 cx,
6902 );
6903 buffer.snapshot(cx)
6904 });
6905 let new_selections = new_cursors
6906 .into_iter()
6907 .map(|(id, cursor)| {
6908 let cursor = cursor.to_point(&buffer);
6909 Selection {
6910 id,
6911 start: cursor,
6912 end: cursor,
6913 reversed: false,
6914 goal: SelectionGoal::None,
6915 }
6916 })
6917 .collect();
6918
6919 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6920 s.select(new_selections);
6921 });
6922 });
6923 }
6924
6925 pub fn join_lines_impl(
6926 &mut self,
6927 insert_whitespace: bool,
6928 window: &mut Window,
6929 cx: &mut Context<Self>,
6930 ) {
6931 if self.read_only(cx) {
6932 return;
6933 }
6934 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6935 for selection in self.selections.all::<Point>(cx) {
6936 let start = MultiBufferRow(selection.start.row);
6937 // Treat single line selections as if they include the next line. Otherwise this action
6938 // would do nothing for single line selections individual cursors.
6939 let end = if selection.start.row == selection.end.row {
6940 MultiBufferRow(selection.start.row + 1)
6941 } else {
6942 MultiBufferRow(selection.end.row)
6943 };
6944
6945 if let Some(last_row_range) = row_ranges.last_mut() {
6946 if start <= last_row_range.end {
6947 last_row_range.end = end;
6948 continue;
6949 }
6950 }
6951 row_ranges.push(start..end);
6952 }
6953
6954 let snapshot = self.buffer.read(cx).snapshot(cx);
6955 let mut cursor_positions = Vec::new();
6956 for row_range in &row_ranges {
6957 let anchor = snapshot.anchor_before(Point::new(
6958 row_range.end.previous_row().0,
6959 snapshot.line_len(row_range.end.previous_row()),
6960 ));
6961 cursor_positions.push(anchor..anchor);
6962 }
6963
6964 self.transact(window, cx, |this, window, cx| {
6965 for row_range in row_ranges.into_iter().rev() {
6966 for row in row_range.iter_rows().rev() {
6967 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6968 let next_line_row = row.next_row();
6969 let indent = snapshot.indent_size_for_line(next_line_row);
6970 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6971
6972 let replace =
6973 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6974 " "
6975 } else {
6976 ""
6977 };
6978
6979 this.buffer.update(cx, |buffer, cx| {
6980 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6981 });
6982 }
6983 }
6984
6985 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6986 s.select_anchor_ranges(cursor_positions)
6987 });
6988 });
6989 }
6990
6991 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6992 self.join_lines_impl(true, window, cx);
6993 }
6994
6995 pub fn sort_lines_case_sensitive(
6996 &mut self,
6997 _: &SortLinesCaseSensitive,
6998 window: &mut Window,
6999 cx: &mut Context<Self>,
7000 ) {
7001 self.manipulate_lines(window, cx, |lines| lines.sort())
7002 }
7003
7004 pub fn sort_lines_case_insensitive(
7005 &mut self,
7006 _: &SortLinesCaseInsensitive,
7007 window: &mut Window,
7008 cx: &mut Context<Self>,
7009 ) {
7010 self.manipulate_lines(window, cx, |lines| {
7011 lines.sort_by_key(|line| line.to_lowercase())
7012 })
7013 }
7014
7015 pub fn unique_lines_case_insensitive(
7016 &mut self,
7017 _: &UniqueLinesCaseInsensitive,
7018 window: &mut Window,
7019 cx: &mut Context<Self>,
7020 ) {
7021 self.manipulate_lines(window, cx, |lines| {
7022 let mut seen = HashSet::default();
7023 lines.retain(|line| seen.insert(line.to_lowercase()));
7024 })
7025 }
7026
7027 pub fn unique_lines_case_sensitive(
7028 &mut self,
7029 _: &UniqueLinesCaseSensitive,
7030 window: &mut Window,
7031 cx: &mut Context<Self>,
7032 ) {
7033 self.manipulate_lines(window, cx, |lines| {
7034 let mut seen = HashSet::default();
7035 lines.retain(|line| seen.insert(*line));
7036 })
7037 }
7038
7039 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7040 let mut revert_changes = HashMap::default();
7041 let snapshot = self.snapshot(window, cx);
7042 for hunk in snapshot
7043 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7044 {
7045 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7046 }
7047 if !revert_changes.is_empty() {
7048 self.transact(window, cx, |editor, window, cx| {
7049 editor.revert(revert_changes, window, cx);
7050 });
7051 }
7052 }
7053
7054 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7055 let Some(project) = self.project.clone() else {
7056 return;
7057 };
7058 self.reload(project, window, cx)
7059 .detach_and_notify_err(window, cx);
7060 }
7061
7062 pub fn revert_selected_hunks(
7063 &mut self,
7064 _: &RevertSelectedHunks,
7065 window: &mut Window,
7066 cx: &mut Context<Self>,
7067 ) {
7068 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7069 self.discard_hunks_in_ranges(selections, window, cx);
7070 }
7071
7072 fn discard_hunks_in_ranges(
7073 &mut self,
7074 ranges: impl Iterator<Item = Range<Point>>,
7075 window: &mut Window,
7076 cx: &mut Context<Editor>,
7077 ) {
7078 let mut revert_changes = HashMap::default();
7079 let snapshot = self.snapshot(window, cx);
7080 for hunk in &snapshot.hunks_for_ranges(ranges) {
7081 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7082 }
7083 if !revert_changes.is_empty() {
7084 self.transact(window, cx, |editor, window, cx| {
7085 editor.revert(revert_changes, window, cx);
7086 });
7087 }
7088 }
7089
7090 pub fn open_active_item_in_terminal(
7091 &mut self,
7092 _: &OpenInTerminal,
7093 window: &mut Window,
7094 cx: &mut Context<Self>,
7095 ) {
7096 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7097 let project_path = buffer.read(cx).project_path(cx)?;
7098 let project = self.project.as_ref()?.read(cx);
7099 let entry = project.entry_for_path(&project_path, cx)?;
7100 let parent = match &entry.canonical_path {
7101 Some(canonical_path) => canonical_path.to_path_buf(),
7102 None => project.absolute_path(&project_path, cx)?,
7103 }
7104 .parent()?
7105 .to_path_buf();
7106 Some(parent)
7107 }) {
7108 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7109 }
7110 }
7111
7112 pub fn prepare_revert_change(
7113 &self,
7114 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7115 hunk: &MultiBufferDiffHunk,
7116 cx: &mut App,
7117 ) -> Option<()> {
7118 let buffer = self.buffer.read(cx);
7119 let diff = buffer.diff_for(hunk.buffer_id)?;
7120 let buffer = buffer.buffer(hunk.buffer_id)?;
7121 let buffer = buffer.read(cx);
7122 let original_text = diff
7123 .read(cx)
7124 .base_text()
7125 .as_ref()?
7126 .as_rope()
7127 .slice(hunk.diff_base_byte_range.clone());
7128 let buffer_snapshot = buffer.snapshot();
7129 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7130 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7131 probe
7132 .0
7133 .start
7134 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7135 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7136 }) {
7137 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7138 Some(())
7139 } else {
7140 None
7141 }
7142 }
7143
7144 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7145 self.manipulate_lines(window, cx, |lines| lines.reverse())
7146 }
7147
7148 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7149 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7150 }
7151
7152 fn manipulate_lines<Fn>(
7153 &mut self,
7154 window: &mut Window,
7155 cx: &mut Context<Self>,
7156 mut callback: Fn,
7157 ) where
7158 Fn: FnMut(&mut Vec<&str>),
7159 {
7160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7161 let buffer = self.buffer.read(cx).snapshot(cx);
7162
7163 let mut edits = Vec::new();
7164
7165 let selections = self.selections.all::<Point>(cx);
7166 let mut selections = selections.iter().peekable();
7167 let mut contiguous_row_selections = Vec::new();
7168 let mut new_selections = Vec::new();
7169 let mut added_lines = 0;
7170 let mut removed_lines = 0;
7171
7172 while let Some(selection) = selections.next() {
7173 let (start_row, end_row) = consume_contiguous_rows(
7174 &mut contiguous_row_selections,
7175 selection,
7176 &display_map,
7177 &mut selections,
7178 );
7179
7180 let start_point = Point::new(start_row.0, 0);
7181 let end_point = Point::new(
7182 end_row.previous_row().0,
7183 buffer.line_len(end_row.previous_row()),
7184 );
7185 let text = buffer
7186 .text_for_range(start_point..end_point)
7187 .collect::<String>();
7188
7189 let mut lines = text.split('\n').collect_vec();
7190
7191 let lines_before = lines.len();
7192 callback(&mut lines);
7193 let lines_after = lines.len();
7194
7195 edits.push((start_point..end_point, lines.join("\n")));
7196
7197 // Selections must change based on added and removed line count
7198 let start_row =
7199 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7200 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7201 new_selections.push(Selection {
7202 id: selection.id,
7203 start: start_row,
7204 end: end_row,
7205 goal: SelectionGoal::None,
7206 reversed: selection.reversed,
7207 });
7208
7209 if lines_after > lines_before {
7210 added_lines += lines_after - lines_before;
7211 } else if lines_before > lines_after {
7212 removed_lines += lines_before - lines_after;
7213 }
7214 }
7215
7216 self.transact(window, cx, |this, window, cx| {
7217 let buffer = this.buffer.update(cx, |buffer, cx| {
7218 buffer.edit(edits, None, cx);
7219 buffer.snapshot(cx)
7220 });
7221
7222 // Recalculate offsets on newly edited buffer
7223 let new_selections = new_selections
7224 .iter()
7225 .map(|s| {
7226 let start_point = Point::new(s.start.0, 0);
7227 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7228 Selection {
7229 id: s.id,
7230 start: buffer.point_to_offset(start_point),
7231 end: buffer.point_to_offset(end_point),
7232 goal: s.goal,
7233 reversed: s.reversed,
7234 }
7235 })
7236 .collect();
7237
7238 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7239 s.select(new_selections);
7240 });
7241
7242 this.request_autoscroll(Autoscroll::fit(), cx);
7243 });
7244 }
7245
7246 pub fn convert_to_upper_case(
7247 &mut self,
7248 _: &ConvertToUpperCase,
7249 window: &mut Window,
7250 cx: &mut Context<Self>,
7251 ) {
7252 self.manipulate_text(window, cx, |text| text.to_uppercase())
7253 }
7254
7255 pub fn convert_to_lower_case(
7256 &mut self,
7257 _: &ConvertToLowerCase,
7258 window: &mut Window,
7259 cx: &mut Context<Self>,
7260 ) {
7261 self.manipulate_text(window, cx, |text| text.to_lowercase())
7262 }
7263
7264 pub fn convert_to_title_case(
7265 &mut self,
7266 _: &ConvertToTitleCase,
7267 window: &mut Window,
7268 cx: &mut Context<Self>,
7269 ) {
7270 self.manipulate_text(window, cx, |text| {
7271 text.split('\n')
7272 .map(|line| line.to_case(Case::Title))
7273 .join("\n")
7274 })
7275 }
7276
7277 pub fn convert_to_snake_case(
7278 &mut self,
7279 _: &ConvertToSnakeCase,
7280 window: &mut Window,
7281 cx: &mut Context<Self>,
7282 ) {
7283 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7284 }
7285
7286 pub fn convert_to_kebab_case(
7287 &mut self,
7288 _: &ConvertToKebabCase,
7289 window: &mut Window,
7290 cx: &mut Context<Self>,
7291 ) {
7292 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7293 }
7294
7295 pub fn convert_to_upper_camel_case(
7296 &mut self,
7297 _: &ConvertToUpperCamelCase,
7298 window: &mut Window,
7299 cx: &mut Context<Self>,
7300 ) {
7301 self.manipulate_text(window, cx, |text| {
7302 text.split('\n')
7303 .map(|line| line.to_case(Case::UpperCamel))
7304 .join("\n")
7305 })
7306 }
7307
7308 pub fn convert_to_lower_camel_case(
7309 &mut self,
7310 _: &ConvertToLowerCamelCase,
7311 window: &mut Window,
7312 cx: &mut Context<Self>,
7313 ) {
7314 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7315 }
7316
7317 pub fn convert_to_opposite_case(
7318 &mut self,
7319 _: &ConvertToOppositeCase,
7320 window: &mut Window,
7321 cx: &mut Context<Self>,
7322 ) {
7323 self.manipulate_text(window, cx, |text| {
7324 text.chars()
7325 .fold(String::with_capacity(text.len()), |mut t, c| {
7326 if c.is_uppercase() {
7327 t.extend(c.to_lowercase());
7328 } else {
7329 t.extend(c.to_uppercase());
7330 }
7331 t
7332 })
7333 })
7334 }
7335
7336 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7337 where
7338 Fn: FnMut(&str) -> String,
7339 {
7340 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7341 let buffer = self.buffer.read(cx).snapshot(cx);
7342
7343 let mut new_selections = Vec::new();
7344 let mut edits = Vec::new();
7345 let mut selection_adjustment = 0i32;
7346
7347 for selection in self.selections.all::<usize>(cx) {
7348 let selection_is_empty = selection.is_empty();
7349
7350 let (start, end) = if selection_is_empty {
7351 let word_range = movement::surrounding_word(
7352 &display_map,
7353 selection.start.to_display_point(&display_map),
7354 );
7355 let start = word_range.start.to_offset(&display_map, Bias::Left);
7356 let end = word_range.end.to_offset(&display_map, Bias::Left);
7357 (start, end)
7358 } else {
7359 (selection.start, selection.end)
7360 };
7361
7362 let text = buffer.text_for_range(start..end).collect::<String>();
7363 let old_length = text.len() as i32;
7364 let text = callback(&text);
7365
7366 new_selections.push(Selection {
7367 start: (start as i32 - selection_adjustment) as usize,
7368 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7369 goal: SelectionGoal::None,
7370 ..selection
7371 });
7372
7373 selection_adjustment += old_length - text.len() as i32;
7374
7375 edits.push((start..end, text));
7376 }
7377
7378 self.transact(window, cx, |this, window, cx| {
7379 this.buffer.update(cx, |buffer, cx| {
7380 buffer.edit(edits, None, cx);
7381 });
7382
7383 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7384 s.select(new_selections);
7385 });
7386
7387 this.request_autoscroll(Autoscroll::fit(), cx);
7388 });
7389 }
7390
7391 pub fn duplicate(
7392 &mut self,
7393 upwards: bool,
7394 whole_lines: bool,
7395 window: &mut Window,
7396 cx: &mut Context<Self>,
7397 ) {
7398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7399 let buffer = &display_map.buffer_snapshot;
7400 let selections = self.selections.all::<Point>(cx);
7401
7402 let mut edits = Vec::new();
7403 let mut selections_iter = selections.iter().peekable();
7404 while let Some(selection) = selections_iter.next() {
7405 let mut rows = selection.spanned_rows(false, &display_map);
7406 // duplicate line-wise
7407 if whole_lines || selection.start == selection.end {
7408 // Avoid duplicating the same lines twice.
7409 while let Some(next_selection) = selections_iter.peek() {
7410 let next_rows = next_selection.spanned_rows(false, &display_map);
7411 if next_rows.start < rows.end {
7412 rows.end = next_rows.end;
7413 selections_iter.next().unwrap();
7414 } else {
7415 break;
7416 }
7417 }
7418
7419 // Copy the text from the selected row region and splice it either at the start
7420 // or end of the region.
7421 let start = Point::new(rows.start.0, 0);
7422 let end = Point::new(
7423 rows.end.previous_row().0,
7424 buffer.line_len(rows.end.previous_row()),
7425 );
7426 let text = buffer
7427 .text_for_range(start..end)
7428 .chain(Some("\n"))
7429 .collect::<String>();
7430 let insert_location = if upwards {
7431 Point::new(rows.end.0, 0)
7432 } else {
7433 start
7434 };
7435 edits.push((insert_location..insert_location, text));
7436 } else {
7437 // duplicate character-wise
7438 let start = selection.start;
7439 let end = selection.end;
7440 let text = buffer.text_for_range(start..end).collect::<String>();
7441 edits.push((selection.end..selection.end, text));
7442 }
7443 }
7444
7445 self.transact(window, cx, |this, _, cx| {
7446 this.buffer.update(cx, |buffer, cx| {
7447 buffer.edit(edits, None, cx);
7448 });
7449
7450 this.request_autoscroll(Autoscroll::fit(), cx);
7451 });
7452 }
7453
7454 pub fn duplicate_line_up(
7455 &mut self,
7456 _: &DuplicateLineUp,
7457 window: &mut Window,
7458 cx: &mut Context<Self>,
7459 ) {
7460 self.duplicate(true, true, window, cx);
7461 }
7462
7463 pub fn duplicate_line_down(
7464 &mut self,
7465 _: &DuplicateLineDown,
7466 window: &mut Window,
7467 cx: &mut Context<Self>,
7468 ) {
7469 self.duplicate(false, true, window, cx);
7470 }
7471
7472 pub fn duplicate_selection(
7473 &mut self,
7474 _: &DuplicateSelection,
7475 window: &mut Window,
7476 cx: &mut Context<Self>,
7477 ) {
7478 self.duplicate(false, false, window, cx);
7479 }
7480
7481 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7482 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7483 let buffer = self.buffer.read(cx).snapshot(cx);
7484
7485 let mut edits = Vec::new();
7486 let mut unfold_ranges = Vec::new();
7487 let mut refold_creases = Vec::new();
7488
7489 let selections = self.selections.all::<Point>(cx);
7490 let mut selections = selections.iter().peekable();
7491 let mut contiguous_row_selections = Vec::new();
7492 let mut new_selections = Vec::new();
7493
7494 while let Some(selection) = selections.next() {
7495 // Find all the selections that span a contiguous row range
7496 let (start_row, end_row) = consume_contiguous_rows(
7497 &mut contiguous_row_selections,
7498 selection,
7499 &display_map,
7500 &mut selections,
7501 );
7502
7503 // Move the text spanned by the row range to be before the line preceding the row range
7504 if start_row.0 > 0 {
7505 let range_to_move = Point::new(
7506 start_row.previous_row().0,
7507 buffer.line_len(start_row.previous_row()),
7508 )
7509 ..Point::new(
7510 end_row.previous_row().0,
7511 buffer.line_len(end_row.previous_row()),
7512 );
7513 let insertion_point = display_map
7514 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7515 .0;
7516
7517 // Don't move lines across excerpts
7518 if buffer
7519 .excerpt_containing(insertion_point..range_to_move.end)
7520 .is_some()
7521 {
7522 let text = buffer
7523 .text_for_range(range_to_move.clone())
7524 .flat_map(|s| s.chars())
7525 .skip(1)
7526 .chain(['\n'])
7527 .collect::<String>();
7528
7529 edits.push((
7530 buffer.anchor_after(range_to_move.start)
7531 ..buffer.anchor_before(range_to_move.end),
7532 String::new(),
7533 ));
7534 let insertion_anchor = buffer.anchor_after(insertion_point);
7535 edits.push((insertion_anchor..insertion_anchor, text));
7536
7537 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7538
7539 // Move selections up
7540 new_selections.extend(contiguous_row_selections.drain(..).map(
7541 |mut selection| {
7542 selection.start.row -= row_delta;
7543 selection.end.row -= row_delta;
7544 selection
7545 },
7546 ));
7547
7548 // Move folds up
7549 unfold_ranges.push(range_to_move.clone());
7550 for fold in display_map.folds_in_range(
7551 buffer.anchor_before(range_to_move.start)
7552 ..buffer.anchor_after(range_to_move.end),
7553 ) {
7554 let mut start = fold.range.start.to_point(&buffer);
7555 let mut end = fold.range.end.to_point(&buffer);
7556 start.row -= row_delta;
7557 end.row -= row_delta;
7558 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7559 }
7560 }
7561 }
7562
7563 // If we didn't move line(s), preserve the existing selections
7564 new_selections.append(&mut contiguous_row_selections);
7565 }
7566
7567 self.transact(window, cx, |this, window, cx| {
7568 this.unfold_ranges(&unfold_ranges, true, true, cx);
7569 this.buffer.update(cx, |buffer, cx| {
7570 for (range, text) in edits {
7571 buffer.edit([(range, text)], None, cx);
7572 }
7573 });
7574 this.fold_creases(refold_creases, true, window, cx);
7575 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7576 s.select(new_selections);
7577 })
7578 });
7579 }
7580
7581 pub fn move_line_down(
7582 &mut self,
7583 _: &MoveLineDown,
7584 window: &mut Window,
7585 cx: &mut Context<Self>,
7586 ) {
7587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7588 let buffer = self.buffer.read(cx).snapshot(cx);
7589
7590 let mut edits = Vec::new();
7591 let mut unfold_ranges = Vec::new();
7592 let mut refold_creases = Vec::new();
7593
7594 let selections = self.selections.all::<Point>(cx);
7595 let mut selections = selections.iter().peekable();
7596 let mut contiguous_row_selections = Vec::new();
7597 let mut new_selections = Vec::new();
7598
7599 while let Some(selection) = selections.next() {
7600 // Find all the selections that span a contiguous row range
7601 let (start_row, end_row) = consume_contiguous_rows(
7602 &mut contiguous_row_selections,
7603 selection,
7604 &display_map,
7605 &mut selections,
7606 );
7607
7608 // Move the text spanned by the row range to be after the last line of the row range
7609 if end_row.0 <= buffer.max_point().row {
7610 let range_to_move =
7611 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7612 let insertion_point = display_map
7613 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7614 .0;
7615
7616 // Don't move lines across excerpt boundaries
7617 if buffer
7618 .excerpt_containing(range_to_move.start..insertion_point)
7619 .is_some()
7620 {
7621 let mut text = String::from("\n");
7622 text.extend(buffer.text_for_range(range_to_move.clone()));
7623 text.pop(); // Drop trailing newline
7624 edits.push((
7625 buffer.anchor_after(range_to_move.start)
7626 ..buffer.anchor_before(range_to_move.end),
7627 String::new(),
7628 ));
7629 let insertion_anchor = buffer.anchor_after(insertion_point);
7630 edits.push((insertion_anchor..insertion_anchor, text));
7631
7632 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7633
7634 // Move selections down
7635 new_selections.extend(contiguous_row_selections.drain(..).map(
7636 |mut selection| {
7637 selection.start.row += row_delta;
7638 selection.end.row += row_delta;
7639 selection
7640 },
7641 ));
7642
7643 // Move folds down
7644 unfold_ranges.push(range_to_move.clone());
7645 for fold in display_map.folds_in_range(
7646 buffer.anchor_before(range_to_move.start)
7647 ..buffer.anchor_after(range_to_move.end),
7648 ) {
7649 let mut start = fold.range.start.to_point(&buffer);
7650 let mut end = fold.range.end.to_point(&buffer);
7651 start.row += row_delta;
7652 end.row += row_delta;
7653 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7654 }
7655 }
7656 }
7657
7658 // If we didn't move line(s), preserve the existing selections
7659 new_selections.append(&mut contiguous_row_selections);
7660 }
7661
7662 self.transact(window, cx, |this, window, cx| {
7663 this.unfold_ranges(&unfold_ranges, true, true, cx);
7664 this.buffer.update(cx, |buffer, cx| {
7665 for (range, text) in edits {
7666 buffer.edit([(range, text)], None, cx);
7667 }
7668 });
7669 this.fold_creases(refold_creases, true, window, cx);
7670 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7671 s.select(new_selections)
7672 });
7673 });
7674 }
7675
7676 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7677 let text_layout_details = &self.text_layout_details(window);
7678 self.transact(window, cx, |this, window, cx| {
7679 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7680 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7681 let line_mode = s.line_mode;
7682 s.move_with(|display_map, selection| {
7683 if !selection.is_empty() || line_mode {
7684 return;
7685 }
7686
7687 let mut head = selection.head();
7688 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7689 if head.column() == display_map.line_len(head.row()) {
7690 transpose_offset = display_map
7691 .buffer_snapshot
7692 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7693 }
7694
7695 if transpose_offset == 0 {
7696 return;
7697 }
7698
7699 *head.column_mut() += 1;
7700 head = display_map.clip_point(head, Bias::Right);
7701 let goal = SelectionGoal::HorizontalPosition(
7702 display_map
7703 .x_for_display_point(head, text_layout_details)
7704 .into(),
7705 );
7706 selection.collapse_to(head, goal);
7707
7708 let transpose_start = display_map
7709 .buffer_snapshot
7710 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7711 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7712 let transpose_end = display_map
7713 .buffer_snapshot
7714 .clip_offset(transpose_offset + 1, Bias::Right);
7715 if let Some(ch) =
7716 display_map.buffer_snapshot.chars_at(transpose_start).next()
7717 {
7718 edits.push((transpose_start..transpose_offset, String::new()));
7719 edits.push((transpose_end..transpose_end, ch.to_string()));
7720 }
7721 }
7722 });
7723 edits
7724 });
7725 this.buffer
7726 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7727 let selections = this.selections.all::<usize>(cx);
7728 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7729 s.select(selections);
7730 });
7731 });
7732 }
7733
7734 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7735 self.rewrap_impl(IsVimMode::No, cx)
7736 }
7737
7738 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7739 let buffer = self.buffer.read(cx).snapshot(cx);
7740 let selections = self.selections.all::<Point>(cx);
7741 let mut selections = selections.iter().peekable();
7742
7743 let mut edits = Vec::new();
7744 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7745
7746 while let Some(selection) = selections.next() {
7747 let mut start_row = selection.start.row;
7748 let mut end_row = selection.end.row;
7749
7750 // Skip selections that overlap with a range that has already been rewrapped.
7751 let selection_range = start_row..end_row;
7752 if rewrapped_row_ranges
7753 .iter()
7754 .any(|range| range.overlaps(&selection_range))
7755 {
7756 continue;
7757 }
7758
7759 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7760
7761 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7762 match language_scope.language_name().as_ref() {
7763 "Markdown" | "Plain Text" => {
7764 should_rewrap = true;
7765 }
7766 _ => {}
7767 }
7768 }
7769
7770 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7771
7772 // Since not all lines in the selection may be at the same indent
7773 // level, choose the indent size that is the most common between all
7774 // of the lines.
7775 //
7776 // If there is a tie, we use the deepest indent.
7777 let (indent_size, indent_end) = {
7778 let mut indent_size_occurrences = HashMap::default();
7779 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7780
7781 for row in start_row..=end_row {
7782 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7783 rows_by_indent_size.entry(indent).or_default().push(row);
7784 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7785 }
7786
7787 let indent_size = indent_size_occurrences
7788 .into_iter()
7789 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7790 .map(|(indent, _)| indent)
7791 .unwrap_or_default();
7792 let row = rows_by_indent_size[&indent_size][0];
7793 let indent_end = Point::new(row, indent_size.len);
7794
7795 (indent_size, indent_end)
7796 };
7797
7798 let mut line_prefix = indent_size.chars().collect::<String>();
7799
7800 if let Some(comment_prefix) =
7801 buffer
7802 .language_scope_at(selection.head())
7803 .and_then(|language| {
7804 language
7805 .line_comment_prefixes()
7806 .iter()
7807 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7808 .cloned()
7809 })
7810 {
7811 line_prefix.push_str(&comment_prefix);
7812 should_rewrap = true;
7813 }
7814
7815 if !should_rewrap {
7816 continue;
7817 }
7818
7819 if selection.is_empty() {
7820 'expand_upwards: while start_row > 0 {
7821 let prev_row = start_row - 1;
7822 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7823 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7824 {
7825 start_row = prev_row;
7826 } else {
7827 break 'expand_upwards;
7828 }
7829 }
7830
7831 'expand_downwards: while end_row < buffer.max_point().row {
7832 let next_row = end_row + 1;
7833 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7834 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7835 {
7836 end_row = next_row;
7837 } else {
7838 break 'expand_downwards;
7839 }
7840 }
7841 }
7842
7843 let start = Point::new(start_row, 0);
7844 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7845 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7846 let Some(lines_without_prefixes) = selection_text
7847 .lines()
7848 .map(|line| {
7849 line.strip_prefix(&line_prefix)
7850 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7851 .ok_or_else(|| {
7852 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7853 })
7854 })
7855 .collect::<Result<Vec<_>, _>>()
7856 .log_err()
7857 else {
7858 continue;
7859 };
7860
7861 let wrap_column = buffer
7862 .settings_at(Point::new(start_row, 0), cx)
7863 .preferred_line_length as usize;
7864 let wrapped_text = wrap_with_prefix(
7865 line_prefix,
7866 lines_without_prefixes.join(" "),
7867 wrap_column,
7868 tab_size,
7869 );
7870
7871 // TODO: should always use char-based diff while still supporting cursor behavior that
7872 // matches vim.
7873 let diff = match is_vim_mode {
7874 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7875 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7876 };
7877 let mut offset = start.to_offset(&buffer);
7878 let mut moved_since_edit = true;
7879
7880 for change in diff.iter_all_changes() {
7881 let value = change.value();
7882 match change.tag() {
7883 ChangeTag::Equal => {
7884 offset += value.len();
7885 moved_since_edit = true;
7886 }
7887 ChangeTag::Delete => {
7888 let start = buffer.anchor_after(offset);
7889 let end = buffer.anchor_before(offset + value.len());
7890
7891 if moved_since_edit {
7892 edits.push((start..end, String::new()));
7893 } else {
7894 edits.last_mut().unwrap().0.end = end;
7895 }
7896
7897 offset += value.len();
7898 moved_since_edit = false;
7899 }
7900 ChangeTag::Insert => {
7901 if moved_since_edit {
7902 let anchor = buffer.anchor_after(offset);
7903 edits.push((anchor..anchor, value.to_string()));
7904 } else {
7905 edits.last_mut().unwrap().1.push_str(value);
7906 }
7907
7908 moved_since_edit = false;
7909 }
7910 }
7911 }
7912
7913 rewrapped_row_ranges.push(start_row..=end_row);
7914 }
7915
7916 self.buffer
7917 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7918 }
7919
7920 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7921 let mut text = String::new();
7922 let buffer = self.buffer.read(cx).snapshot(cx);
7923 let mut selections = self.selections.all::<Point>(cx);
7924 let mut clipboard_selections = Vec::with_capacity(selections.len());
7925 {
7926 let max_point = buffer.max_point();
7927 let mut is_first = true;
7928 for selection in &mut selections {
7929 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7930 if is_entire_line {
7931 selection.start = Point::new(selection.start.row, 0);
7932 if !selection.is_empty() && selection.end.column == 0 {
7933 selection.end = cmp::min(max_point, selection.end);
7934 } else {
7935 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7936 }
7937 selection.goal = SelectionGoal::None;
7938 }
7939 if is_first {
7940 is_first = false;
7941 } else {
7942 text += "\n";
7943 }
7944 let mut len = 0;
7945 for chunk in buffer.text_for_range(selection.start..selection.end) {
7946 text.push_str(chunk);
7947 len += chunk.len();
7948 }
7949 clipboard_selections.push(ClipboardSelection {
7950 len,
7951 is_entire_line,
7952 first_line_indent: buffer
7953 .indent_size_for_line(MultiBufferRow(selection.start.row))
7954 .len,
7955 });
7956 }
7957 }
7958
7959 self.transact(window, cx, |this, window, cx| {
7960 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7961 s.select(selections);
7962 });
7963 this.insert("", window, cx);
7964 });
7965 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7966 }
7967
7968 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7969 let item = self.cut_common(window, cx);
7970 cx.write_to_clipboard(item);
7971 }
7972
7973 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7974 self.change_selections(None, window, cx, |s| {
7975 s.move_with(|snapshot, sel| {
7976 if sel.is_empty() {
7977 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7978 }
7979 });
7980 });
7981 let item = self.cut_common(window, cx);
7982 cx.set_global(KillRing(item))
7983 }
7984
7985 pub fn kill_ring_yank(
7986 &mut self,
7987 _: &KillRingYank,
7988 window: &mut Window,
7989 cx: &mut Context<Self>,
7990 ) {
7991 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7992 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7993 (kill_ring.text().to_string(), kill_ring.metadata_json())
7994 } else {
7995 return;
7996 }
7997 } else {
7998 return;
7999 };
8000 self.do_paste(&text, metadata, false, window, cx);
8001 }
8002
8003 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8004 let selections = self.selections.all::<Point>(cx);
8005 let buffer = self.buffer.read(cx).read(cx);
8006 let mut text = String::new();
8007
8008 let mut clipboard_selections = Vec::with_capacity(selections.len());
8009 {
8010 let max_point = buffer.max_point();
8011 let mut is_first = true;
8012 for selection in selections.iter() {
8013 let mut start = selection.start;
8014 let mut end = selection.end;
8015 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8016 if is_entire_line {
8017 start = Point::new(start.row, 0);
8018 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8019 }
8020 if is_first {
8021 is_first = false;
8022 } else {
8023 text += "\n";
8024 }
8025 let mut len = 0;
8026 for chunk in buffer.text_for_range(start..end) {
8027 text.push_str(chunk);
8028 len += chunk.len();
8029 }
8030 clipboard_selections.push(ClipboardSelection {
8031 len,
8032 is_entire_line,
8033 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8034 });
8035 }
8036 }
8037
8038 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8039 text,
8040 clipboard_selections,
8041 ));
8042 }
8043
8044 pub fn do_paste(
8045 &mut self,
8046 text: &String,
8047 clipboard_selections: Option<Vec<ClipboardSelection>>,
8048 handle_entire_lines: bool,
8049 window: &mut Window,
8050 cx: &mut Context<Self>,
8051 ) {
8052 if self.read_only(cx) {
8053 return;
8054 }
8055
8056 let clipboard_text = Cow::Borrowed(text);
8057
8058 self.transact(window, cx, |this, window, cx| {
8059 if let Some(mut clipboard_selections) = clipboard_selections {
8060 let old_selections = this.selections.all::<usize>(cx);
8061 let all_selections_were_entire_line =
8062 clipboard_selections.iter().all(|s| s.is_entire_line);
8063 let first_selection_indent_column =
8064 clipboard_selections.first().map(|s| s.first_line_indent);
8065 if clipboard_selections.len() != old_selections.len() {
8066 clipboard_selections.drain(..);
8067 }
8068 let cursor_offset = this.selections.last::<usize>(cx).head();
8069 let mut auto_indent_on_paste = true;
8070
8071 this.buffer.update(cx, |buffer, cx| {
8072 let snapshot = buffer.read(cx);
8073 auto_indent_on_paste =
8074 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8075
8076 let mut start_offset = 0;
8077 let mut edits = Vec::new();
8078 let mut original_indent_columns = Vec::new();
8079 for (ix, selection) in old_selections.iter().enumerate() {
8080 let to_insert;
8081 let entire_line;
8082 let original_indent_column;
8083 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8084 let end_offset = start_offset + clipboard_selection.len;
8085 to_insert = &clipboard_text[start_offset..end_offset];
8086 entire_line = clipboard_selection.is_entire_line;
8087 start_offset = end_offset + 1;
8088 original_indent_column = Some(clipboard_selection.first_line_indent);
8089 } else {
8090 to_insert = clipboard_text.as_str();
8091 entire_line = all_selections_were_entire_line;
8092 original_indent_column = first_selection_indent_column
8093 }
8094
8095 // If the corresponding selection was empty when this slice of the
8096 // clipboard text was written, then the entire line containing the
8097 // selection was copied. If this selection is also currently empty,
8098 // then paste the line before the current line of the buffer.
8099 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8100 let column = selection.start.to_point(&snapshot).column as usize;
8101 let line_start = selection.start - column;
8102 line_start..line_start
8103 } else {
8104 selection.range()
8105 };
8106
8107 edits.push((range, to_insert));
8108 original_indent_columns.extend(original_indent_column);
8109 }
8110 drop(snapshot);
8111
8112 buffer.edit(
8113 edits,
8114 if auto_indent_on_paste {
8115 Some(AutoindentMode::Block {
8116 original_indent_columns,
8117 })
8118 } else {
8119 None
8120 },
8121 cx,
8122 );
8123 });
8124
8125 let selections = this.selections.all::<usize>(cx);
8126 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8127 s.select(selections)
8128 });
8129 } else {
8130 this.insert(&clipboard_text, window, cx);
8131 }
8132 });
8133 }
8134
8135 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8136 if let Some(item) = cx.read_from_clipboard() {
8137 let entries = item.entries();
8138
8139 match entries.first() {
8140 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8141 // of all the pasted entries.
8142 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8143 .do_paste(
8144 clipboard_string.text(),
8145 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8146 true,
8147 window,
8148 cx,
8149 ),
8150 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8151 }
8152 }
8153 }
8154
8155 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8156 if self.read_only(cx) {
8157 return;
8158 }
8159
8160 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8161 if let Some((selections, _)) =
8162 self.selection_history.transaction(transaction_id).cloned()
8163 {
8164 self.change_selections(None, window, cx, |s| {
8165 s.select_anchors(selections.to_vec());
8166 });
8167 }
8168 self.request_autoscroll(Autoscroll::fit(), cx);
8169 self.unmark_text(window, cx);
8170 self.refresh_inline_completion(true, false, window, cx);
8171 cx.emit(EditorEvent::Edited { transaction_id });
8172 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8173 }
8174 }
8175
8176 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8177 if self.read_only(cx) {
8178 return;
8179 }
8180
8181 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8182 if let Some((_, Some(selections))) =
8183 self.selection_history.transaction(transaction_id).cloned()
8184 {
8185 self.change_selections(None, window, cx, |s| {
8186 s.select_anchors(selections.to_vec());
8187 });
8188 }
8189 self.request_autoscroll(Autoscroll::fit(), cx);
8190 self.unmark_text(window, cx);
8191 self.refresh_inline_completion(true, false, window, cx);
8192 cx.emit(EditorEvent::Edited { transaction_id });
8193 }
8194 }
8195
8196 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8197 self.buffer
8198 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8199 }
8200
8201 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8202 self.buffer
8203 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8204 }
8205
8206 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8207 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8208 let line_mode = s.line_mode;
8209 s.move_with(|map, selection| {
8210 let cursor = if selection.is_empty() && !line_mode {
8211 movement::left(map, selection.start)
8212 } else {
8213 selection.start
8214 };
8215 selection.collapse_to(cursor, SelectionGoal::None);
8216 });
8217 })
8218 }
8219
8220 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8221 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8222 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8223 })
8224 }
8225
8226 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8228 let line_mode = s.line_mode;
8229 s.move_with(|map, selection| {
8230 let cursor = if selection.is_empty() && !line_mode {
8231 movement::right(map, selection.end)
8232 } else {
8233 selection.end
8234 };
8235 selection.collapse_to(cursor, SelectionGoal::None)
8236 });
8237 })
8238 }
8239
8240 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8242 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8243 })
8244 }
8245
8246 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8247 if self.take_rename(true, window, cx).is_some() {
8248 return;
8249 }
8250
8251 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8252 cx.propagate();
8253 return;
8254 }
8255
8256 let text_layout_details = &self.text_layout_details(window);
8257 let selection_count = self.selections.count();
8258 let first_selection = self.selections.first_anchor();
8259
8260 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8261 let line_mode = s.line_mode;
8262 s.move_with(|map, selection| {
8263 if !selection.is_empty() && !line_mode {
8264 selection.goal = SelectionGoal::None;
8265 }
8266 let (cursor, goal) = movement::up(
8267 map,
8268 selection.start,
8269 selection.goal,
8270 false,
8271 text_layout_details,
8272 );
8273 selection.collapse_to(cursor, goal);
8274 });
8275 });
8276
8277 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8278 {
8279 cx.propagate();
8280 }
8281 }
8282
8283 pub fn move_up_by_lines(
8284 &mut self,
8285 action: &MoveUpByLines,
8286 window: &mut Window,
8287 cx: &mut Context<Self>,
8288 ) {
8289 if self.take_rename(true, window, cx).is_some() {
8290 return;
8291 }
8292
8293 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8294 cx.propagate();
8295 return;
8296 }
8297
8298 let text_layout_details = &self.text_layout_details(window);
8299
8300 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8301 let line_mode = s.line_mode;
8302 s.move_with(|map, selection| {
8303 if !selection.is_empty() && !line_mode {
8304 selection.goal = SelectionGoal::None;
8305 }
8306 let (cursor, goal) = movement::up_by_rows(
8307 map,
8308 selection.start,
8309 action.lines,
8310 selection.goal,
8311 false,
8312 text_layout_details,
8313 );
8314 selection.collapse_to(cursor, goal);
8315 });
8316 })
8317 }
8318
8319 pub fn move_down_by_lines(
8320 &mut self,
8321 action: &MoveDownByLines,
8322 window: &mut Window,
8323 cx: &mut Context<Self>,
8324 ) {
8325 if self.take_rename(true, window, cx).is_some() {
8326 return;
8327 }
8328
8329 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8330 cx.propagate();
8331 return;
8332 }
8333
8334 let text_layout_details = &self.text_layout_details(window);
8335
8336 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8337 let line_mode = s.line_mode;
8338 s.move_with(|map, selection| {
8339 if !selection.is_empty() && !line_mode {
8340 selection.goal = SelectionGoal::None;
8341 }
8342 let (cursor, goal) = movement::down_by_rows(
8343 map,
8344 selection.start,
8345 action.lines,
8346 selection.goal,
8347 false,
8348 text_layout_details,
8349 );
8350 selection.collapse_to(cursor, goal);
8351 });
8352 })
8353 }
8354
8355 pub fn select_down_by_lines(
8356 &mut self,
8357 action: &SelectDownByLines,
8358 window: &mut Window,
8359 cx: &mut Context<Self>,
8360 ) {
8361 let text_layout_details = &self.text_layout_details(window);
8362 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8363 s.move_heads_with(|map, head, goal| {
8364 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8365 })
8366 })
8367 }
8368
8369 pub fn select_up_by_lines(
8370 &mut self,
8371 action: &SelectUpByLines,
8372 window: &mut Window,
8373 cx: &mut Context<Self>,
8374 ) {
8375 let text_layout_details = &self.text_layout_details(window);
8376 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8377 s.move_heads_with(|map, head, goal| {
8378 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8379 })
8380 })
8381 }
8382
8383 pub fn select_page_up(
8384 &mut self,
8385 _: &SelectPageUp,
8386 window: &mut Window,
8387 cx: &mut Context<Self>,
8388 ) {
8389 let Some(row_count) = self.visible_row_count() else {
8390 return;
8391 };
8392
8393 let text_layout_details = &self.text_layout_details(window);
8394
8395 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8396 s.move_heads_with(|map, head, goal| {
8397 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8398 })
8399 })
8400 }
8401
8402 pub fn move_page_up(
8403 &mut self,
8404 action: &MovePageUp,
8405 window: &mut Window,
8406 cx: &mut Context<Self>,
8407 ) {
8408 if self.take_rename(true, window, cx).is_some() {
8409 return;
8410 }
8411
8412 if self
8413 .context_menu
8414 .borrow_mut()
8415 .as_mut()
8416 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8417 .unwrap_or(false)
8418 {
8419 return;
8420 }
8421
8422 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8423 cx.propagate();
8424 return;
8425 }
8426
8427 let Some(row_count) = self.visible_row_count() else {
8428 return;
8429 };
8430
8431 let autoscroll = if action.center_cursor {
8432 Autoscroll::center()
8433 } else {
8434 Autoscroll::fit()
8435 };
8436
8437 let text_layout_details = &self.text_layout_details(window);
8438
8439 self.change_selections(Some(autoscroll), window, cx, |s| {
8440 let line_mode = s.line_mode;
8441 s.move_with(|map, selection| {
8442 if !selection.is_empty() && !line_mode {
8443 selection.goal = SelectionGoal::None;
8444 }
8445 let (cursor, goal) = movement::up_by_rows(
8446 map,
8447 selection.end,
8448 row_count,
8449 selection.goal,
8450 false,
8451 text_layout_details,
8452 );
8453 selection.collapse_to(cursor, goal);
8454 });
8455 });
8456 }
8457
8458 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8459 let text_layout_details = &self.text_layout_details(window);
8460 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8461 s.move_heads_with(|map, head, goal| {
8462 movement::up(map, head, goal, false, text_layout_details)
8463 })
8464 })
8465 }
8466
8467 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8468 self.take_rename(true, window, cx);
8469
8470 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8471 cx.propagate();
8472 return;
8473 }
8474
8475 let text_layout_details = &self.text_layout_details(window);
8476 let selection_count = self.selections.count();
8477 let first_selection = self.selections.first_anchor();
8478
8479 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8480 let line_mode = s.line_mode;
8481 s.move_with(|map, selection| {
8482 if !selection.is_empty() && !line_mode {
8483 selection.goal = SelectionGoal::None;
8484 }
8485 let (cursor, goal) = movement::down(
8486 map,
8487 selection.end,
8488 selection.goal,
8489 false,
8490 text_layout_details,
8491 );
8492 selection.collapse_to(cursor, goal);
8493 });
8494 });
8495
8496 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8497 {
8498 cx.propagate();
8499 }
8500 }
8501
8502 pub fn select_page_down(
8503 &mut self,
8504 _: &SelectPageDown,
8505 window: &mut Window,
8506 cx: &mut Context<Self>,
8507 ) {
8508 let Some(row_count) = self.visible_row_count() else {
8509 return;
8510 };
8511
8512 let text_layout_details = &self.text_layout_details(window);
8513
8514 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8515 s.move_heads_with(|map, head, goal| {
8516 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8517 })
8518 })
8519 }
8520
8521 pub fn move_page_down(
8522 &mut self,
8523 action: &MovePageDown,
8524 window: &mut Window,
8525 cx: &mut Context<Self>,
8526 ) {
8527 if self.take_rename(true, window, cx).is_some() {
8528 return;
8529 }
8530
8531 if self
8532 .context_menu
8533 .borrow_mut()
8534 .as_mut()
8535 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8536 .unwrap_or(false)
8537 {
8538 return;
8539 }
8540
8541 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8542 cx.propagate();
8543 return;
8544 }
8545
8546 let Some(row_count) = self.visible_row_count() else {
8547 return;
8548 };
8549
8550 let autoscroll = if action.center_cursor {
8551 Autoscroll::center()
8552 } else {
8553 Autoscroll::fit()
8554 };
8555
8556 let text_layout_details = &self.text_layout_details(window);
8557 self.change_selections(Some(autoscroll), window, cx, |s| {
8558 let line_mode = s.line_mode;
8559 s.move_with(|map, selection| {
8560 if !selection.is_empty() && !line_mode {
8561 selection.goal = SelectionGoal::None;
8562 }
8563 let (cursor, goal) = movement::down_by_rows(
8564 map,
8565 selection.end,
8566 row_count,
8567 selection.goal,
8568 false,
8569 text_layout_details,
8570 );
8571 selection.collapse_to(cursor, goal);
8572 });
8573 });
8574 }
8575
8576 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8577 let text_layout_details = &self.text_layout_details(window);
8578 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8579 s.move_heads_with(|map, head, goal| {
8580 movement::down(map, head, goal, false, text_layout_details)
8581 })
8582 });
8583 }
8584
8585 pub fn context_menu_first(
8586 &mut self,
8587 _: &ContextMenuFirst,
8588 _window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8592 context_menu.select_first(self.completion_provider.as_deref(), cx);
8593 }
8594 }
8595
8596 pub fn context_menu_prev(
8597 &mut self,
8598 _: &ContextMenuPrev,
8599 _window: &mut Window,
8600 cx: &mut Context<Self>,
8601 ) {
8602 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8603 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8604 }
8605 }
8606
8607 pub fn context_menu_next(
8608 &mut self,
8609 _: &ContextMenuNext,
8610 _window: &mut Window,
8611 cx: &mut Context<Self>,
8612 ) {
8613 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8614 context_menu.select_next(self.completion_provider.as_deref(), cx);
8615 }
8616 }
8617
8618 pub fn context_menu_last(
8619 &mut self,
8620 _: &ContextMenuLast,
8621 _window: &mut Window,
8622 cx: &mut Context<Self>,
8623 ) {
8624 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8625 context_menu.select_last(self.completion_provider.as_deref(), cx);
8626 }
8627 }
8628
8629 pub fn move_to_previous_word_start(
8630 &mut self,
8631 _: &MoveToPreviousWordStart,
8632 window: &mut Window,
8633 cx: &mut Context<Self>,
8634 ) {
8635 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8636 s.move_cursors_with(|map, head, _| {
8637 (
8638 movement::previous_word_start(map, head),
8639 SelectionGoal::None,
8640 )
8641 });
8642 })
8643 }
8644
8645 pub fn move_to_previous_subword_start(
8646 &mut self,
8647 _: &MoveToPreviousSubwordStart,
8648 window: &mut Window,
8649 cx: &mut Context<Self>,
8650 ) {
8651 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8652 s.move_cursors_with(|map, head, _| {
8653 (
8654 movement::previous_subword_start(map, head),
8655 SelectionGoal::None,
8656 )
8657 });
8658 })
8659 }
8660
8661 pub fn select_to_previous_word_start(
8662 &mut self,
8663 _: &SelectToPreviousWordStart,
8664 window: &mut Window,
8665 cx: &mut Context<Self>,
8666 ) {
8667 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8668 s.move_heads_with(|map, head, _| {
8669 (
8670 movement::previous_word_start(map, head),
8671 SelectionGoal::None,
8672 )
8673 });
8674 })
8675 }
8676
8677 pub fn select_to_previous_subword_start(
8678 &mut self,
8679 _: &SelectToPreviousSubwordStart,
8680 window: &mut Window,
8681 cx: &mut Context<Self>,
8682 ) {
8683 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8684 s.move_heads_with(|map, head, _| {
8685 (
8686 movement::previous_subword_start(map, head),
8687 SelectionGoal::None,
8688 )
8689 });
8690 })
8691 }
8692
8693 pub fn delete_to_previous_word_start(
8694 &mut self,
8695 action: &DeleteToPreviousWordStart,
8696 window: &mut Window,
8697 cx: &mut Context<Self>,
8698 ) {
8699 self.transact(window, cx, |this, window, cx| {
8700 this.select_autoclose_pair(window, cx);
8701 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8702 let line_mode = s.line_mode;
8703 s.move_with(|map, selection| {
8704 if selection.is_empty() && !line_mode {
8705 let cursor = if action.ignore_newlines {
8706 movement::previous_word_start(map, selection.head())
8707 } else {
8708 movement::previous_word_start_or_newline(map, selection.head())
8709 };
8710 selection.set_head(cursor, SelectionGoal::None);
8711 }
8712 });
8713 });
8714 this.insert("", window, cx);
8715 });
8716 }
8717
8718 pub fn delete_to_previous_subword_start(
8719 &mut self,
8720 _: &DeleteToPreviousSubwordStart,
8721 window: &mut Window,
8722 cx: &mut Context<Self>,
8723 ) {
8724 self.transact(window, cx, |this, window, cx| {
8725 this.select_autoclose_pair(window, cx);
8726 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8727 let line_mode = s.line_mode;
8728 s.move_with(|map, selection| {
8729 if selection.is_empty() && !line_mode {
8730 let cursor = movement::previous_subword_start(map, selection.head());
8731 selection.set_head(cursor, SelectionGoal::None);
8732 }
8733 });
8734 });
8735 this.insert("", window, cx);
8736 });
8737 }
8738
8739 pub fn move_to_next_word_end(
8740 &mut self,
8741 _: &MoveToNextWordEnd,
8742 window: &mut Window,
8743 cx: &mut Context<Self>,
8744 ) {
8745 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8746 s.move_cursors_with(|map, head, _| {
8747 (movement::next_word_end(map, head), SelectionGoal::None)
8748 });
8749 })
8750 }
8751
8752 pub fn move_to_next_subword_end(
8753 &mut self,
8754 _: &MoveToNextSubwordEnd,
8755 window: &mut Window,
8756 cx: &mut Context<Self>,
8757 ) {
8758 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8759 s.move_cursors_with(|map, head, _| {
8760 (movement::next_subword_end(map, head), SelectionGoal::None)
8761 });
8762 })
8763 }
8764
8765 pub fn select_to_next_word_end(
8766 &mut self,
8767 _: &SelectToNextWordEnd,
8768 window: &mut Window,
8769 cx: &mut Context<Self>,
8770 ) {
8771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8772 s.move_heads_with(|map, head, _| {
8773 (movement::next_word_end(map, head), SelectionGoal::None)
8774 });
8775 })
8776 }
8777
8778 pub fn select_to_next_subword_end(
8779 &mut self,
8780 _: &SelectToNextSubwordEnd,
8781 window: &mut Window,
8782 cx: &mut Context<Self>,
8783 ) {
8784 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8785 s.move_heads_with(|map, head, _| {
8786 (movement::next_subword_end(map, head), SelectionGoal::None)
8787 });
8788 })
8789 }
8790
8791 pub fn delete_to_next_word_end(
8792 &mut self,
8793 action: &DeleteToNextWordEnd,
8794 window: &mut Window,
8795 cx: &mut Context<Self>,
8796 ) {
8797 self.transact(window, cx, |this, window, cx| {
8798 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8799 let line_mode = s.line_mode;
8800 s.move_with(|map, selection| {
8801 if selection.is_empty() && !line_mode {
8802 let cursor = if action.ignore_newlines {
8803 movement::next_word_end(map, selection.head())
8804 } else {
8805 movement::next_word_end_or_newline(map, selection.head())
8806 };
8807 selection.set_head(cursor, SelectionGoal::None);
8808 }
8809 });
8810 });
8811 this.insert("", window, cx);
8812 });
8813 }
8814
8815 pub fn delete_to_next_subword_end(
8816 &mut self,
8817 _: &DeleteToNextSubwordEnd,
8818 window: &mut Window,
8819 cx: &mut Context<Self>,
8820 ) {
8821 self.transact(window, cx, |this, window, cx| {
8822 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8823 s.move_with(|map, selection| {
8824 if selection.is_empty() {
8825 let cursor = movement::next_subword_end(map, selection.head());
8826 selection.set_head(cursor, SelectionGoal::None);
8827 }
8828 });
8829 });
8830 this.insert("", window, cx);
8831 });
8832 }
8833
8834 pub fn move_to_beginning_of_line(
8835 &mut self,
8836 action: &MoveToBeginningOfLine,
8837 window: &mut Window,
8838 cx: &mut Context<Self>,
8839 ) {
8840 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8841 s.move_cursors_with(|map, head, _| {
8842 (
8843 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8844 SelectionGoal::None,
8845 )
8846 });
8847 })
8848 }
8849
8850 pub fn select_to_beginning_of_line(
8851 &mut self,
8852 action: &SelectToBeginningOfLine,
8853 window: &mut Window,
8854 cx: &mut Context<Self>,
8855 ) {
8856 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8857 s.move_heads_with(|map, head, _| {
8858 (
8859 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8860 SelectionGoal::None,
8861 )
8862 });
8863 });
8864 }
8865
8866 pub fn delete_to_beginning_of_line(
8867 &mut self,
8868 _: &DeleteToBeginningOfLine,
8869 window: &mut Window,
8870 cx: &mut Context<Self>,
8871 ) {
8872 self.transact(window, cx, |this, window, cx| {
8873 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8874 s.move_with(|_, selection| {
8875 selection.reversed = true;
8876 });
8877 });
8878
8879 this.select_to_beginning_of_line(
8880 &SelectToBeginningOfLine {
8881 stop_at_soft_wraps: false,
8882 },
8883 window,
8884 cx,
8885 );
8886 this.backspace(&Backspace, window, cx);
8887 });
8888 }
8889
8890 pub fn move_to_end_of_line(
8891 &mut self,
8892 action: &MoveToEndOfLine,
8893 window: &mut Window,
8894 cx: &mut Context<Self>,
8895 ) {
8896 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8897 s.move_cursors_with(|map, head, _| {
8898 (
8899 movement::line_end(map, head, action.stop_at_soft_wraps),
8900 SelectionGoal::None,
8901 )
8902 });
8903 })
8904 }
8905
8906 pub fn select_to_end_of_line(
8907 &mut self,
8908 action: &SelectToEndOfLine,
8909 window: &mut Window,
8910 cx: &mut Context<Self>,
8911 ) {
8912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8913 s.move_heads_with(|map, head, _| {
8914 (
8915 movement::line_end(map, head, action.stop_at_soft_wraps),
8916 SelectionGoal::None,
8917 )
8918 });
8919 })
8920 }
8921
8922 pub fn delete_to_end_of_line(
8923 &mut self,
8924 _: &DeleteToEndOfLine,
8925 window: &mut Window,
8926 cx: &mut Context<Self>,
8927 ) {
8928 self.transact(window, cx, |this, window, cx| {
8929 this.select_to_end_of_line(
8930 &SelectToEndOfLine {
8931 stop_at_soft_wraps: false,
8932 },
8933 window,
8934 cx,
8935 );
8936 this.delete(&Delete, window, cx);
8937 });
8938 }
8939
8940 pub fn cut_to_end_of_line(
8941 &mut self,
8942 _: &CutToEndOfLine,
8943 window: &mut Window,
8944 cx: &mut Context<Self>,
8945 ) {
8946 self.transact(window, cx, |this, window, cx| {
8947 this.select_to_end_of_line(
8948 &SelectToEndOfLine {
8949 stop_at_soft_wraps: false,
8950 },
8951 window,
8952 cx,
8953 );
8954 this.cut(&Cut, window, cx);
8955 });
8956 }
8957
8958 pub fn move_to_start_of_paragraph(
8959 &mut self,
8960 _: &MoveToStartOfParagraph,
8961 window: &mut Window,
8962 cx: &mut Context<Self>,
8963 ) {
8964 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8965 cx.propagate();
8966 return;
8967 }
8968
8969 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8970 s.move_with(|map, selection| {
8971 selection.collapse_to(
8972 movement::start_of_paragraph(map, selection.head(), 1),
8973 SelectionGoal::None,
8974 )
8975 });
8976 })
8977 }
8978
8979 pub fn move_to_end_of_paragraph(
8980 &mut self,
8981 _: &MoveToEndOfParagraph,
8982 window: &mut Window,
8983 cx: &mut Context<Self>,
8984 ) {
8985 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8986 cx.propagate();
8987 return;
8988 }
8989
8990 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8991 s.move_with(|map, selection| {
8992 selection.collapse_to(
8993 movement::end_of_paragraph(map, selection.head(), 1),
8994 SelectionGoal::None,
8995 )
8996 });
8997 })
8998 }
8999
9000 pub fn select_to_start_of_paragraph(
9001 &mut self,
9002 _: &SelectToStartOfParagraph,
9003 window: &mut Window,
9004 cx: &mut Context<Self>,
9005 ) {
9006 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9007 cx.propagate();
9008 return;
9009 }
9010
9011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9012 s.move_heads_with(|map, head, _| {
9013 (
9014 movement::start_of_paragraph(map, head, 1),
9015 SelectionGoal::None,
9016 )
9017 });
9018 })
9019 }
9020
9021 pub fn select_to_end_of_paragraph(
9022 &mut self,
9023 _: &SelectToEndOfParagraph,
9024 window: &mut Window,
9025 cx: &mut Context<Self>,
9026 ) {
9027 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9028 cx.propagate();
9029 return;
9030 }
9031
9032 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9033 s.move_heads_with(|map, head, _| {
9034 (
9035 movement::end_of_paragraph(map, head, 1),
9036 SelectionGoal::None,
9037 )
9038 });
9039 })
9040 }
9041
9042 pub fn move_to_beginning(
9043 &mut self,
9044 _: &MoveToBeginning,
9045 window: &mut Window,
9046 cx: &mut Context<Self>,
9047 ) {
9048 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9049 cx.propagate();
9050 return;
9051 }
9052
9053 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9054 s.select_ranges(vec![0..0]);
9055 });
9056 }
9057
9058 pub fn select_to_beginning(
9059 &mut self,
9060 _: &SelectToBeginning,
9061 window: &mut Window,
9062 cx: &mut Context<Self>,
9063 ) {
9064 let mut selection = self.selections.last::<Point>(cx);
9065 selection.set_head(Point::zero(), SelectionGoal::None);
9066
9067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9068 s.select(vec![selection]);
9069 });
9070 }
9071
9072 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9073 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9074 cx.propagate();
9075 return;
9076 }
9077
9078 let cursor = self.buffer.read(cx).read(cx).len();
9079 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9080 s.select_ranges(vec![cursor..cursor])
9081 });
9082 }
9083
9084 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9085 self.nav_history = nav_history;
9086 }
9087
9088 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9089 self.nav_history.as_ref()
9090 }
9091
9092 fn push_to_nav_history(
9093 &mut self,
9094 cursor_anchor: Anchor,
9095 new_position: Option<Point>,
9096 cx: &mut Context<Self>,
9097 ) {
9098 if let Some(nav_history) = self.nav_history.as_mut() {
9099 let buffer = self.buffer.read(cx).read(cx);
9100 let cursor_position = cursor_anchor.to_point(&buffer);
9101 let scroll_state = self.scroll_manager.anchor();
9102 let scroll_top_row = scroll_state.top_row(&buffer);
9103 drop(buffer);
9104
9105 if let Some(new_position) = new_position {
9106 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9107 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9108 return;
9109 }
9110 }
9111
9112 nav_history.push(
9113 Some(NavigationData {
9114 cursor_anchor,
9115 cursor_position,
9116 scroll_anchor: scroll_state,
9117 scroll_top_row,
9118 }),
9119 cx,
9120 );
9121 }
9122 }
9123
9124 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9125 let buffer = self.buffer.read(cx).snapshot(cx);
9126 let mut selection = self.selections.first::<usize>(cx);
9127 selection.set_head(buffer.len(), SelectionGoal::None);
9128 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9129 s.select(vec![selection]);
9130 });
9131 }
9132
9133 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9134 let end = self.buffer.read(cx).read(cx).len();
9135 self.change_selections(None, window, cx, |s| {
9136 s.select_ranges(vec![0..end]);
9137 });
9138 }
9139
9140 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9141 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9142 let mut selections = self.selections.all::<Point>(cx);
9143 let max_point = display_map.buffer_snapshot.max_point();
9144 for selection in &mut selections {
9145 let rows = selection.spanned_rows(true, &display_map);
9146 selection.start = Point::new(rows.start.0, 0);
9147 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9148 selection.reversed = false;
9149 }
9150 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9151 s.select(selections);
9152 });
9153 }
9154
9155 pub fn split_selection_into_lines(
9156 &mut self,
9157 _: &SplitSelectionIntoLines,
9158 window: &mut Window,
9159 cx: &mut Context<Self>,
9160 ) {
9161 let selections = self
9162 .selections
9163 .all::<Point>(cx)
9164 .into_iter()
9165 .map(|selection| selection.start..selection.end)
9166 .collect::<Vec<_>>();
9167 self.unfold_ranges(&selections, true, true, cx);
9168
9169 let mut new_selection_ranges = Vec::new();
9170 {
9171 let buffer = self.buffer.read(cx).read(cx);
9172 for selection in selections {
9173 for row in selection.start.row..selection.end.row {
9174 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9175 new_selection_ranges.push(cursor..cursor);
9176 }
9177
9178 let is_multiline_selection = selection.start.row != selection.end.row;
9179 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9180 // so this action feels more ergonomic when paired with other selection operations
9181 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9182 if !should_skip_last {
9183 new_selection_ranges.push(selection.end..selection.end);
9184 }
9185 }
9186 }
9187 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9188 s.select_ranges(new_selection_ranges);
9189 });
9190 }
9191
9192 pub fn add_selection_above(
9193 &mut self,
9194 _: &AddSelectionAbove,
9195 window: &mut Window,
9196 cx: &mut Context<Self>,
9197 ) {
9198 self.add_selection(true, window, cx);
9199 }
9200
9201 pub fn add_selection_below(
9202 &mut self,
9203 _: &AddSelectionBelow,
9204 window: &mut Window,
9205 cx: &mut Context<Self>,
9206 ) {
9207 self.add_selection(false, window, cx);
9208 }
9209
9210 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9212 let mut selections = self.selections.all::<Point>(cx);
9213 let text_layout_details = self.text_layout_details(window);
9214 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9215 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9216 let range = oldest_selection.display_range(&display_map).sorted();
9217
9218 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9219 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9220 let positions = start_x.min(end_x)..start_x.max(end_x);
9221
9222 selections.clear();
9223 let mut stack = Vec::new();
9224 for row in range.start.row().0..=range.end.row().0 {
9225 if let Some(selection) = self.selections.build_columnar_selection(
9226 &display_map,
9227 DisplayRow(row),
9228 &positions,
9229 oldest_selection.reversed,
9230 &text_layout_details,
9231 ) {
9232 stack.push(selection.id);
9233 selections.push(selection);
9234 }
9235 }
9236
9237 if above {
9238 stack.reverse();
9239 }
9240
9241 AddSelectionsState { above, stack }
9242 });
9243
9244 let last_added_selection = *state.stack.last().unwrap();
9245 let mut new_selections = Vec::new();
9246 if above == state.above {
9247 let end_row = if above {
9248 DisplayRow(0)
9249 } else {
9250 display_map.max_point().row()
9251 };
9252
9253 'outer: for selection in selections {
9254 if selection.id == last_added_selection {
9255 let range = selection.display_range(&display_map).sorted();
9256 debug_assert_eq!(range.start.row(), range.end.row());
9257 let mut row = range.start.row();
9258 let positions =
9259 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9260 px(start)..px(end)
9261 } else {
9262 let start_x =
9263 display_map.x_for_display_point(range.start, &text_layout_details);
9264 let end_x =
9265 display_map.x_for_display_point(range.end, &text_layout_details);
9266 start_x.min(end_x)..start_x.max(end_x)
9267 };
9268
9269 while row != end_row {
9270 if above {
9271 row.0 -= 1;
9272 } else {
9273 row.0 += 1;
9274 }
9275
9276 if let Some(new_selection) = self.selections.build_columnar_selection(
9277 &display_map,
9278 row,
9279 &positions,
9280 selection.reversed,
9281 &text_layout_details,
9282 ) {
9283 state.stack.push(new_selection.id);
9284 if above {
9285 new_selections.push(new_selection);
9286 new_selections.push(selection);
9287 } else {
9288 new_selections.push(selection);
9289 new_selections.push(new_selection);
9290 }
9291
9292 continue 'outer;
9293 }
9294 }
9295 }
9296
9297 new_selections.push(selection);
9298 }
9299 } else {
9300 new_selections = selections;
9301 new_selections.retain(|s| s.id != last_added_selection);
9302 state.stack.pop();
9303 }
9304
9305 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9306 s.select(new_selections);
9307 });
9308 if state.stack.len() > 1 {
9309 self.add_selections_state = Some(state);
9310 }
9311 }
9312
9313 pub fn select_next_match_internal(
9314 &mut self,
9315 display_map: &DisplaySnapshot,
9316 replace_newest: bool,
9317 autoscroll: Option<Autoscroll>,
9318 window: &mut Window,
9319 cx: &mut Context<Self>,
9320 ) -> Result<()> {
9321 fn select_next_match_ranges(
9322 this: &mut Editor,
9323 range: Range<usize>,
9324 replace_newest: bool,
9325 auto_scroll: Option<Autoscroll>,
9326 window: &mut Window,
9327 cx: &mut Context<Editor>,
9328 ) {
9329 this.unfold_ranges(&[range.clone()], false, true, cx);
9330 this.change_selections(auto_scroll, window, cx, |s| {
9331 if replace_newest {
9332 s.delete(s.newest_anchor().id);
9333 }
9334 s.insert_range(range.clone());
9335 });
9336 }
9337
9338 let buffer = &display_map.buffer_snapshot;
9339 let mut selections = self.selections.all::<usize>(cx);
9340 if let Some(mut select_next_state) = self.select_next_state.take() {
9341 let query = &select_next_state.query;
9342 if !select_next_state.done {
9343 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9344 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9345 let mut next_selected_range = None;
9346
9347 let bytes_after_last_selection =
9348 buffer.bytes_in_range(last_selection.end..buffer.len());
9349 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9350 let query_matches = query
9351 .stream_find_iter(bytes_after_last_selection)
9352 .map(|result| (last_selection.end, result))
9353 .chain(
9354 query
9355 .stream_find_iter(bytes_before_first_selection)
9356 .map(|result| (0, result)),
9357 );
9358
9359 for (start_offset, query_match) in query_matches {
9360 let query_match = query_match.unwrap(); // can only fail due to I/O
9361 let offset_range =
9362 start_offset + query_match.start()..start_offset + query_match.end();
9363 let display_range = offset_range.start.to_display_point(display_map)
9364 ..offset_range.end.to_display_point(display_map);
9365
9366 if !select_next_state.wordwise
9367 || (!movement::is_inside_word(display_map, display_range.start)
9368 && !movement::is_inside_word(display_map, display_range.end))
9369 {
9370 // TODO: This is n^2, because we might check all the selections
9371 if !selections
9372 .iter()
9373 .any(|selection| selection.range().overlaps(&offset_range))
9374 {
9375 next_selected_range = Some(offset_range);
9376 break;
9377 }
9378 }
9379 }
9380
9381 if let Some(next_selected_range) = next_selected_range {
9382 select_next_match_ranges(
9383 self,
9384 next_selected_range,
9385 replace_newest,
9386 autoscroll,
9387 window,
9388 cx,
9389 );
9390 } else {
9391 select_next_state.done = true;
9392 }
9393 }
9394
9395 self.select_next_state = Some(select_next_state);
9396 } else {
9397 let mut only_carets = true;
9398 let mut same_text_selected = true;
9399 let mut selected_text = None;
9400
9401 let mut selections_iter = selections.iter().peekable();
9402 while let Some(selection) = selections_iter.next() {
9403 if selection.start != selection.end {
9404 only_carets = false;
9405 }
9406
9407 if same_text_selected {
9408 if selected_text.is_none() {
9409 selected_text =
9410 Some(buffer.text_for_range(selection.range()).collect::<String>());
9411 }
9412
9413 if let Some(next_selection) = selections_iter.peek() {
9414 if next_selection.range().len() == selection.range().len() {
9415 let next_selected_text = buffer
9416 .text_for_range(next_selection.range())
9417 .collect::<String>();
9418 if Some(next_selected_text) != selected_text {
9419 same_text_selected = false;
9420 selected_text = None;
9421 }
9422 } else {
9423 same_text_selected = false;
9424 selected_text = None;
9425 }
9426 }
9427 }
9428 }
9429
9430 if only_carets {
9431 for selection in &mut selections {
9432 let word_range = movement::surrounding_word(
9433 display_map,
9434 selection.start.to_display_point(display_map),
9435 );
9436 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9437 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9438 selection.goal = SelectionGoal::None;
9439 selection.reversed = false;
9440 select_next_match_ranges(
9441 self,
9442 selection.start..selection.end,
9443 replace_newest,
9444 autoscroll,
9445 window,
9446 cx,
9447 );
9448 }
9449
9450 if selections.len() == 1 {
9451 let selection = selections
9452 .last()
9453 .expect("ensured that there's only one selection");
9454 let query = buffer
9455 .text_for_range(selection.start..selection.end)
9456 .collect::<String>();
9457 let is_empty = query.is_empty();
9458 let select_state = SelectNextState {
9459 query: AhoCorasick::new(&[query])?,
9460 wordwise: true,
9461 done: is_empty,
9462 };
9463 self.select_next_state = Some(select_state);
9464 } else {
9465 self.select_next_state = None;
9466 }
9467 } else if let Some(selected_text) = selected_text {
9468 self.select_next_state = Some(SelectNextState {
9469 query: AhoCorasick::new(&[selected_text])?,
9470 wordwise: false,
9471 done: false,
9472 });
9473 self.select_next_match_internal(
9474 display_map,
9475 replace_newest,
9476 autoscroll,
9477 window,
9478 cx,
9479 )?;
9480 }
9481 }
9482 Ok(())
9483 }
9484
9485 pub fn select_all_matches(
9486 &mut self,
9487 _action: &SelectAllMatches,
9488 window: &mut Window,
9489 cx: &mut Context<Self>,
9490 ) -> Result<()> {
9491 self.push_to_selection_history();
9492 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9493
9494 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9495 let Some(select_next_state) = self.select_next_state.as_mut() else {
9496 return Ok(());
9497 };
9498 if select_next_state.done {
9499 return Ok(());
9500 }
9501
9502 let mut new_selections = self.selections.all::<usize>(cx);
9503
9504 let buffer = &display_map.buffer_snapshot;
9505 let query_matches = select_next_state
9506 .query
9507 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9508
9509 for query_match in query_matches {
9510 let query_match = query_match.unwrap(); // can only fail due to I/O
9511 let offset_range = query_match.start()..query_match.end();
9512 let display_range = offset_range.start.to_display_point(&display_map)
9513 ..offset_range.end.to_display_point(&display_map);
9514
9515 if !select_next_state.wordwise
9516 || (!movement::is_inside_word(&display_map, display_range.start)
9517 && !movement::is_inside_word(&display_map, display_range.end))
9518 {
9519 self.selections.change_with(cx, |selections| {
9520 new_selections.push(Selection {
9521 id: selections.new_selection_id(),
9522 start: offset_range.start,
9523 end: offset_range.end,
9524 reversed: false,
9525 goal: SelectionGoal::None,
9526 });
9527 });
9528 }
9529 }
9530
9531 new_selections.sort_by_key(|selection| selection.start);
9532 let mut ix = 0;
9533 while ix + 1 < new_selections.len() {
9534 let current_selection = &new_selections[ix];
9535 let next_selection = &new_selections[ix + 1];
9536 if current_selection.range().overlaps(&next_selection.range()) {
9537 if current_selection.id < next_selection.id {
9538 new_selections.remove(ix + 1);
9539 } else {
9540 new_selections.remove(ix);
9541 }
9542 } else {
9543 ix += 1;
9544 }
9545 }
9546
9547 let reversed = self.selections.oldest::<usize>(cx).reversed;
9548
9549 for selection in new_selections.iter_mut() {
9550 selection.reversed = reversed;
9551 }
9552
9553 select_next_state.done = true;
9554 self.unfold_ranges(
9555 &new_selections
9556 .iter()
9557 .map(|selection| selection.range())
9558 .collect::<Vec<_>>(),
9559 false,
9560 false,
9561 cx,
9562 );
9563 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9564 selections.select(new_selections)
9565 });
9566
9567 Ok(())
9568 }
9569
9570 pub fn select_next(
9571 &mut self,
9572 action: &SelectNext,
9573 window: &mut Window,
9574 cx: &mut Context<Self>,
9575 ) -> Result<()> {
9576 self.push_to_selection_history();
9577 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9578 self.select_next_match_internal(
9579 &display_map,
9580 action.replace_newest,
9581 Some(Autoscroll::newest()),
9582 window,
9583 cx,
9584 )?;
9585 Ok(())
9586 }
9587
9588 pub fn select_previous(
9589 &mut self,
9590 action: &SelectPrevious,
9591 window: &mut Window,
9592 cx: &mut Context<Self>,
9593 ) -> Result<()> {
9594 self.push_to_selection_history();
9595 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9596 let buffer = &display_map.buffer_snapshot;
9597 let mut selections = self.selections.all::<usize>(cx);
9598 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9599 let query = &select_prev_state.query;
9600 if !select_prev_state.done {
9601 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9602 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9603 let mut next_selected_range = None;
9604 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9605 let bytes_before_last_selection =
9606 buffer.reversed_bytes_in_range(0..last_selection.start);
9607 let bytes_after_first_selection =
9608 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9609 let query_matches = query
9610 .stream_find_iter(bytes_before_last_selection)
9611 .map(|result| (last_selection.start, result))
9612 .chain(
9613 query
9614 .stream_find_iter(bytes_after_first_selection)
9615 .map(|result| (buffer.len(), result)),
9616 );
9617 for (end_offset, query_match) in query_matches {
9618 let query_match = query_match.unwrap(); // can only fail due to I/O
9619 let offset_range =
9620 end_offset - query_match.end()..end_offset - query_match.start();
9621 let display_range = offset_range.start.to_display_point(&display_map)
9622 ..offset_range.end.to_display_point(&display_map);
9623
9624 if !select_prev_state.wordwise
9625 || (!movement::is_inside_word(&display_map, display_range.start)
9626 && !movement::is_inside_word(&display_map, display_range.end))
9627 {
9628 next_selected_range = Some(offset_range);
9629 break;
9630 }
9631 }
9632
9633 if let Some(next_selected_range) = next_selected_range {
9634 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9635 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9636 if action.replace_newest {
9637 s.delete(s.newest_anchor().id);
9638 }
9639 s.insert_range(next_selected_range);
9640 });
9641 } else {
9642 select_prev_state.done = true;
9643 }
9644 }
9645
9646 self.select_prev_state = Some(select_prev_state);
9647 } else {
9648 let mut only_carets = true;
9649 let mut same_text_selected = true;
9650 let mut selected_text = None;
9651
9652 let mut selections_iter = selections.iter().peekable();
9653 while let Some(selection) = selections_iter.next() {
9654 if selection.start != selection.end {
9655 only_carets = false;
9656 }
9657
9658 if same_text_selected {
9659 if selected_text.is_none() {
9660 selected_text =
9661 Some(buffer.text_for_range(selection.range()).collect::<String>());
9662 }
9663
9664 if let Some(next_selection) = selections_iter.peek() {
9665 if next_selection.range().len() == selection.range().len() {
9666 let next_selected_text = buffer
9667 .text_for_range(next_selection.range())
9668 .collect::<String>();
9669 if Some(next_selected_text) != selected_text {
9670 same_text_selected = false;
9671 selected_text = None;
9672 }
9673 } else {
9674 same_text_selected = false;
9675 selected_text = None;
9676 }
9677 }
9678 }
9679 }
9680
9681 if only_carets {
9682 for selection in &mut selections {
9683 let word_range = movement::surrounding_word(
9684 &display_map,
9685 selection.start.to_display_point(&display_map),
9686 );
9687 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9688 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9689 selection.goal = SelectionGoal::None;
9690 selection.reversed = false;
9691 }
9692 if selections.len() == 1 {
9693 let selection = selections
9694 .last()
9695 .expect("ensured that there's only one selection");
9696 let query = buffer
9697 .text_for_range(selection.start..selection.end)
9698 .collect::<String>();
9699 let is_empty = query.is_empty();
9700 let select_state = SelectNextState {
9701 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9702 wordwise: true,
9703 done: is_empty,
9704 };
9705 self.select_prev_state = Some(select_state);
9706 } else {
9707 self.select_prev_state = None;
9708 }
9709
9710 self.unfold_ranges(
9711 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9712 false,
9713 true,
9714 cx,
9715 );
9716 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9717 s.select(selections);
9718 });
9719 } else if let Some(selected_text) = selected_text {
9720 self.select_prev_state = Some(SelectNextState {
9721 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9722 wordwise: false,
9723 done: false,
9724 });
9725 self.select_previous(action, window, cx)?;
9726 }
9727 }
9728 Ok(())
9729 }
9730
9731 pub fn toggle_comments(
9732 &mut self,
9733 action: &ToggleComments,
9734 window: &mut Window,
9735 cx: &mut Context<Self>,
9736 ) {
9737 if self.read_only(cx) {
9738 return;
9739 }
9740 let text_layout_details = &self.text_layout_details(window);
9741 self.transact(window, cx, |this, window, cx| {
9742 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9743 let mut edits = Vec::new();
9744 let mut selection_edit_ranges = Vec::new();
9745 let mut last_toggled_row = None;
9746 let snapshot = this.buffer.read(cx).read(cx);
9747 let empty_str: Arc<str> = Arc::default();
9748 let mut suffixes_inserted = Vec::new();
9749 let ignore_indent = action.ignore_indent;
9750
9751 fn comment_prefix_range(
9752 snapshot: &MultiBufferSnapshot,
9753 row: MultiBufferRow,
9754 comment_prefix: &str,
9755 comment_prefix_whitespace: &str,
9756 ignore_indent: bool,
9757 ) -> Range<Point> {
9758 let indent_size = if ignore_indent {
9759 0
9760 } else {
9761 snapshot.indent_size_for_line(row).len
9762 };
9763
9764 let start = Point::new(row.0, indent_size);
9765
9766 let mut line_bytes = snapshot
9767 .bytes_in_range(start..snapshot.max_point())
9768 .flatten()
9769 .copied();
9770
9771 // If this line currently begins with the line comment prefix, then record
9772 // the range containing the prefix.
9773 if line_bytes
9774 .by_ref()
9775 .take(comment_prefix.len())
9776 .eq(comment_prefix.bytes())
9777 {
9778 // Include any whitespace that matches the comment prefix.
9779 let matching_whitespace_len = line_bytes
9780 .zip(comment_prefix_whitespace.bytes())
9781 .take_while(|(a, b)| a == b)
9782 .count() as u32;
9783 let end = Point::new(
9784 start.row,
9785 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9786 );
9787 start..end
9788 } else {
9789 start..start
9790 }
9791 }
9792
9793 fn comment_suffix_range(
9794 snapshot: &MultiBufferSnapshot,
9795 row: MultiBufferRow,
9796 comment_suffix: &str,
9797 comment_suffix_has_leading_space: bool,
9798 ) -> Range<Point> {
9799 let end = Point::new(row.0, snapshot.line_len(row));
9800 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9801
9802 let mut line_end_bytes = snapshot
9803 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9804 .flatten()
9805 .copied();
9806
9807 let leading_space_len = if suffix_start_column > 0
9808 && line_end_bytes.next() == Some(b' ')
9809 && comment_suffix_has_leading_space
9810 {
9811 1
9812 } else {
9813 0
9814 };
9815
9816 // If this line currently begins with the line comment prefix, then record
9817 // the range containing the prefix.
9818 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9819 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9820 start..end
9821 } else {
9822 end..end
9823 }
9824 }
9825
9826 // TODO: Handle selections that cross excerpts
9827 for selection in &mut selections {
9828 let start_column = snapshot
9829 .indent_size_for_line(MultiBufferRow(selection.start.row))
9830 .len;
9831 let language = if let Some(language) =
9832 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9833 {
9834 language
9835 } else {
9836 continue;
9837 };
9838
9839 selection_edit_ranges.clear();
9840
9841 // If multiple selections contain a given row, avoid processing that
9842 // row more than once.
9843 let mut start_row = MultiBufferRow(selection.start.row);
9844 if last_toggled_row == Some(start_row) {
9845 start_row = start_row.next_row();
9846 }
9847 let end_row =
9848 if selection.end.row > selection.start.row && selection.end.column == 0 {
9849 MultiBufferRow(selection.end.row - 1)
9850 } else {
9851 MultiBufferRow(selection.end.row)
9852 };
9853 last_toggled_row = Some(end_row);
9854
9855 if start_row > end_row {
9856 continue;
9857 }
9858
9859 // If the language has line comments, toggle those.
9860 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9861
9862 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9863 if ignore_indent {
9864 full_comment_prefixes = full_comment_prefixes
9865 .into_iter()
9866 .map(|s| Arc::from(s.trim_end()))
9867 .collect();
9868 }
9869
9870 if !full_comment_prefixes.is_empty() {
9871 let first_prefix = full_comment_prefixes
9872 .first()
9873 .expect("prefixes is non-empty");
9874 let prefix_trimmed_lengths = full_comment_prefixes
9875 .iter()
9876 .map(|p| p.trim_end_matches(' ').len())
9877 .collect::<SmallVec<[usize; 4]>>();
9878
9879 let mut all_selection_lines_are_comments = true;
9880
9881 for row in start_row.0..=end_row.0 {
9882 let row = MultiBufferRow(row);
9883 if start_row < end_row && snapshot.is_line_blank(row) {
9884 continue;
9885 }
9886
9887 let prefix_range = full_comment_prefixes
9888 .iter()
9889 .zip(prefix_trimmed_lengths.iter().copied())
9890 .map(|(prefix, trimmed_prefix_len)| {
9891 comment_prefix_range(
9892 snapshot.deref(),
9893 row,
9894 &prefix[..trimmed_prefix_len],
9895 &prefix[trimmed_prefix_len..],
9896 ignore_indent,
9897 )
9898 })
9899 .max_by_key(|range| range.end.column - range.start.column)
9900 .expect("prefixes is non-empty");
9901
9902 if prefix_range.is_empty() {
9903 all_selection_lines_are_comments = false;
9904 }
9905
9906 selection_edit_ranges.push(prefix_range);
9907 }
9908
9909 if all_selection_lines_are_comments {
9910 edits.extend(
9911 selection_edit_ranges
9912 .iter()
9913 .cloned()
9914 .map(|range| (range, empty_str.clone())),
9915 );
9916 } else {
9917 let min_column = selection_edit_ranges
9918 .iter()
9919 .map(|range| range.start.column)
9920 .min()
9921 .unwrap_or(0);
9922 edits.extend(selection_edit_ranges.iter().map(|range| {
9923 let position = Point::new(range.start.row, min_column);
9924 (position..position, first_prefix.clone())
9925 }));
9926 }
9927 } else if let Some((full_comment_prefix, comment_suffix)) =
9928 language.block_comment_delimiters()
9929 {
9930 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9931 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9932 let prefix_range = comment_prefix_range(
9933 snapshot.deref(),
9934 start_row,
9935 comment_prefix,
9936 comment_prefix_whitespace,
9937 ignore_indent,
9938 );
9939 let suffix_range = comment_suffix_range(
9940 snapshot.deref(),
9941 end_row,
9942 comment_suffix.trim_start_matches(' '),
9943 comment_suffix.starts_with(' '),
9944 );
9945
9946 if prefix_range.is_empty() || suffix_range.is_empty() {
9947 edits.push((
9948 prefix_range.start..prefix_range.start,
9949 full_comment_prefix.clone(),
9950 ));
9951 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9952 suffixes_inserted.push((end_row, comment_suffix.len()));
9953 } else {
9954 edits.push((prefix_range, empty_str.clone()));
9955 edits.push((suffix_range, empty_str.clone()));
9956 }
9957 } else {
9958 continue;
9959 }
9960 }
9961
9962 drop(snapshot);
9963 this.buffer.update(cx, |buffer, cx| {
9964 buffer.edit(edits, None, cx);
9965 });
9966
9967 // Adjust selections so that they end before any comment suffixes that
9968 // were inserted.
9969 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9970 let mut selections = this.selections.all::<Point>(cx);
9971 let snapshot = this.buffer.read(cx).read(cx);
9972 for selection in &mut selections {
9973 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9974 match row.cmp(&MultiBufferRow(selection.end.row)) {
9975 Ordering::Less => {
9976 suffixes_inserted.next();
9977 continue;
9978 }
9979 Ordering::Greater => break,
9980 Ordering::Equal => {
9981 if selection.end.column == snapshot.line_len(row) {
9982 if selection.is_empty() {
9983 selection.start.column -= suffix_len as u32;
9984 }
9985 selection.end.column -= suffix_len as u32;
9986 }
9987 break;
9988 }
9989 }
9990 }
9991 }
9992
9993 drop(snapshot);
9994 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9995 s.select(selections)
9996 });
9997
9998 let selections = this.selections.all::<Point>(cx);
9999 let selections_on_single_row = selections.windows(2).all(|selections| {
10000 selections[0].start.row == selections[1].start.row
10001 && selections[0].end.row == selections[1].end.row
10002 && selections[0].start.row == selections[0].end.row
10003 });
10004 let selections_selecting = selections
10005 .iter()
10006 .any(|selection| selection.start != selection.end);
10007 let advance_downwards = action.advance_downwards
10008 && selections_on_single_row
10009 && !selections_selecting
10010 && !matches!(this.mode, EditorMode::SingleLine { .. });
10011
10012 if advance_downwards {
10013 let snapshot = this.buffer.read(cx).snapshot(cx);
10014
10015 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10016 s.move_cursors_with(|display_snapshot, display_point, _| {
10017 let mut point = display_point.to_point(display_snapshot);
10018 point.row += 1;
10019 point = snapshot.clip_point(point, Bias::Left);
10020 let display_point = point.to_display_point(display_snapshot);
10021 let goal = SelectionGoal::HorizontalPosition(
10022 display_snapshot
10023 .x_for_display_point(display_point, text_layout_details)
10024 .into(),
10025 );
10026 (display_point, goal)
10027 })
10028 });
10029 }
10030 });
10031 }
10032
10033 pub fn select_enclosing_symbol(
10034 &mut self,
10035 _: &SelectEnclosingSymbol,
10036 window: &mut Window,
10037 cx: &mut Context<Self>,
10038 ) {
10039 let buffer = self.buffer.read(cx).snapshot(cx);
10040 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10041
10042 fn update_selection(
10043 selection: &Selection<usize>,
10044 buffer_snap: &MultiBufferSnapshot,
10045 ) -> Option<Selection<usize>> {
10046 let cursor = selection.head();
10047 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10048 for symbol in symbols.iter().rev() {
10049 let start = symbol.range.start.to_offset(buffer_snap);
10050 let end = symbol.range.end.to_offset(buffer_snap);
10051 let new_range = start..end;
10052 if start < selection.start || end > selection.end {
10053 return Some(Selection {
10054 id: selection.id,
10055 start: new_range.start,
10056 end: new_range.end,
10057 goal: SelectionGoal::None,
10058 reversed: selection.reversed,
10059 });
10060 }
10061 }
10062 None
10063 }
10064
10065 let mut selected_larger_symbol = false;
10066 let new_selections = old_selections
10067 .iter()
10068 .map(|selection| match update_selection(selection, &buffer) {
10069 Some(new_selection) => {
10070 if new_selection.range() != selection.range() {
10071 selected_larger_symbol = true;
10072 }
10073 new_selection
10074 }
10075 None => selection.clone(),
10076 })
10077 .collect::<Vec<_>>();
10078
10079 if selected_larger_symbol {
10080 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10081 s.select(new_selections);
10082 });
10083 }
10084 }
10085
10086 pub fn select_larger_syntax_node(
10087 &mut self,
10088 _: &SelectLargerSyntaxNode,
10089 window: &mut Window,
10090 cx: &mut Context<Self>,
10091 ) {
10092 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10093 let buffer = self.buffer.read(cx).snapshot(cx);
10094 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10095
10096 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10097 let mut selected_larger_node = false;
10098 let new_selections = old_selections
10099 .iter()
10100 .map(|selection| {
10101 let old_range = selection.start..selection.end;
10102 let mut new_range = old_range.clone();
10103 let mut new_node = None;
10104 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10105 {
10106 new_node = Some(node);
10107 new_range = containing_range;
10108 if !display_map.intersects_fold(new_range.start)
10109 && !display_map.intersects_fold(new_range.end)
10110 {
10111 break;
10112 }
10113 }
10114
10115 if let Some(node) = new_node {
10116 // Log the ancestor, to support using this action as a way to explore TreeSitter
10117 // nodes. Parent and grandparent are also logged because this operation will not
10118 // visit nodes that have the same range as their parent.
10119 log::info!("Node: {node:?}");
10120 let parent = node.parent();
10121 log::info!("Parent: {parent:?}");
10122 let grandparent = parent.and_then(|x| x.parent());
10123 log::info!("Grandparent: {grandparent:?}");
10124 }
10125
10126 selected_larger_node |= new_range != old_range;
10127 Selection {
10128 id: selection.id,
10129 start: new_range.start,
10130 end: new_range.end,
10131 goal: SelectionGoal::None,
10132 reversed: selection.reversed,
10133 }
10134 })
10135 .collect::<Vec<_>>();
10136
10137 if selected_larger_node {
10138 stack.push(old_selections);
10139 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10140 s.select(new_selections);
10141 });
10142 }
10143 self.select_larger_syntax_node_stack = stack;
10144 }
10145
10146 pub fn select_smaller_syntax_node(
10147 &mut self,
10148 _: &SelectSmallerSyntaxNode,
10149 window: &mut Window,
10150 cx: &mut Context<Self>,
10151 ) {
10152 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10153 if let Some(selections) = stack.pop() {
10154 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10155 s.select(selections.to_vec());
10156 });
10157 }
10158 self.select_larger_syntax_node_stack = stack;
10159 }
10160
10161 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10162 if !EditorSettings::get_global(cx).gutter.runnables {
10163 self.clear_tasks();
10164 return Task::ready(());
10165 }
10166 let project = self.project.as_ref().map(Entity::downgrade);
10167 cx.spawn_in(window, |this, mut cx| async move {
10168 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10169 let Some(project) = project.and_then(|p| p.upgrade()) else {
10170 return;
10171 };
10172 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10173 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10174 }) else {
10175 return;
10176 };
10177
10178 let hide_runnables = project
10179 .update(&mut cx, |project, cx| {
10180 // Do not display any test indicators in non-dev server remote projects.
10181 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10182 })
10183 .unwrap_or(true);
10184 if hide_runnables {
10185 return;
10186 }
10187 let new_rows =
10188 cx.background_executor()
10189 .spawn({
10190 let snapshot = display_snapshot.clone();
10191 async move {
10192 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10193 }
10194 })
10195 .await;
10196
10197 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10198 this.update(&mut cx, |this, _| {
10199 this.clear_tasks();
10200 for (key, value) in rows {
10201 this.insert_tasks(key, value);
10202 }
10203 })
10204 .ok();
10205 })
10206 }
10207 fn fetch_runnable_ranges(
10208 snapshot: &DisplaySnapshot,
10209 range: Range<Anchor>,
10210 ) -> Vec<language::RunnableRange> {
10211 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10212 }
10213
10214 fn runnable_rows(
10215 project: Entity<Project>,
10216 snapshot: DisplaySnapshot,
10217 runnable_ranges: Vec<RunnableRange>,
10218 mut cx: AsyncWindowContext,
10219 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10220 runnable_ranges
10221 .into_iter()
10222 .filter_map(|mut runnable| {
10223 let tasks = cx
10224 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10225 .ok()?;
10226 if tasks.is_empty() {
10227 return None;
10228 }
10229
10230 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10231
10232 let row = snapshot
10233 .buffer_snapshot
10234 .buffer_line_for_row(MultiBufferRow(point.row))?
10235 .1
10236 .start
10237 .row;
10238
10239 let context_range =
10240 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10241 Some((
10242 (runnable.buffer_id, row),
10243 RunnableTasks {
10244 templates: tasks,
10245 offset: MultiBufferOffset(runnable.run_range.start),
10246 context_range,
10247 column: point.column,
10248 extra_variables: runnable.extra_captures,
10249 },
10250 ))
10251 })
10252 .collect()
10253 }
10254
10255 fn templates_with_tags(
10256 project: &Entity<Project>,
10257 runnable: &mut Runnable,
10258 cx: &mut App,
10259 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10260 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10261 let (worktree_id, file) = project
10262 .buffer_for_id(runnable.buffer, cx)
10263 .and_then(|buffer| buffer.read(cx).file())
10264 .map(|file| (file.worktree_id(cx), file.clone()))
10265 .unzip();
10266
10267 (
10268 project.task_store().read(cx).task_inventory().cloned(),
10269 worktree_id,
10270 file,
10271 )
10272 });
10273
10274 let tags = mem::take(&mut runnable.tags);
10275 let mut tags: Vec<_> = tags
10276 .into_iter()
10277 .flat_map(|tag| {
10278 let tag = tag.0.clone();
10279 inventory
10280 .as_ref()
10281 .into_iter()
10282 .flat_map(|inventory| {
10283 inventory.read(cx).list_tasks(
10284 file.clone(),
10285 Some(runnable.language.clone()),
10286 worktree_id,
10287 cx,
10288 )
10289 })
10290 .filter(move |(_, template)| {
10291 template.tags.iter().any(|source_tag| source_tag == &tag)
10292 })
10293 })
10294 .sorted_by_key(|(kind, _)| kind.to_owned())
10295 .collect();
10296 if let Some((leading_tag_source, _)) = tags.first() {
10297 // Strongest source wins; if we have worktree tag binding, prefer that to
10298 // global and language bindings;
10299 // if we have a global binding, prefer that to language binding.
10300 let first_mismatch = tags
10301 .iter()
10302 .position(|(tag_source, _)| tag_source != leading_tag_source);
10303 if let Some(index) = first_mismatch {
10304 tags.truncate(index);
10305 }
10306 }
10307
10308 tags
10309 }
10310
10311 pub fn move_to_enclosing_bracket(
10312 &mut self,
10313 _: &MoveToEnclosingBracket,
10314 window: &mut Window,
10315 cx: &mut Context<Self>,
10316 ) {
10317 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10318 s.move_offsets_with(|snapshot, selection| {
10319 let Some(enclosing_bracket_ranges) =
10320 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10321 else {
10322 return;
10323 };
10324
10325 let mut best_length = usize::MAX;
10326 let mut best_inside = false;
10327 let mut best_in_bracket_range = false;
10328 let mut best_destination = None;
10329 for (open, close) in enclosing_bracket_ranges {
10330 let close = close.to_inclusive();
10331 let length = close.end() - open.start;
10332 let inside = selection.start >= open.end && selection.end <= *close.start();
10333 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10334 || close.contains(&selection.head());
10335
10336 // If best is next to a bracket and current isn't, skip
10337 if !in_bracket_range && best_in_bracket_range {
10338 continue;
10339 }
10340
10341 // Prefer smaller lengths unless best is inside and current isn't
10342 if length > best_length && (best_inside || !inside) {
10343 continue;
10344 }
10345
10346 best_length = length;
10347 best_inside = inside;
10348 best_in_bracket_range = in_bracket_range;
10349 best_destination = Some(
10350 if close.contains(&selection.start) && close.contains(&selection.end) {
10351 if inside {
10352 open.end
10353 } else {
10354 open.start
10355 }
10356 } else if inside {
10357 *close.start()
10358 } else {
10359 *close.end()
10360 },
10361 );
10362 }
10363
10364 if let Some(destination) = best_destination {
10365 selection.collapse_to(destination, SelectionGoal::None);
10366 }
10367 })
10368 });
10369 }
10370
10371 pub fn undo_selection(
10372 &mut self,
10373 _: &UndoSelection,
10374 window: &mut Window,
10375 cx: &mut Context<Self>,
10376 ) {
10377 self.end_selection(window, cx);
10378 self.selection_history.mode = SelectionHistoryMode::Undoing;
10379 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10380 self.change_selections(None, window, cx, |s| {
10381 s.select_anchors(entry.selections.to_vec())
10382 });
10383 self.select_next_state = entry.select_next_state;
10384 self.select_prev_state = entry.select_prev_state;
10385 self.add_selections_state = entry.add_selections_state;
10386 self.request_autoscroll(Autoscroll::newest(), cx);
10387 }
10388 self.selection_history.mode = SelectionHistoryMode::Normal;
10389 }
10390
10391 pub fn redo_selection(
10392 &mut self,
10393 _: &RedoSelection,
10394 window: &mut Window,
10395 cx: &mut Context<Self>,
10396 ) {
10397 self.end_selection(window, cx);
10398 self.selection_history.mode = SelectionHistoryMode::Redoing;
10399 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10400 self.change_selections(None, window, cx, |s| {
10401 s.select_anchors(entry.selections.to_vec())
10402 });
10403 self.select_next_state = entry.select_next_state;
10404 self.select_prev_state = entry.select_prev_state;
10405 self.add_selections_state = entry.add_selections_state;
10406 self.request_autoscroll(Autoscroll::newest(), cx);
10407 }
10408 self.selection_history.mode = SelectionHistoryMode::Normal;
10409 }
10410
10411 pub fn expand_excerpts(
10412 &mut self,
10413 action: &ExpandExcerpts,
10414 _: &mut Window,
10415 cx: &mut Context<Self>,
10416 ) {
10417 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10418 }
10419
10420 pub fn expand_excerpts_down(
10421 &mut self,
10422 action: &ExpandExcerptsDown,
10423 _: &mut Window,
10424 cx: &mut Context<Self>,
10425 ) {
10426 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10427 }
10428
10429 pub fn expand_excerpts_up(
10430 &mut self,
10431 action: &ExpandExcerptsUp,
10432 _: &mut Window,
10433 cx: &mut Context<Self>,
10434 ) {
10435 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10436 }
10437
10438 pub fn expand_excerpts_for_direction(
10439 &mut self,
10440 lines: u32,
10441 direction: ExpandExcerptDirection,
10442
10443 cx: &mut Context<Self>,
10444 ) {
10445 let selections = self.selections.disjoint_anchors();
10446
10447 let lines = if lines == 0 {
10448 EditorSettings::get_global(cx).expand_excerpt_lines
10449 } else {
10450 lines
10451 };
10452
10453 self.buffer.update(cx, |buffer, cx| {
10454 let snapshot = buffer.snapshot(cx);
10455 let mut excerpt_ids = selections
10456 .iter()
10457 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10458 .collect::<Vec<_>>();
10459 excerpt_ids.sort();
10460 excerpt_ids.dedup();
10461 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10462 })
10463 }
10464
10465 pub fn expand_excerpt(
10466 &mut self,
10467 excerpt: ExcerptId,
10468 direction: ExpandExcerptDirection,
10469 cx: &mut Context<Self>,
10470 ) {
10471 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10472 self.buffer.update(cx, |buffer, cx| {
10473 buffer.expand_excerpts([excerpt], lines, direction, cx)
10474 })
10475 }
10476
10477 pub fn go_to_singleton_buffer_point(
10478 &mut self,
10479 point: Point,
10480 window: &mut Window,
10481 cx: &mut Context<Self>,
10482 ) {
10483 self.go_to_singleton_buffer_range(point..point, window, cx);
10484 }
10485
10486 pub fn go_to_singleton_buffer_range(
10487 &mut self,
10488 range: Range<Point>,
10489 window: &mut Window,
10490 cx: &mut Context<Self>,
10491 ) {
10492 let multibuffer = self.buffer().read(cx);
10493 let Some(buffer) = multibuffer.as_singleton() else {
10494 return;
10495 };
10496 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10497 return;
10498 };
10499 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10500 return;
10501 };
10502 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10503 s.select_anchor_ranges([start..end])
10504 });
10505 }
10506
10507 fn go_to_diagnostic(
10508 &mut self,
10509 _: &GoToDiagnostic,
10510 window: &mut Window,
10511 cx: &mut Context<Self>,
10512 ) {
10513 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10514 }
10515
10516 fn go_to_prev_diagnostic(
10517 &mut self,
10518 _: &GoToPrevDiagnostic,
10519 window: &mut Window,
10520 cx: &mut Context<Self>,
10521 ) {
10522 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10523 }
10524
10525 pub fn go_to_diagnostic_impl(
10526 &mut self,
10527 direction: Direction,
10528 window: &mut Window,
10529 cx: &mut Context<Self>,
10530 ) {
10531 let buffer = self.buffer.read(cx).snapshot(cx);
10532 let selection = self.selections.newest::<usize>(cx);
10533
10534 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10535 if direction == Direction::Next {
10536 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10537 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10538 return;
10539 };
10540 self.activate_diagnostics(
10541 buffer_id,
10542 popover.local_diagnostic.diagnostic.group_id,
10543 window,
10544 cx,
10545 );
10546 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10547 let primary_range_start = active_diagnostics.primary_range.start;
10548 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10549 let mut new_selection = s.newest_anchor().clone();
10550 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10551 s.select_anchors(vec![new_selection.clone()]);
10552 });
10553 self.refresh_inline_completion(false, true, window, cx);
10554 }
10555 return;
10556 }
10557 }
10558
10559 let active_group_id = self
10560 .active_diagnostics
10561 .as_ref()
10562 .map(|active_group| active_group.group_id);
10563 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10564 active_diagnostics
10565 .primary_range
10566 .to_offset(&buffer)
10567 .to_inclusive()
10568 });
10569 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10570 if active_primary_range.contains(&selection.head()) {
10571 *active_primary_range.start()
10572 } else {
10573 selection.head()
10574 }
10575 } else {
10576 selection.head()
10577 };
10578
10579 let snapshot = self.snapshot(window, cx);
10580 let primary_diagnostics_before = buffer
10581 .diagnostics_in_range::<usize>(0..search_start)
10582 .filter(|entry| entry.diagnostic.is_primary)
10583 .filter(|entry| entry.range.start != entry.range.end)
10584 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10585 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10586 .collect::<Vec<_>>();
10587 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10588 primary_diagnostics_before
10589 .iter()
10590 .position(|entry| entry.diagnostic.group_id == active_group_id)
10591 });
10592
10593 let primary_diagnostics_after = buffer
10594 .diagnostics_in_range::<usize>(search_start..buffer.len())
10595 .filter(|entry| entry.diagnostic.is_primary)
10596 .filter(|entry| entry.range.start != entry.range.end)
10597 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10598 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10599 .collect::<Vec<_>>();
10600 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10601 primary_diagnostics_after
10602 .iter()
10603 .enumerate()
10604 .rev()
10605 .find_map(|(i, entry)| {
10606 if entry.diagnostic.group_id == active_group_id {
10607 Some(i)
10608 } else {
10609 None
10610 }
10611 })
10612 });
10613
10614 let next_primary_diagnostic = match direction {
10615 Direction::Prev => primary_diagnostics_before
10616 .iter()
10617 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10618 .rev()
10619 .next(),
10620 Direction::Next => primary_diagnostics_after
10621 .iter()
10622 .skip(
10623 last_same_group_diagnostic_after
10624 .map(|index| index + 1)
10625 .unwrap_or(0),
10626 )
10627 .next(),
10628 };
10629
10630 // Cycle around to the start of the buffer, potentially moving back to the start of
10631 // the currently active diagnostic.
10632 let cycle_around = || match direction {
10633 Direction::Prev => primary_diagnostics_after
10634 .iter()
10635 .rev()
10636 .chain(primary_diagnostics_before.iter().rev())
10637 .next(),
10638 Direction::Next => primary_diagnostics_before
10639 .iter()
10640 .chain(primary_diagnostics_after.iter())
10641 .next(),
10642 };
10643
10644 if let Some((primary_range, group_id)) = next_primary_diagnostic
10645 .or_else(cycle_around)
10646 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10647 {
10648 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10649 return;
10650 };
10651 self.activate_diagnostics(buffer_id, group_id, window, cx);
10652 if self.active_diagnostics.is_some() {
10653 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10654 s.select(vec![Selection {
10655 id: selection.id,
10656 start: primary_range.start,
10657 end: primary_range.start,
10658 reversed: false,
10659 goal: SelectionGoal::None,
10660 }]);
10661 });
10662 self.refresh_inline_completion(false, true, window, cx);
10663 }
10664 }
10665 }
10666
10667 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10668 let snapshot = self.snapshot(window, cx);
10669 let selection = self.selections.newest::<Point>(cx);
10670 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10671 }
10672
10673 fn go_to_hunk_after_position(
10674 &mut self,
10675 snapshot: &EditorSnapshot,
10676 position: Point,
10677 window: &mut Window,
10678 cx: &mut Context<Editor>,
10679 ) -> Option<MultiBufferDiffHunk> {
10680 let mut hunk = snapshot
10681 .buffer_snapshot
10682 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10683 .find(|hunk| hunk.row_range.start.0 > position.row);
10684 if hunk.is_none() {
10685 hunk = snapshot
10686 .buffer_snapshot
10687 .diff_hunks_in_range(Point::zero()..position)
10688 .find(|hunk| hunk.row_range.end.0 < position.row)
10689 }
10690 if let Some(hunk) = &hunk {
10691 let destination = Point::new(hunk.row_range.start.0, 0);
10692 self.unfold_ranges(&[destination..destination], false, false, cx);
10693 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10694 s.select_ranges(vec![destination..destination]);
10695 });
10696 }
10697
10698 hunk
10699 }
10700
10701 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10702 let snapshot = self.snapshot(window, cx);
10703 let selection = self.selections.newest::<Point>(cx);
10704 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10705 }
10706
10707 fn go_to_hunk_before_position(
10708 &mut self,
10709 snapshot: &EditorSnapshot,
10710 position: Point,
10711 window: &mut Window,
10712 cx: &mut Context<Editor>,
10713 ) -> Option<MultiBufferDiffHunk> {
10714 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10715 if hunk.is_none() {
10716 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10717 }
10718 if let Some(hunk) = &hunk {
10719 let destination = Point::new(hunk.row_range.start.0, 0);
10720 self.unfold_ranges(&[destination..destination], false, false, cx);
10721 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10722 s.select_ranges(vec![destination..destination]);
10723 });
10724 }
10725
10726 hunk
10727 }
10728
10729 pub fn go_to_definition(
10730 &mut self,
10731 _: &GoToDefinition,
10732 window: &mut Window,
10733 cx: &mut Context<Self>,
10734 ) -> Task<Result<Navigated>> {
10735 let definition =
10736 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10737 cx.spawn_in(window, |editor, mut cx| async move {
10738 if definition.await? == Navigated::Yes {
10739 return Ok(Navigated::Yes);
10740 }
10741 match editor.update_in(&mut cx, |editor, window, cx| {
10742 editor.find_all_references(&FindAllReferences, window, cx)
10743 })? {
10744 Some(references) => references.await,
10745 None => Ok(Navigated::No),
10746 }
10747 })
10748 }
10749
10750 pub fn go_to_declaration(
10751 &mut self,
10752 _: &GoToDeclaration,
10753 window: &mut Window,
10754 cx: &mut Context<Self>,
10755 ) -> Task<Result<Navigated>> {
10756 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10757 }
10758
10759 pub fn go_to_declaration_split(
10760 &mut self,
10761 _: &GoToDeclaration,
10762 window: &mut Window,
10763 cx: &mut Context<Self>,
10764 ) -> Task<Result<Navigated>> {
10765 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10766 }
10767
10768 pub fn go_to_implementation(
10769 &mut self,
10770 _: &GoToImplementation,
10771 window: &mut Window,
10772 cx: &mut Context<Self>,
10773 ) -> Task<Result<Navigated>> {
10774 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10775 }
10776
10777 pub fn go_to_implementation_split(
10778 &mut self,
10779 _: &GoToImplementationSplit,
10780 window: &mut Window,
10781 cx: &mut Context<Self>,
10782 ) -> Task<Result<Navigated>> {
10783 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10784 }
10785
10786 pub fn go_to_type_definition(
10787 &mut self,
10788 _: &GoToTypeDefinition,
10789 window: &mut Window,
10790 cx: &mut Context<Self>,
10791 ) -> Task<Result<Navigated>> {
10792 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10793 }
10794
10795 pub fn go_to_definition_split(
10796 &mut self,
10797 _: &GoToDefinitionSplit,
10798 window: &mut Window,
10799 cx: &mut Context<Self>,
10800 ) -> Task<Result<Navigated>> {
10801 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10802 }
10803
10804 pub fn go_to_type_definition_split(
10805 &mut self,
10806 _: &GoToTypeDefinitionSplit,
10807 window: &mut Window,
10808 cx: &mut Context<Self>,
10809 ) -> Task<Result<Navigated>> {
10810 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10811 }
10812
10813 fn go_to_definition_of_kind(
10814 &mut self,
10815 kind: GotoDefinitionKind,
10816 split: bool,
10817 window: &mut Window,
10818 cx: &mut Context<Self>,
10819 ) -> Task<Result<Navigated>> {
10820 let Some(provider) = self.semantics_provider.clone() else {
10821 return Task::ready(Ok(Navigated::No));
10822 };
10823 let head = self.selections.newest::<usize>(cx).head();
10824 let buffer = self.buffer.read(cx);
10825 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10826 text_anchor
10827 } else {
10828 return Task::ready(Ok(Navigated::No));
10829 };
10830
10831 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10832 return Task::ready(Ok(Navigated::No));
10833 };
10834
10835 cx.spawn_in(window, |editor, mut cx| async move {
10836 let definitions = definitions.await?;
10837 let navigated = editor
10838 .update_in(&mut cx, |editor, window, cx| {
10839 editor.navigate_to_hover_links(
10840 Some(kind),
10841 definitions
10842 .into_iter()
10843 .filter(|location| {
10844 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10845 })
10846 .map(HoverLink::Text)
10847 .collect::<Vec<_>>(),
10848 split,
10849 window,
10850 cx,
10851 )
10852 })?
10853 .await?;
10854 anyhow::Ok(navigated)
10855 })
10856 }
10857
10858 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10859 let selection = self.selections.newest_anchor();
10860 let head = selection.head();
10861 let tail = selection.tail();
10862
10863 let Some((buffer, start_position)) =
10864 self.buffer.read(cx).text_anchor_for_position(head, cx)
10865 else {
10866 return;
10867 };
10868
10869 let end_position = if head != tail {
10870 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10871 return;
10872 };
10873 Some(pos)
10874 } else {
10875 None
10876 };
10877
10878 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10879 let url = if let Some(end_pos) = end_position {
10880 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10881 } else {
10882 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10883 };
10884
10885 if let Some(url) = url {
10886 editor.update(&mut cx, |_, cx| {
10887 cx.open_url(&url);
10888 })
10889 } else {
10890 Ok(())
10891 }
10892 });
10893
10894 url_finder.detach();
10895 }
10896
10897 pub fn open_selected_filename(
10898 &mut self,
10899 _: &OpenSelectedFilename,
10900 window: &mut Window,
10901 cx: &mut Context<Self>,
10902 ) {
10903 let Some(workspace) = self.workspace() else {
10904 return;
10905 };
10906
10907 let position = self.selections.newest_anchor().head();
10908
10909 let Some((buffer, buffer_position)) =
10910 self.buffer.read(cx).text_anchor_for_position(position, cx)
10911 else {
10912 return;
10913 };
10914
10915 let project = self.project.clone();
10916
10917 cx.spawn_in(window, |_, mut cx| async move {
10918 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10919
10920 if let Some((_, path)) = result {
10921 workspace
10922 .update_in(&mut cx, |workspace, window, cx| {
10923 workspace.open_resolved_path(path, window, cx)
10924 })?
10925 .await?;
10926 }
10927 anyhow::Ok(())
10928 })
10929 .detach();
10930 }
10931
10932 pub(crate) fn navigate_to_hover_links(
10933 &mut self,
10934 kind: Option<GotoDefinitionKind>,
10935 mut definitions: Vec<HoverLink>,
10936 split: bool,
10937 window: &mut Window,
10938 cx: &mut Context<Editor>,
10939 ) -> Task<Result<Navigated>> {
10940 // If there is one definition, just open it directly
10941 if definitions.len() == 1 {
10942 let definition = definitions.pop().unwrap();
10943
10944 enum TargetTaskResult {
10945 Location(Option<Location>),
10946 AlreadyNavigated,
10947 }
10948
10949 let target_task = match definition {
10950 HoverLink::Text(link) => {
10951 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10952 }
10953 HoverLink::InlayHint(lsp_location, server_id) => {
10954 let computation =
10955 self.compute_target_location(lsp_location, server_id, window, cx);
10956 cx.background_executor().spawn(async move {
10957 let location = computation.await?;
10958 Ok(TargetTaskResult::Location(location))
10959 })
10960 }
10961 HoverLink::Url(url) => {
10962 cx.open_url(&url);
10963 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10964 }
10965 HoverLink::File(path) => {
10966 if let Some(workspace) = self.workspace() {
10967 cx.spawn_in(window, |_, mut cx| async move {
10968 workspace
10969 .update_in(&mut cx, |workspace, window, cx| {
10970 workspace.open_resolved_path(path, window, cx)
10971 })?
10972 .await
10973 .map(|_| TargetTaskResult::AlreadyNavigated)
10974 })
10975 } else {
10976 Task::ready(Ok(TargetTaskResult::Location(None)))
10977 }
10978 }
10979 };
10980 cx.spawn_in(window, |editor, mut cx| async move {
10981 let target = match target_task.await.context("target resolution task")? {
10982 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10983 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10984 TargetTaskResult::Location(Some(target)) => target,
10985 };
10986
10987 editor.update_in(&mut cx, |editor, window, cx| {
10988 let Some(workspace) = editor.workspace() else {
10989 return Navigated::No;
10990 };
10991 let pane = workspace.read(cx).active_pane().clone();
10992
10993 let range = target.range.to_point(target.buffer.read(cx));
10994 let range = editor.range_for_match(&range);
10995 let range = collapse_multiline_range(range);
10996
10997 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10998 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10999 } else {
11000 window.defer(cx, move |window, cx| {
11001 let target_editor: Entity<Self> =
11002 workspace.update(cx, |workspace, cx| {
11003 let pane = if split {
11004 workspace.adjacent_pane(window, cx)
11005 } else {
11006 workspace.active_pane().clone()
11007 };
11008
11009 workspace.open_project_item(
11010 pane,
11011 target.buffer.clone(),
11012 true,
11013 true,
11014 window,
11015 cx,
11016 )
11017 });
11018 target_editor.update(cx, |target_editor, cx| {
11019 // When selecting a definition in a different buffer, disable the nav history
11020 // to avoid creating a history entry at the previous cursor location.
11021 pane.update(cx, |pane, _| pane.disable_history());
11022 target_editor.go_to_singleton_buffer_range(range, window, cx);
11023 pane.update(cx, |pane, _| pane.enable_history());
11024 });
11025 });
11026 }
11027 Navigated::Yes
11028 })
11029 })
11030 } else if !definitions.is_empty() {
11031 cx.spawn_in(window, |editor, mut cx| async move {
11032 let (title, location_tasks, workspace) = editor
11033 .update_in(&mut cx, |editor, window, cx| {
11034 let tab_kind = match kind {
11035 Some(GotoDefinitionKind::Implementation) => "Implementations",
11036 _ => "Definitions",
11037 };
11038 let title = definitions
11039 .iter()
11040 .find_map(|definition| match definition {
11041 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11042 let buffer = origin.buffer.read(cx);
11043 format!(
11044 "{} for {}",
11045 tab_kind,
11046 buffer
11047 .text_for_range(origin.range.clone())
11048 .collect::<String>()
11049 )
11050 }),
11051 HoverLink::InlayHint(_, _) => None,
11052 HoverLink::Url(_) => None,
11053 HoverLink::File(_) => None,
11054 })
11055 .unwrap_or(tab_kind.to_string());
11056 let location_tasks = definitions
11057 .into_iter()
11058 .map(|definition| match definition {
11059 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11060 HoverLink::InlayHint(lsp_location, server_id) => editor
11061 .compute_target_location(lsp_location, server_id, window, cx),
11062 HoverLink::Url(_) => Task::ready(Ok(None)),
11063 HoverLink::File(_) => Task::ready(Ok(None)),
11064 })
11065 .collect::<Vec<_>>();
11066 (title, location_tasks, editor.workspace().clone())
11067 })
11068 .context("location tasks preparation")?;
11069
11070 let locations = future::join_all(location_tasks)
11071 .await
11072 .into_iter()
11073 .filter_map(|location| location.transpose())
11074 .collect::<Result<_>>()
11075 .context("location tasks")?;
11076
11077 let Some(workspace) = workspace else {
11078 return Ok(Navigated::No);
11079 };
11080 let opened = workspace
11081 .update_in(&mut cx, |workspace, window, cx| {
11082 Self::open_locations_in_multibuffer(
11083 workspace,
11084 locations,
11085 title,
11086 split,
11087 MultibufferSelectionMode::First,
11088 window,
11089 cx,
11090 )
11091 })
11092 .ok();
11093
11094 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11095 })
11096 } else {
11097 Task::ready(Ok(Navigated::No))
11098 }
11099 }
11100
11101 fn compute_target_location(
11102 &self,
11103 lsp_location: lsp::Location,
11104 server_id: LanguageServerId,
11105 window: &mut Window,
11106 cx: &mut Context<Self>,
11107 ) -> Task<anyhow::Result<Option<Location>>> {
11108 let Some(project) = self.project.clone() else {
11109 return Task::ready(Ok(None));
11110 };
11111
11112 cx.spawn_in(window, move |editor, mut cx| async move {
11113 let location_task = editor.update(&mut cx, |_, cx| {
11114 project.update(cx, |project, cx| {
11115 let language_server_name = project
11116 .language_server_statuses(cx)
11117 .find(|(id, _)| server_id == *id)
11118 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11119 language_server_name.map(|language_server_name| {
11120 project.open_local_buffer_via_lsp(
11121 lsp_location.uri.clone(),
11122 server_id,
11123 language_server_name,
11124 cx,
11125 )
11126 })
11127 })
11128 })?;
11129 let location = match location_task {
11130 Some(task) => Some({
11131 let target_buffer_handle = task.await.context("open local buffer")?;
11132 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11133 let target_start = target_buffer
11134 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11135 let target_end = target_buffer
11136 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11137 target_buffer.anchor_after(target_start)
11138 ..target_buffer.anchor_before(target_end)
11139 })?;
11140 Location {
11141 buffer: target_buffer_handle,
11142 range,
11143 }
11144 }),
11145 None => None,
11146 };
11147 Ok(location)
11148 })
11149 }
11150
11151 pub fn find_all_references(
11152 &mut self,
11153 _: &FindAllReferences,
11154 window: &mut Window,
11155 cx: &mut Context<Self>,
11156 ) -> Option<Task<Result<Navigated>>> {
11157 let selection = self.selections.newest::<usize>(cx);
11158 let multi_buffer = self.buffer.read(cx);
11159 let head = selection.head();
11160
11161 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11162 let head_anchor = multi_buffer_snapshot.anchor_at(
11163 head,
11164 if head < selection.tail() {
11165 Bias::Right
11166 } else {
11167 Bias::Left
11168 },
11169 );
11170
11171 match self
11172 .find_all_references_task_sources
11173 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11174 {
11175 Ok(_) => {
11176 log::info!(
11177 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11178 );
11179 return None;
11180 }
11181 Err(i) => {
11182 self.find_all_references_task_sources.insert(i, head_anchor);
11183 }
11184 }
11185
11186 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11187 let workspace = self.workspace()?;
11188 let project = workspace.read(cx).project().clone();
11189 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11190 Some(cx.spawn_in(window, |editor, mut cx| async move {
11191 let _cleanup = defer({
11192 let mut cx = cx.clone();
11193 move || {
11194 let _ = editor.update(&mut cx, |editor, _| {
11195 if let Ok(i) =
11196 editor
11197 .find_all_references_task_sources
11198 .binary_search_by(|anchor| {
11199 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11200 })
11201 {
11202 editor.find_all_references_task_sources.remove(i);
11203 }
11204 });
11205 }
11206 });
11207
11208 let locations = references.await?;
11209 if locations.is_empty() {
11210 return anyhow::Ok(Navigated::No);
11211 }
11212
11213 workspace.update_in(&mut cx, |workspace, window, cx| {
11214 let title = locations
11215 .first()
11216 .as_ref()
11217 .map(|location| {
11218 let buffer = location.buffer.read(cx);
11219 format!(
11220 "References to `{}`",
11221 buffer
11222 .text_for_range(location.range.clone())
11223 .collect::<String>()
11224 )
11225 })
11226 .unwrap();
11227 Self::open_locations_in_multibuffer(
11228 workspace,
11229 locations,
11230 title,
11231 false,
11232 MultibufferSelectionMode::First,
11233 window,
11234 cx,
11235 );
11236 Navigated::Yes
11237 })
11238 }))
11239 }
11240
11241 /// Opens a multibuffer with the given project locations in it
11242 pub fn open_locations_in_multibuffer(
11243 workspace: &mut Workspace,
11244 mut locations: Vec<Location>,
11245 title: String,
11246 split: bool,
11247 multibuffer_selection_mode: MultibufferSelectionMode,
11248 window: &mut Window,
11249 cx: &mut Context<Workspace>,
11250 ) {
11251 // If there are multiple definitions, open them in a multibuffer
11252 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11253 let mut locations = locations.into_iter().peekable();
11254 let mut ranges = Vec::new();
11255 let capability = workspace.project().read(cx).capability();
11256
11257 let excerpt_buffer = cx.new(|cx| {
11258 let mut multibuffer = MultiBuffer::new(capability);
11259 while let Some(location) = locations.next() {
11260 let buffer = location.buffer.read(cx);
11261 let mut ranges_for_buffer = Vec::new();
11262 let range = location.range.to_offset(buffer);
11263 ranges_for_buffer.push(range.clone());
11264
11265 while let Some(next_location) = locations.peek() {
11266 if next_location.buffer == location.buffer {
11267 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11268 locations.next();
11269 } else {
11270 break;
11271 }
11272 }
11273
11274 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11275 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11276 location.buffer.clone(),
11277 ranges_for_buffer,
11278 DEFAULT_MULTIBUFFER_CONTEXT,
11279 cx,
11280 ))
11281 }
11282
11283 multibuffer.with_title(title)
11284 });
11285
11286 let editor = cx.new(|cx| {
11287 Editor::for_multibuffer(
11288 excerpt_buffer,
11289 Some(workspace.project().clone()),
11290 true,
11291 window,
11292 cx,
11293 )
11294 });
11295 editor.update(cx, |editor, cx| {
11296 match multibuffer_selection_mode {
11297 MultibufferSelectionMode::First => {
11298 if let Some(first_range) = ranges.first() {
11299 editor.change_selections(None, window, cx, |selections| {
11300 selections.clear_disjoint();
11301 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11302 });
11303 }
11304 editor.highlight_background::<Self>(
11305 &ranges,
11306 |theme| theme.editor_highlighted_line_background,
11307 cx,
11308 );
11309 }
11310 MultibufferSelectionMode::All => {
11311 editor.change_selections(None, window, cx, |selections| {
11312 selections.clear_disjoint();
11313 selections.select_anchor_ranges(ranges);
11314 });
11315 }
11316 }
11317 editor.register_buffers_with_language_servers(cx);
11318 });
11319
11320 let item = Box::new(editor);
11321 let item_id = item.item_id();
11322
11323 if split {
11324 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11325 } else {
11326 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11327 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11328 pane.close_current_preview_item(window, cx)
11329 } else {
11330 None
11331 }
11332 });
11333 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11334 }
11335 workspace.active_pane().update(cx, |pane, cx| {
11336 pane.set_preview_item_id(Some(item_id), cx);
11337 });
11338 }
11339
11340 pub fn rename(
11341 &mut self,
11342 _: &Rename,
11343 window: &mut Window,
11344 cx: &mut Context<Self>,
11345 ) -> Option<Task<Result<()>>> {
11346 use language::ToOffset as _;
11347
11348 let provider = self.semantics_provider.clone()?;
11349 let selection = self.selections.newest_anchor().clone();
11350 let (cursor_buffer, cursor_buffer_position) = self
11351 .buffer
11352 .read(cx)
11353 .text_anchor_for_position(selection.head(), cx)?;
11354 let (tail_buffer, cursor_buffer_position_end) = self
11355 .buffer
11356 .read(cx)
11357 .text_anchor_for_position(selection.tail(), cx)?;
11358 if tail_buffer != cursor_buffer {
11359 return None;
11360 }
11361
11362 let snapshot = cursor_buffer.read(cx).snapshot();
11363 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11364 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11365 let prepare_rename = provider
11366 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11367 .unwrap_or_else(|| Task::ready(Ok(None)));
11368 drop(snapshot);
11369
11370 Some(cx.spawn_in(window, |this, mut cx| async move {
11371 let rename_range = if let Some(range) = prepare_rename.await? {
11372 Some(range)
11373 } else {
11374 this.update(&mut cx, |this, cx| {
11375 let buffer = this.buffer.read(cx).snapshot(cx);
11376 let mut buffer_highlights = this
11377 .document_highlights_for_position(selection.head(), &buffer)
11378 .filter(|highlight| {
11379 highlight.start.excerpt_id == selection.head().excerpt_id
11380 && highlight.end.excerpt_id == selection.head().excerpt_id
11381 });
11382 buffer_highlights
11383 .next()
11384 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11385 })?
11386 };
11387 if let Some(rename_range) = rename_range {
11388 this.update_in(&mut cx, |this, window, cx| {
11389 let snapshot = cursor_buffer.read(cx).snapshot();
11390 let rename_buffer_range = rename_range.to_offset(&snapshot);
11391 let cursor_offset_in_rename_range =
11392 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11393 let cursor_offset_in_rename_range_end =
11394 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11395
11396 this.take_rename(false, window, cx);
11397 let buffer = this.buffer.read(cx).read(cx);
11398 let cursor_offset = selection.head().to_offset(&buffer);
11399 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11400 let rename_end = rename_start + rename_buffer_range.len();
11401 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11402 let mut old_highlight_id = None;
11403 let old_name: Arc<str> = buffer
11404 .chunks(rename_start..rename_end, true)
11405 .map(|chunk| {
11406 if old_highlight_id.is_none() {
11407 old_highlight_id = chunk.syntax_highlight_id;
11408 }
11409 chunk.text
11410 })
11411 .collect::<String>()
11412 .into();
11413
11414 drop(buffer);
11415
11416 // Position the selection in the rename editor so that it matches the current selection.
11417 this.show_local_selections = false;
11418 let rename_editor = cx.new(|cx| {
11419 let mut editor = Editor::single_line(window, cx);
11420 editor.buffer.update(cx, |buffer, cx| {
11421 buffer.edit([(0..0, old_name.clone())], None, cx)
11422 });
11423 let rename_selection_range = match cursor_offset_in_rename_range
11424 .cmp(&cursor_offset_in_rename_range_end)
11425 {
11426 Ordering::Equal => {
11427 editor.select_all(&SelectAll, window, cx);
11428 return editor;
11429 }
11430 Ordering::Less => {
11431 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11432 }
11433 Ordering::Greater => {
11434 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11435 }
11436 };
11437 if rename_selection_range.end > old_name.len() {
11438 editor.select_all(&SelectAll, window, cx);
11439 } else {
11440 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11441 s.select_ranges([rename_selection_range]);
11442 });
11443 }
11444 editor
11445 });
11446 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11447 if e == &EditorEvent::Focused {
11448 cx.emit(EditorEvent::FocusedIn)
11449 }
11450 })
11451 .detach();
11452
11453 let write_highlights =
11454 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11455 let read_highlights =
11456 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11457 let ranges = write_highlights
11458 .iter()
11459 .flat_map(|(_, ranges)| ranges.iter())
11460 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11461 .cloned()
11462 .collect();
11463
11464 this.highlight_text::<Rename>(
11465 ranges,
11466 HighlightStyle {
11467 fade_out: Some(0.6),
11468 ..Default::default()
11469 },
11470 cx,
11471 );
11472 let rename_focus_handle = rename_editor.focus_handle(cx);
11473 window.focus(&rename_focus_handle);
11474 let block_id = this.insert_blocks(
11475 [BlockProperties {
11476 style: BlockStyle::Flex,
11477 placement: BlockPlacement::Below(range.start),
11478 height: 1,
11479 render: Arc::new({
11480 let rename_editor = rename_editor.clone();
11481 move |cx: &mut BlockContext| {
11482 let mut text_style = cx.editor_style.text.clone();
11483 if let Some(highlight_style) = old_highlight_id
11484 .and_then(|h| h.style(&cx.editor_style.syntax))
11485 {
11486 text_style = text_style.highlight(highlight_style);
11487 }
11488 div()
11489 .block_mouse_down()
11490 .pl(cx.anchor_x)
11491 .child(EditorElement::new(
11492 &rename_editor,
11493 EditorStyle {
11494 background: cx.theme().system().transparent,
11495 local_player: cx.editor_style.local_player,
11496 text: text_style,
11497 scrollbar_width: cx.editor_style.scrollbar_width,
11498 syntax: cx.editor_style.syntax.clone(),
11499 status: cx.editor_style.status.clone(),
11500 inlay_hints_style: HighlightStyle {
11501 font_weight: Some(FontWeight::BOLD),
11502 ..make_inlay_hints_style(cx.app)
11503 },
11504 inline_completion_styles: make_suggestion_styles(
11505 cx.app,
11506 ),
11507 ..EditorStyle::default()
11508 },
11509 ))
11510 .into_any_element()
11511 }
11512 }),
11513 priority: 0,
11514 }],
11515 Some(Autoscroll::fit()),
11516 cx,
11517 )[0];
11518 this.pending_rename = Some(RenameState {
11519 range,
11520 old_name,
11521 editor: rename_editor,
11522 block_id,
11523 });
11524 })?;
11525 }
11526
11527 Ok(())
11528 }))
11529 }
11530
11531 pub fn confirm_rename(
11532 &mut self,
11533 _: &ConfirmRename,
11534 window: &mut Window,
11535 cx: &mut Context<Self>,
11536 ) -> Option<Task<Result<()>>> {
11537 let rename = self.take_rename(false, window, cx)?;
11538 let workspace = self.workspace()?.downgrade();
11539 let (buffer, start) = self
11540 .buffer
11541 .read(cx)
11542 .text_anchor_for_position(rename.range.start, cx)?;
11543 let (end_buffer, _) = self
11544 .buffer
11545 .read(cx)
11546 .text_anchor_for_position(rename.range.end, cx)?;
11547 if buffer != end_buffer {
11548 return None;
11549 }
11550
11551 let old_name = rename.old_name;
11552 let new_name = rename.editor.read(cx).text(cx);
11553
11554 let rename = self.semantics_provider.as_ref()?.perform_rename(
11555 &buffer,
11556 start,
11557 new_name.clone(),
11558 cx,
11559 )?;
11560
11561 Some(cx.spawn_in(window, |editor, mut cx| async move {
11562 let project_transaction = rename.await?;
11563 Self::open_project_transaction(
11564 &editor,
11565 workspace,
11566 project_transaction,
11567 format!("Rename: {} → {}", old_name, new_name),
11568 cx.clone(),
11569 )
11570 .await?;
11571
11572 editor.update(&mut cx, |editor, cx| {
11573 editor.refresh_document_highlights(cx);
11574 })?;
11575 Ok(())
11576 }))
11577 }
11578
11579 fn take_rename(
11580 &mut self,
11581 moving_cursor: bool,
11582 window: &mut Window,
11583 cx: &mut Context<Self>,
11584 ) -> Option<RenameState> {
11585 let rename = self.pending_rename.take()?;
11586 if rename.editor.focus_handle(cx).is_focused(window) {
11587 window.focus(&self.focus_handle);
11588 }
11589
11590 self.remove_blocks(
11591 [rename.block_id].into_iter().collect(),
11592 Some(Autoscroll::fit()),
11593 cx,
11594 );
11595 self.clear_highlights::<Rename>(cx);
11596 self.show_local_selections = true;
11597
11598 if moving_cursor {
11599 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11600 editor.selections.newest::<usize>(cx).head()
11601 });
11602
11603 // Update the selection to match the position of the selection inside
11604 // the rename editor.
11605 let snapshot = self.buffer.read(cx).read(cx);
11606 let rename_range = rename.range.to_offset(&snapshot);
11607 let cursor_in_editor = snapshot
11608 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11609 .min(rename_range.end);
11610 drop(snapshot);
11611
11612 self.change_selections(None, window, cx, |s| {
11613 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11614 });
11615 } else {
11616 self.refresh_document_highlights(cx);
11617 }
11618
11619 Some(rename)
11620 }
11621
11622 pub fn pending_rename(&self) -> Option<&RenameState> {
11623 self.pending_rename.as_ref()
11624 }
11625
11626 fn format(
11627 &mut self,
11628 _: &Format,
11629 window: &mut Window,
11630 cx: &mut Context<Self>,
11631 ) -> Option<Task<Result<()>>> {
11632 let project = match &self.project {
11633 Some(project) => project.clone(),
11634 None => return None,
11635 };
11636
11637 Some(self.perform_format(
11638 project,
11639 FormatTrigger::Manual,
11640 FormatTarget::Buffers,
11641 window,
11642 cx,
11643 ))
11644 }
11645
11646 fn format_selections(
11647 &mut self,
11648 _: &FormatSelections,
11649 window: &mut Window,
11650 cx: &mut Context<Self>,
11651 ) -> Option<Task<Result<()>>> {
11652 let project = match &self.project {
11653 Some(project) => project.clone(),
11654 None => return None,
11655 };
11656
11657 let ranges = self
11658 .selections
11659 .all_adjusted(cx)
11660 .into_iter()
11661 .map(|selection| selection.range())
11662 .collect_vec();
11663
11664 Some(self.perform_format(
11665 project,
11666 FormatTrigger::Manual,
11667 FormatTarget::Ranges(ranges),
11668 window,
11669 cx,
11670 ))
11671 }
11672
11673 fn perform_format(
11674 &mut self,
11675 project: Entity<Project>,
11676 trigger: FormatTrigger,
11677 target: FormatTarget,
11678 window: &mut Window,
11679 cx: &mut Context<Self>,
11680 ) -> Task<Result<()>> {
11681 let buffer = self.buffer.clone();
11682 let (buffers, target) = match target {
11683 FormatTarget::Buffers => {
11684 let mut buffers = buffer.read(cx).all_buffers();
11685 if trigger == FormatTrigger::Save {
11686 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11687 }
11688 (buffers, LspFormatTarget::Buffers)
11689 }
11690 FormatTarget::Ranges(selection_ranges) => {
11691 let multi_buffer = buffer.read(cx);
11692 let snapshot = multi_buffer.read(cx);
11693 let mut buffers = HashSet::default();
11694 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11695 BTreeMap::new();
11696 for selection_range in selection_ranges {
11697 for (buffer, buffer_range, _) in
11698 snapshot.range_to_buffer_ranges(selection_range)
11699 {
11700 let buffer_id = buffer.remote_id();
11701 let start = buffer.anchor_before(buffer_range.start);
11702 let end = buffer.anchor_after(buffer_range.end);
11703 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11704 buffer_id_to_ranges
11705 .entry(buffer_id)
11706 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11707 .or_insert_with(|| vec![start..end]);
11708 }
11709 }
11710 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11711 }
11712 };
11713
11714 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11715 let format = project.update(cx, |project, cx| {
11716 project.format(buffers, target, true, trigger, cx)
11717 });
11718
11719 cx.spawn_in(window, |_, mut cx| async move {
11720 let transaction = futures::select_biased! {
11721 () = timeout => {
11722 log::warn!("timed out waiting for formatting");
11723 None
11724 }
11725 transaction = format.log_err().fuse() => transaction,
11726 };
11727
11728 buffer
11729 .update(&mut cx, |buffer, cx| {
11730 if let Some(transaction) = transaction {
11731 if !buffer.is_singleton() {
11732 buffer.push_transaction(&transaction.0, cx);
11733 }
11734 }
11735
11736 cx.notify();
11737 })
11738 .ok();
11739
11740 Ok(())
11741 })
11742 }
11743
11744 fn restart_language_server(
11745 &mut self,
11746 _: &RestartLanguageServer,
11747 _: &mut Window,
11748 cx: &mut Context<Self>,
11749 ) {
11750 if let Some(project) = self.project.clone() {
11751 self.buffer.update(cx, |multi_buffer, cx| {
11752 project.update(cx, |project, cx| {
11753 project.restart_language_servers_for_buffers(
11754 multi_buffer.all_buffers().into_iter().collect(),
11755 cx,
11756 );
11757 });
11758 })
11759 }
11760 }
11761
11762 fn cancel_language_server_work(
11763 workspace: &mut Workspace,
11764 _: &actions::CancelLanguageServerWork,
11765 _: &mut Window,
11766 cx: &mut Context<Workspace>,
11767 ) {
11768 let project = workspace.project();
11769 let buffers = workspace
11770 .active_item(cx)
11771 .and_then(|item| item.act_as::<Editor>(cx))
11772 .map_or(HashSet::default(), |editor| {
11773 editor.read(cx).buffer.read(cx).all_buffers()
11774 });
11775 project.update(cx, |project, cx| {
11776 project.cancel_language_server_work_for_buffers(buffers, cx);
11777 });
11778 }
11779
11780 fn show_character_palette(
11781 &mut self,
11782 _: &ShowCharacterPalette,
11783 window: &mut Window,
11784 _: &mut Context<Self>,
11785 ) {
11786 window.show_character_palette();
11787 }
11788
11789 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11790 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11791 let buffer = self.buffer.read(cx).snapshot(cx);
11792 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11793 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11794 let is_valid = buffer
11795 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11796 .any(|entry| {
11797 entry.diagnostic.is_primary
11798 && !entry.range.is_empty()
11799 && entry.range.start == primary_range_start
11800 && entry.diagnostic.message == active_diagnostics.primary_message
11801 });
11802
11803 if is_valid != active_diagnostics.is_valid {
11804 active_diagnostics.is_valid = is_valid;
11805 let mut new_styles = HashMap::default();
11806 for (block_id, diagnostic) in &active_diagnostics.blocks {
11807 new_styles.insert(
11808 *block_id,
11809 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11810 );
11811 }
11812 self.display_map.update(cx, |display_map, _cx| {
11813 display_map.replace_blocks(new_styles)
11814 });
11815 }
11816 }
11817 }
11818
11819 fn activate_diagnostics(
11820 &mut self,
11821 buffer_id: BufferId,
11822 group_id: usize,
11823 window: &mut Window,
11824 cx: &mut Context<Self>,
11825 ) {
11826 self.dismiss_diagnostics(cx);
11827 let snapshot = self.snapshot(window, cx);
11828 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11829 let buffer = self.buffer.read(cx).snapshot(cx);
11830
11831 let mut primary_range = None;
11832 let mut primary_message = None;
11833 let diagnostic_group = buffer
11834 .diagnostic_group(buffer_id, group_id)
11835 .filter_map(|entry| {
11836 let start = entry.range.start;
11837 let end = entry.range.end;
11838 if snapshot.is_line_folded(MultiBufferRow(start.row))
11839 && (start.row == end.row
11840 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11841 {
11842 return None;
11843 }
11844 if entry.diagnostic.is_primary {
11845 primary_range = Some(entry.range.clone());
11846 primary_message = Some(entry.diagnostic.message.clone());
11847 }
11848 Some(entry)
11849 })
11850 .collect::<Vec<_>>();
11851 let primary_range = primary_range?;
11852 let primary_message = primary_message?;
11853
11854 let blocks = display_map
11855 .insert_blocks(
11856 diagnostic_group.iter().map(|entry| {
11857 let diagnostic = entry.diagnostic.clone();
11858 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11859 BlockProperties {
11860 style: BlockStyle::Fixed,
11861 placement: BlockPlacement::Below(
11862 buffer.anchor_after(entry.range.start),
11863 ),
11864 height: message_height,
11865 render: diagnostic_block_renderer(diagnostic, None, true, true),
11866 priority: 0,
11867 }
11868 }),
11869 cx,
11870 )
11871 .into_iter()
11872 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11873 .collect();
11874
11875 Some(ActiveDiagnosticGroup {
11876 primary_range: buffer.anchor_before(primary_range.start)
11877 ..buffer.anchor_after(primary_range.end),
11878 primary_message,
11879 group_id,
11880 blocks,
11881 is_valid: true,
11882 })
11883 });
11884 }
11885
11886 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11887 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11888 self.display_map.update(cx, |display_map, cx| {
11889 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11890 });
11891 cx.notify();
11892 }
11893 }
11894
11895 pub fn set_selections_from_remote(
11896 &mut self,
11897 selections: Vec<Selection<Anchor>>,
11898 pending_selection: Option<Selection<Anchor>>,
11899 window: &mut Window,
11900 cx: &mut Context<Self>,
11901 ) {
11902 let old_cursor_position = self.selections.newest_anchor().head();
11903 self.selections.change_with(cx, |s| {
11904 s.select_anchors(selections);
11905 if let Some(pending_selection) = pending_selection {
11906 s.set_pending(pending_selection, SelectMode::Character);
11907 } else {
11908 s.clear_pending();
11909 }
11910 });
11911 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11912 }
11913
11914 fn push_to_selection_history(&mut self) {
11915 self.selection_history.push(SelectionHistoryEntry {
11916 selections: self.selections.disjoint_anchors(),
11917 select_next_state: self.select_next_state.clone(),
11918 select_prev_state: self.select_prev_state.clone(),
11919 add_selections_state: self.add_selections_state.clone(),
11920 });
11921 }
11922
11923 pub fn transact(
11924 &mut self,
11925 window: &mut Window,
11926 cx: &mut Context<Self>,
11927 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11928 ) -> Option<TransactionId> {
11929 self.start_transaction_at(Instant::now(), window, cx);
11930 update(self, window, cx);
11931 self.end_transaction_at(Instant::now(), cx)
11932 }
11933
11934 pub fn start_transaction_at(
11935 &mut self,
11936 now: Instant,
11937 window: &mut Window,
11938 cx: &mut Context<Self>,
11939 ) {
11940 self.end_selection(window, cx);
11941 if let Some(tx_id) = self
11942 .buffer
11943 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11944 {
11945 self.selection_history
11946 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11947 cx.emit(EditorEvent::TransactionBegun {
11948 transaction_id: tx_id,
11949 })
11950 }
11951 }
11952
11953 pub fn end_transaction_at(
11954 &mut self,
11955 now: Instant,
11956 cx: &mut Context<Self>,
11957 ) -> Option<TransactionId> {
11958 if let Some(transaction_id) = self
11959 .buffer
11960 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11961 {
11962 if let Some((_, end_selections)) =
11963 self.selection_history.transaction_mut(transaction_id)
11964 {
11965 *end_selections = Some(self.selections.disjoint_anchors());
11966 } else {
11967 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11968 }
11969
11970 cx.emit(EditorEvent::Edited { transaction_id });
11971 Some(transaction_id)
11972 } else {
11973 None
11974 }
11975 }
11976
11977 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11978 if self.selection_mark_mode {
11979 self.change_selections(None, window, cx, |s| {
11980 s.move_with(|_, sel| {
11981 sel.collapse_to(sel.head(), SelectionGoal::None);
11982 });
11983 })
11984 }
11985 self.selection_mark_mode = true;
11986 cx.notify();
11987 }
11988
11989 pub fn swap_selection_ends(
11990 &mut self,
11991 _: &actions::SwapSelectionEnds,
11992 window: &mut Window,
11993 cx: &mut Context<Self>,
11994 ) {
11995 self.change_selections(None, window, cx, |s| {
11996 s.move_with(|_, sel| {
11997 if sel.start != sel.end {
11998 sel.reversed = !sel.reversed
11999 }
12000 });
12001 });
12002 self.request_autoscroll(Autoscroll::newest(), cx);
12003 cx.notify();
12004 }
12005
12006 pub fn toggle_fold(
12007 &mut self,
12008 _: &actions::ToggleFold,
12009 window: &mut Window,
12010 cx: &mut Context<Self>,
12011 ) {
12012 if self.is_singleton(cx) {
12013 let selection = self.selections.newest::<Point>(cx);
12014
12015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12016 let range = if selection.is_empty() {
12017 let point = selection.head().to_display_point(&display_map);
12018 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12019 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12020 .to_point(&display_map);
12021 start..end
12022 } else {
12023 selection.range()
12024 };
12025 if display_map.folds_in_range(range).next().is_some() {
12026 self.unfold_lines(&Default::default(), window, cx)
12027 } else {
12028 self.fold(&Default::default(), window, cx)
12029 }
12030 } else {
12031 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12032 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12033 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12034 .map(|(snapshot, _, _)| snapshot.remote_id())
12035 .collect();
12036
12037 for buffer_id in buffer_ids {
12038 if self.is_buffer_folded(buffer_id, cx) {
12039 self.unfold_buffer(buffer_id, cx);
12040 } else {
12041 self.fold_buffer(buffer_id, cx);
12042 }
12043 }
12044 }
12045 }
12046
12047 pub fn toggle_fold_recursive(
12048 &mut self,
12049 _: &actions::ToggleFoldRecursive,
12050 window: &mut Window,
12051 cx: &mut Context<Self>,
12052 ) {
12053 let selection = self.selections.newest::<Point>(cx);
12054
12055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12056 let range = if selection.is_empty() {
12057 let point = selection.head().to_display_point(&display_map);
12058 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12059 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12060 .to_point(&display_map);
12061 start..end
12062 } else {
12063 selection.range()
12064 };
12065 if display_map.folds_in_range(range).next().is_some() {
12066 self.unfold_recursive(&Default::default(), window, cx)
12067 } else {
12068 self.fold_recursive(&Default::default(), window, cx)
12069 }
12070 }
12071
12072 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12073 if self.is_singleton(cx) {
12074 let mut to_fold = Vec::new();
12075 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12076 let selections = self.selections.all_adjusted(cx);
12077
12078 for selection in selections {
12079 let range = selection.range().sorted();
12080 let buffer_start_row = range.start.row;
12081
12082 if range.start.row != range.end.row {
12083 let mut found = false;
12084 let mut row = range.start.row;
12085 while row <= range.end.row {
12086 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12087 {
12088 found = true;
12089 row = crease.range().end.row + 1;
12090 to_fold.push(crease);
12091 } else {
12092 row += 1
12093 }
12094 }
12095 if found {
12096 continue;
12097 }
12098 }
12099
12100 for row in (0..=range.start.row).rev() {
12101 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12102 if crease.range().end.row >= buffer_start_row {
12103 to_fold.push(crease);
12104 if row <= range.start.row {
12105 break;
12106 }
12107 }
12108 }
12109 }
12110 }
12111
12112 self.fold_creases(to_fold, true, window, cx);
12113 } else {
12114 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12115
12116 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12117 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12118 .map(|(snapshot, _, _)| snapshot.remote_id())
12119 .collect();
12120 for buffer_id in buffer_ids {
12121 self.fold_buffer(buffer_id, cx);
12122 }
12123 }
12124 }
12125
12126 fn fold_at_level(
12127 &mut self,
12128 fold_at: &FoldAtLevel,
12129 window: &mut Window,
12130 cx: &mut Context<Self>,
12131 ) {
12132 if !self.buffer.read(cx).is_singleton() {
12133 return;
12134 }
12135
12136 let fold_at_level = fold_at.0;
12137 let snapshot = self.buffer.read(cx).snapshot(cx);
12138 let mut to_fold = Vec::new();
12139 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12140
12141 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12142 while start_row < end_row {
12143 match self
12144 .snapshot(window, cx)
12145 .crease_for_buffer_row(MultiBufferRow(start_row))
12146 {
12147 Some(crease) => {
12148 let nested_start_row = crease.range().start.row + 1;
12149 let nested_end_row = crease.range().end.row;
12150
12151 if current_level < fold_at_level {
12152 stack.push((nested_start_row, nested_end_row, current_level + 1));
12153 } else if current_level == fold_at_level {
12154 to_fold.push(crease);
12155 }
12156
12157 start_row = nested_end_row + 1;
12158 }
12159 None => start_row += 1,
12160 }
12161 }
12162 }
12163
12164 self.fold_creases(to_fold, true, window, cx);
12165 }
12166
12167 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12168 if self.buffer.read(cx).is_singleton() {
12169 let mut fold_ranges = Vec::new();
12170 let snapshot = self.buffer.read(cx).snapshot(cx);
12171
12172 for row in 0..snapshot.max_row().0 {
12173 if let Some(foldable_range) = self
12174 .snapshot(window, cx)
12175 .crease_for_buffer_row(MultiBufferRow(row))
12176 {
12177 fold_ranges.push(foldable_range);
12178 }
12179 }
12180
12181 self.fold_creases(fold_ranges, true, window, cx);
12182 } else {
12183 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12184 editor
12185 .update_in(&mut cx, |editor, _, cx| {
12186 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12187 editor.fold_buffer(buffer_id, cx);
12188 }
12189 })
12190 .ok();
12191 });
12192 }
12193 }
12194
12195 pub fn fold_function_bodies(
12196 &mut self,
12197 _: &actions::FoldFunctionBodies,
12198 window: &mut Window,
12199 cx: &mut Context<Self>,
12200 ) {
12201 let snapshot = self.buffer.read(cx).snapshot(cx);
12202
12203 let ranges = snapshot
12204 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12205 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12206 .collect::<Vec<_>>();
12207
12208 let creases = ranges
12209 .into_iter()
12210 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12211 .collect();
12212
12213 self.fold_creases(creases, true, window, cx);
12214 }
12215
12216 pub fn fold_recursive(
12217 &mut self,
12218 _: &actions::FoldRecursive,
12219 window: &mut Window,
12220 cx: &mut Context<Self>,
12221 ) {
12222 let mut to_fold = Vec::new();
12223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12224 let selections = self.selections.all_adjusted(cx);
12225
12226 for selection in selections {
12227 let range = selection.range().sorted();
12228 let buffer_start_row = range.start.row;
12229
12230 if range.start.row != range.end.row {
12231 let mut found = false;
12232 for row in range.start.row..=range.end.row {
12233 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12234 found = true;
12235 to_fold.push(crease);
12236 }
12237 }
12238 if found {
12239 continue;
12240 }
12241 }
12242
12243 for row in (0..=range.start.row).rev() {
12244 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12245 if crease.range().end.row >= buffer_start_row {
12246 to_fold.push(crease);
12247 } else {
12248 break;
12249 }
12250 }
12251 }
12252 }
12253
12254 self.fold_creases(to_fold, true, window, cx);
12255 }
12256
12257 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12258 let buffer_row = fold_at.buffer_row;
12259 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12260
12261 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12262 let autoscroll = self
12263 .selections
12264 .all::<Point>(cx)
12265 .iter()
12266 .any(|selection| crease.range().overlaps(&selection.range()));
12267
12268 self.fold_creases(vec![crease], autoscroll, window, cx);
12269 }
12270 }
12271
12272 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12273 if self.is_singleton(cx) {
12274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12275 let buffer = &display_map.buffer_snapshot;
12276 let selections = self.selections.all::<Point>(cx);
12277 let ranges = selections
12278 .iter()
12279 .map(|s| {
12280 let range = s.display_range(&display_map).sorted();
12281 let mut start = range.start.to_point(&display_map);
12282 let mut end = range.end.to_point(&display_map);
12283 start.column = 0;
12284 end.column = buffer.line_len(MultiBufferRow(end.row));
12285 start..end
12286 })
12287 .collect::<Vec<_>>();
12288
12289 self.unfold_ranges(&ranges, true, true, cx);
12290 } else {
12291 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12292 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12293 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12294 .map(|(snapshot, _, _)| snapshot.remote_id())
12295 .collect();
12296 for buffer_id in buffer_ids {
12297 self.unfold_buffer(buffer_id, cx);
12298 }
12299 }
12300 }
12301
12302 pub fn unfold_recursive(
12303 &mut self,
12304 _: &UnfoldRecursive,
12305 _window: &mut Window,
12306 cx: &mut Context<Self>,
12307 ) {
12308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12309 let selections = self.selections.all::<Point>(cx);
12310 let ranges = selections
12311 .iter()
12312 .map(|s| {
12313 let mut range = s.display_range(&display_map).sorted();
12314 *range.start.column_mut() = 0;
12315 *range.end.column_mut() = display_map.line_len(range.end.row());
12316 let start = range.start.to_point(&display_map);
12317 let end = range.end.to_point(&display_map);
12318 start..end
12319 })
12320 .collect::<Vec<_>>();
12321
12322 self.unfold_ranges(&ranges, true, true, cx);
12323 }
12324
12325 pub fn unfold_at(
12326 &mut self,
12327 unfold_at: &UnfoldAt,
12328 _window: &mut Window,
12329 cx: &mut Context<Self>,
12330 ) {
12331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12332
12333 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12334 ..Point::new(
12335 unfold_at.buffer_row.0,
12336 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12337 );
12338
12339 let autoscroll = self
12340 .selections
12341 .all::<Point>(cx)
12342 .iter()
12343 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12344
12345 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12346 }
12347
12348 pub fn unfold_all(
12349 &mut self,
12350 _: &actions::UnfoldAll,
12351 _window: &mut Window,
12352 cx: &mut Context<Self>,
12353 ) {
12354 if self.buffer.read(cx).is_singleton() {
12355 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12356 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12357 } else {
12358 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12359 editor
12360 .update(&mut cx, |editor, cx| {
12361 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12362 editor.unfold_buffer(buffer_id, cx);
12363 }
12364 })
12365 .ok();
12366 });
12367 }
12368 }
12369
12370 pub fn fold_selected_ranges(
12371 &mut self,
12372 _: &FoldSelectedRanges,
12373 window: &mut Window,
12374 cx: &mut Context<Self>,
12375 ) {
12376 let selections = self.selections.all::<Point>(cx);
12377 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12378 let line_mode = self.selections.line_mode;
12379 let ranges = selections
12380 .into_iter()
12381 .map(|s| {
12382 if line_mode {
12383 let start = Point::new(s.start.row, 0);
12384 let end = Point::new(
12385 s.end.row,
12386 display_map
12387 .buffer_snapshot
12388 .line_len(MultiBufferRow(s.end.row)),
12389 );
12390 Crease::simple(start..end, display_map.fold_placeholder.clone())
12391 } else {
12392 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12393 }
12394 })
12395 .collect::<Vec<_>>();
12396 self.fold_creases(ranges, true, window, cx);
12397 }
12398
12399 pub fn fold_ranges<T: ToOffset + Clone>(
12400 &mut self,
12401 ranges: Vec<Range<T>>,
12402 auto_scroll: bool,
12403 window: &mut Window,
12404 cx: &mut Context<Self>,
12405 ) {
12406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12407 let ranges = ranges
12408 .into_iter()
12409 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12410 .collect::<Vec<_>>();
12411 self.fold_creases(ranges, auto_scroll, window, cx);
12412 }
12413
12414 pub fn fold_creases<T: ToOffset + Clone>(
12415 &mut self,
12416 creases: Vec<Crease<T>>,
12417 auto_scroll: bool,
12418 window: &mut Window,
12419 cx: &mut Context<Self>,
12420 ) {
12421 if creases.is_empty() {
12422 return;
12423 }
12424
12425 let mut buffers_affected = HashSet::default();
12426 let multi_buffer = self.buffer().read(cx);
12427 for crease in &creases {
12428 if let Some((_, buffer, _)) =
12429 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12430 {
12431 buffers_affected.insert(buffer.read(cx).remote_id());
12432 };
12433 }
12434
12435 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12436
12437 if auto_scroll {
12438 self.request_autoscroll(Autoscroll::fit(), cx);
12439 }
12440
12441 cx.notify();
12442
12443 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12444 // Clear diagnostics block when folding a range that contains it.
12445 let snapshot = self.snapshot(window, cx);
12446 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12447 drop(snapshot);
12448 self.active_diagnostics = Some(active_diagnostics);
12449 self.dismiss_diagnostics(cx);
12450 } else {
12451 self.active_diagnostics = Some(active_diagnostics);
12452 }
12453 }
12454
12455 self.scrollbar_marker_state.dirty = true;
12456 }
12457
12458 /// Removes any folds whose ranges intersect any of the given ranges.
12459 pub fn unfold_ranges<T: ToOffset + Clone>(
12460 &mut self,
12461 ranges: &[Range<T>],
12462 inclusive: bool,
12463 auto_scroll: bool,
12464 cx: &mut Context<Self>,
12465 ) {
12466 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12467 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12468 });
12469 }
12470
12471 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12472 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12473 return;
12474 }
12475 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12476 self.display_map
12477 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12478 cx.emit(EditorEvent::BufferFoldToggled {
12479 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12480 folded: true,
12481 });
12482 cx.notify();
12483 }
12484
12485 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12486 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12487 return;
12488 }
12489 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12490 self.display_map.update(cx, |display_map, cx| {
12491 display_map.unfold_buffer(buffer_id, cx);
12492 });
12493 cx.emit(EditorEvent::BufferFoldToggled {
12494 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12495 folded: false,
12496 });
12497 cx.notify();
12498 }
12499
12500 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12501 self.display_map.read(cx).is_buffer_folded(buffer)
12502 }
12503
12504 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12505 self.display_map.read(cx).folded_buffers()
12506 }
12507
12508 /// Removes any folds with the given ranges.
12509 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12510 &mut self,
12511 ranges: &[Range<T>],
12512 type_id: TypeId,
12513 auto_scroll: bool,
12514 cx: &mut Context<Self>,
12515 ) {
12516 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12517 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12518 });
12519 }
12520
12521 fn remove_folds_with<T: ToOffset + Clone>(
12522 &mut self,
12523 ranges: &[Range<T>],
12524 auto_scroll: bool,
12525 cx: &mut Context<Self>,
12526 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12527 ) {
12528 if ranges.is_empty() {
12529 return;
12530 }
12531
12532 let mut buffers_affected = HashSet::default();
12533 let multi_buffer = self.buffer().read(cx);
12534 for range in ranges {
12535 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12536 buffers_affected.insert(buffer.read(cx).remote_id());
12537 };
12538 }
12539
12540 self.display_map.update(cx, update);
12541
12542 if auto_scroll {
12543 self.request_autoscroll(Autoscroll::fit(), cx);
12544 }
12545
12546 cx.notify();
12547 self.scrollbar_marker_state.dirty = true;
12548 self.active_indent_guides_state.dirty = true;
12549 }
12550
12551 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12552 self.display_map.read(cx).fold_placeholder.clone()
12553 }
12554
12555 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12556 self.buffer.update(cx, |buffer, cx| {
12557 buffer.set_all_diff_hunks_expanded(cx);
12558 });
12559 }
12560
12561 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12562 self.distinguish_unstaged_diff_hunks = true;
12563 }
12564
12565 pub fn expand_all_diff_hunks(
12566 &mut self,
12567 _: &ExpandAllHunkDiffs,
12568 _window: &mut Window,
12569 cx: &mut Context<Self>,
12570 ) {
12571 self.buffer.update(cx, |buffer, cx| {
12572 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12573 });
12574 }
12575
12576 pub fn toggle_selected_diff_hunks(
12577 &mut self,
12578 _: &ToggleSelectedDiffHunks,
12579 _window: &mut Window,
12580 cx: &mut Context<Self>,
12581 ) {
12582 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12583 self.toggle_diff_hunks_in_ranges(ranges, cx);
12584 }
12585
12586 fn diff_hunks_in_ranges<'a>(
12587 &'a self,
12588 ranges: &'a [Range<Anchor>],
12589 buffer: &'a MultiBufferSnapshot,
12590 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12591 ranges.iter().flat_map(move |range| {
12592 let end_excerpt_id = range.end.excerpt_id;
12593 let range = range.to_point(buffer);
12594 let mut peek_end = range.end;
12595 if range.end.row < buffer.max_row().0 {
12596 peek_end = Point::new(range.end.row + 1, 0);
12597 }
12598 buffer
12599 .diff_hunks_in_range(range.start..peek_end)
12600 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12601 })
12602 }
12603
12604 pub fn has_stageable_diff_hunks_in_ranges(
12605 &self,
12606 ranges: &[Range<Anchor>],
12607 snapshot: &MultiBufferSnapshot,
12608 ) -> bool {
12609 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12610 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12611 }
12612
12613 pub fn toggle_staged_selected_diff_hunks(
12614 &mut self,
12615 _: &ToggleStagedSelectedDiffHunks,
12616 _window: &mut Window,
12617 cx: &mut Context<Self>,
12618 ) {
12619 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12620 self.stage_or_unstage_diff_hunks(&ranges, cx);
12621 }
12622
12623 pub fn stage_or_unstage_diff_hunks(
12624 &mut self,
12625 ranges: &[Range<Anchor>],
12626 cx: &mut Context<Self>,
12627 ) {
12628 let Some(project) = &self.project else {
12629 return;
12630 };
12631 let snapshot = self.buffer.read(cx).snapshot(cx);
12632 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12633
12634 let chunk_by = self
12635 .diff_hunks_in_ranges(&ranges, &snapshot)
12636 .chunk_by(|hunk| hunk.buffer_id);
12637 for (buffer_id, hunks) in &chunk_by {
12638 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12639 log::debug!("no buffer for id");
12640 continue;
12641 };
12642 let buffer = buffer.read(cx).snapshot();
12643 let Some((repo, path)) = project
12644 .read(cx)
12645 .repository_and_path_for_buffer_id(buffer_id, cx)
12646 else {
12647 log::debug!("no git repo for buffer id");
12648 continue;
12649 };
12650 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12651 log::debug!("no diff for buffer id");
12652 continue;
12653 };
12654 let Some(secondary_diff) = diff.secondary_diff() else {
12655 log::debug!("no secondary diff for buffer id");
12656 continue;
12657 };
12658
12659 let edits = diff.secondary_edits_for_stage_or_unstage(
12660 stage,
12661 hunks.map(|hunk| {
12662 (
12663 hunk.diff_base_byte_range.clone(),
12664 hunk.secondary_diff_base_byte_range.clone(),
12665 hunk.buffer_range.clone(),
12666 )
12667 }),
12668 &buffer,
12669 );
12670
12671 let index_base = secondary_diff.base_text().map_or_else(
12672 || Rope::from(""),
12673 |snapshot| snapshot.text.as_rope().clone(),
12674 );
12675 let index_buffer = cx.new(|cx| {
12676 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12677 });
12678 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12679 index_buffer.edit(edits, None, cx);
12680 index_buffer.snapshot().as_rope().to_string()
12681 });
12682 let new_index_text = if new_index_text.is_empty()
12683 && (diff.is_single_insertion
12684 || buffer
12685 .file()
12686 .map_or(false, |file| file.disk_state() == DiskState::New))
12687 {
12688 log::debug!("removing from index");
12689 None
12690 } else {
12691 Some(new_index_text)
12692 };
12693
12694 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12695 }
12696 }
12697
12698 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12699 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12700 self.buffer
12701 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12702 }
12703
12704 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12705 self.buffer.update(cx, |buffer, cx| {
12706 let ranges = vec![Anchor::min()..Anchor::max()];
12707 if !buffer.all_diff_hunks_expanded()
12708 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12709 {
12710 buffer.collapse_diff_hunks(ranges, cx);
12711 true
12712 } else {
12713 false
12714 }
12715 })
12716 }
12717
12718 fn toggle_diff_hunks_in_ranges(
12719 &mut self,
12720 ranges: Vec<Range<Anchor>>,
12721 cx: &mut Context<'_, Editor>,
12722 ) {
12723 self.buffer.update(cx, |buffer, cx| {
12724 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12725 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12726 })
12727 }
12728
12729 fn toggle_diff_hunks_in_ranges_narrow(
12730 &mut self,
12731 ranges: Vec<Range<Anchor>>,
12732 cx: &mut Context<'_, Editor>,
12733 ) {
12734 self.buffer.update(cx, |buffer, cx| {
12735 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12736 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12737 })
12738 }
12739
12740 pub(crate) fn apply_all_diff_hunks(
12741 &mut self,
12742 _: &ApplyAllDiffHunks,
12743 window: &mut Window,
12744 cx: &mut Context<Self>,
12745 ) {
12746 let buffers = self.buffer.read(cx).all_buffers();
12747 for branch_buffer in buffers {
12748 branch_buffer.update(cx, |branch_buffer, cx| {
12749 branch_buffer.merge_into_base(Vec::new(), cx);
12750 });
12751 }
12752
12753 if let Some(project) = self.project.clone() {
12754 self.save(true, project, window, cx).detach_and_log_err(cx);
12755 }
12756 }
12757
12758 pub(crate) fn apply_selected_diff_hunks(
12759 &mut self,
12760 _: &ApplyDiffHunk,
12761 window: &mut Window,
12762 cx: &mut Context<Self>,
12763 ) {
12764 let snapshot = self.snapshot(window, cx);
12765 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12766 let mut ranges_by_buffer = HashMap::default();
12767 self.transact(window, cx, |editor, _window, cx| {
12768 for hunk in hunks {
12769 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12770 ranges_by_buffer
12771 .entry(buffer.clone())
12772 .or_insert_with(Vec::new)
12773 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12774 }
12775 }
12776
12777 for (buffer, ranges) in ranges_by_buffer {
12778 buffer.update(cx, |buffer, cx| {
12779 buffer.merge_into_base(ranges, cx);
12780 });
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 fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12790 if hovered != self.gutter_hovered {
12791 self.gutter_hovered = hovered;
12792 cx.notify();
12793 }
12794 }
12795
12796 pub fn insert_blocks(
12797 &mut self,
12798 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12799 autoscroll: Option<Autoscroll>,
12800 cx: &mut Context<Self>,
12801 ) -> Vec<CustomBlockId> {
12802 let blocks = self
12803 .display_map
12804 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12805 if let Some(autoscroll) = autoscroll {
12806 self.request_autoscroll(autoscroll, cx);
12807 }
12808 cx.notify();
12809 blocks
12810 }
12811
12812 pub fn resize_blocks(
12813 &mut self,
12814 heights: HashMap<CustomBlockId, u32>,
12815 autoscroll: Option<Autoscroll>,
12816 cx: &mut Context<Self>,
12817 ) {
12818 self.display_map
12819 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12820 if let Some(autoscroll) = autoscroll {
12821 self.request_autoscroll(autoscroll, cx);
12822 }
12823 cx.notify();
12824 }
12825
12826 pub fn replace_blocks(
12827 &mut self,
12828 renderers: HashMap<CustomBlockId, RenderBlock>,
12829 autoscroll: Option<Autoscroll>,
12830 cx: &mut Context<Self>,
12831 ) {
12832 self.display_map
12833 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12834 if let Some(autoscroll) = autoscroll {
12835 self.request_autoscroll(autoscroll, cx);
12836 }
12837 cx.notify();
12838 }
12839
12840 pub fn remove_blocks(
12841 &mut self,
12842 block_ids: HashSet<CustomBlockId>,
12843 autoscroll: Option<Autoscroll>,
12844 cx: &mut Context<Self>,
12845 ) {
12846 self.display_map.update(cx, |display_map, cx| {
12847 display_map.remove_blocks(block_ids, cx)
12848 });
12849 if let Some(autoscroll) = autoscroll {
12850 self.request_autoscroll(autoscroll, cx);
12851 }
12852 cx.notify();
12853 }
12854
12855 pub fn row_for_block(
12856 &self,
12857 block_id: CustomBlockId,
12858 cx: &mut Context<Self>,
12859 ) -> Option<DisplayRow> {
12860 self.display_map
12861 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12862 }
12863
12864 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12865 self.focused_block = Some(focused_block);
12866 }
12867
12868 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12869 self.focused_block.take()
12870 }
12871
12872 pub fn insert_creases(
12873 &mut self,
12874 creases: impl IntoIterator<Item = Crease<Anchor>>,
12875 cx: &mut Context<Self>,
12876 ) -> Vec<CreaseId> {
12877 self.display_map
12878 .update(cx, |map, cx| map.insert_creases(creases, cx))
12879 }
12880
12881 pub fn remove_creases(
12882 &mut self,
12883 ids: impl IntoIterator<Item = CreaseId>,
12884 cx: &mut Context<Self>,
12885 ) {
12886 self.display_map
12887 .update(cx, |map, cx| map.remove_creases(ids, cx));
12888 }
12889
12890 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12891 self.display_map
12892 .update(cx, |map, cx| map.snapshot(cx))
12893 .longest_row()
12894 }
12895
12896 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12897 self.display_map
12898 .update(cx, |map, cx| map.snapshot(cx))
12899 .max_point()
12900 }
12901
12902 pub fn text(&self, cx: &App) -> String {
12903 self.buffer.read(cx).read(cx).text()
12904 }
12905
12906 pub fn is_empty(&self, cx: &App) -> bool {
12907 self.buffer.read(cx).read(cx).is_empty()
12908 }
12909
12910 pub fn text_option(&self, cx: &App) -> Option<String> {
12911 let text = self.text(cx);
12912 let text = text.trim();
12913
12914 if text.is_empty() {
12915 return None;
12916 }
12917
12918 Some(text.to_string())
12919 }
12920
12921 pub fn set_text(
12922 &mut self,
12923 text: impl Into<Arc<str>>,
12924 window: &mut Window,
12925 cx: &mut Context<Self>,
12926 ) {
12927 self.transact(window, cx, |this, _, cx| {
12928 this.buffer
12929 .read(cx)
12930 .as_singleton()
12931 .expect("you can only call set_text on editors for singleton buffers")
12932 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12933 });
12934 }
12935
12936 pub fn display_text(&self, cx: &mut App) -> String {
12937 self.display_map
12938 .update(cx, |map, cx| map.snapshot(cx))
12939 .text()
12940 }
12941
12942 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12943 let mut wrap_guides = smallvec::smallvec![];
12944
12945 if self.show_wrap_guides == Some(false) {
12946 return wrap_guides;
12947 }
12948
12949 let settings = self.buffer.read(cx).settings_at(0, cx);
12950 if settings.show_wrap_guides {
12951 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12952 wrap_guides.push((soft_wrap as usize, true));
12953 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12954 wrap_guides.push((soft_wrap as usize, true));
12955 }
12956 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12957 }
12958
12959 wrap_guides
12960 }
12961
12962 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12963 let settings = self.buffer.read(cx).settings_at(0, cx);
12964 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12965 match mode {
12966 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12967 SoftWrap::None
12968 }
12969 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12970 language_settings::SoftWrap::PreferredLineLength => {
12971 SoftWrap::Column(settings.preferred_line_length)
12972 }
12973 language_settings::SoftWrap::Bounded => {
12974 SoftWrap::Bounded(settings.preferred_line_length)
12975 }
12976 }
12977 }
12978
12979 pub fn set_soft_wrap_mode(
12980 &mut self,
12981 mode: language_settings::SoftWrap,
12982
12983 cx: &mut Context<Self>,
12984 ) {
12985 self.soft_wrap_mode_override = Some(mode);
12986 cx.notify();
12987 }
12988
12989 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12990 self.text_style_refinement = Some(style);
12991 }
12992
12993 /// called by the Element so we know what style we were most recently rendered with.
12994 pub(crate) fn set_style(
12995 &mut self,
12996 style: EditorStyle,
12997 window: &mut Window,
12998 cx: &mut Context<Self>,
12999 ) {
13000 let rem_size = window.rem_size();
13001 self.display_map.update(cx, |map, cx| {
13002 map.set_font(
13003 style.text.font(),
13004 style.text.font_size.to_pixels(rem_size),
13005 cx,
13006 )
13007 });
13008 self.style = Some(style);
13009 }
13010
13011 pub fn style(&self) -> Option<&EditorStyle> {
13012 self.style.as_ref()
13013 }
13014
13015 // Called by the element. This method is not designed to be called outside of the editor
13016 // element's layout code because it does not notify when rewrapping is computed synchronously.
13017 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13018 self.display_map
13019 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13020 }
13021
13022 pub fn set_soft_wrap(&mut self) {
13023 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13024 }
13025
13026 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13027 if self.soft_wrap_mode_override.is_some() {
13028 self.soft_wrap_mode_override.take();
13029 } else {
13030 let soft_wrap = match self.soft_wrap_mode(cx) {
13031 SoftWrap::GitDiff => return,
13032 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13033 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13034 language_settings::SoftWrap::None
13035 }
13036 };
13037 self.soft_wrap_mode_override = Some(soft_wrap);
13038 }
13039 cx.notify();
13040 }
13041
13042 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13043 let Some(workspace) = self.workspace() else {
13044 return;
13045 };
13046 let fs = workspace.read(cx).app_state().fs.clone();
13047 let current_show = TabBarSettings::get_global(cx).show;
13048 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13049 setting.show = Some(!current_show);
13050 });
13051 }
13052
13053 pub fn toggle_indent_guides(
13054 &mut self,
13055 _: &ToggleIndentGuides,
13056 _: &mut Window,
13057 cx: &mut Context<Self>,
13058 ) {
13059 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13060 self.buffer
13061 .read(cx)
13062 .settings_at(0, cx)
13063 .indent_guides
13064 .enabled
13065 });
13066 self.show_indent_guides = Some(!currently_enabled);
13067 cx.notify();
13068 }
13069
13070 fn should_show_indent_guides(&self) -> Option<bool> {
13071 self.show_indent_guides
13072 }
13073
13074 pub fn toggle_line_numbers(
13075 &mut self,
13076 _: &ToggleLineNumbers,
13077 _: &mut Window,
13078 cx: &mut Context<Self>,
13079 ) {
13080 let mut editor_settings = EditorSettings::get_global(cx).clone();
13081 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13082 EditorSettings::override_global(editor_settings, cx);
13083 }
13084
13085 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13086 self.use_relative_line_numbers
13087 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13088 }
13089
13090 pub fn toggle_relative_line_numbers(
13091 &mut self,
13092 _: &ToggleRelativeLineNumbers,
13093 _: &mut Window,
13094 cx: &mut Context<Self>,
13095 ) {
13096 let is_relative = self.should_use_relative_line_numbers(cx);
13097 self.set_relative_line_number(Some(!is_relative), cx)
13098 }
13099
13100 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13101 self.use_relative_line_numbers = is_relative;
13102 cx.notify();
13103 }
13104
13105 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13106 self.show_gutter = show_gutter;
13107 cx.notify();
13108 }
13109
13110 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13111 self.show_scrollbars = show_scrollbars;
13112 cx.notify();
13113 }
13114
13115 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13116 self.show_line_numbers = Some(show_line_numbers);
13117 cx.notify();
13118 }
13119
13120 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13121 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13122 cx.notify();
13123 }
13124
13125 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13126 self.show_code_actions = Some(show_code_actions);
13127 cx.notify();
13128 }
13129
13130 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13131 self.show_runnables = Some(show_runnables);
13132 cx.notify();
13133 }
13134
13135 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13136 if self.display_map.read(cx).masked != masked {
13137 self.display_map.update(cx, |map, _| map.masked = masked);
13138 }
13139 cx.notify()
13140 }
13141
13142 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13143 self.show_wrap_guides = Some(show_wrap_guides);
13144 cx.notify();
13145 }
13146
13147 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13148 self.show_indent_guides = Some(show_indent_guides);
13149 cx.notify();
13150 }
13151
13152 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13153 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13154 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13155 if let Some(dir) = file.abs_path(cx).parent() {
13156 return Some(dir.to_owned());
13157 }
13158 }
13159
13160 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13161 return Some(project_path.path.to_path_buf());
13162 }
13163 }
13164
13165 None
13166 }
13167
13168 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13169 self.active_excerpt(cx)?
13170 .1
13171 .read(cx)
13172 .file()
13173 .and_then(|f| f.as_local())
13174 }
13175
13176 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13177 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13178 let buffer = buffer.read(cx);
13179 if let Some(project_path) = buffer.project_path(cx) {
13180 let project = self.project.as_ref()?.read(cx);
13181 project.absolute_path(&project_path, cx)
13182 } else {
13183 buffer
13184 .file()
13185 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13186 }
13187 })
13188 }
13189
13190 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13191 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13192 let project_path = buffer.read(cx).project_path(cx)?;
13193 let project = self.project.as_ref()?.read(cx);
13194 let entry = project.entry_for_path(&project_path, cx)?;
13195 let path = entry.path.to_path_buf();
13196 Some(path)
13197 })
13198 }
13199
13200 pub fn reveal_in_finder(
13201 &mut self,
13202 _: &RevealInFileManager,
13203 _window: &mut Window,
13204 cx: &mut Context<Self>,
13205 ) {
13206 if let Some(target) = self.target_file(cx) {
13207 cx.reveal_path(&target.abs_path(cx));
13208 }
13209 }
13210
13211 pub fn copy_path(
13212 &mut self,
13213 _: &zed_actions::workspace::CopyPath,
13214 _window: &mut Window,
13215 cx: &mut Context<Self>,
13216 ) {
13217 if let Some(path) = self.target_file_abs_path(cx) {
13218 if let Some(path) = path.to_str() {
13219 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13220 }
13221 }
13222 }
13223
13224 pub fn copy_relative_path(
13225 &mut self,
13226 _: &zed_actions::workspace::CopyRelativePath,
13227 _window: &mut Window,
13228 cx: &mut Context<Self>,
13229 ) {
13230 if let Some(path) = self.target_file_path(cx) {
13231 if let Some(path) = path.to_str() {
13232 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13233 }
13234 }
13235 }
13236
13237 pub fn copy_file_name_without_extension(
13238 &mut self,
13239 _: &CopyFileNameWithoutExtension,
13240 _: &mut Window,
13241 cx: &mut Context<Self>,
13242 ) {
13243 if let Some(file) = self.target_file(cx) {
13244 if let Some(file_stem) = file.path().file_stem() {
13245 if let Some(name) = file_stem.to_str() {
13246 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13247 }
13248 }
13249 }
13250 }
13251
13252 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13253 if let Some(file) = self.target_file(cx) {
13254 if let Some(file_name) = file.path().file_name() {
13255 if let Some(name) = file_name.to_str() {
13256 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13257 }
13258 }
13259 }
13260 }
13261
13262 pub fn toggle_git_blame(
13263 &mut self,
13264 _: &ToggleGitBlame,
13265 window: &mut Window,
13266 cx: &mut Context<Self>,
13267 ) {
13268 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13269
13270 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13271 self.start_git_blame(true, window, cx);
13272 }
13273
13274 cx.notify();
13275 }
13276
13277 pub fn toggle_git_blame_inline(
13278 &mut self,
13279 _: &ToggleGitBlameInline,
13280 window: &mut Window,
13281 cx: &mut Context<Self>,
13282 ) {
13283 self.toggle_git_blame_inline_internal(true, window, cx);
13284 cx.notify();
13285 }
13286
13287 pub fn git_blame_inline_enabled(&self) -> bool {
13288 self.git_blame_inline_enabled
13289 }
13290
13291 pub fn toggle_selection_menu(
13292 &mut self,
13293 _: &ToggleSelectionMenu,
13294 _: &mut Window,
13295 cx: &mut Context<Self>,
13296 ) {
13297 self.show_selection_menu = self
13298 .show_selection_menu
13299 .map(|show_selections_menu| !show_selections_menu)
13300 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13301
13302 cx.notify();
13303 }
13304
13305 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13306 self.show_selection_menu
13307 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13308 }
13309
13310 fn start_git_blame(
13311 &mut self,
13312 user_triggered: bool,
13313 window: &mut Window,
13314 cx: &mut Context<Self>,
13315 ) {
13316 if let Some(project) = self.project.as_ref() {
13317 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13318 return;
13319 };
13320
13321 if buffer.read(cx).file().is_none() {
13322 return;
13323 }
13324
13325 let focused = self.focus_handle(cx).contains_focused(window, cx);
13326
13327 let project = project.clone();
13328 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13329 self.blame_subscription =
13330 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13331 self.blame = Some(blame);
13332 }
13333 }
13334
13335 fn toggle_git_blame_inline_internal(
13336 &mut self,
13337 user_triggered: bool,
13338 window: &mut Window,
13339 cx: &mut Context<Self>,
13340 ) {
13341 if self.git_blame_inline_enabled {
13342 self.git_blame_inline_enabled = false;
13343 self.show_git_blame_inline = false;
13344 self.show_git_blame_inline_delay_task.take();
13345 } else {
13346 self.git_blame_inline_enabled = true;
13347 self.start_git_blame_inline(user_triggered, window, cx);
13348 }
13349
13350 cx.notify();
13351 }
13352
13353 fn start_git_blame_inline(
13354 &mut self,
13355 user_triggered: bool,
13356 window: &mut Window,
13357 cx: &mut Context<Self>,
13358 ) {
13359 self.start_git_blame(user_triggered, window, cx);
13360
13361 if ProjectSettings::get_global(cx)
13362 .git
13363 .inline_blame_delay()
13364 .is_some()
13365 {
13366 self.start_inline_blame_timer(window, cx);
13367 } else {
13368 self.show_git_blame_inline = true
13369 }
13370 }
13371
13372 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13373 self.blame.as_ref()
13374 }
13375
13376 pub fn show_git_blame_gutter(&self) -> bool {
13377 self.show_git_blame_gutter
13378 }
13379
13380 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13381 self.show_git_blame_gutter && self.has_blame_entries(cx)
13382 }
13383
13384 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13385 self.show_git_blame_inline
13386 && self.focus_handle.is_focused(window)
13387 && !self.newest_selection_head_on_empty_line(cx)
13388 && self.has_blame_entries(cx)
13389 }
13390
13391 fn has_blame_entries(&self, cx: &App) -> bool {
13392 self.blame()
13393 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13394 }
13395
13396 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13397 let cursor_anchor = self.selections.newest_anchor().head();
13398
13399 let snapshot = self.buffer.read(cx).snapshot(cx);
13400 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13401
13402 snapshot.line_len(buffer_row) == 0
13403 }
13404
13405 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13406 let buffer_and_selection = maybe!({
13407 let selection = self.selections.newest::<Point>(cx);
13408 let selection_range = selection.range();
13409
13410 let multi_buffer = self.buffer().read(cx);
13411 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13412 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13413
13414 let (buffer, range, _) = if selection.reversed {
13415 buffer_ranges.first()
13416 } else {
13417 buffer_ranges.last()
13418 }?;
13419
13420 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13421 ..text::ToPoint::to_point(&range.end, &buffer).row;
13422 Some((
13423 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13424 selection,
13425 ))
13426 });
13427
13428 let Some((buffer, selection)) = buffer_and_selection else {
13429 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13430 };
13431
13432 let Some(project) = self.project.as_ref() else {
13433 return Task::ready(Err(anyhow!("editor does not have project")));
13434 };
13435
13436 project.update(cx, |project, cx| {
13437 project.get_permalink_to_line(&buffer, selection, cx)
13438 })
13439 }
13440
13441 pub fn copy_permalink_to_line(
13442 &mut self,
13443 _: &CopyPermalinkToLine,
13444 window: &mut Window,
13445 cx: &mut Context<Self>,
13446 ) {
13447 let permalink_task = self.get_permalink_to_line(cx);
13448 let workspace = self.workspace();
13449
13450 cx.spawn_in(window, |_, mut cx| async move {
13451 match permalink_task.await {
13452 Ok(permalink) => {
13453 cx.update(|_, cx| {
13454 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13455 })
13456 .ok();
13457 }
13458 Err(err) => {
13459 let message = format!("Failed to copy permalink: {err}");
13460
13461 Err::<(), anyhow::Error>(err).log_err();
13462
13463 if let Some(workspace) = workspace {
13464 workspace
13465 .update_in(&mut cx, |workspace, _, cx| {
13466 struct CopyPermalinkToLine;
13467
13468 workspace.show_toast(
13469 Toast::new(
13470 NotificationId::unique::<CopyPermalinkToLine>(),
13471 message,
13472 ),
13473 cx,
13474 )
13475 })
13476 .ok();
13477 }
13478 }
13479 }
13480 })
13481 .detach();
13482 }
13483
13484 pub fn copy_file_location(
13485 &mut self,
13486 _: &CopyFileLocation,
13487 _: &mut Window,
13488 cx: &mut Context<Self>,
13489 ) {
13490 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13491 if let Some(file) = self.target_file(cx) {
13492 if let Some(path) = file.path().to_str() {
13493 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13494 }
13495 }
13496 }
13497
13498 pub fn open_permalink_to_line(
13499 &mut self,
13500 _: &OpenPermalinkToLine,
13501 window: &mut Window,
13502 cx: &mut Context<Self>,
13503 ) {
13504 let permalink_task = self.get_permalink_to_line(cx);
13505 let workspace = self.workspace();
13506
13507 cx.spawn_in(window, |_, mut cx| async move {
13508 match permalink_task.await {
13509 Ok(permalink) => {
13510 cx.update(|_, cx| {
13511 cx.open_url(permalink.as_ref());
13512 })
13513 .ok();
13514 }
13515 Err(err) => {
13516 let message = format!("Failed to open permalink: {err}");
13517
13518 Err::<(), anyhow::Error>(err).log_err();
13519
13520 if let Some(workspace) = workspace {
13521 workspace
13522 .update(&mut cx, |workspace, cx| {
13523 struct OpenPermalinkToLine;
13524
13525 workspace.show_toast(
13526 Toast::new(
13527 NotificationId::unique::<OpenPermalinkToLine>(),
13528 message,
13529 ),
13530 cx,
13531 )
13532 })
13533 .ok();
13534 }
13535 }
13536 }
13537 })
13538 .detach();
13539 }
13540
13541 pub fn insert_uuid_v4(
13542 &mut self,
13543 _: &InsertUuidV4,
13544 window: &mut Window,
13545 cx: &mut Context<Self>,
13546 ) {
13547 self.insert_uuid(UuidVersion::V4, window, cx);
13548 }
13549
13550 pub fn insert_uuid_v7(
13551 &mut self,
13552 _: &InsertUuidV7,
13553 window: &mut Window,
13554 cx: &mut Context<Self>,
13555 ) {
13556 self.insert_uuid(UuidVersion::V7, window, cx);
13557 }
13558
13559 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13560 self.transact(window, cx, |this, window, cx| {
13561 let edits = this
13562 .selections
13563 .all::<Point>(cx)
13564 .into_iter()
13565 .map(|selection| {
13566 let uuid = match version {
13567 UuidVersion::V4 => uuid::Uuid::new_v4(),
13568 UuidVersion::V7 => uuid::Uuid::now_v7(),
13569 };
13570
13571 (selection.range(), uuid.to_string())
13572 });
13573 this.edit(edits, cx);
13574 this.refresh_inline_completion(true, false, window, cx);
13575 });
13576 }
13577
13578 pub fn open_selections_in_multibuffer(
13579 &mut self,
13580 _: &OpenSelectionsInMultibuffer,
13581 window: &mut Window,
13582 cx: &mut Context<Self>,
13583 ) {
13584 let multibuffer = self.buffer.read(cx);
13585
13586 let Some(buffer) = multibuffer.as_singleton() else {
13587 return;
13588 };
13589
13590 let Some(workspace) = self.workspace() else {
13591 return;
13592 };
13593
13594 let locations = self
13595 .selections
13596 .disjoint_anchors()
13597 .iter()
13598 .map(|range| Location {
13599 buffer: buffer.clone(),
13600 range: range.start.text_anchor..range.end.text_anchor,
13601 })
13602 .collect::<Vec<_>>();
13603
13604 let title = multibuffer.title(cx).to_string();
13605
13606 cx.spawn_in(window, |_, mut cx| async move {
13607 workspace.update_in(&mut cx, |workspace, window, cx| {
13608 Self::open_locations_in_multibuffer(
13609 workspace,
13610 locations,
13611 format!("Selections for '{title}'"),
13612 false,
13613 MultibufferSelectionMode::All,
13614 window,
13615 cx,
13616 );
13617 })
13618 })
13619 .detach();
13620 }
13621
13622 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13623 /// last highlight added will be used.
13624 ///
13625 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13626 pub fn highlight_rows<T: 'static>(
13627 &mut self,
13628 range: Range<Anchor>,
13629 color: Hsla,
13630 should_autoscroll: bool,
13631 cx: &mut Context<Self>,
13632 ) {
13633 let snapshot = self.buffer().read(cx).snapshot(cx);
13634 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13635 let ix = row_highlights.binary_search_by(|highlight| {
13636 Ordering::Equal
13637 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13638 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13639 });
13640
13641 if let Err(mut ix) = ix {
13642 let index = post_inc(&mut self.highlight_order);
13643
13644 // If this range intersects with the preceding highlight, then merge it with
13645 // the preceding highlight. Otherwise insert a new highlight.
13646 let mut merged = false;
13647 if ix > 0 {
13648 let prev_highlight = &mut row_highlights[ix - 1];
13649 if prev_highlight
13650 .range
13651 .end
13652 .cmp(&range.start, &snapshot)
13653 .is_ge()
13654 {
13655 ix -= 1;
13656 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13657 prev_highlight.range.end = range.end;
13658 }
13659 merged = true;
13660 prev_highlight.index = index;
13661 prev_highlight.color = color;
13662 prev_highlight.should_autoscroll = should_autoscroll;
13663 }
13664 }
13665
13666 if !merged {
13667 row_highlights.insert(
13668 ix,
13669 RowHighlight {
13670 range: range.clone(),
13671 index,
13672 color,
13673 should_autoscroll,
13674 },
13675 );
13676 }
13677
13678 // If any of the following highlights intersect with this one, merge them.
13679 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13680 let highlight = &row_highlights[ix];
13681 if next_highlight
13682 .range
13683 .start
13684 .cmp(&highlight.range.end, &snapshot)
13685 .is_le()
13686 {
13687 if next_highlight
13688 .range
13689 .end
13690 .cmp(&highlight.range.end, &snapshot)
13691 .is_gt()
13692 {
13693 row_highlights[ix].range.end = next_highlight.range.end;
13694 }
13695 row_highlights.remove(ix + 1);
13696 } else {
13697 break;
13698 }
13699 }
13700 }
13701 }
13702
13703 /// Remove any highlighted row ranges of the given type that intersect the
13704 /// given ranges.
13705 pub fn remove_highlighted_rows<T: 'static>(
13706 &mut self,
13707 ranges_to_remove: Vec<Range<Anchor>>,
13708 cx: &mut Context<Self>,
13709 ) {
13710 let snapshot = self.buffer().read(cx).snapshot(cx);
13711 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13712 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13713 row_highlights.retain(|highlight| {
13714 while let Some(range_to_remove) = ranges_to_remove.peek() {
13715 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13716 Ordering::Less | Ordering::Equal => {
13717 ranges_to_remove.next();
13718 }
13719 Ordering::Greater => {
13720 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13721 Ordering::Less | Ordering::Equal => {
13722 return false;
13723 }
13724 Ordering::Greater => break,
13725 }
13726 }
13727 }
13728 }
13729
13730 true
13731 })
13732 }
13733
13734 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13735 pub fn clear_row_highlights<T: 'static>(&mut self) {
13736 self.highlighted_rows.remove(&TypeId::of::<T>());
13737 }
13738
13739 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13740 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13741 self.highlighted_rows
13742 .get(&TypeId::of::<T>())
13743 .map_or(&[] as &[_], |vec| vec.as_slice())
13744 .iter()
13745 .map(|highlight| (highlight.range.clone(), highlight.color))
13746 }
13747
13748 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13749 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13750 /// Allows to ignore certain kinds of highlights.
13751 pub fn highlighted_display_rows(
13752 &self,
13753 window: &mut Window,
13754 cx: &mut App,
13755 ) -> BTreeMap<DisplayRow, Hsla> {
13756 let snapshot = self.snapshot(window, cx);
13757 let mut used_highlight_orders = HashMap::default();
13758 self.highlighted_rows
13759 .iter()
13760 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13761 .fold(
13762 BTreeMap::<DisplayRow, Hsla>::new(),
13763 |mut unique_rows, highlight| {
13764 let start = highlight.range.start.to_display_point(&snapshot);
13765 let end = highlight.range.end.to_display_point(&snapshot);
13766 let start_row = start.row().0;
13767 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13768 && end.column() == 0
13769 {
13770 end.row().0.saturating_sub(1)
13771 } else {
13772 end.row().0
13773 };
13774 for row in start_row..=end_row {
13775 let used_index =
13776 used_highlight_orders.entry(row).or_insert(highlight.index);
13777 if highlight.index >= *used_index {
13778 *used_index = highlight.index;
13779 unique_rows.insert(DisplayRow(row), highlight.color);
13780 }
13781 }
13782 unique_rows
13783 },
13784 )
13785 }
13786
13787 pub fn highlighted_display_row_for_autoscroll(
13788 &self,
13789 snapshot: &DisplaySnapshot,
13790 ) -> Option<DisplayRow> {
13791 self.highlighted_rows
13792 .values()
13793 .flat_map(|highlighted_rows| highlighted_rows.iter())
13794 .filter_map(|highlight| {
13795 if highlight.should_autoscroll {
13796 Some(highlight.range.start.to_display_point(snapshot).row())
13797 } else {
13798 None
13799 }
13800 })
13801 .min()
13802 }
13803
13804 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13805 self.highlight_background::<SearchWithinRange>(
13806 ranges,
13807 |colors| colors.editor_document_highlight_read_background,
13808 cx,
13809 )
13810 }
13811
13812 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13813 self.breadcrumb_header = Some(new_header);
13814 }
13815
13816 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13817 self.clear_background_highlights::<SearchWithinRange>(cx);
13818 }
13819
13820 pub fn highlight_background<T: 'static>(
13821 &mut self,
13822 ranges: &[Range<Anchor>],
13823 color_fetcher: fn(&ThemeColors) -> Hsla,
13824 cx: &mut Context<Self>,
13825 ) {
13826 self.background_highlights
13827 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13828 self.scrollbar_marker_state.dirty = true;
13829 cx.notify();
13830 }
13831
13832 pub fn clear_background_highlights<T: 'static>(
13833 &mut self,
13834 cx: &mut Context<Self>,
13835 ) -> Option<BackgroundHighlight> {
13836 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13837 if !text_highlights.1.is_empty() {
13838 self.scrollbar_marker_state.dirty = true;
13839 cx.notify();
13840 }
13841 Some(text_highlights)
13842 }
13843
13844 pub fn highlight_gutter<T: 'static>(
13845 &mut self,
13846 ranges: &[Range<Anchor>],
13847 color_fetcher: fn(&App) -> Hsla,
13848 cx: &mut Context<Self>,
13849 ) {
13850 self.gutter_highlights
13851 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13852 cx.notify();
13853 }
13854
13855 pub fn clear_gutter_highlights<T: 'static>(
13856 &mut self,
13857 cx: &mut Context<Self>,
13858 ) -> Option<GutterHighlight> {
13859 cx.notify();
13860 self.gutter_highlights.remove(&TypeId::of::<T>())
13861 }
13862
13863 #[cfg(feature = "test-support")]
13864 pub fn all_text_background_highlights(
13865 &self,
13866 window: &mut Window,
13867 cx: &mut Context<Self>,
13868 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13869 let snapshot = self.snapshot(window, cx);
13870 let buffer = &snapshot.buffer_snapshot;
13871 let start = buffer.anchor_before(0);
13872 let end = buffer.anchor_after(buffer.len());
13873 let theme = cx.theme().colors();
13874 self.background_highlights_in_range(start..end, &snapshot, theme)
13875 }
13876
13877 #[cfg(feature = "test-support")]
13878 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13879 let snapshot = self.buffer().read(cx).snapshot(cx);
13880
13881 let highlights = self
13882 .background_highlights
13883 .get(&TypeId::of::<items::BufferSearchHighlights>());
13884
13885 if let Some((_color, ranges)) = highlights {
13886 ranges
13887 .iter()
13888 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13889 .collect_vec()
13890 } else {
13891 vec![]
13892 }
13893 }
13894
13895 fn document_highlights_for_position<'a>(
13896 &'a self,
13897 position: Anchor,
13898 buffer: &'a MultiBufferSnapshot,
13899 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13900 let read_highlights = self
13901 .background_highlights
13902 .get(&TypeId::of::<DocumentHighlightRead>())
13903 .map(|h| &h.1);
13904 let write_highlights = self
13905 .background_highlights
13906 .get(&TypeId::of::<DocumentHighlightWrite>())
13907 .map(|h| &h.1);
13908 let left_position = position.bias_left(buffer);
13909 let right_position = position.bias_right(buffer);
13910 read_highlights
13911 .into_iter()
13912 .chain(write_highlights)
13913 .flat_map(move |ranges| {
13914 let start_ix = match ranges.binary_search_by(|probe| {
13915 let cmp = probe.end.cmp(&left_position, buffer);
13916 if cmp.is_ge() {
13917 Ordering::Greater
13918 } else {
13919 Ordering::Less
13920 }
13921 }) {
13922 Ok(i) | Err(i) => i,
13923 };
13924
13925 ranges[start_ix..]
13926 .iter()
13927 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13928 })
13929 }
13930
13931 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13932 self.background_highlights
13933 .get(&TypeId::of::<T>())
13934 .map_or(false, |(_, highlights)| !highlights.is_empty())
13935 }
13936
13937 pub fn background_highlights_in_range(
13938 &self,
13939 search_range: Range<Anchor>,
13940 display_snapshot: &DisplaySnapshot,
13941 theme: &ThemeColors,
13942 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13943 let mut results = Vec::new();
13944 for (color_fetcher, ranges) in self.background_highlights.values() {
13945 let color = color_fetcher(theme);
13946 let start_ix = match ranges.binary_search_by(|probe| {
13947 let cmp = probe
13948 .end
13949 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13950 if cmp.is_gt() {
13951 Ordering::Greater
13952 } else {
13953 Ordering::Less
13954 }
13955 }) {
13956 Ok(i) | Err(i) => i,
13957 };
13958 for range in &ranges[start_ix..] {
13959 if range
13960 .start
13961 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13962 .is_ge()
13963 {
13964 break;
13965 }
13966
13967 let start = range.start.to_display_point(display_snapshot);
13968 let end = range.end.to_display_point(display_snapshot);
13969 results.push((start..end, color))
13970 }
13971 }
13972 results
13973 }
13974
13975 pub fn background_highlight_row_ranges<T: 'static>(
13976 &self,
13977 search_range: Range<Anchor>,
13978 display_snapshot: &DisplaySnapshot,
13979 count: usize,
13980 ) -> Vec<RangeInclusive<DisplayPoint>> {
13981 let mut results = Vec::new();
13982 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13983 return vec![];
13984 };
13985
13986 let start_ix = match ranges.binary_search_by(|probe| {
13987 let cmp = probe
13988 .end
13989 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13990 if cmp.is_gt() {
13991 Ordering::Greater
13992 } else {
13993 Ordering::Less
13994 }
13995 }) {
13996 Ok(i) | Err(i) => i,
13997 };
13998 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13999 if let (Some(start_display), Some(end_display)) = (start, end) {
14000 results.push(
14001 start_display.to_display_point(display_snapshot)
14002 ..=end_display.to_display_point(display_snapshot),
14003 );
14004 }
14005 };
14006 let mut start_row: Option<Point> = None;
14007 let mut end_row: Option<Point> = None;
14008 if ranges.len() > count {
14009 return Vec::new();
14010 }
14011 for range in &ranges[start_ix..] {
14012 if range
14013 .start
14014 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14015 .is_ge()
14016 {
14017 break;
14018 }
14019 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14020 if let Some(current_row) = &end_row {
14021 if end.row == current_row.row {
14022 continue;
14023 }
14024 }
14025 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14026 if start_row.is_none() {
14027 assert_eq!(end_row, None);
14028 start_row = Some(start);
14029 end_row = Some(end);
14030 continue;
14031 }
14032 if let Some(current_end) = end_row.as_mut() {
14033 if start.row > current_end.row + 1 {
14034 push_region(start_row, end_row);
14035 start_row = Some(start);
14036 end_row = Some(end);
14037 } else {
14038 // Merge two hunks.
14039 *current_end = end;
14040 }
14041 } else {
14042 unreachable!();
14043 }
14044 }
14045 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14046 push_region(start_row, end_row);
14047 results
14048 }
14049
14050 pub fn gutter_highlights_in_range(
14051 &self,
14052 search_range: Range<Anchor>,
14053 display_snapshot: &DisplaySnapshot,
14054 cx: &App,
14055 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14056 let mut results = Vec::new();
14057 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14058 let color = color_fetcher(cx);
14059 let start_ix = match ranges.binary_search_by(|probe| {
14060 let cmp = probe
14061 .end
14062 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14063 if cmp.is_gt() {
14064 Ordering::Greater
14065 } else {
14066 Ordering::Less
14067 }
14068 }) {
14069 Ok(i) | Err(i) => i,
14070 };
14071 for range in &ranges[start_ix..] {
14072 if range
14073 .start
14074 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14075 .is_ge()
14076 {
14077 break;
14078 }
14079
14080 let start = range.start.to_display_point(display_snapshot);
14081 let end = range.end.to_display_point(display_snapshot);
14082 results.push((start..end, color))
14083 }
14084 }
14085 results
14086 }
14087
14088 /// Get the text ranges corresponding to the redaction query
14089 pub fn redacted_ranges(
14090 &self,
14091 search_range: Range<Anchor>,
14092 display_snapshot: &DisplaySnapshot,
14093 cx: &App,
14094 ) -> Vec<Range<DisplayPoint>> {
14095 display_snapshot
14096 .buffer_snapshot
14097 .redacted_ranges(search_range, |file| {
14098 if let Some(file) = file {
14099 file.is_private()
14100 && EditorSettings::get(
14101 Some(SettingsLocation {
14102 worktree_id: file.worktree_id(cx),
14103 path: file.path().as_ref(),
14104 }),
14105 cx,
14106 )
14107 .redact_private_values
14108 } else {
14109 false
14110 }
14111 })
14112 .map(|range| {
14113 range.start.to_display_point(display_snapshot)
14114 ..range.end.to_display_point(display_snapshot)
14115 })
14116 .collect()
14117 }
14118
14119 pub fn highlight_text<T: 'static>(
14120 &mut self,
14121 ranges: Vec<Range<Anchor>>,
14122 style: HighlightStyle,
14123 cx: &mut Context<Self>,
14124 ) {
14125 self.display_map.update(cx, |map, _| {
14126 map.highlight_text(TypeId::of::<T>(), ranges, style)
14127 });
14128 cx.notify();
14129 }
14130
14131 pub(crate) fn highlight_inlays<T: 'static>(
14132 &mut self,
14133 highlights: Vec<InlayHighlight>,
14134 style: HighlightStyle,
14135 cx: &mut Context<Self>,
14136 ) {
14137 self.display_map.update(cx, |map, _| {
14138 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14139 });
14140 cx.notify();
14141 }
14142
14143 pub fn text_highlights<'a, T: 'static>(
14144 &'a self,
14145 cx: &'a App,
14146 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14147 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14148 }
14149
14150 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14151 let cleared = self
14152 .display_map
14153 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14154 if cleared {
14155 cx.notify();
14156 }
14157 }
14158
14159 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14160 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14161 && self.focus_handle.is_focused(window)
14162 }
14163
14164 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14165 self.show_cursor_when_unfocused = is_enabled;
14166 cx.notify();
14167 }
14168
14169 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14170 cx.notify();
14171 }
14172
14173 fn on_buffer_event(
14174 &mut self,
14175 multibuffer: &Entity<MultiBuffer>,
14176 event: &multi_buffer::Event,
14177 window: &mut Window,
14178 cx: &mut Context<Self>,
14179 ) {
14180 match event {
14181 multi_buffer::Event::Edited {
14182 singleton_buffer_edited,
14183 edited_buffer: buffer_edited,
14184 } => {
14185 self.scrollbar_marker_state.dirty = true;
14186 self.active_indent_guides_state.dirty = true;
14187 self.refresh_active_diagnostics(cx);
14188 self.refresh_code_actions(window, cx);
14189 if self.has_active_inline_completion() {
14190 self.update_visible_inline_completion(window, cx);
14191 }
14192 if let Some(buffer) = buffer_edited {
14193 let buffer_id = buffer.read(cx).remote_id();
14194 if !self.registered_buffers.contains_key(&buffer_id) {
14195 if let Some(project) = self.project.as_ref() {
14196 project.update(cx, |project, cx| {
14197 self.registered_buffers.insert(
14198 buffer_id,
14199 project.register_buffer_with_language_servers(&buffer, cx),
14200 );
14201 })
14202 }
14203 }
14204 }
14205 cx.emit(EditorEvent::BufferEdited);
14206 cx.emit(SearchEvent::MatchesInvalidated);
14207 if *singleton_buffer_edited {
14208 if let Some(project) = &self.project {
14209 #[allow(clippy::mutable_key_type)]
14210 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14211 multibuffer
14212 .all_buffers()
14213 .into_iter()
14214 .filter_map(|buffer| {
14215 buffer.update(cx, |buffer, cx| {
14216 let language = buffer.language()?;
14217 let should_discard = project.update(cx, |project, cx| {
14218 project.is_local()
14219 && !project.has_language_servers_for(buffer, cx)
14220 });
14221 should_discard.not().then_some(language.clone())
14222 })
14223 })
14224 .collect::<HashSet<_>>()
14225 });
14226 if !languages_affected.is_empty() {
14227 self.refresh_inlay_hints(
14228 InlayHintRefreshReason::BufferEdited(languages_affected),
14229 cx,
14230 );
14231 }
14232 }
14233 }
14234
14235 let Some(project) = &self.project else { return };
14236 let (telemetry, is_via_ssh) = {
14237 let project = project.read(cx);
14238 let telemetry = project.client().telemetry().clone();
14239 let is_via_ssh = project.is_via_ssh();
14240 (telemetry, is_via_ssh)
14241 };
14242 refresh_linked_ranges(self, window, cx);
14243 telemetry.log_edit_event("editor", is_via_ssh);
14244 }
14245 multi_buffer::Event::ExcerptsAdded {
14246 buffer,
14247 predecessor,
14248 excerpts,
14249 } => {
14250 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14251 let buffer_id = buffer.read(cx).remote_id();
14252 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14253 if let Some(project) = &self.project {
14254 get_uncommitted_diff_for_buffer(
14255 project,
14256 [buffer.clone()],
14257 self.buffer.clone(),
14258 cx,
14259 )
14260 .detach();
14261 }
14262 }
14263 cx.emit(EditorEvent::ExcerptsAdded {
14264 buffer: buffer.clone(),
14265 predecessor: *predecessor,
14266 excerpts: excerpts.clone(),
14267 });
14268 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14269 }
14270 multi_buffer::Event::ExcerptsRemoved { ids } => {
14271 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14272 let buffer = self.buffer.read(cx);
14273 self.registered_buffers
14274 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14275 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14276 }
14277 multi_buffer::Event::ExcerptsEdited { ids } => {
14278 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14279 }
14280 multi_buffer::Event::ExcerptsExpanded { ids } => {
14281 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14282 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14283 }
14284 multi_buffer::Event::Reparsed(buffer_id) => {
14285 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14286
14287 cx.emit(EditorEvent::Reparsed(*buffer_id));
14288 }
14289 multi_buffer::Event::DiffHunksToggled => {
14290 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14291 }
14292 multi_buffer::Event::LanguageChanged(buffer_id) => {
14293 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14294 cx.emit(EditorEvent::Reparsed(*buffer_id));
14295 cx.notify();
14296 }
14297 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14298 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14299 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14300 cx.emit(EditorEvent::TitleChanged)
14301 }
14302 // multi_buffer::Event::DiffBaseChanged => {
14303 // self.scrollbar_marker_state.dirty = true;
14304 // cx.emit(EditorEvent::DiffBaseChanged);
14305 // cx.notify();
14306 // }
14307 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14308 multi_buffer::Event::DiagnosticsUpdated => {
14309 self.refresh_active_diagnostics(cx);
14310 self.scrollbar_marker_state.dirty = true;
14311 cx.notify();
14312 }
14313 _ => {}
14314 };
14315 }
14316
14317 fn on_display_map_changed(
14318 &mut self,
14319 _: Entity<DisplayMap>,
14320 _: &mut Window,
14321 cx: &mut Context<Self>,
14322 ) {
14323 cx.notify();
14324 }
14325
14326 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14327 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14328 self.refresh_inline_completion(true, false, window, cx);
14329 self.refresh_inlay_hints(
14330 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14331 self.selections.newest_anchor().head(),
14332 &self.buffer.read(cx).snapshot(cx),
14333 cx,
14334 )),
14335 cx,
14336 );
14337
14338 let old_cursor_shape = self.cursor_shape;
14339
14340 {
14341 let editor_settings = EditorSettings::get_global(cx);
14342 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14343 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14344 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14345 }
14346
14347 if old_cursor_shape != self.cursor_shape {
14348 cx.emit(EditorEvent::CursorShapeChanged);
14349 }
14350
14351 let project_settings = ProjectSettings::get_global(cx);
14352 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14353
14354 if self.mode == EditorMode::Full {
14355 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14356 if self.git_blame_inline_enabled != inline_blame_enabled {
14357 self.toggle_git_blame_inline_internal(false, window, cx);
14358 }
14359 }
14360
14361 cx.notify();
14362 }
14363
14364 pub fn set_searchable(&mut self, searchable: bool) {
14365 self.searchable = searchable;
14366 }
14367
14368 pub fn searchable(&self) -> bool {
14369 self.searchable
14370 }
14371
14372 fn open_proposed_changes_editor(
14373 &mut self,
14374 _: &OpenProposedChangesEditor,
14375 window: &mut Window,
14376 cx: &mut Context<Self>,
14377 ) {
14378 let Some(workspace) = self.workspace() else {
14379 cx.propagate();
14380 return;
14381 };
14382
14383 let selections = self.selections.all::<usize>(cx);
14384 let multi_buffer = self.buffer.read(cx);
14385 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14386 let mut new_selections_by_buffer = HashMap::default();
14387 for selection in selections {
14388 for (buffer, range, _) in
14389 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14390 {
14391 let mut range = range.to_point(buffer);
14392 range.start.column = 0;
14393 range.end.column = buffer.line_len(range.end.row);
14394 new_selections_by_buffer
14395 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14396 .or_insert(Vec::new())
14397 .push(range)
14398 }
14399 }
14400
14401 let proposed_changes_buffers = new_selections_by_buffer
14402 .into_iter()
14403 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14404 .collect::<Vec<_>>();
14405 let proposed_changes_editor = cx.new(|cx| {
14406 ProposedChangesEditor::new(
14407 "Proposed changes",
14408 proposed_changes_buffers,
14409 self.project.clone(),
14410 window,
14411 cx,
14412 )
14413 });
14414
14415 window.defer(cx, move |window, cx| {
14416 workspace.update(cx, |workspace, cx| {
14417 workspace.active_pane().update(cx, |pane, cx| {
14418 pane.add_item(
14419 Box::new(proposed_changes_editor),
14420 true,
14421 true,
14422 None,
14423 window,
14424 cx,
14425 );
14426 });
14427 });
14428 });
14429 }
14430
14431 pub fn open_excerpts_in_split(
14432 &mut self,
14433 _: &OpenExcerptsSplit,
14434 window: &mut Window,
14435 cx: &mut Context<Self>,
14436 ) {
14437 self.open_excerpts_common(None, true, window, cx)
14438 }
14439
14440 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14441 self.open_excerpts_common(None, false, window, cx)
14442 }
14443
14444 fn open_excerpts_common(
14445 &mut self,
14446 jump_data: Option<JumpData>,
14447 split: bool,
14448 window: &mut Window,
14449 cx: &mut Context<Self>,
14450 ) {
14451 let Some(workspace) = self.workspace() else {
14452 cx.propagate();
14453 return;
14454 };
14455
14456 if self.buffer.read(cx).is_singleton() {
14457 cx.propagate();
14458 return;
14459 }
14460
14461 let mut new_selections_by_buffer = HashMap::default();
14462 match &jump_data {
14463 Some(JumpData::MultiBufferPoint {
14464 excerpt_id,
14465 position,
14466 anchor,
14467 line_offset_from_top,
14468 }) => {
14469 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14470 if let Some(buffer) = multi_buffer_snapshot
14471 .buffer_id_for_excerpt(*excerpt_id)
14472 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14473 {
14474 let buffer_snapshot = buffer.read(cx).snapshot();
14475 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14476 language::ToPoint::to_point(anchor, &buffer_snapshot)
14477 } else {
14478 buffer_snapshot.clip_point(*position, Bias::Left)
14479 };
14480 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14481 new_selections_by_buffer.insert(
14482 buffer,
14483 (
14484 vec![jump_to_offset..jump_to_offset],
14485 Some(*line_offset_from_top),
14486 ),
14487 );
14488 }
14489 }
14490 Some(JumpData::MultiBufferRow {
14491 row,
14492 line_offset_from_top,
14493 }) => {
14494 let point = MultiBufferPoint::new(row.0, 0);
14495 if let Some((buffer, buffer_point, _)) =
14496 self.buffer.read(cx).point_to_buffer_point(point, cx)
14497 {
14498 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14499 new_selections_by_buffer
14500 .entry(buffer)
14501 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14502 .0
14503 .push(buffer_offset..buffer_offset)
14504 }
14505 }
14506 None => {
14507 let selections = self.selections.all::<usize>(cx);
14508 let multi_buffer = self.buffer.read(cx);
14509 for selection in selections {
14510 for (buffer, mut range, _) in multi_buffer
14511 .snapshot(cx)
14512 .range_to_buffer_ranges(selection.range())
14513 {
14514 // When editing branch buffers, jump to the corresponding location
14515 // in their base buffer.
14516 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14517 let buffer = buffer_handle.read(cx);
14518 if let Some(base_buffer) = buffer.base_buffer() {
14519 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14520 buffer_handle = base_buffer;
14521 }
14522
14523 if selection.reversed {
14524 mem::swap(&mut range.start, &mut range.end);
14525 }
14526 new_selections_by_buffer
14527 .entry(buffer_handle)
14528 .or_insert((Vec::new(), None))
14529 .0
14530 .push(range)
14531 }
14532 }
14533 }
14534 }
14535
14536 if new_selections_by_buffer.is_empty() {
14537 return;
14538 }
14539
14540 // We defer the pane interaction because we ourselves are a workspace item
14541 // and activating a new item causes the pane to call a method on us reentrantly,
14542 // which panics if we're on the stack.
14543 window.defer(cx, move |window, cx| {
14544 workspace.update(cx, |workspace, cx| {
14545 let pane = if split {
14546 workspace.adjacent_pane(window, cx)
14547 } else {
14548 workspace.active_pane().clone()
14549 };
14550
14551 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14552 let editor = buffer
14553 .read(cx)
14554 .file()
14555 .is_none()
14556 .then(|| {
14557 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14558 // so `workspace.open_project_item` will never find them, always opening a new editor.
14559 // Instead, we try to activate the existing editor in the pane first.
14560 let (editor, pane_item_index) =
14561 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14562 let editor = item.downcast::<Editor>()?;
14563 let singleton_buffer =
14564 editor.read(cx).buffer().read(cx).as_singleton()?;
14565 if singleton_buffer == buffer {
14566 Some((editor, i))
14567 } else {
14568 None
14569 }
14570 })?;
14571 pane.update(cx, |pane, cx| {
14572 pane.activate_item(pane_item_index, true, true, window, cx)
14573 });
14574 Some(editor)
14575 })
14576 .flatten()
14577 .unwrap_or_else(|| {
14578 workspace.open_project_item::<Self>(
14579 pane.clone(),
14580 buffer,
14581 true,
14582 true,
14583 window,
14584 cx,
14585 )
14586 });
14587
14588 editor.update(cx, |editor, cx| {
14589 let autoscroll = match scroll_offset {
14590 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14591 None => Autoscroll::newest(),
14592 };
14593 let nav_history = editor.nav_history.take();
14594 editor.change_selections(Some(autoscroll), window, cx, |s| {
14595 s.select_ranges(ranges);
14596 });
14597 editor.nav_history = nav_history;
14598 });
14599 }
14600 })
14601 });
14602 }
14603
14604 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14605 let snapshot = self.buffer.read(cx).read(cx);
14606 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14607 Some(
14608 ranges
14609 .iter()
14610 .map(move |range| {
14611 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14612 })
14613 .collect(),
14614 )
14615 }
14616
14617 fn selection_replacement_ranges(
14618 &self,
14619 range: Range<OffsetUtf16>,
14620 cx: &mut App,
14621 ) -> Vec<Range<OffsetUtf16>> {
14622 let selections = self.selections.all::<OffsetUtf16>(cx);
14623 let newest_selection = selections
14624 .iter()
14625 .max_by_key(|selection| selection.id)
14626 .unwrap();
14627 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14628 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14629 let snapshot = self.buffer.read(cx).read(cx);
14630 selections
14631 .into_iter()
14632 .map(|mut selection| {
14633 selection.start.0 =
14634 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14635 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14636 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14637 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14638 })
14639 .collect()
14640 }
14641
14642 fn report_editor_event(
14643 &self,
14644 event_type: &'static str,
14645 file_extension: Option<String>,
14646 cx: &App,
14647 ) {
14648 if cfg!(any(test, feature = "test-support")) {
14649 return;
14650 }
14651
14652 let Some(project) = &self.project else { return };
14653
14654 // If None, we are in a file without an extension
14655 let file = self
14656 .buffer
14657 .read(cx)
14658 .as_singleton()
14659 .and_then(|b| b.read(cx).file());
14660 let file_extension = file_extension.or(file
14661 .as_ref()
14662 .and_then(|file| Path::new(file.file_name(cx)).extension())
14663 .and_then(|e| e.to_str())
14664 .map(|a| a.to_string()));
14665
14666 let vim_mode = cx
14667 .global::<SettingsStore>()
14668 .raw_user_settings()
14669 .get("vim_mode")
14670 == Some(&serde_json::Value::Bool(true));
14671
14672 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14673 let copilot_enabled = edit_predictions_provider
14674 == language::language_settings::EditPredictionProvider::Copilot;
14675 let copilot_enabled_for_language = self
14676 .buffer
14677 .read(cx)
14678 .settings_at(0, cx)
14679 .show_edit_predictions;
14680
14681 let project = project.read(cx);
14682 telemetry::event!(
14683 event_type,
14684 file_extension,
14685 vim_mode,
14686 copilot_enabled,
14687 copilot_enabled_for_language,
14688 edit_predictions_provider,
14689 is_via_ssh = project.is_via_ssh(),
14690 );
14691 }
14692
14693 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14694 /// with each line being an array of {text, highlight} objects.
14695 fn copy_highlight_json(
14696 &mut self,
14697 _: &CopyHighlightJson,
14698 window: &mut Window,
14699 cx: &mut Context<Self>,
14700 ) {
14701 #[derive(Serialize)]
14702 struct Chunk<'a> {
14703 text: String,
14704 highlight: Option<&'a str>,
14705 }
14706
14707 let snapshot = self.buffer.read(cx).snapshot(cx);
14708 let range = self
14709 .selected_text_range(false, window, cx)
14710 .and_then(|selection| {
14711 if selection.range.is_empty() {
14712 None
14713 } else {
14714 Some(selection.range)
14715 }
14716 })
14717 .unwrap_or_else(|| 0..snapshot.len());
14718
14719 let chunks = snapshot.chunks(range, true);
14720 let mut lines = Vec::new();
14721 let mut line: VecDeque<Chunk> = VecDeque::new();
14722
14723 let Some(style) = self.style.as_ref() else {
14724 return;
14725 };
14726
14727 for chunk in chunks {
14728 let highlight = chunk
14729 .syntax_highlight_id
14730 .and_then(|id| id.name(&style.syntax));
14731 let mut chunk_lines = chunk.text.split('\n').peekable();
14732 while let Some(text) = chunk_lines.next() {
14733 let mut merged_with_last_token = false;
14734 if let Some(last_token) = line.back_mut() {
14735 if last_token.highlight == highlight {
14736 last_token.text.push_str(text);
14737 merged_with_last_token = true;
14738 }
14739 }
14740
14741 if !merged_with_last_token {
14742 line.push_back(Chunk {
14743 text: text.into(),
14744 highlight,
14745 });
14746 }
14747
14748 if chunk_lines.peek().is_some() {
14749 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14750 line.pop_front();
14751 }
14752 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14753 line.pop_back();
14754 }
14755
14756 lines.push(mem::take(&mut line));
14757 }
14758 }
14759 }
14760
14761 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14762 return;
14763 };
14764 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14765 }
14766
14767 pub fn open_context_menu(
14768 &mut self,
14769 _: &OpenContextMenu,
14770 window: &mut Window,
14771 cx: &mut Context<Self>,
14772 ) {
14773 self.request_autoscroll(Autoscroll::newest(), cx);
14774 let position = self.selections.newest_display(cx).start;
14775 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14776 }
14777
14778 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14779 &self.inlay_hint_cache
14780 }
14781
14782 pub fn replay_insert_event(
14783 &mut self,
14784 text: &str,
14785 relative_utf16_range: Option<Range<isize>>,
14786 window: &mut Window,
14787 cx: &mut Context<Self>,
14788 ) {
14789 if !self.input_enabled {
14790 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14791 return;
14792 }
14793 if let Some(relative_utf16_range) = relative_utf16_range {
14794 let selections = self.selections.all::<OffsetUtf16>(cx);
14795 self.change_selections(None, window, cx, |s| {
14796 let new_ranges = selections.into_iter().map(|range| {
14797 let start = OffsetUtf16(
14798 range
14799 .head()
14800 .0
14801 .saturating_add_signed(relative_utf16_range.start),
14802 );
14803 let end = OffsetUtf16(
14804 range
14805 .head()
14806 .0
14807 .saturating_add_signed(relative_utf16_range.end),
14808 );
14809 start..end
14810 });
14811 s.select_ranges(new_ranges);
14812 });
14813 }
14814
14815 self.handle_input(text, window, cx);
14816 }
14817
14818 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14819 let Some(provider) = self.semantics_provider.as_ref() else {
14820 return false;
14821 };
14822
14823 let mut supports = false;
14824 self.buffer().update(cx, |this, cx| {
14825 this.for_each_buffer(|buffer| {
14826 supports |= provider.supports_inlay_hints(buffer, cx);
14827 });
14828 });
14829
14830 supports
14831 }
14832
14833 pub fn is_focused(&self, window: &Window) -> bool {
14834 self.focus_handle.is_focused(window)
14835 }
14836
14837 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14838 cx.emit(EditorEvent::Focused);
14839
14840 if let Some(descendant) = self
14841 .last_focused_descendant
14842 .take()
14843 .and_then(|descendant| descendant.upgrade())
14844 {
14845 window.focus(&descendant);
14846 } else {
14847 if let Some(blame) = self.blame.as_ref() {
14848 blame.update(cx, GitBlame::focus)
14849 }
14850
14851 self.blink_manager.update(cx, BlinkManager::enable);
14852 self.show_cursor_names(window, cx);
14853 self.buffer.update(cx, |buffer, cx| {
14854 buffer.finalize_last_transaction(cx);
14855 if self.leader_peer_id.is_none() {
14856 buffer.set_active_selections(
14857 &self.selections.disjoint_anchors(),
14858 self.selections.line_mode,
14859 self.cursor_shape,
14860 cx,
14861 );
14862 }
14863 });
14864 }
14865 }
14866
14867 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14868 cx.emit(EditorEvent::FocusedIn)
14869 }
14870
14871 fn handle_focus_out(
14872 &mut self,
14873 event: FocusOutEvent,
14874 _window: &mut Window,
14875 _cx: &mut Context<Self>,
14876 ) {
14877 if event.blurred != self.focus_handle {
14878 self.last_focused_descendant = Some(event.blurred);
14879 }
14880 }
14881
14882 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14883 self.blink_manager.update(cx, BlinkManager::disable);
14884 self.buffer
14885 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14886
14887 if let Some(blame) = self.blame.as_ref() {
14888 blame.update(cx, GitBlame::blur)
14889 }
14890 if !self.hover_state.focused(window, cx) {
14891 hide_hover(self, cx);
14892 }
14893
14894 self.hide_context_menu(window, cx);
14895 self.discard_inline_completion(false, cx);
14896 cx.emit(EditorEvent::Blurred);
14897 cx.notify();
14898 }
14899
14900 pub fn register_action<A: Action>(
14901 &mut self,
14902 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14903 ) -> Subscription {
14904 let id = self.next_editor_action_id.post_inc();
14905 let listener = Arc::new(listener);
14906 self.editor_actions.borrow_mut().insert(
14907 id,
14908 Box::new(move |window, _| {
14909 let listener = listener.clone();
14910 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14911 let action = action.downcast_ref().unwrap();
14912 if phase == DispatchPhase::Bubble {
14913 listener(action, window, cx)
14914 }
14915 })
14916 }),
14917 );
14918
14919 let editor_actions = self.editor_actions.clone();
14920 Subscription::new(move || {
14921 editor_actions.borrow_mut().remove(&id);
14922 })
14923 }
14924
14925 pub fn file_header_size(&self) -> u32 {
14926 FILE_HEADER_HEIGHT
14927 }
14928
14929 pub fn revert(
14930 &mut self,
14931 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14932 window: &mut Window,
14933 cx: &mut Context<Self>,
14934 ) {
14935 self.buffer().update(cx, |multi_buffer, cx| {
14936 for (buffer_id, changes) in revert_changes {
14937 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14938 buffer.update(cx, |buffer, cx| {
14939 buffer.edit(
14940 changes.into_iter().map(|(range, text)| {
14941 (range, text.to_string().map(Arc::<str>::from))
14942 }),
14943 None,
14944 cx,
14945 );
14946 });
14947 }
14948 }
14949 });
14950 self.change_selections(None, window, cx, |selections| selections.refresh());
14951 }
14952
14953 pub fn to_pixel_point(
14954 &self,
14955 source: multi_buffer::Anchor,
14956 editor_snapshot: &EditorSnapshot,
14957 window: &mut Window,
14958 ) -> Option<gpui::Point<Pixels>> {
14959 let source_point = source.to_display_point(editor_snapshot);
14960 self.display_to_pixel_point(source_point, editor_snapshot, window)
14961 }
14962
14963 pub fn display_to_pixel_point(
14964 &self,
14965 source: DisplayPoint,
14966 editor_snapshot: &EditorSnapshot,
14967 window: &mut Window,
14968 ) -> Option<gpui::Point<Pixels>> {
14969 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14970 let text_layout_details = self.text_layout_details(window);
14971 let scroll_top = text_layout_details
14972 .scroll_anchor
14973 .scroll_position(editor_snapshot)
14974 .y;
14975
14976 if source.row().as_f32() < scroll_top.floor() {
14977 return None;
14978 }
14979 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14980 let source_y = line_height * (source.row().as_f32() - scroll_top);
14981 Some(gpui::Point::new(source_x, source_y))
14982 }
14983
14984 pub fn has_visible_completions_menu(&self) -> bool {
14985 !self.edit_prediction_preview_is_active()
14986 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14987 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14988 })
14989 }
14990
14991 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14992 self.addons
14993 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14994 }
14995
14996 pub fn unregister_addon<T: Addon>(&mut self) {
14997 self.addons.remove(&std::any::TypeId::of::<T>());
14998 }
14999
15000 pub fn addon<T: Addon>(&self) -> Option<&T> {
15001 let type_id = std::any::TypeId::of::<T>();
15002 self.addons
15003 .get(&type_id)
15004 .and_then(|item| item.to_any().downcast_ref::<T>())
15005 }
15006
15007 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15008 let text_layout_details = self.text_layout_details(window);
15009 let style = &text_layout_details.editor_style;
15010 let font_id = window.text_system().resolve_font(&style.text.font());
15011 let font_size = style.text.font_size.to_pixels(window.rem_size());
15012 let line_height = style.text.line_height_in_pixels(window.rem_size());
15013 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15014
15015 gpui::Size::new(em_width, line_height)
15016 }
15017
15018 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15019 self.load_diff_task.clone()
15020 }
15021
15022 fn read_selections_from_db(
15023 &mut self,
15024 item_id: u64,
15025 workspace_id: WorkspaceId,
15026 window: &mut Window,
15027 cx: &mut Context<Editor>,
15028 ) {
15029 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
15030 return;
15031 }
15032 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15033 return;
15034 };
15035 if selections.is_empty() {
15036 return;
15037 }
15038
15039 let snapshot = self.buffer.read(cx).snapshot(cx);
15040 self.change_selections(None, window, cx, |s| {
15041 s.select_ranges(selections.into_iter().map(|(start, end)| {
15042 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15043 }));
15044 });
15045 }
15046}
15047
15048fn get_uncommitted_diff_for_buffer(
15049 project: &Entity<Project>,
15050 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15051 buffer: Entity<MultiBuffer>,
15052 cx: &mut App,
15053) -> Task<()> {
15054 let mut tasks = Vec::new();
15055 project.update(cx, |project, cx| {
15056 for buffer in buffers {
15057 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15058 }
15059 });
15060 cx.spawn(|mut cx| async move {
15061 let diffs = futures::future::join_all(tasks).await;
15062 buffer
15063 .update(&mut cx, |buffer, cx| {
15064 for diff in diffs.into_iter().flatten() {
15065 buffer.add_diff(diff, cx);
15066 }
15067 })
15068 .ok();
15069 })
15070}
15071
15072fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15073 let tab_size = tab_size.get() as usize;
15074 let mut width = offset;
15075
15076 for ch in text.chars() {
15077 width += if ch == '\t' {
15078 tab_size - (width % tab_size)
15079 } else {
15080 1
15081 };
15082 }
15083
15084 width - offset
15085}
15086
15087#[cfg(test)]
15088mod tests {
15089 use super::*;
15090
15091 #[test]
15092 fn test_string_size_with_expanded_tabs() {
15093 let nz = |val| NonZeroU32::new(val).unwrap();
15094 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15095 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15096 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15097 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15098 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15099 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15100 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15101 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15102 }
15103}
15104
15105/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15106struct WordBreakingTokenizer<'a> {
15107 input: &'a str,
15108}
15109
15110impl<'a> WordBreakingTokenizer<'a> {
15111 fn new(input: &'a str) -> Self {
15112 Self { input }
15113 }
15114}
15115
15116fn is_char_ideographic(ch: char) -> bool {
15117 use unicode_script::Script::*;
15118 use unicode_script::UnicodeScript;
15119 matches!(ch.script(), Han | Tangut | Yi)
15120}
15121
15122fn is_grapheme_ideographic(text: &str) -> bool {
15123 text.chars().any(is_char_ideographic)
15124}
15125
15126fn is_grapheme_whitespace(text: &str) -> bool {
15127 text.chars().any(|x| x.is_whitespace())
15128}
15129
15130fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15131 text.chars().next().map_or(false, |ch| {
15132 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15133 })
15134}
15135
15136#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15137struct WordBreakToken<'a> {
15138 token: &'a str,
15139 grapheme_len: usize,
15140 is_whitespace: bool,
15141}
15142
15143impl<'a> Iterator for WordBreakingTokenizer<'a> {
15144 /// Yields a span, the count of graphemes in the token, and whether it was
15145 /// whitespace. Note that it also breaks at word boundaries.
15146 type Item = WordBreakToken<'a>;
15147
15148 fn next(&mut self) -> Option<Self::Item> {
15149 use unicode_segmentation::UnicodeSegmentation;
15150 if self.input.is_empty() {
15151 return None;
15152 }
15153
15154 let mut iter = self.input.graphemes(true).peekable();
15155 let mut offset = 0;
15156 let mut graphemes = 0;
15157 if let Some(first_grapheme) = iter.next() {
15158 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15159 offset += first_grapheme.len();
15160 graphemes += 1;
15161 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15162 if let Some(grapheme) = iter.peek().copied() {
15163 if should_stay_with_preceding_ideograph(grapheme) {
15164 offset += grapheme.len();
15165 graphemes += 1;
15166 }
15167 }
15168 } else {
15169 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15170 let mut next_word_bound = words.peek().copied();
15171 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15172 next_word_bound = words.next();
15173 }
15174 while let Some(grapheme) = iter.peek().copied() {
15175 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15176 break;
15177 };
15178 if is_grapheme_whitespace(grapheme) != is_whitespace {
15179 break;
15180 };
15181 offset += grapheme.len();
15182 graphemes += 1;
15183 iter.next();
15184 }
15185 }
15186 let token = &self.input[..offset];
15187 self.input = &self.input[offset..];
15188 if is_whitespace {
15189 Some(WordBreakToken {
15190 token: " ",
15191 grapheme_len: 1,
15192 is_whitespace: true,
15193 })
15194 } else {
15195 Some(WordBreakToken {
15196 token,
15197 grapheme_len: graphemes,
15198 is_whitespace: false,
15199 })
15200 }
15201 } else {
15202 None
15203 }
15204 }
15205}
15206
15207#[test]
15208fn test_word_breaking_tokenizer() {
15209 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15210 ("", &[]),
15211 (" ", &[(" ", 1, true)]),
15212 ("Ʒ", &[("Ʒ", 1, false)]),
15213 ("Ǽ", &[("Ǽ", 1, false)]),
15214 ("⋑", &[("⋑", 1, false)]),
15215 ("⋑⋑", &[("⋑⋑", 2, false)]),
15216 (
15217 "原理,进而",
15218 &[
15219 ("原", 1, false),
15220 ("理,", 2, false),
15221 ("进", 1, false),
15222 ("而", 1, false),
15223 ],
15224 ),
15225 (
15226 "hello world",
15227 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15228 ),
15229 (
15230 "hello, world",
15231 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15232 ),
15233 (
15234 " hello world",
15235 &[
15236 (" ", 1, true),
15237 ("hello", 5, false),
15238 (" ", 1, true),
15239 ("world", 5, false),
15240 ],
15241 ),
15242 (
15243 "这是什么 \n 钢笔",
15244 &[
15245 ("这", 1, false),
15246 ("是", 1, false),
15247 ("什", 1, false),
15248 ("么", 1, false),
15249 (" ", 1, true),
15250 ("钢", 1, false),
15251 ("笔", 1, false),
15252 ],
15253 ),
15254 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15255 ];
15256
15257 for (input, result) in tests {
15258 assert_eq!(
15259 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15260 result
15261 .iter()
15262 .copied()
15263 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15264 token,
15265 grapheme_len,
15266 is_whitespace,
15267 })
15268 .collect::<Vec<_>>()
15269 );
15270 }
15271}
15272
15273fn wrap_with_prefix(
15274 line_prefix: String,
15275 unwrapped_text: String,
15276 wrap_column: usize,
15277 tab_size: NonZeroU32,
15278) -> String {
15279 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15280 let mut wrapped_text = String::new();
15281 let mut current_line = line_prefix.clone();
15282
15283 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15284 let mut current_line_len = line_prefix_len;
15285 for WordBreakToken {
15286 token,
15287 grapheme_len,
15288 is_whitespace,
15289 } in tokenizer
15290 {
15291 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15292 wrapped_text.push_str(current_line.trim_end());
15293 wrapped_text.push('\n');
15294 current_line.truncate(line_prefix.len());
15295 current_line_len = line_prefix_len;
15296 if !is_whitespace {
15297 current_line.push_str(token);
15298 current_line_len += grapheme_len;
15299 }
15300 } else if !is_whitespace {
15301 current_line.push_str(token);
15302 current_line_len += grapheme_len;
15303 } else if current_line_len != line_prefix_len {
15304 current_line.push(' ');
15305 current_line_len += 1;
15306 }
15307 }
15308
15309 if !current_line.is_empty() {
15310 wrapped_text.push_str(¤t_line);
15311 }
15312 wrapped_text
15313}
15314
15315#[test]
15316fn test_wrap_with_prefix() {
15317 assert_eq!(
15318 wrap_with_prefix(
15319 "# ".to_string(),
15320 "abcdefg".to_string(),
15321 4,
15322 NonZeroU32::new(4).unwrap()
15323 ),
15324 "# abcdefg"
15325 );
15326 assert_eq!(
15327 wrap_with_prefix(
15328 "".to_string(),
15329 "\thello world".to_string(),
15330 8,
15331 NonZeroU32::new(4).unwrap()
15332 ),
15333 "hello\nworld"
15334 );
15335 assert_eq!(
15336 wrap_with_prefix(
15337 "// ".to_string(),
15338 "xx \nyy zz aa bb cc".to_string(),
15339 12,
15340 NonZeroU32::new(4).unwrap()
15341 ),
15342 "// xx yy zz\n// aa bb cc"
15343 );
15344 assert_eq!(
15345 wrap_with_prefix(
15346 String::new(),
15347 "这是什么 \n 钢笔".to_string(),
15348 3,
15349 NonZeroU32::new(4).unwrap()
15350 ),
15351 "这是什\n么 钢\n笔"
15352 );
15353}
15354
15355pub trait CollaborationHub {
15356 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15357 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15358 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15359}
15360
15361impl CollaborationHub for Entity<Project> {
15362 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15363 self.read(cx).collaborators()
15364 }
15365
15366 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15367 self.read(cx).user_store().read(cx).participant_indices()
15368 }
15369
15370 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15371 let this = self.read(cx);
15372 let user_ids = this.collaborators().values().map(|c| c.user_id);
15373 this.user_store().read_with(cx, |user_store, cx| {
15374 user_store.participant_names(user_ids, cx)
15375 })
15376 }
15377}
15378
15379pub trait SemanticsProvider {
15380 fn hover(
15381 &self,
15382 buffer: &Entity<Buffer>,
15383 position: text::Anchor,
15384 cx: &mut App,
15385 ) -> Option<Task<Vec<project::Hover>>>;
15386
15387 fn inlay_hints(
15388 &self,
15389 buffer_handle: Entity<Buffer>,
15390 range: Range<text::Anchor>,
15391 cx: &mut App,
15392 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15393
15394 fn resolve_inlay_hint(
15395 &self,
15396 hint: InlayHint,
15397 buffer_handle: Entity<Buffer>,
15398 server_id: LanguageServerId,
15399 cx: &mut App,
15400 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15401
15402 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15403
15404 fn document_highlights(
15405 &self,
15406 buffer: &Entity<Buffer>,
15407 position: text::Anchor,
15408 cx: &mut App,
15409 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15410
15411 fn definitions(
15412 &self,
15413 buffer: &Entity<Buffer>,
15414 position: text::Anchor,
15415 kind: GotoDefinitionKind,
15416 cx: &mut App,
15417 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15418
15419 fn range_for_rename(
15420 &self,
15421 buffer: &Entity<Buffer>,
15422 position: text::Anchor,
15423 cx: &mut App,
15424 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15425
15426 fn perform_rename(
15427 &self,
15428 buffer: &Entity<Buffer>,
15429 position: text::Anchor,
15430 new_name: String,
15431 cx: &mut App,
15432 ) -> Option<Task<Result<ProjectTransaction>>>;
15433}
15434
15435pub trait CompletionProvider {
15436 fn completions(
15437 &self,
15438 buffer: &Entity<Buffer>,
15439 buffer_position: text::Anchor,
15440 trigger: CompletionContext,
15441 window: &mut Window,
15442 cx: &mut Context<Editor>,
15443 ) -> Task<Result<Vec<Completion>>>;
15444
15445 fn resolve_completions(
15446 &self,
15447 buffer: Entity<Buffer>,
15448 completion_indices: Vec<usize>,
15449 completions: Rc<RefCell<Box<[Completion]>>>,
15450 cx: &mut Context<Editor>,
15451 ) -> Task<Result<bool>>;
15452
15453 fn apply_additional_edits_for_completion(
15454 &self,
15455 _buffer: Entity<Buffer>,
15456 _completions: Rc<RefCell<Box<[Completion]>>>,
15457 _completion_index: usize,
15458 _push_to_history: bool,
15459 _cx: &mut Context<Editor>,
15460 ) -> Task<Result<Option<language::Transaction>>> {
15461 Task::ready(Ok(None))
15462 }
15463
15464 fn is_completion_trigger(
15465 &self,
15466 buffer: &Entity<Buffer>,
15467 position: language::Anchor,
15468 text: &str,
15469 trigger_in_words: bool,
15470 cx: &mut Context<Editor>,
15471 ) -> bool;
15472
15473 fn sort_completions(&self) -> bool {
15474 true
15475 }
15476}
15477
15478pub trait CodeActionProvider {
15479 fn id(&self) -> Arc<str>;
15480
15481 fn code_actions(
15482 &self,
15483 buffer: &Entity<Buffer>,
15484 range: Range<text::Anchor>,
15485 window: &mut Window,
15486 cx: &mut App,
15487 ) -> Task<Result<Vec<CodeAction>>>;
15488
15489 fn apply_code_action(
15490 &self,
15491 buffer_handle: Entity<Buffer>,
15492 action: CodeAction,
15493 excerpt_id: ExcerptId,
15494 push_to_history: bool,
15495 window: &mut Window,
15496 cx: &mut App,
15497 ) -> Task<Result<ProjectTransaction>>;
15498}
15499
15500impl CodeActionProvider for Entity<Project> {
15501 fn id(&self) -> Arc<str> {
15502 "project".into()
15503 }
15504
15505 fn code_actions(
15506 &self,
15507 buffer: &Entity<Buffer>,
15508 range: Range<text::Anchor>,
15509 _window: &mut Window,
15510 cx: &mut App,
15511 ) -> Task<Result<Vec<CodeAction>>> {
15512 self.update(cx, |project, cx| {
15513 project.code_actions(buffer, range, None, cx)
15514 })
15515 }
15516
15517 fn apply_code_action(
15518 &self,
15519 buffer_handle: Entity<Buffer>,
15520 action: CodeAction,
15521 _excerpt_id: ExcerptId,
15522 push_to_history: bool,
15523 _window: &mut Window,
15524 cx: &mut App,
15525 ) -> Task<Result<ProjectTransaction>> {
15526 self.update(cx, |project, cx| {
15527 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15528 })
15529 }
15530}
15531
15532fn snippet_completions(
15533 project: &Project,
15534 buffer: &Entity<Buffer>,
15535 buffer_position: text::Anchor,
15536 cx: &mut App,
15537) -> Task<Result<Vec<Completion>>> {
15538 let language = buffer.read(cx).language_at(buffer_position);
15539 let language_name = language.as_ref().map(|language| language.lsp_id());
15540 let snippet_store = project.snippets().read(cx);
15541 let snippets = snippet_store.snippets_for(language_name, cx);
15542
15543 if snippets.is_empty() {
15544 return Task::ready(Ok(vec![]));
15545 }
15546 let snapshot = buffer.read(cx).text_snapshot();
15547 let chars: String = snapshot
15548 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15549 .collect();
15550
15551 let scope = language.map(|language| language.default_scope());
15552 let executor = cx.background_executor().clone();
15553
15554 cx.background_executor().spawn(async move {
15555 let classifier = CharClassifier::new(scope).for_completion(true);
15556 let mut last_word = chars
15557 .chars()
15558 .take_while(|c| classifier.is_word(*c))
15559 .collect::<String>();
15560 last_word = last_word.chars().rev().collect();
15561
15562 if last_word.is_empty() {
15563 return Ok(vec![]);
15564 }
15565
15566 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15567 let to_lsp = |point: &text::Anchor| {
15568 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15569 point_to_lsp(end)
15570 };
15571 let lsp_end = to_lsp(&buffer_position);
15572
15573 let candidates = snippets
15574 .iter()
15575 .enumerate()
15576 .flat_map(|(ix, snippet)| {
15577 snippet
15578 .prefix
15579 .iter()
15580 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15581 })
15582 .collect::<Vec<StringMatchCandidate>>();
15583
15584 let mut matches = fuzzy::match_strings(
15585 &candidates,
15586 &last_word,
15587 last_word.chars().any(|c| c.is_uppercase()),
15588 100,
15589 &Default::default(),
15590 executor,
15591 )
15592 .await;
15593
15594 // Remove all candidates where the query's start does not match the start of any word in the candidate
15595 if let Some(query_start) = last_word.chars().next() {
15596 matches.retain(|string_match| {
15597 split_words(&string_match.string).any(|word| {
15598 // Check that the first codepoint of the word as lowercase matches the first
15599 // codepoint of the query as lowercase
15600 word.chars()
15601 .flat_map(|codepoint| codepoint.to_lowercase())
15602 .zip(query_start.to_lowercase())
15603 .all(|(word_cp, query_cp)| word_cp == query_cp)
15604 })
15605 });
15606 }
15607
15608 let matched_strings = matches
15609 .into_iter()
15610 .map(|m| m.string)
15611 .collect::<HashSet<_>>();
15612
15613 let result: Vec<Completion> = snippets
15614 .into_iter()
15615 .filter_map(|snippet| {
15616 let matching_prefix = snippet
15617 .prefix
15618 .iter()
15619 .find(|prefix| matched_strings.contains(*prefix))?;
15620 let start = as_offset - last_word.len();
15621 let start = snapshot.anchor_before(start);
15622 let range = start..buffer_position;
15623 let lsp_start = to_lsp(&start);
15624 let lsp_range = lsp::Range {
15625 start: lsp_start,
15626 end: lsp_end,
15627 };
15628 Some(Completion {
15629 old_range: range,
15630 new_text: snippet.body.clone(),
15631 resolved: false,
15632 label: CodeLabel {
15633 text: matching_prefix.clone(),
15634 runs: vec![],
15635 filter_range: 0..matching_prefix.len(),
15636 },
15637 server_id: LanguageServerId(usize::MAX),
15638 documentation: snippet
15639 .description
15640 .clone()
15641 .map(CompletionDocumentation::SingleLine),
15642 lsp_completion: lsp::CompletionItem {
15643 label: snippet.prefix.first().unwrap().clone(),
15644 kind: Some(CompletionItemKind::SNIPPET),
15645 label_details: snippet.description.as_ref().map(|description| {
15646 lsp::CompletionItemLabelDetails {
15647 detail: Some(description.clone()),
15648 description: None,
15649 }
15650 }),
15651 insert_text_format: Some(InsertTextFormat::SNIPPET),
15652 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15653 lsp::InsertReplaceEdit {
15654 new_text: snippet.body.clone(),
15655 insert: lsp_range,
15656 replace: lsp_range,
15657 },
15658 )),
15659 filter_text: Some(snippet.body.clone()),
15660 sort_text: Some(char::MAX.to_string()),
15661 ..Default::default()
15662 },
15663 confirm: None,
15664 })
15665 })
15666 .collect();
15667
15668 Ok(result)
15669 })
15670}
15671
15672impl CompletionProvider for Entity<Project> {
15673 fn completions(
15674 &self,
15675 buffer: &Entity<Buffer>,
15676 buffer_position: text::Anchor,
15677 options: CompletionContext,
15678 _window: &mut Window,
15679 cx: &mut Context<Editor>,
15680 ) -> Task<Result<Vec<Completion>>> {
15681 self.update(cx, |project, cx| {
15682 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15683 let project_completions = project.completions(buffer, buffer_position, options, cx);
15684 cx.background_executor().spawn(async move {
15685 let mut completions = project_completions.await?;
15686 let snippets_completions = snippets.await?;
15687 completions.extend(snippets_completions);
15688 Ok(completions)
15689 })
15690 })
15691 }
15692
15693 fn resolve_completions(
15694 &self,
15695 buffer: Entity<Buffer>,
15696 completion_indices: Vec<usize>,
15697 completions: Rc<RefCell<Box<[Completion]>>>,
15698 cx: &mut Context<Editor>,
15699 ) -> Task<Result<bool>> {
15700 self.update(cx, |project, cx| {
15701 project.lsp_store().update(cx, |lsp_store, cx| {
15702 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15703 })
15704 })
15705 }
15706
15707 fn apply_additional_edits_for_completion(
15708 &self,
15709 buffer: Entity<Buffer>,
15710 completions: Rc<RefCell<Box<[Completion]>>>,
15711 completion_index: usize,
15712 push_to_history: bool,
15713 cx: &mut Context<Editor>,
15714 ) -> Task<Result<Option<language::Transaction>>> {
15715 self.update(cx, |project, cx| {
15716 project.lsp_store().update(cx, |lsp_store, cx| {
15717 lsp_store.apply_additional_edits_for_completion(
15718 buffer,
15719 completions,
15720 completion_index,
15721 push_to_history,
15722 cx,
15723 )
15724 })
15725 })
15726 }
15727
15728 fn is_completion_trigger(
15729 &self,
15730 buffer: &Entity<Buffer>,
15731 position: language::Anchor,
15732 text: &str,
15733 trigger_in_words: bool,
15734 cx: &mut Context<Editor>,
15735 ) -> bool {
15736 let mut chars = text.chars();
15737 let char = if let Some(char) = chars.next() {
15738 char
15739 } else {
15740 return false;
15741 };
15742 if chars.next().is_some() {
15743 return false;
15744 }
15745
15746 let buffer = buffer.read(cx);
15747 let snapshot = buffer.snapshot();
15748 if !snapshot.settings_at(position, cx).show_completions_on_input {
15749 return false;
15750 }
15751 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15752 if trigger_in_words && classifier.is_word(char) {
15753 return true;
15754 }
15755
15756 buffer.completion_triggers().contains(text)
15757 }
15758}
15759
15760impl SemanticsProvider for Entity<Project> {
15761 fn hover(
15762 &self,
15763 buffer: &Entity<Buffer>,
15764 position: text::Anchor,
15765 cx: &mut App,
15766 ) -> Option<Task<Vec<project::Hover>>> {
15767 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15768 }
15769
15770 fn document_highlights(
15771 &self,
15772 buffer: &Entity<Buffer>,
15773 position: text::Anchor,
15774 cx: &mut App,
15775 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15776 Some(self.update(cx, |project, cx| {
15777 project.document_highlights(buffer, position, cx)
15778 }))
15779 }
15780
15781 fn definitions(
15782 &self,
15783 buffer: &Entity<Buffer>,
15784 position: text::Anchor,
15785 kind: GotoDefinitionKind,
15786 cx: &mut App,
15787 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15788 Some(self.update(cx, |project, cx| match kind {
15789 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15790 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15791 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15792 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15793 }))
15794 }
15795
15796 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15797 // TODO: make this work for remote projects
15798 self.update(cx, |this, cx| {
15799 buffer.update(cx, |buffer, cx| {
15800 this.any_language_server_supports_inlay_hints(buffer, cx)
15801 })
15802 })
15803 }
15804
15805 fn inlay_hints(
15806 &self,
15807 buffer_handle: Entity<Buffer>,
15808 range: Range<text::Anchor>,
15809 cx: &mut App,
15810 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15811 Some(self.update(cx, |project, cx| {
15812 project.inlay_hints(buffer_handle, range, cx)
15813 }))
15814 }
15815
15816 fn resolve_inlay_hint(
15817 &self,
15818 hint: InlayHint,
15819 buffer_handle: Entity<Buffer>,
15820 server_id: LanguageServerId,
15821 cx: &mut App,
15822 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15823 Some(self.update(cx, |project, cx| {
15824 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15825 }))
15826 }
15827
15828 fn range_for_rename(
15829 &self,
15830 buffer: &Entity<Buffer>,
15831 position: text::Anchor,
15832 cx: &mut App,
15833 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15834 Some(self.update(cx, |project, cx| {
15835 let buffer = buffer.clone();
15836 let task = project.prepare_rename(buffer.clone(), position, cx);
15837 cx.spawn(|_, mut cx| async move {
15838 Ok(match task.await? {
15839 PrepareRenameResponse::Success(range) => Some(range),
15840 PrepareRenameResponse::InvalidPosition => None,
15841 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15842 // Fallback on using TreeSitter info to determine identifier range
15843 buffer.update(&mut cx, |buffer, _| {
15844 let snapshot = buffer.snapshot();
15845 let (range, kind) = snapshot.surrounding_word(position);
15846 if kind != Some(CharKind::Word) {
15847 return None;
15848 }
15849 Some(
15850 snapshot.anchor_before(range.start)
15851 ..snapshot.anchor_after(range.end),
15852 )
15853 })?
15854 }
15855 })
15856 })
15857 }))
15858 }
15859
15860 fn perform_rename(
15861 &self,
15862 buffer: &Entity<Buffer>,
15863 position: text::Anchor,
15864 new_name: String,
15865 cx: &mut App,
15866 ) -> Option<Task<Result<ProjectTransaction>>> {
15867 Some(self.update(cx, |project, cx| {
15868 project.perform_rename(buffer.clone(), position, new_name, cx)
15869 }))
15870 }
15871}
15872
15873fn inlay_hint_settings(
15874 location: Anchor,
15875 snapshot: &MultiBufferSnapshot,
15876 cx: &mut Context<Editor>,
15877) -> InlayHintSettings {
15878 let file = snapshot.file_at(location);
15879 let language = snapshot.language_at(location).map(|l| l.name());
15880 language_settings(language, file, cx).inlay_hints
15881}
15882
15883fn consume_contiguous_rows(
15884 contiguous_row_selections: &mut Vec<Selection<Point>>,
15885 selection: &Selection<Point>,
15886 display_map: &DisplaySnapshot,
15887 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15888) -> (MultiBufferRow, MultiBufferRow) {
15889 contiguous_row_selections.push(selection.clone());
15890 let start_row = MultiBufferRow(selection.start.row);
15891 let mut end_row = ending_row(selection, display_map);
15892
15893 while let Some(next_selection) = selections.peek() {
15894 if next_selection.start.row <= end_row.0 {
15895 end_row = ending_row(next_selection, display_map);
15896 contiguous_row_selections.push(selections.next().unwrap().clone());
15897 } else {
15898 break;
15899 }
15900 }
15901 (start_row, end_row)
15902}
15903
15904fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15905 if next_selection.end.column > 0 || next_selection.is_empty() {
15906 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15907 } else {
15908 MultiBufferRow(next_selection.end.row)
15909 }
15910}
15911
15912impl EditorSnapshot {
15913 pub fn remote_selections_in_range<'a>(
15914 &'a self,
15915 range: &'a Range<Anchor>,
15916 collaboration_hub: &dyn CollaborationHub,
15917 cx: &'a App,
15918 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15919 let participant_names = collaboration_hub.user_names(cx);
15920 let participant_indices = collaboration_hub.user_participant_indices(cx);
15921 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15922 let collaborators_by_replica_id = collaborators_by_peer_id
15923 .iter()
15924 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15925 .collect::<HashMap<_, _>>();
15926 self.buffer_snapshot
15927 .selections_in_range(range, false)
15928 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15929 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15930 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15931 let user_name = participant_names.get(&collaborator.user_id).cloned();
15932 Some(RemoteSelection {
15933 replica_id,
15934 selection,
15935 cursor_shape,
15936 line_mode,
15937 participant_index,
15938 peer_id: collaborator.peer_id,
15939 user_name,
15940 })
15941 })
15942 }
15943
15944 pub fn hunks_for_ranges(
15945 &self,
15946 ranges: impl Iterator<Item = Range<Point>>,
15947 ) -> Vec<MultiBufferDiffHunk> {
15948 let mut hunks = Vec::new();
15949 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15950 HashMap::default();
15951 for query_range in ranges {
15952 let query_rows =
15953 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15954 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15955 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15956 ) {
15957 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15958 // when the caret is just above or just below the deleted hunk.
15959 let allow_adjacent = hunk.status().is_removed();
15960 let related_to_selection = if allow_adjacent {
15961 hunk.row_range.overlaps(&query_rows)
15962 || hunk.row_range.start == query_rows.end
15963 || hunk.row_range.end == query_rows.start
15964 } else {
15965 hunk.row_range.overlaps(&query_rows)
15966 };
15967 if related_to_selection {
15968 if !processed_buffer_rows
15969 .entry(hunk.buffer_id)
15970 .or_default()
15971 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15972 {
15973 continue;
15974 }
15975 hunks.push(hunk);
15976 }
15977 }
15978 }
15979
15980 hunks
15981 }
15982
15983 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15984 self.display_snapshot.buffer_snapshot.language_at(position)
15985 }
15986
15987 pub fn is_focused(&self) -> bool {
15988 self.is_focused
15989 }
15990
15991 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15992 self.placeholder_text.as_ref()
15993 }
15994
15995 pub fn scroll_position(&self) -> gpui::Point<f32> {
15996 self.scroll_anchor.scroll_position(&self.display_snapshot)
15997 }
15998
15999 fn gutter_dimensions(
16000 &self,
16001 font_id: FontId,
16002 font_size: Pixels,
16003 max_line_number_width: Pixels,
16004 cx: &App,
16005 ) -> Option<GutterDimensions> {
16006 if !self.show_gutter {
16007 return None;
16008 }
16009
16010 let descent = cx.text_system().descent(font_id, font_size);
16011 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16012 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16013
16014 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16015 matches!(
16016 ProjectSettings::get_global(cx).git.git_gutter,
16017 Some(GitGutterSetting::TrackedFiles)
16018 )
16019 });
16020 let gutter_settings = EditorSettings::get_global(cx).gutter;
16021 let show_line_numbers = self
16022 .show_line_numbers
16023 .unwrap_or(gutter_settings.line_numbers);
16024 let line_gutter_width = if show_line_numbers {
16025 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16026 let min_width_for_number_on_gutter = em_advance * 4.0;
16027 max_line_number_width.max(min_width_for_number_on_gutter)
16028 } else {
16029 0.0.into()
16030 };
16031
16032 let show_code_actions = self
16033 .show_code_actions
16034 .unwrap_or(gutter_settings.code_actions);
16035
16036 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16037
16038 let git_blame_entries_width =
16039 self.git_blame_gutter_max_author_length
16040 .map(|max_author_length| {
16041 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16042
16043 /// The number of characters to dedicate to gaps and margins.
16044 const SPACING_WIDTH: usize = 4;
16045
16046 let max_char_count = max_author_length
16047 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16048 + ::git::SHORT_SHA_LENGTH
16049 + MAX_RELATIVE_TIMESTAMP.len()
16050 + SPACING_WIDTH;
16051
16052 em_advance * max_char_count
16053 });
16054
16055 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16056 left_padding += if show_code_actions || show_runnables {
16057 em_width * 3.0
16058 } else if show_git_gutter && show_line_numbers {
16059 em_width * 2.0
16060 } else if show_git_gutter || show_line_numbers {
16061 em_width
16062 } else {
16063 px(0.)
16064 };
16065
16066 let right_padding = if gutter_settings.folds && show_line_numbers {
16067 em_width * 4.0
16068 } else if gutter_settings.folds {
16069 em_width * 3.0
16070 } else if show_line_numbers {
16071 em_width
16072 } else {
16073 px(0.)
16074 };
16075
16076 Some(GutterDimensions {
16077 left_padding,
16078 right_padding,
16079 width: line_gutter_width + left_padding + right_padding,
16080 margin: -descent,
16081 git_blame_entries_width,
16082 })
16083 }
16084
16085 pub fn render_crease_toggle(
16086 &self,
16087 buffer_row: MultiBufferRow,
16088 row_contains_cursor: bool,
16089 editor: Entity<Editor>,
16090 window: &mut Window,
16091 cx: &mut App,
16092 ) -> Option<AnyElement> {
16093 let folded = self.is_line_folded(buffer_row);
16094 let mut is_foldable = false;
16095
16096 if let Some(crease) = self
16097 .crease_snapshot
16098 .query_row(buffer_row, &self.buffer_snapshot)
16099 {
16100 is_foldable = true;
16101 match crease {
16102 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16103 if let Some(render_toggle) = render_toggle {
16104 let toggle_callback =
16105 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16106 if folded {
16107 editor.update(cx, |editor, cx| {
16108 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16109 });
16110 } else {
16111 editor.update(cx, |editor, cx| {
16112 editor.unfold_at(
16113 &crate::UnfoldAt { buffer_row },
16114 window,
16115 cx,
16116 )
16117 });
16118 }
16119 });
16120 return Some((render_toggle)(
16121 buffer_row,
16122 folded,
16123 toggle_callback,
16124 window,
16125 cx,
16126 ));
16127 }
16128 }
16129 }
16130 }
16131
16132 is_foldable |= self.starts_indent(buffer_row);
16133
16134 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16135 Some(
16136 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16137 .toggle_state(folded)
16138 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16139 if folded {
16140 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16141 } else {
16142 this.fold_at(&FoldAt { buffer_row }, window, cx);
16143 }
16144 }))
16145 .into_any_element(),
16146 )
16147 } else {
16148 None
16149 }
16150 }
16151
16152 pub fn render_crease_trailer(
16153 &self,
16154 buffer_row: MultiBufferRow,
16155 window: &mut Window,
16156 cx: &mut App,
16157 ) -> Option<AnyElement> {
16158 let folded = self.is_line_folded(buffer_row);
16159 if let Crease::Inline { render_trailer, .. } = self
16160 .crease_snapshot
16161 .query_row(buffer_row, &self.buffer_snapshot)?
16162 {
16163 let render_trailer = render_trailer.as_ref()?;
16164 Some(render_trailer(buffer_row, folded, window, cx))
16165 } else {
16166 None
16167 }
16168 }
16169}
16170
16171impl Deref for EditorSnapshot {
16172 type Target = DisplaySnapshot;
16173
16174 fn deref(&self) -> &Self::Target {
16175 &self.display_snapshot
16176 }
16177}
16178
16179#[derive(Clone, Debug, PartialEq, Eq)]
16180pub enum EditorEvent {
16181 InputIgnored {
16182 text: Arc<str>,
16183 },
16184 InputHandled {
16185 utf16_range_to_replace: Option<Range<isize>>,
16186 text: Arc<str>,
16187 },
16188 ExcerptsAdded {
16189 buffer: Entity<Buffer>,
16190 predecessor: ExcerptId,
16191 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16192 },
16193 ExcerptsRemoved {
16194 ids: Vec<ExcerptId>,
16195 },
16196 BufferFoldToggled {
16197 ids: Vec<ExcerptId>,
16198 folded: bool,
16199 },
16200 ExcerptsEdited {
16201 ids: Vec<ExcerptId>,
16202 },
16203 ExcerptsExpanded {
16204 ids: Vec<ExcerptId>,
16205 },
16206 BufferEdited,
16207 Edited {
16208 transaction_id: clock::Lamport,
16209 },
16210 Reparsed(BufferId),
16211 Focused,
16212 FocusedIn,
16213 Blurred,
16214 DirtyChanged,
16215 Saved,
16216 TitleChanged,
16217 DiffBaseChanged,
16218 SelectionsChanged {
16219 local: bool,
16220 },
16221 ScrollPositionChanged {
16222 local: bool,
16223 autoscroll: bool,
16224 },
16225 Closed,
16226 TransactionUndone {
16227 transaction_id: clock::Lamport,
16228 },
16229 TransactionBegun {
16230 transaction_id: clock::Lamport,
16231 },
16232 Reloaded,
16233 CursorShapeChanged,
16234}
16235
16236impl EventEmitter<EditorEvent> for Editor {}
16237
16238impl Focusable for Editor {
16239 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16240 self.focus_handle.clone()
16241 }
16242}
16243
16244impl Render for Editor {
16245 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16246 let settings = ThemeSettings::get_global(cx);
16247
16248 let mut text_style = match self.mode {
16249 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16250 color: cx.theme().colors().editor_foreground,
16251 font_family: settings.ui_font.family.clone(),
16252 font_features: settings.ui_font.features.clone(),
16253 font_fallbacks: settings.ui_font.fallbacks.clone(),
16254 font_size: rems(0.875).into(),
16255 font_weight: settings.ui_font.weight,
16256 line_height: relative(settings.buffer_line_height.value()),
16257 ..Default::default()
16258 },
16259 EditorMode::Full => TextStyle {
16260 color: cx.theme().colors().editor_foreground,
16261 font_family: settings.buffer_font.family.clone(),
16262 font_features: settings.buffer_font.features.clone(),
16263 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16264 font_size: settings.buffer_font_size(cx).into(),
16265 font_weight: settings.buffer_font.weight,
16266 line_height: relative(settings.buffer_line_height.value()),
16267 ..Default::default()
16268 },
16269 };
16270 if let Some(text_style_refinement) = &self.text_style_refinement {
16271 text_style.refine(text_style_refinement)
16272 }
16273
16274 let background = match self.mode {
16275 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16276 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16277 EditorMode::Full => cx.theme().colors().editor_background,
16278 };
16279
16280 EditorElement::new(
16281 &cx.entity(),
16282 EditorStyle {
16283 background,
16284 local_player: cx.theme().players().local(),
16285 text: text_style,
16286 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16287 syntax: cx.theme().syntax().clone(),
16288 status: cx.theme().status().clone(),
16289 inlay_hints_style: make_inlay_hints_style(cx),
16290 inline_completion_styles: make_suggestion_styles(cx),
16291 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16292 },
16293 )
16294 }
16295}
16296
16297impl EntityInputHandler for Editor {
16298 fn text_for_range(
16299 &mut self,
16300 range_utf16: Range<usize>,
16301 adjusted_range: &mut Option<Range<usize>>,
16302 _: &mut Window,
16303 cx: &mut Context<Self>,
16304 ) -> Option<String> {
16305 let snapshot = self.buffer.read(cx).read(cx);
16306 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16307 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16308 if (start.0..end.0) != range_utf16 {
16309 adjusted_range.replace(start.0..end.0);
16310 }
16311 Some(snapshot.text_for_range(start..end).collect())
16312 }
16313
16314 fn selected_text_range(
16315 &mut self,
16316 ignore_disabled_input: bool,
16317 _: &mut Window,
16318 cx: &mut Context<Self>,
16319 ) -> Option<UTF16Selection> {
16320 // Prevent the IME menu from appearing when holding down an alphabetic key
16321 // while input is disabled.
16322 if !ignore_disabled_input && !self.input_enabled {
16323 return None;
16324 }
16325
16326 let selection = self.selections.newest::<OffsetUtf16>(cx);
16327 let range = selection.range();
16328
16329 Some(UTF16Selection {
16330 range: range.start.0..range.end.0,
16331 reversed: selection.reversed,
16332 })
16333 }
16334
16335 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16336 let snapshot = self.buffer.read(cx).read(cx);
16337 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16338 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16339 }
16340
16341 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16342 self.clear_highlights::<InputComposition>(cx);
16343 self.ime_transaction.take();
16344 }
16345
16346 fn replace_text_in_range(
16347 &mut self,
16348 range_utf16: Option<Range<usize>>,
16349 text: &str,
16350 window: &mut Window,
16351 cx: &mut Context<Self>,
16352 ) {
16353 if !self.input_enabled {
16354 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16355 return;
16356 }
16357
16358 self.transact(window, cx, |this, window, cx| {
16359 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16360 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16361 Some(this.selection_replacement_ranges(range_utf16, cx))
16362 } else {
16363 this.marked_text_ranges(cx)
16364 };
16365
16366 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16367 let newest_selection_id = this.selections.newest_anchor().id;
16368 this.selections
16369 .all::<OffsetUtf16>(cx)
16370 .iter()
16371 .zip(ranges_to_replace.iter())
16372 .find_map(|(selection, range)| {
16373 if selection.id == newest_selection_id {
16374 Some(
16375 (range.start.0 as isize - selection.head().0 as isize)
16376 ..(range.end.0 as isize - selection.head().0 as isize),
16377 )
16378 } else {
16379 None
16380 }
16381 })
16382 });
16383
16384 cx.emit(EditorEvent::InputHandled {
16385 utf16_range_to_replace: range_to_replace,
16386 text: text.into(),
16387 });
16388
16389 if let Some(new_selected_ranges) = new_selected_ranges {
16390 this.change_selections(None, window, cx, |selections| {
16391 selections.select_ranges(new_selected_ranges)
16392 });
16393 this.backspace(&Default::default(), window, cx);
16394 }
16395
16396 this.handle_input(text, window, cx);
16397 });
16398
16399 if let Some(transaction) = self.ime_transaction {
16400 self.buffer.update(cx, |buffer, cx| {
16401 buffer.group_until_transaction(transaction, cx);
16402 });
16403 }
16404
16405 self.unmark_text(window, cx);
16406 }
16407
16408 fn replace_and_mark_text_in_range(
16409 &mut self,
16410 range_utf16: Option<Range<usize>>,
16411 text: &str,
16412 new_selected_range_utf16: Option<Range<usize>>,
16413 window: &mut Window,
16414 cx: &mut Context<Self>,
16415 ) {
16416 if !self.input_enabled {
16417 return;
16418 }
16419
16420 let transaction = self.transact(window, cx, |this, window, cx| {
16421 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16422 let snapshot = this.buffer.read(cx).read(cx);
16423 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16424 for marked_range in &mut marked_ranges {
16425 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16426 marked_range.start.0 += relative_range_utf16.start;
16427 marked_range.start =
16428 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16429 marked_range.end =
16430 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16431 }
16432 }
16433 Some(marked_ranges)
16434 } else if let Some(range_utf16) = range_utf16 {
16435 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16436 Some(this.selection_replacement_ranges(range_utf16, cx))
16437 } else {
16438 None
16439 };
16440
16441 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16442 let newest_selection_id = this.selections.newest_anchor().id;
16443 this.selections
16444 .all::<OffsetUtf16>(cx)
16445 .iter()
16446 .zip(ranges_to_replace.iter())
16447 .find_map(|(selection, range)| {
16448 if selection.id == newest_selection_id {
16449 Some(
16450 (range.start.0 as isize - selection.head().0 as isize)
16451 ..(range.end.0 as isize - selection.head().0 as isize),
16452 )
16453 } else {
16454 None
16455 }
16456 })
16457 });
16458
16459 cx.emit(EditorEvent::InputHandled {
16460 utf16_range_to_replace: range_to_replace,
16461 text: text.into(),
16462 });
16463
16464 if let Some(ranges) = ranges_to_replace {
16465 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16466 }
16467
16468 let marked_ranges = {
16469 let snapshot = this.buffer.read(cx).read(cx);
16470 this.selections
16471 .disjoint_anchors()
16472 .iter()
16473 .map(|selection| {
16474 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16475 })
16476 .collect::<Vec<_>>()
16477 };
16478
16479 if text.is_empty() {
16480 this.unmark_text(window, cx);
16481 } else {
16482 this.highlight_text::<InputComposition>(
16483 marked_ranges.clone(),
16484 HighlightStyle {
16485 underline: Some(UnderlineStyle {
16486 thickness: px(1.),
16487 color: None,
16488 wavy: false,
16489 }),
16490 ..Default::default()
16491 },
16492 cx,
16493 );
16494 }
16495
16496 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16497 let use_autoclose = this.use_autoclose;
16498 let use_auto_surround = this.use_auto_surround;
16499 this.set_use_autoclose(false);
16500 this.set_use_auto_surround(false);
16501 this.handle_input(text, window, cx);
16502 this.set_use_autoclose(use_autoclose);
16503 this.set_use_auto_surround(use_auto_surround);
16504
16505 if let Some(new_selected_range) = new_selected_range_utf16 {
16506 let snapshot = this.buffer.read(cx).read(cx);
16507 let new_selected_ranges = marked_ranges
16508 .into_iter()
16509 .map(|marked_range| {
16510 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16511 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16512 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16513 snapshot.clip_offset_utf16(new_start, Bias::Left)
16514 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16515 })
16516 .collect::<Vec<_>>();
16517
16518 drop(snapshot);
16519 this.change_selections(None, window, cx, |selections| {
16520 selections.select_ranges(new_selected_ranges)
16521 });
16522 }
16523 });
16524
16525 self.ime_transaction = self.ime_transaction.or(transaction);
16526 if let Some(transaction) = self.ime_transaction {
16527 self.buffer.update(cx, |buffer, cx| {
16528 buffer.group_until_transaction(transaction, cx);
16529 });
16530 }
16531
16532 if self.text_highlights::<InputComposition>(cx).is_none() {
16533 self.ime_transaction.take();
16534 }
16535 }
16536
16537 fn bounds_for_range(
16538 &mut self,
16539 range_utf16: Range<usize>,
16540 element_bounds: gpui::Bounds<Pixels>,
16541 window: &mut Window,
16542 cx: &mut Context<Self>,
16543 ) -> Option<gpui::Bounds<Pixels>> {
16544 let text_layout_details = self.text_layout_details(window);
16545 let gpui::Size {
16546 width: em_width,
16547 height: line_height,
16548 } = self.character_size(window);
16549
16550 let snapshot = self.snapshot(window, cx);
16551 let scroll_position = snapshot.scroll_position();
16552 let scroll_left = scroll_position.x * em_width;
16553
16554 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16555 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16556 + self.gutter_dimensions.width
16557 + self.gutter_dimensions.margin;
16558 let y = line_height * (start.row().as_f32() - scroll_position.y);
16559
16560 Some(Bounds {
16561 origin: element_bounds.origin + point(x, y),
16562 size: size(em_width, line_height),
16563 })
16564 }
16565
16566 fn character_index_for_point(
16567 &mut self,
16568 point: gpui::Point<Pixels>,
16569 _window: &mut Window,
16570 _cx: &mut Context<Self>,
16571 ) -> Option<usize> {
16572 let position_map = self.last_position_map.as_ref()?;
16573 if !position_map.text_hitbox.contains(&point) {
16574 return None;
16575 }
16576 let display_point = position_map.point_for_position(point).previous_valid;
16577 let anchor = position_map
16578 .snapshot
16579 .display_point_to_anchor(display_point, Bias::Left);
16580 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16581 Some(utf16_offset.0)
16582 }
16583}
16584
16585trait SelectionExt {
16586 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16587 fn spanned_rows(
16588 &self,
16589 include_end_if_at_line_start: bool,
16590 map: &DisplaySnapshot,
16591 ) -> Range<MultiBufferRow>;
16592}
16593
16594impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16595 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16596 let start = self
16597 .start
16598 .to_point(&map.buffer_snapshot)
16599 .to_display_point(map);
16600 let end = self
16601 .end
16602 .to_point(&map.buffer_snapshot)
16603 .to_display_point(map);
16604 if self.reversed {
16605 end..start
16606 } else {
16607 start..end
16608 }
16609 }
16610
16611 fn spanned_rows(
16612 &self,
16613 include_end_if_at_line_start: bool,
16614 map: &DisplaySnapshot,
16615 ) -> Range<MultiBufferRow> {
16616 let start = self.start.to_point(&map.buffer_snapshot);
16617 let mut end = self.end.to_point(&map.buffer_snapshot);
16618 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16619 end.row -= 1;
16620 }
16621
16622 let buffer_start = map.prev_line_boundary(start).0;
16623 let buffer_end = map.next_line_boundary(end).0;
16624 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16625 }
16626}
16627
16628impl<T: InvalidationRegion> InvalidationStack<T> {
16629 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16630 where
16631 S: Clone + ToOffset,
16632 {
16633 while let Some(region) = self.last() {
16634 let all_selections_inside_invalidation_ranges =
16635 if selections.len() == region.ranges().len() {
16636 selections
16637 .iter()
16638 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16639 .all(|(selection, invalidation_range)| {
16640 let head = selection.head().to_offset(buffer);
16641 invalidation_range.start <= head && invalidation_range.end >= head
16642 })
16643 } else {
16644 false
16645 };
16646
16647 if all_selections_inside_invalidation_ranges {
16648 break;
16649 } else {
16650 self.pop();
16651 }
16652 }
16653 }
16654}
16655
16656impl<T> Default for InvalidationStack<T> {
16657 fn default() -> Self {
16658 Self(Default::default())
16659 }
16660}
16661
16662impl<T> Deref for InvalidationStack<T> {
16663 type Target = Vec<T>;
16664
16665 fn deref(&self) -> &Self::Target {
16666 &self.0
16667 }
16668}
16669
16670impl<T> DerefMut for InvalidationStack<T> {
16671 fn deref_mut(&mut self) -> &mut Self::Target {
16672 &mut self.0
16673 }
16674}
16675
16676impl InvalidationRegion for SnippetState {
16677 fn ranges(&self) -> &[Range<Anchor>] {
16678 &self.ranges[self.active_index]
16679 }
16680}
16681
16682pub fn diagnostic_block_renderer(
16683 diagnostic: Diagnostic,
16684 max_message_rows: Option<u8>,
16685 allow_closing: bool,
16686 _is_valid: bool,
16687) -> RenderBlock {
16688 let (text_without_backticks, code_ranges) =
16689 highlight_diagnostic_message(&diagnostic, max_message_rows);
16690
16691 Arc::new(move |cx: &mut BlockContext| {
16692 let group_id: SharedString = cx.block_id.to_string().into();
16693
16694 let mut text_style = cx.window.text_style().clone();
16695 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16696 let theme_settings = ThemeSettings::get_global(cx);
16697 text_style.font_family = theme_settings.buffer_font.family.clone();
16698 text_style.font_style = theme_settings.buffer_font.style;
16699 text_style.font_features = theme_settings.buffer_font.features.clone();
16700 text_style.font_weight = theme_settings.buffer_font.weight;
16701
16702 let multi_line_diagnostic = diagnostic.message.contains('\n');
16703
16704 let buttons = |diagnostic: &Diagnostic| {
16705 if multi_line_diagnostic {
16706 v_flex()
16707 } else {
16708 h_flex()
16709 }
16710 .when(allow_closing, |div| {
16711 div.children(diagnostic.is_primary.then(|| {
16712 IconButton::new("close-block", IconName::XCircle)
16713 .icon_color(Color::Muted)
16714 .size(ButtonSize::Compact)
16715 .style(ButtonStyle::Transparent)
16716 .visible_on_hover(group_id.clone())
16717 .on_click(move |_click, window, cx| {
16718 window.dispatch_action(Box::new(Cancel), cx)
16719 })
16720 .tooltip(|window, cx| {
16721 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16722 })
16723 }))
16724 })
16725 .child(
16726 IconButton::new("copy-block", IconName::Copy)
16727 .icon_color(Color::Muted)
16728 .size(ButtonSize::Compact)
16729 .style(ButtonStyle::Transparent)
16730 .visible_on_hover(group_id.clone())
16731 .on_click({
16732 let message = diagnostic.message.clone();
16733 move |_click, _, cx| {
16734 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16735 }
16736 })
16737 .tooltip(Tooltip::text("Copy diagnostic message")),
16738 )
16739 };
16740
16741 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16742 AvailableSpace::min_size(),
16743 cx.window,
16744 cx.app,
16745 );
16746
16747 h_flex()
16748 .id(cx.block_id)
16749 .group(group_id.clone())
16750 .relative()
16751 .size_full()
16752 .block_mouse_down()
16753 .pl(cx.gutter_dimensions.width)
16754 .w(cx.max_width - cx.gutter_dimensions.full_width())
16755 .child(
16756 div()
16757 .flex()
16758 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16759 .flex_shrink(),
16760 )
16761 .child(buttons(&diagnostic))
16762 .child(div().flex().flex_shrink_0().child(
16763 StyledText::new(text_without_backticks.clone()).with_highlights(
16764 &text_style,
16765 code_ranges.iter().map(|range| {
16766 (
16767 range.clone(),
16768 HighlightStyle {
16769 font_weight: Some(FontWeight::BOLD),
16770 ..Default::default()
16771 },
16772 )
16773 }),
16774 ),
16775 ))
16776 .into_any_element()
16777 })
16778}
16779
16780fn inline_completion_edit_text(
16781 current_snapshot: &BufferSnapshot,
16782 edits: &[(Range<Anchor>, String)],
16783 edit_preview: &EditPreview,
16784 include_deletions: bool,
16785 cx: &App,
16786) -> HighlightedText {
16787 let edits = edits
16788 .iter()
16789 .map(|(anchor, text)| {
16790 (
16791 anchor.start.text_anchor..anchor.end.text_anchor,
16792 text.clone(),
16793 )
16794 })
16795 .collect::<Vec<_>>();
16796
16797 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16798}
16799
16800pub fn highlight_diagnostic_message(
16801 diagnostic: &Diagnostic,
16802 mut max_message_rows: Option<u8>,
16803) -> (SharedString, Vec<Range<usize>>) {
16804 let mut text_without_backticks = String::new();
16805 let mut code_ranges = Vec::new();
16806
16807 if let Some(source) = &diagnostic.source {
16808 text_without_backticks.push_str(source);
16809 code_ranges.push(0..source.len());
16810 text_without_backticks.push_str(": ");
16811 }
16812
16813 let mut prev_offset = 0;
16814 let mut in_code_block = false;
16815 let has_row_limit = max_message_rows.is_some();
16816 let mut newline_indices = diagnostic
16817 .message
16818 .match_indices('\n')
16819 .filter(|_| has_row_limit)
16820 .map(|(ix, _)| ix)
16821 .fuse()
16822 .peekable();
16823
16824 for (quote_ix, _) in diagnostic
16825 .message
16826 .match_indices('`')
16827 .chain([(diagnostic.message.len(), "")])
16828 {
16829 let mut first_newline_ix = None;
16830 let mut last_newline_ix = None;
16831 while let Some(newline_ix) = newline_indices.peek() {
16832 if *newline_ix < quote_ix {
16833 if first_newline_ix.is_none() {
16834 first_newline_ix = Some(*newline_ix);
16835 }
16836 last_newline_ix = Some(*newline_ix);
16837
16838 if let Some(rows_left) = &mut max_message_rows {
16839 if *rows_left == 0 {
16840 break;
16841 } else {
16842 *rows_left -= 1;
16843 }
16844 }
16845 let _ = newline_indices.next();
16846 } else {
16847 break;
16848 }
16849 }
16850 let prev_len = text_without_backticks.len();
16851 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16852 text_without_backticks.push_str(new_text);
16853 if in_code_block {
16854 code_ranges.push(prev_len..text_without_backticks.len());
16855 }
16856 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16857 in_code_block = !in_code_block;
16858 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16859 text_without_backticks.push_str("...");
16860 break;
16861 }
16862 }
16863
16864 (text_without_backticks.into(), code_ranges)
16865}
16866
16867fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16868 match severity {
16869 DiagnosticSeverity::ERROR => colors.error,
16870 DiagnosticSeverity::WARNING => colors.warning,
16871 DiagnosticSeverity::INFORMATION => colors.info,
16872 DiagnosticSeverity::HINT => colors.info,
16873 _ => colors.ignored,
16874 }
16875}
16876
16877pub fn styled_runs_for_code_label<'a>(
16878 label: &'a CodeLabel,
16879 syntax_theme: &'a theme::SyntaxTheme,
16880) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16881 let fade_out = HighlightStyle {
16882 fade_out: Some(0.35),
16883 ..Default::default()
16884 };
16885
16886 let mut prev_end = label.filter_range.end;
16887 label
16888 .runs
16889 .iter()
16890 .enumerate()
16891 .flat_map(move |(ix, (range, highlight_id))| {
16892 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16893 style
16894 } else {
16895 return Default::default();
16896 };
16897 let mut muted_style = style;
16898 muted_style.highlight(fade_out);
16899
16900 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16901 if range.start >= label.filter_range.end {
16902 if range.start > prev_end {
16903 runs.push((prev_end..range.start, fade_out));
16904 }
16905 runs.push((range.clone(), muted_style));
16906 } else if range.end <= label.filter_range.end {
16907 runs.push((range.clone(), style));
16908 } else {
16909 runs.push((range.start..label.filter_range.end, style));
16910 runs.push((label.filter_range.end..range.end, muted_style));
16911 }
16912 prev_end = cmp::max(prev_end, range.end);
16913
16914 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16915 runs.push((prev_end..label.text.len(), fade_out));
16916 }
16917
16918 runs
16919 })
16920}
16921
16922pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16923 let mut prev_index = 0;
16924 let mut prev_codepoint: Option<char> = None;
16925 text.char_indices()
16926 .chain([(text.len(), '\0')])
16927 .filter_map(move |(index, codepoint)| {
16928 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16929 let is_boundary = index == text.len()
16930 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16931 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16932 if is_boundary {
16933 let chunk = &text[prev_index..index];
16934 prev_index = index;
16935 Some(chunk)
16936 } else {
16937 None
16938 }
16939 })
16940}
16941
16942pub trait RangeToAnchorExt: Sized {
16943 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16944
16945 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16946 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16947 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16948 }
16949}
16950
16951impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16952 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16953 let start_offset = self.start.to_offset(snapshot);
16954 let end_offset = self.end.to_offset(snapshot);
16955 if start_offset == end_offset {
16956 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16957 } else {
16958 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16959 }
16960 }
16961}
16962
16963pub trait RowExt {
16964 fn as_f32(&self) -> f32;
16965
16966 fn next_row(&self) -> Self;
16967
16968 fn previous_row(&self) -> Self;
16969
16970 fn minus(&self, other: Self) -> u32;
16971}
16972
16973impl RowExt for DisplayRow {
16974 fn as_f32(&self) -> f32 {
16975 self.0 as f32
16976 }
16977
16978 fn next_row(&self) -> Self {
16979 Self(self.0 + 1)
16980 }
16981
16982 fn previous_row(&self) -> Self {
16983 Self(self.0.saturating_sub(1))
16984 }
16985
16986 fn minus(&self, other: Self) -> u32 {
16987 self.0 - other.0
16988 }
16989}
16990
16991impl RowExt for MultiBufferRow {
16992 fn as_f32(&self) -> f32 {
16993 self.0 as f32
16994 }
16995
16996 fn next_row(&self) -> Self {
16997 Self(self.0 + 1)
16998 }
16999
17000 fn previous_row(&self) -> Self {
17001 Self(self.0.saturating_sub(1))
17002 }
17003
17004 fn minus(&self, other: Self) -> u32 {
17005 self.0 - other.0
17006 }
17007}
17008
17009trait RowRangeExt {
17010 type Row;
17011
17012 fn len(&self) -> usize;
17013
17014 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17015}
17016
17017impl RowRangeExt for Range<MultiBufferRow> {
17018 type Row = MultiBufferRow;
17019
17020 fn len(&self) -> usize {
17021 (self.end.0 - self.start.0) as usize
17022 }
17023
17024 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17025 (self.start.0..self.end.0).map(MultiBufferRow)
17026 }
17027}
17028
17029impl RowRangeExt for Range<DisplayRow> {
17030 type Row = DisplayRow;
17031
17032 fn len(&self) -> usize {
17033 (self.end.0 - self.start.0) as usize
17034 }
17035
17036 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17037 (self.start.0..self.end.0).map(DisplayRow)
17038 }
17039}
17040
17041/// If select range has more than one line, we
17042/// just point the cursor to range.start.
17043fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17044 if range.start.row == range.end.row {
17045 range
17046 } else {
17047 range.start..range.start
17048 }
17049}
17050pub struct KillRing(ClipboardItem);
17051impl Global for KillRing {}
17052
17053const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17054
17055fn all_edits_insertions_or_deletions(
17056 edits: &Vec<(Range<Anchor>, String)>,
17057 snapshot: &MultiBufferSnapshot,
17058) -> bool {
17059 let mut all_insertions = true;
17060 let mut all_deletions = true;
17061
17062 for (range, new_text) in edits.iter() {
17063 let range_is_empty = range.to_offset(&snapshot).is_empty();
17064 let text_is_empty = new_text.is_empty();
17065
17066 if range_is_empty != text_is_empty {
17067 if range_is_empty {
17068 all_deletions = false;
17069 } else {
17070 all_insertions = false;
17071 }
17072 } else {
17073 return false;
17074 }
17075
17076 if !all_insertions && !all_deletions {
17077 return false;
17078 }
17079 }
17080 all_insertions || all_deletions
17081}