1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use code_context_menus::{
77 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
78 CompletionsMenu, ContextMenuOrigin,
79};
80use git::blame::GitBlame;
81use gpui::{
82 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
83 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
84 ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
85 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
86 HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
87 PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
88 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
89 WeakEntity, WeakFocusHandle, Window,
90};
91use highlight_matching_bracket::refresh_matching_bracket_highlights;
92use hover_popover::{hide_hover, HoverState};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 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;
109pub use proposed_changes_editor::{
110 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
111};
112use similar::{ChangeTag, TextDiff};
113use std::iter::Peekable;
114use task::{ResolvedTask, TaskTemplate, TaskVariables};
115
116use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
117pub use lsp::CompletionContext;
118use lsp::{
119 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
120 LanguageServerId, LanguageServerName,
121};
122
123use language::BufferSnapshot;
124use movement::TextLayoutDetails;
125pub use multi_buffer::{
126 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
127 ToOffset, ToPoint,
128};
129use multi_buffer::{
130 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
131 ToOffsetUtf16,
132};
133use project::{
134 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
135 project_settings::{GitGutterSetting, ProjectSettings},
136 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
137 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
138};
139use rand::prelude::*;
140use rpc::{proto::*, ErrorExt};
141use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
142use selections_collection::{
143 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
144};
145use serde::{Deserialize, Serialize};
146use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
147use smallvec::SmallVec;
148use snippet::Snippet;
149use std::{
150 any::TypeId,
151 borrow::Cow,
152 cell::RefCell,
153 cmp::{self, Ordering, Reverse},
154 mem,
155 num::NonZeroU32,
156 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
157 path::{Path, PathBuf},
158 rc::Rc,
159 sync::Arc,
160 time::{Duration, Instant},
161};
162pub use sum_tree::Bias;
163use sum_tree::TreeMap;
164use text::{BufferId, OffsetUtf16, Rope};
165use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
166use ui::{
167 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
168 Tooltip,
169};
170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
171use workspace::item::{ItemHandle, PreviewTabsSettings};
172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
173use workspace::{
174 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
175};
176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
177
178use crate::hover_links::{find_url, find_url_from_range};
179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
180
181pub const FILE_HEADER_HEIGHT: u32 = 2;
182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
186const MAX_LINE_LEN: usize = 1024;
187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
190#[doc(hidden)]
191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
192
193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
195
196pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
197pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
198
199pub fn render_parsed_markdown(
200 element_id: impl Into<ElementId>,
201 parsed: &language::ParsedMarkdown,
202 editor_style: &EditorStyle,
203 workspace: Option<WeakEntity<Workspace>>,
204 cx: &mut App,
205) -> InteractiveText {
206 let code_span_background_color = cx
207 .theme()
208 .colors()
209 .editor_document_highlight_read_background;
210
211 let highlights = gpui::combine_highlights(
212 parsed.highlights.iter().filter_map(|(range, highlight)| {
213 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
214 Some((range.clone(), highlight))
215 }),
216 parsed
217 .regions
218 .iter()
219 .zip(&parsed.region_ranges)
220 .filter_map(|(region, range)| {
221 if region.code {
222 Some((
223 range.clone(),
224 HighlightStyle {
225 background_color: Some(code_span_background_color),
226 ..Default::default()
227 },
228 ))
229 } else {
230 None
231 }
232 }),
233 );
234
235 let mut links = Vec::new();
236 let mut link_ranges = Vec::new();
237 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
238 if let Some(link) = region.link.clone() {
239 links.push(link);
240 link_ranges.push(range.clone());
241 }
242 }
243
244 InteractiveText::new(
245 element_id,
246 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
247 )
248 .on_click(
249 link_ranges,
250 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
251 markdown::Link::Web { url } => cx.open_url(url),
252 markdown::Link::Path { path } => {
253 if let Some(workspace) = &workspace {
254 _ = workspace.update(cx, |workspace, cx| {
255 workspace
256 .open_abs_path(path.clone(), false, window, cx)
257 .detach();
258 });
259 }
260 }
261 },
262 )
263}
264
265#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
266pub enum InlayId {
267 InlineCompletion(usize),
268 Hint(usize),
269}
270
271impl InlayId {
272 fn id(&self) -> usize {
273 match self {
274 Self::InlineCompletion(id) => *id,
275 Self::Hint(id) => *id,
276 }
277 }
278}
279
280enum DocumentHighlightRead {}
281enum DocumentHighlightWrite {}
282enum InputComposition {}
283
284#[derive(Debug, Copy, Clone, PartialEq, Eq)]
285pub enum Navigated {
286 Yes,
287 No,
288}
289
290impl Navigated {
291 pub fn from_bool(yes: bool) -> Navigated {
292 if yes {
293 Navigated::Yes
294 } else {
295 Navigated::No
296 }
297 }
298}
299
300pub fn init_settings(cx: &mut App) {
301 EditorSettings::register(cx);
302}
303
304pub fn init(cx: &mut App) {
305 init_settings(cx);
306
307 workspace::register_project_item::<Editor>(cx);
308 workspace::FollowableViewRegistry::register::<Editor>(cx);
309 workspace::register_serializable_item::<Editor>(cx);
310
311 cx.observe_new(
312 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
313 workspace.register_action(Editor::new_file);
314 workspace.register_action(Editor::new_file_vertical);
315 workspace.register_action(Editor::new_file_horizontal);
316 workspace.register_action(Editor::cancel_language_server_work);
317 },
318 )
319 .detach();
320
321 cx.on_action(move |_: &workspace::NewFile, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(
325 Default::default(),
326 app_state,
327 cx,
328 |workspace, window, cx| {
329 Editor::new_file(workspace, &Default::default(), window, cx)
330 },
331 )
332 .detach();
333 }
334 });
335 cx.on_action(move |_: &workspace::NewWindow, cx| {
336 let app_state = workspace::AppState::global(cx);
337 if let Some(app_state) = app_state.upgrade() {
338 workspace::open_new(
339 Default::default(),
340 app_state,
341 cx,
342 |workspace, window, cx| {
343 cx.activate(true);
344 Editor::new_file(workspace, &Default::default(), window, cx)
345 },
346 )
347 .detach();
348 }
349 });
350}
351
352pub struct SearchWithinRange;
353
354trait InvalidationRegion {
355 fn ranges(&self) -> &[Range<Anchor>];
356}
357
358#[derive(Clone, Debug, PartialEq)]
359pub enum SelectPhase {
360 Begin {
361 position: DisplayPoint,
362 add: bool,
363 click_count: usize,
364 },
365 BeginColumnar {
366 position: DisplayPoint,
367 reset: bool,
368 goal_column: u32,
369 },
370 Extend {
371 position: DisplayPoint,
372 click_count: usize,
373 },
374 Update {
375 position: DisplayPoint,
376 goal_column: u32,
377 scroll_delta: gpui::Point<f32>,
378 },
379 End,
380}
381
382#[derive(Clone, Debug)]
383pub enum SelectMode {
384 Character,
385 Word(Range<Anchor>),
386 Line(Range<Anchor>),
387 All,
388}
389
390#[derive(Copy, Clone, PartialEq, Eq, Debug)]
391pub enum EditorMode {
392 SingleLine { auto_width: bool },
393 AutoHeight { max_lines: usize },
394 Full,
395}
396
397#[derive(Copy, Clone, Debug)]
398pub enum SoftWrap {
399 /// Prefer not to wrap at all.
400 ///
401 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
402 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
403 GitDiff,
404 /// Prefer a single line generally, unless an overly long line is encountered.
405 None,
406 /// Soft wrap lines that exceed the editor width.
407 EditorWidth,
408 /// Soft wrap lines at the preferred line length.
409 Column(u32),
410 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
411 Bounded(u32),
412}
413
414#[derive(Clone)]
415pub struct EditorStyle {
416 pub background: Hsla,
417 pub local_player: PlayerColor,
418 pub text: TextStyle,
419 pub scrollbar_width: Pixels,
420 pub syntax: Arc<SyntaxTheme>,
421 pub status: StatusColors,
422 pub inlay_hints_style: HighlightStyle,
423 pub inline_completion_styles: InlineCompletionStyles,
424 pub unnecessary_code_fade: f32,
425}
426
427impl Default for EditorStyle {
428 fn default() -> Self {
429 Self {
430 background: Hsla::default(),
431 local_player: PlayerColor::default(),
432 text: TextStyle::default(),
433 scrollbar_width: Pixels::default(),
434 syntax: Default::default(),
435 // HACK: Status colors don't have a real default.
436 // We should look into removing the status colors from the editor
437 // style and retrieve them directly from the theme.
438 status: StatusColors::dark(),
439 inlay_hints_style: HighlightStyle::default(),
440 inline_completion_styles: InlineCompletionStyles {
441 insertion: HighlightStyle::default(),
442 whitespace: HighlightStyle::default(),
443 },
444 unnecessary_code_fade: Default::default(),
445 }
446 }
447}
448
449pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
450 let show_background = language_settings::language_settings(None, None, cx)
451 .inlay_hints
452 .show_background;
453
454 HighlightStyle {
455 color: Some(cx.theme().status().hint),
456 background_color: show_background.then(|| cx.theme().status().hint_background),
457 ..HighlightStyle::default()
458 }
459}
460
461pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
462 InlineCompletionStyles {
463 insertion: HighlightStyle {
464 color: Some(cx.theme().status().predictive),
465 ..HighlightStyle::default()
466 },
467 whitespace: HighlightStyle {
468 background_color: Some(cx.theme().status().created_background),
469 ..HighlightStyle::default()
470 },
471 }
472}
473
474type CompletionId = usize;
475
476pub(crate) enum EditDisplayMode {
477 TabAccept,
478 DiffPopover,
479 Inline,
480}
481
482enum InlineCompletion {
483 Edit {
484 edits: Vec<(Range<Anchor>, String)>,
485 edit_preview: Option<EditPreview>,
486 display_mode: EditDisplayMode,
487 snapshot: BufferSnapshot,
488 },
489 Move {
490 target: Anchor,
491 snapshot: BufferSnapshot,
492 },
493}
494
495struct InlineCompletionState {
496 inlay_ids: Vec<InlayId>,
497 completion: InlineCompletion,
498 completion_id: Option<SharedString>,
499 invalidation_range: Range<Anchor>,
500}
501
502enum EditPredictionSettings {
503 Disabled,
504 Enabled {
505 show_in_menu: bool,
506 preview_requires_modifier: bool,
507 },
508}
509
510impl EditPredictionSettings {
511 pub fn is_enabled(&self) -> bool {
512 match self {
513 EditPredictionSettings::Disabled => false,
514 EditPredictionSettings::Enabled { .. } => true,
515 }
516 }
517}
518
519enum InlineCompletionHighlight {}
520
521pub enum MenuInlineCompletionsPolicy {
522 Never,
523 ByProvider,
524}
525
526pub enum EditPredictionPreview {
527 /// Modifier is not pressed
528 Inactive,
529 /// Modifier pressed
530 Active {
531 previous_scroll_position: Option<ScrollAnchor>,
532 },
533}
534
535#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
536struct EditorActionId(usize);
537
538impl EditorActionId {
539 pub fn post_inc(&mut self) -> Self {
540 let answer = self.0;
541
542 *self = Self(answer + 1);
543
544 Self(answer)
545 }
546}
547
548// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
549// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
550
551type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
552type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
553
554#[derive(Default)]
555struct ScrollbarMarkerState {
556 scrollbar_size: Size<Pixels>,
557 dirty: bool,
558 markers: Arc<[PaintQuad]>,
559 pending_refresh: Option<Task<Result<()>>>,
560}
561
562impl ScrollbarMarkerState {
563 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
564 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
565 }
566}
567
568#[derive(Clone, Debug)]
569struct RunnableTasks {
570 templates: Vec<(TaskSourceKind, TaskTemplate)>,
571 offset: MultiBufferOffset,
572 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
573 column: u32,
574 // Values of all named captures, including those starting with '_'
575 extra_variables: HashMap<String, String>,
576 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
577 context_range: Range<BufferOffset>,
578}
579
580impl RunnableTasks {
581 fn resolve<'a>(
582 &'a self,
583 cx: &'a task::TaskContext,
584 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
585 self.templates.iter().filter_map(|(kind, template)| {
586 template
587 .resolve_task(&kind.to_id_base(), cx)
588 .map(|task| (kind.clone(), task))
589 })
590 }
591}
592
593#[derive(Clone)]
594struct ResolvedTasks {
595 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
596 position: Anchor,
597}
598#[derive(Copy, Clone, Debug)]
599struct MultiBufferOffset(usize);
600#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
601struct BufferOffset(usize);
602
603// Addons allow storing per-editor state in other crates (e.g. Vim)
604pub trait Addon: 'static {
605 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
606
607 fn render_buffer_header_controls(
608 &self,
609 _: &ExcerptInfo,
610 _: &Window,
611 _: &App,
612 ) -> Option<AnyElement> {
613 None
614 }
615
616 fn to_any(&self) -> &dyn std::any::Any;
617}
618
619#[derive(Debug, Copy, Clone, PartialEq, Eq)]
620pub enum IsVimMode {
621 Yes,
622 No,
623}
624
625/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
626///
627/// See the [module level documentation](self) for more information.
628pub struct Editor {
629 focus_handle: FocusHandle,
630 last_focused_descendant: Option<WeakFocusHandle>,
631 /// The text buffer being edited
632 buffer: Entity<MultiBuffer>,
633 /// Map of how text in the buffer should be displayed.
634 /// Handles soft wraps, folds, fake inlay text insertions, etc.
635 pub display_map: Entity<DisplayMap>,
636 pub selections: SelectionsCollection,
637 pub scroll_manager: ScrollManager,
638 /// When inline assist editors are linked, they all render cursors because
639 /// typing enters text into each of them, even the ones that aren't focused.
640 pub(crate) show_cursor_when_unfocused: bool,
641 columnar_selection_tail: Option<Anchor>,
642 add_selections_state: Option<AddSelectionsState>,
643 select_next_state: Option<SelectNextState>,
644 select_prev_state: Option<SelectNextState>,
645 selection_history: SelectionHistory,
646 autoclose_regions: Vec<AutocloseRegion>,
647 snippet_stack: InvalidationStack<SnippetState>,
648 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
649 ime_transaction: Option<TransactionId>,
650 active_diagnostics: Option<ActiveDiagnosticGroup>,
651 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
652
653 // TODO: make this a access method
654 pub project: Option<Entity<Project>>,
655 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
656 completion_provider: Option<Box<dyn CompletionProvider>>,
657 collaboration_hub: Option<Box<dyn CollaborationHub>>,
658 blink_manager: Entity<BlinkManager>,
659 show_cursor_names: bool,
660 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
661 pub show_local_selections: bool,
662 mode: EditorMode,
663 show_breadcrumbs: bool,
664 show_gutter: bool,
665 show_scrollbars: bool,
666 show_line_numbers: Option<bool>,
667 use_relative_line_numbers: Option<bool>,
668 show_git_diff_gutter: Option<bool>,
669 show_code_actions: Option<bool>,
670 show_runnables: Option<bool>,
671 show_wrap_guides: Option<bool>,
672 show_indent_guides: Option<bool>,
673 placeholder_text: Option<Arc<str>>,
674 highlight_order: usize,
675 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
676 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
677 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
678 scrollbar_marker_state: ScrollbarMarkerState,
679 active_indent_guides_state: ActiveIndentGuidesState,
680 nav_history: Option<ItemNavHistory>,
681 context_menu: RefCell<Option<CodeContextMenu>>,
682 mouse_context_menu: Option<MouseContextMenu>,
683 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
684 signature_help_state: SignatureHelpState,
685 auto_signature_help: Option<bool>,
686 find_all_references_task_sources: Vec<Anchor>,
687 next_completion_id: CompletionId,
688 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
689 code_actions_task: Option<Task<Result<()>>>,
690 document_highlights_task: Option<Task<()>>,
691 linked_editing_range_task: Option<Task<Option<()>>>,
692 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
693 pending_rename: Option<RenameState>,
694 searchable: bool,
695 cursor_shape: CursorShape,
696 current_line_highlight: Option<CurrentLineHighlight>,
697 collapse_matches: bool,
698 autoindent_mode: Option<AutoindentMode>,
699 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
700 input_enabled: bool,
701 use_modal_editing: bool,
702 read_only: bool,
703 leader_peer_id: Option<PeerId>,
704 remote_id: Option<ViewId>,
705 hover_state: HoverState,
706 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
707 gutter_hovered: bool,
708 hovered_link_state: Option<HoveredLinkState>,
709 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
710 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
711 active_inline_completion: Option<InlineCompletionState>,
712 /// Used to prevent flickering as the user types while the menu is open
713 stale_inline_completion_in_menu: Option<InlineCompletionState>,
714 edit_prediction_settings: EditPredictionSettings,
715 inline_completions_hidden_for_vim_mode: bool,
716 show_inline_completions_override: Option<bool>,
717 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
718 edit_prediction_preview: EditPredictionPreview,
719 edit_prediction_cursor_on_leading_whitespace: bool,
720 edit_prediction_requires_modifier_in_leading_space: bool,
721 inlay_hint_cache: InlayHintCache,
722 next_inlay_id: usize,
723 _subscriptions: Vec<Subscription>,
724 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
725 gutter_dimensions: GutterDimensions,
726 style: Option<EditorStyle>,
727 text_style_refinement: Option<TextStyleRefinement>,
728 next_editor_action_id: EditorActionId,
729 editor_actions:
730 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
731 use_autoclose: bool,
732 use_auto_surround: bool,
733 auto_replace_emoji_shortcode: bool,
734 show_git_blame_gutter: bool,
735 show_git_blame_inline: bool,
736 show_git_blame_inline_delay_task: Option<Task<()>>,
737 distinguish_unstaged_diff_hunks: bool,
738 git_blame_inline_enabled: bool,
739 serialize_dirty_buffers: bool,
740 show_selection_menu: Option<bool>,
741 blame: Option<Entity<GitBlame>>,
742 blame_subscription: Option<Subscription>,
743 custom_context_menu: Option<
744 Box<
745 dyn 'static
746 + Fn(
747 &mut Self,
748 DisplayPoint,
749 &mut Window,
750 &mut Context<Self>,
751 ) -> Option<Entity<ui::ContextMenu>>,
752 >,
753 >,
754 last_bounds: Option<Bounds<Pixels>>,
755 last_position_map: Option<Rc<PositionMap>>,
756 expect_bounds_change: Option<Bounds<Pixels>>,
757 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
758 tasks_update_task: Option<Task<()>>,
759 in_project_search: bool,
760 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
761 breadcrumb_header: Option<String>,
762 focused_block: Option<FocusedBlock>,
763 next_scroll_position: NextScrollCursorCenterTopBottom,
764 addons: HashMap<TypeId, Box<dyn Addon>>,
765 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
766 load_diff_task: Option<Shared<Task<()>>>,
767 selection_mark_mode: bool,
768 toggle_fold_multiple_buffers: Task<()>,
769 _scroll_cursor_center_top_bottom_task: Task<()>,
770}
771
772#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
773enum NextScrollCursorCenterTopBottom {
774 #[default]
775 Center,
776 Top,
777 Bottom,
778}
779
780impl NextScrollCursorCenterTopBottom {
781 fn next(&self) -> Self {
782 match self {
783 Self::Center => Self::Top,
784 Self::Top => Self::Bottom,
785 Self::Bottom => Self::Center,
786 }
787 }
788}
789
790#[derive(Clone)]
791pub struct EditorSnapshot {
792 pub mode: EditorMode,
793 show_gutter: bool,
794 show_line_numbers: Option<bool>,
795 show_git_diff_gutter: Option<bool>,
796 show_code_actions: Option<bool>,
797 show_runnables: Option<bool>,
798 git_blame_gutter_max_author_length: Option<usize>,
799 pub display_snapshot: DisplaySnapshot,
800 pub placeholder_text: Option<Arc<str>>,
801 is_focused: bool,
802 scroll_anchor: ScrollAnchor,
803 ongoing_scroll: OngoingScroll,
804 current_line_highlight: CurrentLineHighlight,
805 gutter_hovered: bool,
806}
807
808const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
809
810#[derive(Default, Debug, Clone, Copy)]
811pub struct GutterDimensions {
812 pub left_padding: Pixels,
813 pub right_padding: Pixels,
814 pub width: Pixels,
815 pub margin: Pixels,
816 pub git_blame_entries_width: Option<Pixels>,
817}
818
819impl GutterDimensions {
820 /// The full width of the space taken up by the gutter.
821 pub fn full_width(&self) -> Pixels {
822 self.margin + self.width
823 }
824
825 /// The width of the space reserved for the fold indicators,
826 /// use alongside 'justify_end' and `gutter_width` to
827 /// right align content with the line numbers
828 pub fn fold_area_width(&self) -> Pixels {
829 self.margin + self.right_padding
830 }
831}
832
833#[derive(Debug)]
834pub struct RemoteSelection {
835 pub replica_id: ReplicaId,
836 pub selection: Selection<Anchor>,
837 pub cursor_shape: CursorShape,
838 pub peer_id: PeerId,
839 pub line_mode: bool,
840 pub participant_index: Option<ParticipantIndex>,
841 pub user_name: Option<SharedString>,
842}
843
844#[derive(Clone, Debug)]
845struct SelectionHistoryEntry {
846 selections: Arc<[Selection<Anchor>]>,
847 select_next_state: Option<SelectNextState>,
848 select_prev_state: Option<SelectNextState>,
849 add_selections_state: Option<AddSelectionsState>,
850}
851
852enum SelectionHistoryMode {
853 Normal,
854 Undoing,
855 Redoing,
856}
857
858#[derive(Clone, PartialEq, Eq, Hash)]
859struct HoveredCursor {
860 replica_id: u16,
861 selection_id: usize,
862}
863
864impl Default for SelectionHistoryMode {
865 fn default() -> Self {
866 Self::Normal
867 }
868}
869
870#[derive(Default)]
871struct SelectionHistory {
872 #[allow(clippy::type_complexity)]
873 selections_by_transaction:
874 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
875 mode: SelectionHistoryMode,
876 undo_stack: VecDeque<SelectionHistoryEntry>,
877 redo_stack: VecDeque<SelectionHistoryEntry>,
878}
879
880impl SelectionHistory {
881 fn insert_transaction(
882 &mut self,
883 transaction_id: TransactionId,
884 selections: Arc<[Selection<Anchor>]>,
885 ) {
886 self.selections_by_transaction
887 .insert(transaction_id, (selections, None));
888 }
889
890 #[allow(clippy::type_complexity)]
891 fn transaction(
892 &self,
893 transaction_id: TransactionId,
894 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
895 self.selections_by_transaction.get(&transaction_id)
896 }
897
898 #[allow(clippy::type_complexity)]
899 fn transaction_mut(
900 &mut self,
901 transaction_id: TransactionId,
902 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
903 self.selections_by_transaction.get_mut(&transaction_id)
904 }
905
906 fn push(&mut self, entry: SelectionHistoryEntry) {
907 if !entry.selections.is_empty() {
908 match self.mode {
909 SelectionHistoryMode::Normal => {
910 self.push_undo(entry);
911 self.redo_stack.clear();
912 }
913 SelectionHistoryMode::Undoing => self.push_redo(entry),
914 SelectionHistoryMode::Redoing => self.push_undo(entry),
915 }
916 }
917 }
918
919 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
920 if self
921 .undo_stack
922 .back()
923 .map_or(true, |e| e.selections != entry.selections)
924 {
925 self.undo_stack.push_back(entry);
926 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
927 self.undo_stack.pop_front();
928 }
929 }
930 }
931
932 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
933 if self
934 .redo_stack
935 .back()
936 .map_or(true, |e| e.selections != entry.selections)
937 {
938 self.redo_stack.push_back(entry);
939 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
940 self.redo_stack.pop_front();
941 }
942 }
943 }
944}
945
946struct RowHighlight {
947 index: usize,
948 range: Range<Anchor>,
949 color: Hsla,
950 should_autoscroll: bool,
951}
952
953#[derive(Clone, Debug)]
954struct AddSelectionsState {
955 above: bool,
956 stack: Vec<usize>,
957}
958
959#[derive(Clone)]
960struct SelectNextState {
961 query: AhoCorasick,
962 wordwise: bool,
963 done: bool,
964}
965
966impl std::fmt::Debug for SelectNextState {
967 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
968 f.debug_struct(std::any::type_name::<Self>())
969 .field("wordwise", &self.wordwise)
970 .field("done", &self.done)
971 .finish()
972 }
973}
974
975#[derive(Debug)]
976struct AutocloseRegion {
977 selection_id: usize,
978 range: Range<Anchor>,
979 pair: BracketPair,
980}
981
982#[derive(Debug)]
983struct SnippetState {
984 ranges: Vec<Vec<Range<Anchor>>>,
985 active_index: usize,
986 choices: Vec<Option<Vec<String>>>,
987}
988
989#[doc(hidden)]
990pub struct RenameState {
991 pub range: Range<Anchor>,
992 pub old_name: Arc<str>,
993 pub editor: Entity<Editor>,
994 block_id: CustomBlockId,
995}
996
997struct InvalidationStack<T>(Vec<T>);
998
999struct RegisteredInlineCompletionProvider {
1000 provider: Arc<dyn InlineCompletionProviderHandle>,
1001 _subscription: Subscription,
1002}
1003
1004#[derive(Debug)]
1005struct ActiveDiagnosticGroup {
1006 primary_range: Range<Anchor>,
1007 primary_message: String,
1008 group_id: usize,
1009 blocks: HashMap<CustomBlockId, Diagnostic>,
1010 is_valid: bool,
1011}
1012
1013#[derive(Serialize, Deserialize, Clone, Debug)]
1014pub struct ClipboardSelection {
1015 pub len: usize,
1016 pub is_entire_line: bool,
1017 pub first_line_indent: u32,
1018}
1019
1020#[derive(Debug)]
1021pub(crate) struct NavigationData {
1022 cursor_anchor: Anchor,
1023 cursor_position: Point,
1024 scroll_anchor: ScrollAnchor,
1025 scroll_top_row: u32,
1026}
1027
1028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1029pub enum GotoDefinitionKind {
1030 Symbol,
1031 Declaration,
1032 Type,
1033 Implementation,
1034}
1035
1036#[derive(Debug, Clone)]
1037enum InlayHintRefreshReason {
1038 Toggle(bool),
1039 SettingsChange(InlayHintSettings),
1040 NewLinesShown,
1041 BufferEdited(HashSet<Arc<Language>>),
1042 RefreshRequested,
1043 ExcerptsRemoved(Vec<ExcerptId>),
1044}
1045
1046impl InlayHintRefreshReason {
1047 fn description(&self) -> &'static str {
1048 match self {
1049 Self::Toggle(_) => "toggle",
1050 Self::SettingsChange(_) => "settings change",
1051 Self::NewLinesShown => "new lines shown",
1052 Self::BufferEdited(_) => "buffer edited",
1053 Self::RefreshRequested => "refresh requested",
1054 Self::ExcerptsRemoved(_) => "excerpts removed",
1055 }
1056 }
1057}
1058
1059pub enum FormatTarget {
1060 Buffers,
1061 Ranges(Vec<Range<MultiBufferPoint>>),
1062}
1063
1064pub(crate) struct FocusedBlock {
1065 id: BlockId,
1066 focus_handle: WeakFocusHandle,
1067}
1068
1069#[derive(Clone)]
1070enum JumpData {
1071 MultiBufferRow {
1072 row: MultiBufferRow,
1073 line_offset_from_top: u32,
1074 },
1075 MultiBufferPoint {
1076 excerpt_id: ExcerptId,
1077 position: Point,
1078 anchor: text::Anchor,
1079 line_offset_from_top: u32,
1080 },
1081}
1082
1083pub enum MultibufferSelectionMode {
1084 First,
1085 All,
1086}
1087
1088impl Editor {
1089 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1090 let buffer = cx.new(|cx| Buffer::local("", cx));
1091 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1092 Self::new(
1093 EditorMode::SingleLine { auto_width: false },
1094 buffer,
1095 None,
1096 false,
1097 window,
1098 cx,
1099 )
1100 }
1101
1102 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1103 let buffer = cx.new(|cx| Buffer::local("", cx));
1104 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1105 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1106 }
1107
1108 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1109 let buffer = cx.new(|cx| Buffer::local("", cx));
1110 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1111 Self::new(
1112 EditorMode::SingleLine { auto_width: true },
1113 buffer,
1114 None,
1115 false,
1116 window,
1117 cx,
1118 )
1119 }
1120
1121 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1122 let buffer = cx.new(|cx| Buffer::local("", cx));
1123 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1124 Self::new(
1125 EditorMode::AutoHeight { max_lines },
1126 buffer,
1127 None,
1128 false,
1129 window,
1130 cx,
1131 )
1132 }
1133
1134 pub fn for_buffer(
1135 buffer: Entity<Buffer>,
1136 project: Option<Entity<Project>>,
1137 window: &mut Window,
1138 cx: &mut Context<Self>,
1139 ) -> Self {
1140 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1141 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1142 }
1143
1144 pub fn for_multibuffer(
1145 buffer: Entity<MultiBuffer>,
1146 project: Option<Entity<Project>>,
1147 show_excerpt_controls: bool,
1148 window: &mut Window,
1149 cx: &mut Context<Self>,
1150 ) -> Self {
1151 Self::new(
1152 EditorMode::Full,
1153 buffer,
1154 project,
1155 show_excerpt_controls,
1156 window,
1157 cx,
1158 )
1159 }
1160
1161 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1162 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1163 let mut clone = Self::new(
1164 self.mode,
1165 self.buffer.clone(),
1166 self.project.clone(),
1167 show_excerpt_controls,
1168 window,
1169 cx,
1170 );
1171 self.display_map.update(cx, |display_map, cx| {
1172 let snapshot = display_map.snapshot(cx);
1173 clone.display_map.update(cx, |display_map, cx| {
1174 display_map.set_state(&snapshot, cx);
1175 });
1176 });
1177 clone.selections.clone_state(&self.selections);
1178 clone.scroll_manager.clone_state(&self.scroll_manager);
1179 clone.searchable = self.searchable;
1180 clone
1181 }
1182
1183 pub fn new(
1184 mode: EditorMode,
1185 buffer: Entity<MultiBuffer>,
1186 project: Option<Entity<Project>>,
1187 show_excerpt_controls: bool,
1188 window: &mut Window,
1189 cx: &mut Context<Self>,
1190 ) -> Self {
1191 let style = window.text_style();
1192 let font_size = style.font_size.to_pixels(window.rem_size());
1193 let editor = cx.entity().downgrade();
1194 let fold_placeholder = FoldPlaceholder {
1195 constrain_width: true,
1196 render: Arc::new(move |fold_id, fold_range, _, cx| {
1197 let editor = editor.clone();
1198 div()
1199 .id(fold_id)
1200 .bg(cx.theme().colors().ghost_element_background)
1201 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1202 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1203 .rounded_sm()
1204 .size_full()
1205 .cursor_pointer()
1206 .child("⋯")
1207 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1208 .on_click(move |_, _window, cx| {
1209 editor
1210 .update(cx, |editor, cx| {
1211 editor.unfold_ranges(
1212 &[fold_range.start..fold_range.end],
1213 true,
1214 false,
1215 cx,
1216 );
1217 cx.stop_propagation();
1218 })
1219 .ok();
1220 })
1221 .into_any()
1222 }),
1223 merge_adjacent: true,
1224 ..Default::default()
1225 };
1226 let display_map = cx.new(|cx| {
1227 DisplayMap::new(
1228 buffer.clone(),
1229 style.font(),
1230 font_size,
1231 None,
1232 show_excerpt_controls,
1233 FILE_HEADER_HEIGHT,
1234 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1235 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1236 fold_placeholder,
1237 cx,
1238 )
1239 });
1240
1241 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1242
1243 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1244
1245 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1246 .then(|| language_settings::SoftWrap::None);
1247
1248 let mut project_subscriptions = Vec::new();
1249 if mode == EditorMode::Full {
1250 if let Some(project) = project.as_ref() {
1251 if buffer.read(cx).is_singleton() {
1252 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1253 cx.emit(EditorEvent::TitleChanged);
1254 }));
1255 }
1256 project_subscriptions.push(cx.subscribe_in(
1257 project,
1258 window,
1259 |editor, _, event, window, cx| {
1260 if let project::Event::RefreshInlayHints = event {
1261 editor
1262 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1263 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1264 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1265 let focus_handle = editor.focus_handle(cx);
1266 if focus_handle.is_focused(window) {
1267 let snapshot = buffer.read(cx).snapshot();
1268 for (range, snippet) in snippet_edits {
1269 let editor_range =
1270 language::range_from_lsp(*range).to_offset(&snapshot);
1271 editor
1272 .insert_snippet(
1273 &[editor_range],
1274 snippet.clone(),
1275 window,
1276 cx,
1277 )
1278 .ok();
1279 }
1280 }
1281 }
1282 }
1283 },
1284 ));
1285 if let Some(task_inventory) = project
1286 .read(cx)
1287 .task_store()
1288 .read(cx)
1289 .task_inventory()
1290 .cloned()
1291 {
1292 project_subscriptions.push(cx.observe_in(
1293 &task_inventory,
1294 window,
1295 |editor, _, window, cx| {
1296 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1297 },
1298 ));
1299 }
1300 }
1301 }
1302
1303 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1304
1305 let inlay_hint_settings =
1306 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1307 let focus_handle = cx.focus_handle();
1308 cx.on_focus(&focus_handle, window, Self::handle_focus)
1309 .detach();
1310 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1311 .detach();
1312 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1313 .detach();
1314 cx.on_blur(&focus_handle, window, Self::handle_blur)
1315 .detach();
1316
1317 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1318 Some(false)
1319 } else {
1320 None
1321 };
1322
1323 let mut code_action_providers = Vec::new();
1324 let mut load_uncommitted_diff = None;
1325 if let Some(project) = project.clone() {
1326 load_uncommitted_diff = Some(
1327 get_uncommitted_diff_for_buffer(
1328 &project,
1329 buffer.read(cx).all_buffers(),
1330 buffer.clone(),
1331 cx,
1332 )
1333 .shared(),
1334 );
1335 code_action_providers.push(Rc::new(project) as Rc<_>);
1336 }
1337
1338 let mut this = Self {
1339 focus_handle,
1340 show_cursor_when_unfocused: false,
1341 last_focused_descendant: None,
1342 buffer: buffer.clone(),
1343 display_map: display_map.clone(),
1344 selections,
1345 scroll_manager: ScrollManager::new(cx),
1346 columnar_selection_tail: None,
1347 add_selections_state: None,
1348 select_next_state: None,
1349 select_prev_state: None,
1350 selection_history: Default::default(),
1351 autoclose_regions: Default::default(),
1352 snippet_stack: Default::default(),
1353 select_larger_syntax_node_stack: Vec::new(),
1354 ime_transaction: Default::default(),
1355 active_diagnostics: None,
1356 soft_wrap_mode_override,
1357 completion_provider: project.clone().map(|project| Box::new(project) as _),
1358 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1359 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1360 project,
1361 blink_manager: blink_manager.clone(),
1362 show_local_selections: true,
1363 show_scrollbars: true,
1364 mode,
1365 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1366 show_gutter: mode == EditorMode::Full,
1367 show_line_numbers: None,
1368 use_relative_line_numbers: None,
1369 show_git_diff_gutter: None,
1370 show_code_actions: None,
1371 show_runnables: None,
1372 show_wrap_guides: None,
1373 show_indent_guides,
1374 placeholder_text: None,
1375 highlight_order: 0,
1376 highlighted_rows: HashMap::default(),
1377 background_highlights: Default::default(),
1378 gutter_highlights: TreeMap::default(),
1379 scrollbar_marker_state: ScrollbarMarkerState::default(),
1380 active_indent_guides_state: ActiveIndentGuidesState::default(),
1381 nav_history: None,
1382 context_menu: RefCell::new(None),
1383 mouse_context_menu: None,
1384 completion_tasks: Default::default(),
1385 signature_help_state: SignatureHelpState::default(),
1386 auto_signature_help: None,
1387 find_all_references_task_sources: Vec::new(),
1388 next_completion_id: 0,
1389 next_inlay_id: 0,
1390 code_action_providers,
1391 available_code_actions: Default::default(),
1392 code_actions_task: Default::default(),
1393 document_highlights_task: Default::default(),
1394 linked_editing_range_task: Default::default(),
1395 pending_rename: Default::default(),
1396 searchable: true,
1397 cursor_shape: EditorSettings::get_global(cx)
1398 .cursor_shape
1399 .unwrap_or_default(),
1400 current_line_highlight: None,
1401 autoindent_mode: Some(AutoindentMode::EachLine),
1402 collapse_matches: false,
1403 workspace: None,
1404 input_enabled: true,
1405 use_modal_editing: mode == EditorMode::Full,
1406 read_only: false,
1407 use_autoclose: true,
1408 use_auto_surround: true,
1409 auto_replace_emoji_shortcode: false,
1410 leader_peer_id: None,
1411 remote_id: None,
1412 hover_state: Default::default(),
1413 pending_mouse_down: None,
1414 hovered_link_state: Default::default(),
1415 edit_prediction_provider: None,
1416 active_inline_completion: None,
1417 stale_inline_completion_in_menu: None,
1418 edit_prediction_preview: EditPredictionPreview::Inactive,
1419 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1420
1421 gutter_hovered: false,
1422 pixel_position_of_newest_cursor: None,
1423 last_bounds: None,
1424 last_position_map: None,
1425 expect_bounds_change: None,
1426 gutter_dimensions: GutterDimensions::default(),
1427 style: None,
1428 show_cursor_names: false,
1429 hovered_cursors: Default::default(),
1430 next_editor_action_id: EditorActionId::default(),
1431 editor_actions: Rc::default(),
1432 inline_completions_hidden_for_vim_mode: false,
1433 show_inline_completions_override: None,
1434 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1435 edit_prediction_settings: EditPredictionSettings::Disabled,
1436 edit_prediction_cursor_on_leading_whitespace: false,
1437 edit_prediction_requires_modifier_in_leading_space: true,
1438 custom_context_menu: None,
1439 show_git_blame_gutter: false,
1440 show_git_blame_inline: false,
1441 distinguish_unstaged_diff_hunks: false,
1442 show_selection_menu: None,
1443 show_git_blame_inline_delay_task: None,
1444 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1445 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1446 .session
1447 .restore_unsaved_buffers,
1448 blame: None,
1449 blame_subscription: None,
1450 tasks: Default::default(),
1451 _subscriptions: vec![
1452 cx.observe(&buffer, Self::on_buffer_changed),
1453 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1454 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1455 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1456 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1457 cx.observe_window_activation(window, |editor, window, cx| {
1458 let active = window.is_window_active();
1459 editor.blink_manager.update(cx, |blink_manager, cx| {
1460 if active {
1461 blink_manager.enable(cx);
1462 } else {
1463 blink_manager.disable(cx);
1464 }
1465 });
1466 }),
1467 ],
1468 tasks_update_task: None,
1469 linked_edit_ranges: Default::default(),
1470 in_project_search: false,
1471 previous_search_ranges: None,
1472 breadcrumb_header: None,
1473 focused_block: None,
1474 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1475 addons: HashMap::default(),
1476 registered_buffers: HashMap::default(),
1477 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1478 selection_mark_mode: false,
1479 toggle_fold_multiple_buffers: Task::ready(()),
1480 text_style_refinement: None,
1481 load_diff_task: load_uncommitted_diff,
1482 };
1483 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1484 this._subscriptions.extend(project_subscriptions);
1485
1486 this.end_selection(window, cx);
1487 this.scroll_manager.show_scrollbar(window, cx);
1488
1489 if mode == EditorMode::Full {
1490 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1491 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1492
1493 if this.git_blame_inline_enabled {
1494 this.git_blame_inline_enabled = true;
1495 this.start_git_blame_inline(false, window, cx);
1496 }
1497
1498 if let Some(buffer) = buffer.read(cx).as_singleton() {
1499 if let Some(project) = this.project.as_ref() {
1500 let lsp_store = project.read(cx).lsp_store();
1501 let handle = lsp_store.update(cx, |lsp_store, cx| {
1502 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1503 });
1504 this.registered_buffers
1505 .insert(buffer.read(cx).remote_id(), handle);
1506 }
1507 }
1508 }
1509
1510 this.report_editor_event("Editor Opened", None, cx);
1511 this
1512 }
1513
1514 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1515 self.mouse_context_menu
1516 .as_ref()
1517 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1518 }
1519
1520 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1521 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1522 }
1523
1524 fn key_context_internal(
1525 &self,
1526 has_active_edit_prediction: bool,
1527 window: &Window,
1528 cx: &App,
1529 ) -> KeyContext {
1530 let mut key_context = KeyContext::new_with_defaults();
1531 key_context.add("Editor");
1532 let mode = match self.mode {
1533 EditorMode::SingleLine { .. } => "single_line",
1534 EditorMode::AutoHeight { .. } => "auto_height",
1535 EditorMode::Full => "full",
1536 };
1537
1538 if EditorSettings::jupyter_enabled(cx) {
1539 key_context.add("jupyter");
1540 }
1541
1542 key_context.set("mode", mode);
1543 if self.pending_rename.is_some() {
1544 key_context.add("renaming");
1545 }
1546
1547 match self.context_menu.borrow().as_ref() {
1548 Some(CodeContextMenu::Completions(_)) => {
1549 key_context.add("menu");
1550 key_context.add("showing_completions");
1551 }
1552 Some(CodeContextMenu::CodeActions(_)) => {
1553 key_context.add("menu");
1554 key_context.add("showing_code_actions")
1555 }
1556 None => {}
1557 }
1558
1559 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1560 if !self.focus_handle(cx).contains_focused(window, cx)
1561 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1562 {
1563 for addon in self.addons.values() {
1564 addon.extend_key_context(&mut key_context, cx)
1565 }
1566 }
1567
1568 if let Some(extension) = self
1569 .buffer
1570 .read(cx)
1571 .as_singleton()
1572 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1573 {
1574 key_context.set("extension", extension.to_string());
1575 }
1576
1577 if has_active_edit_prediction {
1578 if self.edit_prediction_in_conflict() {
1579 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1580 } else {
1581 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1582 key_context.add("copilot_suggestion");
1583 }
1584 }
1585
1586 if self.selection_mark_mode {
1587 key_context.add("selection_mode");
1588 }
1589
1590 key_context
1591 }
1592
1593 pub fn edit_prediction_in_conflict(&self) -> bool {
1594 if !self.show_edit_predictions_in_menu() {
1595 return false;
1596 }
1597
1598 let showing_completions = self
1599 .context_menu
1600 .borrow()
1601 .as_ref()
1602 .map_or(false, |context| {
1603 matches!(context, CodeContextMenu::Completions(_))
1604 });
1605
1606 showing_completions
1607 || self.edit_prediction_requires_modifier()
1608 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1609 // bindings to insert tab characters.
1610 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1611 }
1612
1613 pub fn accept_edit_prediction_keybind(
1614 &self,
1615 window: &Window,
1616 cx: &App,
1617 ) -> AcceptEditPredictionBinding {
1618 let key_context = self.key_context_internal(true, window, cx);
1619 let in_conflict = self.edit_prediction_in_conflict();
1620 AcceptEditPredictionBinding(
1621 window
1622 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1623 .into_iter()
1624 .filter(|binding| {
1625 !in_conflict
1626 || binding
1627 .keystrokes()
1628 .first()
1629 .map_or(false, |keystroke| keystroke.modifiers.modified())
1630 })
1631 .rev()
1632 .next(),
1633 )
1634 }
1635
1636 pub fn new_file(
1637 workspace: &mut Workspace,
1638 _: &workspace::NewFile,
1639 window: &mut Window,
1640 cx: &mut Context<Workspace>,
1641 ) {
1642 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1643 "Failed to create buffer",
1644 window,
1645 cx,
1646 |e, _, _| match e.error_code() {
1647 ErrorCode::RemoteUpgradeRequired => Some(format!(
1648 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1649 e.error_tag("required").unwrap_or("the latest version")
1650 )),
1651 _ => None,
1652 },
1653 );
1654 }
1655
1656 pub fn new_in_workspace(
1657 workspace: &mut Workspace,
1658 window: &mut Window,
1659 cx: &mut Context<Workspace>,
1660 ) -> Task<Result<Entity<Editor>>> {
1661 let project = workspace.project().clone();
1662 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1663
1664 cx.spawn_in(window, |workspace, mut cx| async move {
1665 let buffer = create.await?;
1666 workspace.update_in(&mut cx, |workspace, window, cx| {
1667 let editor =
1668 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1669 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1670 editor
1671 })
1672 })
1673 }
1674
1675 fn new_file_vertical(
1676 workspace: &mut Workspace,
1677 _: &workspace::NewFileSplitVertical,
1678 window: &mut Window,
1679 cx: &mut Context<Workspace>,
1680 ) {
1681 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1682 }
1683
1684 fn new_file_horizontal(
1685 workspace: &mut Workspace,
1686 _: &workspace::NewFileSplitHorizontal,
1687 window: &mut Window,
1688 cx: &mut Context<Workspace>,
1689 ) {
1690 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1691 }
1692
1693 fn new_file_in_direction(
1694 workspace: &mut Workspace,
1695 direction: SplitDirection,
1696 window: &mut Window,
1697 cx: &mut Context<Workspace>,
1698 ) {
1699 let project = workspace.project().clone();
1700 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1701
1702 cx.spawn_in(window, |workspace, mut cx| async move {
1703 let buffer = create.await?;
1704 workspace.update_in(&mut cx, move |workspace, window, cx| {
1705 workspace.split_item(
1706 direction,
1707 Box::new(
1708 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1709 ),
1710 window,
1711 cx,
1712 )
1713 })?;
1714 anyhow::Ok(())
1715 })
1716 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1717 match e.error_code() {
1718 ErrorCode::RemoteUpgradeRequired => Some(format!(
1719 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1720 e.error_tag("required").unwrap_or("the latest version")
1721 )),
1722 _ => None,
1723 }
1724 });
1725 }
1726
1727 pub fn leader_peer_id(&self) -> Option<PeerId> {
1728 self.leader_peer_id
1729 }
1730
1731 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1732 &self.buffer
1733 }
1734
1735 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1736 self.workspace.as_ref()?.0.upgrade()
1737 }
1738
1739 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1740 self.buffer().read(cx).title(cx)
1741 }
1742
1743 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1744 let git_blame_gutter_max_author_length = self
1745 .render_git_blame_gutter(cx)
1746 .then(|| {
1747 if let Some(blame) = self.blame.as_ref() {
1748 let max_author_length =
1749 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1750 Some(max_author_length)
1751 } else {
1752 None
1753 }
1754 })
1755 .flatten();
1756
1757 EditorSnapshot {
1758 mode: self.mode,
1759 show_gutter: self.show_gutter,
1760 show_line_numbers: self.show_line_numbers,
1761 show_git_diff_gutter: self.show_git_diff_gutter,
1762 show_code_actions: self.show_code_actions,
1763 show_runnables: self.show_runnables,
1764 git_blame_gutter_max_author_length,
1765 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1766 scroll_anchor: self.scroll_manager.anchor(),
1767 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1768 placeholder_text: self.placeholder_text.clone(),
1769 is_focused: self.focus_handle.is_focused(window),
1770 current_line_highlight: self
1771 .current_line_highlight
1772 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1773 gutter_hovered: self.gutter_hovered,
1774 }
1775 }
1776
1777 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1778 self.buffer.read(cx).language_at(point, cx)
1779 }
1780
1781 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1782 self.buffer.read(cx).read(cx).file_at(point).cloned()
1783 }
1784
1785 pub fn active_excerpt(
1786 &self,
1787 cx: &App,
1788 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1789 self.buffer
1790 .read(cx)
1791 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1792 }
1793
1794 pub fn mode(&self) -> EditorMode {
1795 self.mode
1796 }
1797
1798 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1799 self.collaboration_hub.as_deref()
1800 }
1801
1802 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1803 self.collaboration_hub = Some(hub);
1804 }
1805
1806 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1807 self.in_project_search = in_project_search;
1808 }
1809
1810 pub fn set_custom_context_menu(
1811 &mut self,
1812 f: impl 'static
1813 + Fn(
1814 &mut Self,
1815 DisplayPoint,
1816 &mut Window,
1817 &mut Context<Self>,
1818 ) -> Option<Entity<ui::ContextMenu>>,
1819 ) {
1820 self.custom_context_menu = Some(Box::new(f))
1821 }
1822
1823 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1824 self.completion_provider = provider;
1825 }
1826
1827 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1828 self.semantics_provider.clone()
1829 }
1830
1831 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1832 self.semantics_provider = provider;
1833 }
1834
1835 pub fn set_edit_prediction_provider<T>(
1836 &mut self,
1837 provider: Option<Entity<T>>,
1838 window: &mut Window,
1839 cx: &mut Context<Self>,
1840 ) where
1841 T: EditPredictionProvider,
1842 {
1843 self.edit_prediction_provider =
1844 provider.map(|provider| RegisteredInlineCompletionProvider {
1845 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1846 if this.focus_handle.is_focused(window) {
1847 this.update_visible_inline_completion(window, cx);
1848 }
1849 }),
1850 provider: Arc::new(provider),
1851 });
1852 self.refresh_inline_completion(false, false, window, cx);
1853 }
1854
1855 pub fn placeholder_text(&self) -> Option<&str> {
1856 self.placeholder_text.as_deref()
1857 }
1858
1859 pub fn set_placeholder_text(
1860 &mut self,
1861 placeholder_text: impl Into<Arc<str>>,
1862 cx: &mut Context<Self>,
1863 ) {
1864 let placeholder_text = Some(placeholder_text.into());
1865 if self.placeholder_text != placeholder_text {
1866 self.placeholder_text = placeholder_text;
1867 cx.notify();
1868 }
1869 }
1870
1871 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1872 self.cursor_shape = cursor_shape;
1873
1874 // Disrupt blink for immediate user feedback that the cursor shape has changed
1875 self.blink_manager.update(cx, BlinkManager::show_cursor);
1876
1877 cx.notify();
1878 }
1879
1880 pub fn set_current_line_highlight(
1881 &mut self,
1882 current_line_highlight: Option<CurrentLineHighlight>,
1883 ) {
1884 self.current_line_highlight = current_line_highlight;
1885 }
1886
1887 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1888 self.collapse_matches = collapse_matches;
1889 }
1890
1891 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1892 let buffers = self.buffer.read(cx).all_buffers();
1893 let Some(lsp_store) = self.lsp_store(cx) else {
1894 return;
1895 };
1896 lsp_store.update(cx, |lsp_store, cx| {
1897 for buffer in buffers {
1898 self.registered_buffers
1899 .entry(buffer.read(cx).remote_id())
1900 .or_insert_with(|| {
1901 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1902 });
1903 }
1904 })
1905 }
1906
1907 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1908 if self.collapse_matches {
1909 return range.start..range.start;
1910 }
1911 range.clone()
1912 }
1913
1914 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1915 if self.display_map.read(cx).clip_at_line_ends != clip {
1916 self.display_map
1917 .update(cx, |map, _| map.clip_at_line_ends = clip);
1918 }
1919 }
1920
1921 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1922 self.input_enabled = input_enabled;
1923 }
1924
1925 pub fn set_inline_completions_hidden_for_vim_mode(
1926 &mut self,
1927 hidden: bool,
1928 window: &mut Window,
1929 cx: &mut Context<Self>,
1930 ) {
1931 if hidden != self.inline_completions_hidden_for_vim_mode {
1932 self.inline_completions_hidden_for_vim_mode = hidden;
1933 if hidden {
1934 self.update_visible_inline_completion(window, cx);
1935 } else {
1936 self.refresh_inline_completion(true, false, window, cx);
1937 }
1938 }
1939 }
1940
1941 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1942 self.menu_inline_completions_policy = value;
1943 }
1944
1945 pub fn set_autoindent(&mut self, autoindent: bool) {
1946 if autoindent {
1947 self.autoindent_mode = Some(AutoindentMode::EachLine);
1948 } else {
1949 self.autoindent_mode = None;
1950 }
1951 }
1952
1953 pub fn read_only(&self, cx: &App) -> bool {
1954 self.read_only || self.buffer.read(cx).read_only()
1955 }
1956
1957 pub fn set_read_only(&mut self, read_only: bool) {
1958 self.read_only = read_only;
1959 }
1960
1961 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1962 self.use_autoclose = autoclose;
1963 }
1964
1965 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1966 self.use_auto_surround = auto_surround;
1967 }
1968
1969 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1970 self.auto_replace_emoji_shortcode = auto_replace;
1971 }
1972
1973 pub fn toggle_inline_completions(
1974 &mut self,
1975 _: &ToggleEditPrediction,
1976 window: &mut Window,
1977 cx: &mut Context<Self>,
1978 ) {
1979 if self.show_inline_completions_override.is_some() {
1980 self.set_show_edit_predictions(None, window, cx);
1981 } else {
1982 let show_edit_predictions = !self.edit_predictions_enabled();
1983 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1984 }
1985 }
1986
1987 pub fn set_show_edit_predictions(
1988 &mut self,
1989 show_edit_predictions: Option<bool>,
1990 window: &mut Window,
1991 cx: &mut Context<Self>,
1992 ) {
1993 self.show_inline_completions_override = show_edit_predictions;
1994 self.refresh_inline_completion(false, true, window, cx);
1995 }
1996
1997 fn inline_completions_disabled_in_scope(
1998 &self,
1999 buffer: &Entity<Buffer>,
2000 buffer_position: language::Anchor,
2001 cx: &App,
2002 ) -> bool {
2003 let snapshot = buffer.read(cx).snapshot();
2004 let settings = snapshot.settings_at(buffer_position, cx);
2005
2006 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2007 return false;
2008 };
2009
2010 scope.override_name().map_or(false, |scope_name| {
2011 settings
2012 .edit_predictions_disabled_in
2013 .iter()
2014 .any(|s| s == scope_name)
2015 })
2016 }
2017
2018 pub fn set_use_modal_editing(&mut self, to: bool) {
2019 self.use_modal_editing = to;
2020 }
2021
2022 pub fn use_modal_editing(&self) -> bool {
2023 self.use_modal_editing
2024 }
2025
2026 fn selections_did_change(
2027 &mut self,
2028 local: bool,
2029 old_cursor_position: &Anchor,
2030 show_completions: bool,
2031 window: &mut Window,
2032 cx: &mut Context<Self>,
2033 ) {
2034 window.invalidate_character_coordinates();
2035
2036 // Copy selections to primary selection buffer
2037 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2038 if local {
2039 let selections = self.selections.all::<usize>(cx);
2040 let buffer_handle = self.buffer.read(cx).read(cx);
2041
2042 let mut text = String::new();
2043 for (index, selection) in selections.iter().enumerate() {
2044 let text_for_selection = buffer_handle
2045 .text_for_range(selection.start..selection.end)
2046 .collect::<String>();
2047
2048 text.push_str(&text_for_selection);
2049 if index != selections.len() - 1 {
2050 text.push('\n');
2051 }
2052 }
2053
2054 if !text.is_empty() {
2055 cx.write_to_primary(ClipboardItem::new_string(text));
2056 }
2057 }
2058
2059 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2060 self.buffer.update(cx, |buffer, cx| {
2061 buffer.set_active_selections(
2062 &self.selections.disjoint_anchors(),
2063 self.selections.line_mode,
2064 self.cursor_shape,
2065 cx,
2066 )
2067 });
2068 }
2069 let display_map = self
2070 .display_map
2071 .update(cx, |display_map, cx| display_map.snapshot(cx));
2072 let buffer = &display_map.buffer_snapshot;
2073 self.add_selections_state = None;
2074 self.select_next_state = None;
2075 self.select_prev_state = None;
2076 self.select_larger_syntax_node_stack.clear();
2077 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2078 self.snippet_stack
2079 .invalidate(&self.selections.disjoint_anchors(), buffer);
2080 self.take_rename(false, window, cx);
2081
2082 let new_cursor_position = self.selections.newest_anchor().head();
2083
2084 self.push_to_nav_history(
2085 *old_cursor_position,
2086 Some(new_cursor_position.to_point(buffer)),
2087 cx,
2088 );
2089
2090 if local {
2091 let new_cursor_position = self.selections.newest_anchor().head();
2092 let mut context_menu = self.context_menu.borrow_mut();
2093 let completion_menu = match context_menu.as_ref() {
2094 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2095 _ => {
2096 *context_menu = None;
2097 None
2098 }
2099 };
2100 if let Some(buffer_id) = new_cursor_position.buffer_id {
2101 if !self.registered_buffers.contains_key(&buffer_id) {
2102 if let Some(lsp_store) = self.lsp_store(cx) {
2103 lsp_store.update(cx, |lsp_store, cx| {
2104 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2105 return;
2106 };
2107 self.registered_buffers.insert(
2108 buffer_id,
2109 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2110 );
2111 })
2112 }
2113 }
2114 }
2115
2116 if let Some(completion_menu) = completion_menu {
2117 let cursor_position = new_cursor_position.to_offset(buffer);
2118 let (word_range, kind) =
2119 buffer.surrounding_word(completion_menu.initial_position, true);
2120 if kind == Some(CharKind::Word)
2121 && word_range.to_inclusive().contains(&cursor_position)
2122 {
2123 let mut completion_menu = completion_menu.clone();
2124 drop(context_menu);
2125
2126 let query = Self::completion_query(buffer, cursor_position);
2127 cx.spawn(move |this, mut cx| async move {
2128 completion_menu
2129 .filter(query.as_deref(), cx.background_executor().clone())
2130 .await;
2131
2132 this.update(&mut cx, |this, cx| {
2133 let mut context_menu = this.context_menu.borrow_mut();
2134 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2135 else {
2136 return;
2137 };
2138
2139 if menu.id > completion_menu.id {
2140 return;
2141 }
2142
2143 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2144 drop(context_menu);
2145 cx.notify();
2146 })
2147 })
2148 .detach();
2149
2150 if show_completions {
2151 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2152 }
2153 } else {
2154 drop(context_menu);
2155 self.hide_context_menu(window, cx);
2156 }
2157 } else {
2158 drop(context_menu);
2159 }
2160
2161 hide_hover(self, cx);
2162
2163 if old_cursor_position.to_display_point(&display_map).row()
2164 != new_cursor_position.to_display_point(&display_map).row()
2165 {
2166 self.available_code_actions.take();
2167 }
2168 self.refresh_code_actions(window, cx);
2169 self.refresh_document_highlights(cx);
2170 refresh_matching_bracket_highlights(self, window, cx);
2171 self.update_visible_inline_completion(window, cx);
2172 self.edit_prediction_requires_modifier_in_leading_space = true;
2173 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2174 if self.git_blame_inline_enabled {
2175 self.start_inline_blame_timer(window, cx);
2176 }
2177 }
2178
2179 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2180 cx.emit(EditorEvent::SelectionsChanged { local });
2181
2182 if self.selections.disjoint_anchors().len() == 1 {
2183 cx.emit(SearchEvent::ActiveMatchChanged)
2184 }
2185 cx.notify();
2186 }
2187
2188 pub fn change_selections<R>(
2189 &mut self,
2190 autoscroll: Option<Autoscroll>,
2191 window: &mut Window,
2192 cx: &mut Context<Self>,
2193 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2194 ) -> R {
2195 self.change_selections_inner(autoscroll, true, window, cx, change)
2196 }
2197
2198 pub fn change_selections_inner<R>(
2199 &mut self,
2200 autoscroll: Option<Autoscroll>,
2201 request_completions: bool,
2202 window: &mut Window,
2203 cx: &mut Context<Self>,
2204 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2205 ) -> R {
2206 let old_cursor_position = self.selections.newest_anchor().head();
2207 self.push_to_selection_history();
2208
2209 let (changed, result) = self.selections.change_with(cx, change);
2210
2211 if changed {
2212 if let Some(autoscroll) = autoscroll {
2213 self.request_autoscroll(autoscroll, cx);
2214 }
2215 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2216
2217 if self.should_open_signature_help_automatically(
2218 &old_cursor_position,
2219 self.signature_help_state.backspace_pressed(),
2220 cx,
2221 ) {
2222 self.show_signature_help(&ShowSignatureHelp, window, cx);
2223 }
2224 self.signature_help_state.set_backspace_pressed(false);
2225 }
2226
2227 result
2228 }
2229
2230 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2231 where
2232 I: IntoIterator<Item = (Range<S>, T)>,
2233 S: ToOffset,
2234 T: Into<Arc<str>>,
2235 {
2236 if self.read_only(cx) {
2237 return;
2238 }
2239
2240 self.buffer
2241 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2242 }
2243
2244 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2245 where
2246 I: IntoIterator<Item = (Range<S>, T)>,
2247 S: ToOffset,
2248 T: Into<Arc<str>>,
2249 {
2250 if self.read_only(cx) {
2251 return;
2252 }
2253
2254 self.buffer.update(cx, |buffer, cx| {
2255 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2256 });
2257 }
2258
2259 pub fn edit_with_block_indent<I, S, T>(
2260 &mut self,
2261 edits: I,
2262 original_indent_columns: Vec<u32>,
2263 cx: &mut Context<Self>,
2264 ) where
2265 I: IntoIterator<Item = (Range<S>, T)>,
2266 S: ToOffset,
2267 T: Into<Arc<str>>,
2268 {
2269 if self.read_only(cx) {
2270 return;
2271 }
2272
2273 self.buffer.update(cx, |buffer, cx| {
2274 buffer.edit(
2275 edits,
2276 Some(AutoindentMode::Block {
2277 original_indent_columns,
2278 }),
2279 cx,
2280 )
2281 });
2282 }
2283
2284 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2285 self.hide_context_menu(window, cx);
2286
2287 match phase {
2288 SelectPhase::Begin {
2289 position,
2290 add,
2291 click_count,
2292 } => self.begin_selection(position, add, click_count, window, cx),
2293 SelectPhase::BeginColumnar {
2294 position,
2295 goal_column,
2296 reset,
2297 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2298 SelectPhase::Extend {
2299 position,
2300 click_count,
2301 } => self.extend_selection(position, click_count, window, cx),
2302 SelectPhase::Update {
2303 position,
2304 goal_column,
2305 scroll_delta,
2306 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2307 SelectPhase::End => self.end_selection(window, cx),
2308 }
2309 }
2310
2311 fn extend_selection(
2312 &mut self,
2313 position: DisplayPoint,
2314 click_count: usize,
2315 window: &mut Window,
2316 cx: &mut Context<Self>,
2317 ) {
2318 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2319 let tail = self.selections.newest::<usize>(cx).tail();
2320 self.begin_selection(position, false, click_count, window, cx);
2321
2322 let position = position.to_offset(&display_map, Bias::Left);
2323 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2324
2325 let mut pending_selection = self
2326 .selections
2327 .pending_anchor()
2328 .expect("extend_selection not called with pending selection");
2329 if position >= tail {
2330 pending_selection.start = tail_anchor;
2331 } else {
2332 pending_selection.end = tail_anchor;
2333 pending_selection.reversed = true;
2334 }
2335
2336 let mut pending_mode = self.selections.pending_mode().unwrap();
2337 match &mut pending_mode {
2338 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2339 _ => {}
2340 }
2341
2342 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2343 s.set_pending(pending_selection, pending_mode)
2344 });
2345 }
2346
2347 fn begin_selection(
2348 &mut self,
2349 position: DisplayPoint,
2350 add: bool,
2351 click_count: usize,
2352 window: &mut Window,
2353 cx: &mut Context<Self>,
2354 ) {
2355 if !self.focus_handle.is_focused(window) {
2356 self.last_focused_descendant = None;
2357 window.focus(&self.focus_handle);
2358 }
2359
2360 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2361 let buffer = &display_map.buffer_snapshot;
2362 let newest_selection = self.selections.newest_anchor().clone();
2363 let position = display_map.clip_point(position, Bias::Left);
2364
2365 let start;
2366 let end;
2367 let mode;
2368 let mut auto_scroll;
2369 match click_count {
2370 1 => {
2371 start = buffer.anchor_before(position.to_point(&display_map));
2372 end = start;
2373 mode = SelectMode::Character;
2374 auto_scroll = true;
2375 }
2376 2 => {
2377 let range = movement::surrounding_word(&display_map, position);
2378 start = buffer.anchor_before(range.start.to_point(&display_map));
2379 end = buffer.anchor_before(range.end.to_point(&display_map));
2380 mode = SelectMode::Word(start..end);
2381 auto_scroll = true;
2382 }
2383 3 => {
2384 let position = display_map
2385 .clip_point(position, Bias::Left)
2386 .to_point(&display_map);
2387 let line_start = display_map.prev_line_boundary(position).0;
2388 let next_line_start = buffer.clip_point(
2389 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2390 Bias::Left,
2391 );
2392 start = buffer.anchor_before(line_start);
2393 end = buffer.anchor_before(next_line_start);
2394 mode = SelectMode::Line(start..end);
2395 auto_scroll = true;
2396 }
2397 _ => {
2398 start = buffer.anchor_before(0);
2399 end = buffer.anchor_before(buffer.len());
2400 mode = SelectMode::All;
2401 auto_scroll = false;
2402 }
2403 }
2404 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2405
2406 let point_to_delete: Option<usize> = {
2407 let selected_points: Vec<Selection<Point>> =
2408 self.selections.disjoint_in_range(start..end, cx);
2409
2410 if !add || click_count > 1 {
2411 None
2412 } else if !selected_points.is_empty() {
2413 Some(selected_points[0].id)
2414 } else {
2415 let clicked_point_already_selected =
2416 self.selections.disjoint.iter().find(|selection| {
2417 selection.start.to_point(buffer) == start.to_point(buffer)
2418 || selection.end.to_point(buffer) == end.to_point(buffer)
2419 });
2420
2421 clicked_point_already_selected.map(|selection| selection.id)
2422 }
2423 };
2424
2425 let selections_count = self.selections.count();
2426
2427 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2428 if let Some(point_to_delete) = point_to_delete {
2429 s.delete(point_to_delete);
2430
2431 if selections_count == 1 {
2432 s.set_pending_anchor_range(start..end, mode);
2433 }
2434 } else {
2435 if !add {
2436 s.clear_disjoint();
2437 } else if click_count > 1 {
2438 s.delete(newest_selection.id)
2439 }
2440
2441 s.set_pending_anchor_range(start..end, mode);
2442 }
2443 });
2444 }
2445
2446 fn begin_columnar_selection(
2447 &mut self,
2448 position: DisplayPoint,
2449 goal_column: u32,
2450 reset: bool,
2451 window: &mut Window,
2452 cx: &mut Context<Self>,
2453 ) {
2454 if !self.focus_handle.is_focused(window) {
2455 self.last_focused_descendant = None;
2456 window.focus(&self.focus_handle);
2457 }
2458
2459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2460
2461 if reset {
2462 let pointer_position = display_map
2463 .buffer_snapshot
2464 .anchor_before(position.to_point(&display_map));
2465
2466 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2467 s.clear_disjoint();
2468 s.set_pending_anchor_range(
2469 pointer_position..pointer_position,
2470 SelectMode::Character,
2471 );
2472 });
2473 }
2474
2475 let tail = self.selections.newest::<Point>(cx).tail();
2476 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2477
2478 if !reset {
2479 self.select_columns(
2480 tail.to_display_point(&display_map),
2481 position,
2482 goal_column,
2483 &display_map,
2484 window,
2485 cx,
2486 );
2487 }
2488 }
2489
2490 fn update_selection(
2491 &mut self,
2492 position: DisplayPoint,
2493 goal_column: u32,
2494 scroll_delta: gpui::Point<f32>,
2495 window: &mut Window,
2496 cx: &mut Context<Self>,
2497 ) {
2498 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2499
2500 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2501 let tail = tail.to_display_point(&display_map);
2502 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2503 } else if let Some(mut pending) = self.selections.pending_anchor() {
2504 let buffer = self.buffer.read(cx).snapshot(cx);
2505 let head;
2506 let tail;
2507 let mode = self.selections.pending_mode().unwrap();
2508 match &mode {
2509 SelectMode::Character => {
2510 head = position.to_point(&display_map);
2511 tail = pending.tail().to_point(&buffer);
2512 }
2513 SelectMode::Word(original_range) => {
2514 let original_display_range = original_range.start.to_display_point(&display_map)
2515 ..original_range.end.to_display_point(&display_map);
2516 let original_buffer_range = original_display_range.start.to_point(&display_map)
2517 ..original_display_range.end.to_point(&display_map);
2518 if movement::is_inside_word(&display_map, position)
2519 || original_display_range.contains(&position)
2520 {
2521 let word_range = movement::surrounding_word(&display_map, position);
2522 if word_range.start < original_display_range.start {
2523 head = word_range.start.to_point(&display_map);
2524 } else {
2525 head = word_range.end.to_point(&display_map);
2526 }
2527 } else {
2528 head = position.to_point(&display_map);
2529 }
2530
2531 if head <= original_buffer_range.start {
2532 tail = original_buffer_range.end;
2533 } else {
2534 tail = original_buffer_range.start;
2535 }
2536 }
2537 SelectMode::Line(original_range) => {
2538 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2539
2540 let position = display_map
2541 .clip_point(position, Bias::Left)
2542 .to_point(&display_map);
2543 let line_start = display_map.prev_line_boundary(position).0;
2544 let next_line_start = buffer.clip_point(
2545 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2546 Bias::Left,
2547 );
2548
2549 if line_start < original_range.start {
2550 head = line_start
2551 } else {
2552 head = next_line_start
2553 }
2554
2555 if head <= original_range.start {
2556 tail = original_range.end;
2557 } else {
2558 tail = original_range.start;
2559 }
2560 }
2561 SelectMode::All => {
2562 return;
2563 }
2564 };
2565
2566 if head < tail {
2567 pending.start = buffer.anchor_before(head);
2568 pending.end = buffer.anchor_before(tail);
2569 pending.reversed = true;
2570 } else {
2571 pending.start = buffer.anchor_before(tail);
2572 pending.end = buffer.anchor_before(head);
2573 pending.reversed = false;
2574 }
2575
2576 self.change_selections(None, window, cx, |s| {
2577 s.set_pending(pending, mode);
2578 });
2579 } else {
2580 log::error!("update_selection dispatched with no pending selection");
2581 return;
2582 }
2583
2584 self.apply_scroll_delta(scroll_delta, window, cx);
2585 cx.notify();
2586 }
2587
2588 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2589 self.columnar_selection_tail.take();
2590 if self.selections.pending_anchor().is_some() {
2591 let selections = self.selections.all::<usize>(cx);
2592 self.change_selections(None, window, cx, |s| {
2593 s.select(selections);
2594 s.clear_pending();
2595 });
2596 }
2597 }
2598
2599 fn select_columns(
2600 &mut self,
2601 tail: DisplayPoint,
2602 head: DisplayPoint,
2603 goal_column: u32,
2604 display_map: &DisplaySnapshot,
2605 window: &mut Window,
2606 cx: &mut Context<Self>,
2607 ) {
2608 let start_row = cmp::min(tail.row(), head.row());
2609 let end_row = cmp::max(tail.row(), head.row());
2610 let start_column = cmp::min(tail.column(), goal_column);
2611 let end_column = cmp::max(tail.column(), goal_column);
2612 let reversed = start_column < tail.column();
2613
2614 let selection_ranges = (start_row.0..=end_row.0)
2615 .map(DisplayRow)
2616 .filter_map(|row| {
2617 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2618 let start = display_map
2619 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2620 .to_point(display_map);
2621 let end = display_map
2622 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2623 .to_point(display_map);
2624 if reversed {
2625 Some(end..start)
2626 } else {
2627 Some(start..end)
2628 }
2629 } else {
2630 None
2631 }
2632 })
2633 .collect::<Vec<_>>();
2634
2635 self.change_selections(None, window, cx, |s| {
2636 s.select_ranges(selection_ranges);
2637 });
2638 cx.notify();
2639 }
2640
2641 pub fn has_pending_nonempty_selection(&self) -> bool {
2642 let pending_nonempty_selection = match self.selections.pending_anchor() {
2643 Some(Selection { start, end, .. }) => start != end,
2644 None => false,
2645 };
2646
2647 pending_nonempty_selection
2648 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2649 }
2650
2651 pub fn has_pending_selection(&self) -> bool {
2652 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2653 }
2654
2655 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2656 self.selection_mark_mode = false;
2657
2658 if self.clear_expanded_diff_hunks(cx) {
2659 cx.notify();
2660 return;
2661 }
2662 if self.dismiss_menus_and_popups(true, window, cx) {
2663 return;
2664 }
2665
2666 if self.mode == EditorMode::Full
2667 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2668 {
2669 return;
2670 }
2671
2672 cx.propagate();
2673 }
2674
2675 pub fn dismiss_menus_and_popups(
2676 &mut self,
2677 is_user_requested: bool,
2678 window: &mut Window,
2679 cx: &mut Context<Self>,
2680 ) -> bool {
2681 if self.take_rename(false, window, cx).is_some() {
2682 return true;
2683 }
2684
2685 if hide_hover(self, cx) {
2686 return true;
2687 }
2688
2689 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2690 return true;
2691 }
2692
2693 if self.hide_context_menu(window, cx).is_some() {
2694 return true;
2695 }
2696
2697 if self.mouse_context_menu.take().is_some() {
2698 return true;
2699 }
2700
2701 if is_user_requested && self.discard_inline_completion(true, cx) {
2702 return true;
2703 }
2704
2705 if self.snippet_stack.pop().is_some() {
2706 return true;
2707 }
2708
2709 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2710 self.dismiss_diagnostics(cx);
2711 return true;
2712 }
2713
2714 false
2715 }
2716
2717 fn linked_editing_ranges_for(
2718 &self,
2719 selection: Range<text::Anchor>,
2720 cx: &App,
2721 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2722 if self.linked_edit_ranges.is_empty() {
2723 return None;
2724 }
2725 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2726 selection.end.buffer_id.and_then(|end_buffer_id| {
2727 if selection.start.buffer_id != Some(end_buffer_id) {
2728 return None;
2729 }
2730 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2731 let snapshot = buffer.read(cx).snapshot();
2732 self.linked_edit_ranges
2733 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2734 .map(|ranges| (ranges, snapshot, buffer))
2735 })?;
2736 use text::ToOffset as TO;
2737 // find offset from the start of current range to current cursor position
2738 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2739
2740 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2741 let start_difference = start_offset - start_byte_offset;
2742 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2743 let end_difference = end_offset - start_byte_offset;
2744 // Current range has associated linked ranges.
2745 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2746 for range in linked_ranges.iter() {
2747 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2748 let end_offset = start_offset + end_difference;
2749 let start_offset = start_offset + start_difference;
2750 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2751 continue;
2752 }
2753 if self.selections.disjoint_anchor_ranges().any(|s| {
2754 if s.start.buffer_id != selection.start.buffer_id
2755 || s.end.buffer_id != selection.end.buffer_id
2756 {
2757 return false;
2758 }
2759 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2760 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2761 }) {
2762 continue;
2763 }
2764 let start = buffer_snapshot.anchor_after(start_offset);
2765 let end = buffer_snapshot.anchor_after(end_offset);
2766 linked_edits
2767 .entry(buffer.clone())
2768 .or_default()
2769 .push(start..end);
2770 }
2771 Some(linked_edits)
2772 }
2773
2774 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2775 let text: Arc<str> = text.into();
2776
2777 if self.read_only(cx) {
2778 return;
2779 }
2780
2781 let selections = self.selections.all_adjusted(cx);
2782 let mut bracket_inserted = false;
2783 let mut edits = Vec::new();
2784 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2785 let mut new_selections = Vec::with_capacity(selections.len());
2786 let mut new_autoclose_regions = Vec::new();
2787 let snapshot = self.buffer.read(cx).read(cx);
2788
2789 for (selection, autoclose_region) in
2790 self.selections_with_autoclose_regions(selections, &snapshot)
2791 {
2792 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2793 // Determine if the inserted text matches the opening or closing
2794 // bracket of any of this language's bracket pairs.
2795 let mut bracket_pair = None;
2796 let mut is_bracket_pair_start = false;
2797 let mut is_bracket_pair_end = false;
2798 if !text.is_empty() {
2799 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2800 // and they are removing the character that triggered IME popup.
2801 for (pair, enabled) in scope.brackets() {
2802 if !pair.close && !pair.surround {
2803 continue;
2804 }
2805
2806 if enabled && pair.start.ends_with(text.as_ref()) {
2807 let prefix_len = pair.start.len() - text.len();
2808 let preceding_text_matches_prefix = prefix_len == 0
2809 || (selection.start.column >= (prefix_len as u32)
2810 && snapshot.contains_str_at(
2811 Point::new(
2812 selection.start.row,
2813 selection.start.column - (prefix_len as u32),
2814 ),
2815 &pair.start[..prefix_len],
2816 ));
2817 if preceding_text_matches_prefix {
2818 bracket_pair = Some(pair.clone());
2819 is_bracket_pair_start = true;
2820 break;
2821 }
2822 }
2823 if pair.end.as_str() == text.as_ref() {
2824 bracket_pair = Some(pair.clone());
2825 is_bracket_pair_end = true;
2826 break;
2827 }
2828 }
2829 }
2830
2831 if let Some(bracket_pair) = bracket_pair {
2832 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2833 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2834 let auto_surround =
2835 self.use_auto_surround && snapshot_settings.use_auto_surround;
2836 if selection.is_empty() {
2837 if is_bracket_pair_start {
2838 // If the inserted text is a suffix of an opening bracket and the
2839 // selection is preceded by the rest of the opening bracket, then
2840 // insert the closing bracket.
2841 let following_text_allows_autoclose = snapshot
2842 .chars_at(selection.start)
2843 .next()
2844 .map_or(true, |c| scope.should_autoclose_before(c));
2845
2846 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2847 && bracket_pair.start.len() == 1
2848 {
2849 let target = bracket_pair.start.chars().next().unwrap();
2850 let current_line_count = snapshot
2851 .reversed_chars_at(selection.start)
2852 .take_while(|&c| c != '\n')
2853 .filter(|&c| c == target)
2854 .count();
2855 current_line_count % 2 == 1
2856 } else {
2857 false
2858 };
2859
2860 if autoclose
2861 && bracket_pair.close
2862 && following_text_allows_autoclose
2863 && !is_closing_quote
2864 {
2865 let anchor = snapshot.anchor_before(selection.end);
2866 new_selections.push((selection.map(|_| anchor), text.len()));
2867 new_autoclose_regions.push((
2868 anchor,
2869 text.len(),
2870 selection.id,
2871 bracket_pair.clone(),
2872 ));
2873 edits.push((
2874 selection.range(),
2875 format!("{}{}", text, bracket_pair.end).into(),
2876 ));
2877 bracket_inserted = true;
2878 continue;
2879 }
2880 }
2881
2882 if let Some(region) = autoclose_region {
2883 // If the selection is followed by an auto-inserted closing bracket,
2884 // then don't insert that closing bracket again; just move the selection
2885 // past the closing bracket.
2886 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2887 && text.as_ref() == region.pair.end.as_str();
2888 if should_skip {
2889 let anchor = snapshot.anchor_after(selection.end);
2890 new_selections
2891 .push((selection.map(|_| anchor), region.pair.end.len()));
2892 continue;
2893 }
2894 }
2895
2896 let always_treat_brackets_as_autoclosed = snapshot
2897 .settings_at(selection.start, cx)
2898 .always_treat_brackets_as_autoclosed;
2899 if always_treat_brackets_as_autoclosed
2900 && is_bracket_pair_end
2901 && snapshot.contains_str_at(selection.end, text.as_ref())
2902 {
2903 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2904 // and the inserted text is a closing bracket and the selection is followed
2905 // by the closing bracket then move the selection past the closing bracket.
2906 let anchor = snapshot.anchor_after(selection.end);
2907 new_selections.push((selection.map(|_| anchor), text.len()));
2908 continue;
2909 }
2910 }
2911 // If an opening bracket is 1 character long and is typed while
2912 // text is selected, then surround that text with the bracket pair.
2913 else if auto_surround
2914 && bracket_pair.surround
2915 && is_bracket_pair_start
2916 && bracket_pair.start.chars().count() == 1
2917 {
2918 edits.push((selection.start..selection.start, text.clone()));
2919 edits.push((
2920 selection.end..selection.end,
2921 bracket_pair.end.as_str().into(),
2922 ));
2923 bracket_inserted = true;
2924 new_selections.push((
2925 Selection {
2926 id: selection.id,
2927 start: snapshot.anchor_after(selection.start),
2928 end: snapshot.anchor_before(selection.end),
2929 reversed: selection.reversed,
2930 goal: selection.goal,
2931 },
2932 0,
2933 ));
2934 continue;
2935 }
2936 }
2937 }
2938
2939 if self.auto_replace_emoji_shortcode
2940 && selection.is_empty()
2941 && text.as_ref().ends_with(':')
2942 {
2943 if let Some(possible_emoji_short_code) =
2944 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2945 {
2946 if !possible_emoji_short_code.is_empty() {
2947 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2948 let emoji_shortcode_start = Point::new(
2949 selection.start.row,
2950 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2951 );
2952
2953 // Remove shortcode from buffer
2954 edits.push((
2955 emoji_shortcode_start..selection.start,
2956 "".to_string().into(),
2957 ));
2958 new_selections.push((
2959 Selection {
2960 id: selection.id,
2961 start: snapshot.anchor_after(emoji_shortcode_start),
2962 end: snapshot.anchor_before(selection.start),
2963 reversed: selection.reversed,
2964 goal: selection.goal,
2965 },
2966 0,
2967 ));
2968
2969 // Insert emoji
2970 let selection_start_anchor = snapshot.anchor_after(selection.start);
2971 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2972 edits.push((selection.start..selection.end, emoji.to_string().into()));
2973
2974 continue;
2975 }
2976 }
2977 }
2978 }
2979
2980 // If not handling any auto-close operation, then just replace the selected
2981 // text with the given input and move the selection to the end of the
2982 // newly inserted text.
2983 let anchor = snapshot.anchor_after(selection.end);
2984 if !self.linked_edit_ranges.is_empty() {
2985 let start_anchor = snapshot.anchor_before(selection.start);
2986
2987 let is_word_char = text.chars().next().map_or(true, |char| {
2988 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2989 classifier.is_word(char)
2990 });
2991
2992 if is_word_char {
2993 if let Some(ranges) = self
2994 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2995 {
2996 for (buffer, edits) in ranges {
2997 linked_edits
2998 .entry(buffer.clone())
2999 .or_default()
3000 .extend(edits.into_iter().map(|range| (range, text.clone())));
3001 }
3002 }
3003 }
3004 }
3005
3006 new_selections.push((selection.map(|_| anchor), 0));
3007 edits.push((selection.start..selection.end, text.clone()));
3008 }
3009
3010 drop(snapshot);
3011
3012 self.transact(window, cx, |this, window, cx| {
3013 this.buffer.update(cx, |buffer, cx| {
3014 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3015 });
3016 for (buffer, edits) in linked_edits {
3017 buffer.update(cx, |buffer, cx| {
3018 let snapshot = buffer.snapshot();
3019 let edits = edits
3020 .into_iter()
3021 .map(|(range, text)| {
3022 use text::ToPoint as TP;
3023 let end_point = TP::to_point(&range.end, &snapshot);
3024 let start_point = TP::to_point(&range.start, &snapshot);
3025 (start_point..end_point, text)
3026 })
3027 .sorted_by_key(|(range, _)| range.start)
3028 .collect::<Vec<_>>();
3029 buffer.edit(edits, None, cx);
3030 })
3031 }
3032 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3033 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3034 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3035 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3036 .zip(new_selection_deltas)
3037 .map(|(selection, delta)| Selection {
3038 id: selection.id,
3039 start: selection.start + delta,
3040 end: selection.end + delta,
3041 reversed: selection.reversed,
3042 goal: SelectionGoal::None,
3043 })
3044 .collect::<Vec<_>>();
3045
3046 let mut i = 0;
3047 for (position, delta, selection_id, pair) in new_autoclose_regions {
3048 let position = position.to_offset(&map.buffer_snapshot) + delta;
3049 let start = map.buffer_snapshot.anchor_before(position);
3050 let end = map.buffer_snapshot.anchor_after(position);
3051 while let Some(existing_state) = this.autoclose_regions.get(i) {
3052 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3053 Ordering::Less => i += 1,
3054 Ordering::Greater => break,
3055 Ordering::Equal => {
3056 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3057 Ordering::Less => i += 1,
3058 Ordering::Equal => break,
3059 Ordering::Greater => break,
3060 }
3061 }
3062 }
3063 }
3064 this.autoclose_regions.insert(
3065 i,
3066 AutocloseRegion {
3067 selection_id,
3068 range: start..end,
3069 pair,
3070 },
3071 );
3072 }
3073
3074 let had_active_inline_completion = this.has_active_inline_completion();
3075 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3076 s.select(new_selections)
3077 });
3078
3079 if !bracket_inserted {
3080 if let Some(on_type_format_task) =
3081 this.trigger_on_type_formatting(text.to_string(), window, cx)
3082 {
3083 on_type_format_task.detach_and_log_err(cx);
3084 }
3085 }
3086
3087 let editor_settings = EditorSettings::get_global(cx);
3088 if bracket_inserted
3089 && (editor_settings.auto_signature_help
3090 || editor_settings.show_signature_help_after_edits)
3091 {
3092 this.show_signature_help(&ShowSignatureHelp, window, cx);
3093 }
3094
3095 let trigger_in_words =
3096 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3097 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3098 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3099 this.refresh_inline_completion(true, false, window, cx);
3100 });
3101 }
3102
3103 fn find_possible_emoji_shortcode_at_position(
3104 snapshot: &MultiBufferSnapshot,
3105 position: Point,
3106 ) -> Option<String> {
3107 let mut chars = Vec::new();
3108 let mut found_colon = false;
3109 for char in snapshot.reversed_chars_at(position).take(100) {
3110 // Found a possible emoji shortcode in the middle of the buffer
3111 if found_colon {
3112 if char.is_whitespace() {
3113 chars.reverse();
3114 return Some(chars.iter().collect());
3115 }
3116 // If the previous character is not a whitespace, we are in the middle of a word
3117 // and we only want to complete the shortcode if the word is made up of other emojis
3118 let mut containing_word = String::new();
3119 for ch in snapshot
3120 .reversed_chars_at(position)
3121 .skip(chars.len() + 1)
3122 .take(100)
3123 {
3124 if ch.is_whitespace() {
3125 break;
3126 }
3127 containing_word.push(ch);
3128 }
3129 let containing_word = containing_word.chars().rev().collect::<String>();
3130 if util::word_consists_of_emojis(containing_word.as_str()) {
3131 chars.reverse();
3132 return Some(chars.iter().collect());
3133 }
3134 }
3135
3136 if char.is_whitespace() || !char.is_ascii() {
3137 return None;
3138 }
3139 if char == ':' {
3140 found_colon = true;
3141 } else {
3142 chars.push(char);
3143 }
3144 }
3145 // Found a possible emoji shortcode at the beginning of the buffer
3146 chars.reverse();
3147 Some(chars.iter().collect())
3148 }
3149
3150 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3151 self.transact(window, cx, |this, window, cx| {
3152 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3153 let selections = this.selections.all::<usize>(cx);
3154 let multi_buffer = this.buffer.read(cx);
3155 let buffer = multi_buffer.snapshot(cx);
3156 selections
3157 .iter()
3158 .map(|selection| {
3159 let start_point = selection.start.to_point(&buffer);
3160 let mut indent =
3161 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3162 indent.len = cmp::min(indent.len, start_point.column);
3163 let start = selection.start;
3164 let end = selection.end;
3165 let selection_is_empty = start == end;
3166 let language_scope = buffer.language_scope_at(start);
3167 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3168 &language_scope
3169 {
3170 let leading_whitespace_len = buffer
3171 .reversed_chars_at(start)
3172 .take_while(|c| c.is_whitespace() && *c != '\n')
3173 .map(|c| c.len_utf8())
3174 .sum::<usize>();
3175
3176 let trailing_whitespace_len = buffer
3177 .chars_at(end)
3178 .take_while(|c| c.is_whitespace() && *c != '\n')
3179 .map(|c| c.len_utf8())
3180 .sum::<usize>();
3181
3182 let insert_extra_newline =
3183 language.brackets().any(|(pair, enabled)| {
3184 let pair_start = pair.start.trim_end();
3185 let pair_end = pair.end.trim_start();
3186
3187 enabled
3188 && pair.newline
3189 && buffer.contains_str_at(
3190 end + trailing_whitespace_len,
3191 pair_end,
3192 )
3193 && buffer.contains_str_at(
3194 (start - leading_whitespace_len)
3195 .saturating_sub(pair_start.len()),
3196 pair_start,
3197 )
3198 });
3199
3200 // Comment extension on newline is allowed only for cursor selections
3201 let comment_delimiter = maybe!({
3202 if !selection_is_empty {
3203 return None;
3204 }
3205
3206 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3207 return None;
3208 }
3209
3210 let delimiters = language.line_comment_prefixes();
3211 let max_len_of_delimiter =
3212 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3213 let (snapshot, range) =
3214 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3215
3216 let mut index_of_first_non_whitespace = 0;
3217 let comment_candidate = snapshot
3218 .chars_for_range(range)
3219 .skip_while(|c| {
3220 let should_skip = c.is_whitespace();
3221 if should_skip {
3222 index_of_first_non_whitespace += 1;
3223 }
3224 should_skip
3225 })
3226 .take(max_len_of_delimiter)
3227 .collect::<String>();
3228 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3229 comment_candidate.starts_with(comment_prefix.as_ref())
3230 })?;
3231 let cursor_is_placed_after_comment_marker =
3232 index_of_first_non_whitespace + comment_prefix.len()
3233 <= start_point.column as usize;
3234 if cursor_is_placed_after_comment_marker {
3235 Some(comment_prefix.clone())
3236 } else {
3237 None
3238 }
3239 });
3240 (comment_delimiter, insert_extra_newline)
3241 } else {
3242 (None, false)
3243 };
3244
3245 let capacity_for_delimiter = comment_delimiter
3246 .as_deref()
3247 .map(str::len)
3248 .unwrap_or_default();
3249 let mut new_text =
3250 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3251 new_text.push('\n');
3252 new_text.extend(indent.chars());
3253 if let Some(delimiter) = &comment_delimiter {
3254 new_text.push_str(delimiter);
3255 }
3256 if insert_extra_newline {
3257 new_text = new_text.repeat(2);
3258 }
3259
3260 let anchor = buffer.anchor_after(end);
3261 let new_selection = selection.map(|_| anchor);
3262 (
3263 (start..end, new_text),
3264 (insert_extra_newline, new_selection),
3265 )
3266 })
3267 .unzip()
3268 };
3269
3270 this.edit_with_autoindent(edits, cx);
3271 let buffer = this.buffer.read(cx).snapshot(cx);
3272 let new_selections = selection_fixup_info
3273 .into_iter()
3274 .map(|(extra_newline_inserted, new_selection)| {
3275 let mut cursor = new_selection.end.to_point(&buffer);
3276 if extra_newline_inserted {
3277 cursor.row -= 1;
3278 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3279 }
3280 new_selection.map(|_| cursor)
3281 })
3282 .collect();
3283
3284 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3285 s.select(new_selections)
3286 });
3287 this.refresh_inline_completion(true, false, window, cx);
3288 });
3289 }
3290
3291 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3292 let buffer = self.buffer.read(cx);
3293 let snapshot = buffer.snapshot(cx);
3294
3295 let mut edits = Vec::new();
3296 let mut rows = Vec::new();
3297
3298 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3299 let cursor = selection.head();
3300 let row = cursor.row;
3301
3302 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3303
3304 let newline = "\n".to_string();
3305 edits.push((start_of_line..start_of_line, newline));
3306
3307 rows.push(row + rows_inserted as u32);
3308 }
3309
3310 self.transact(window, cx, |editor, window, cx| {
3311 editor.edit(edits, cx);
3312
3313 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3314 let mut index = 0;
3315 s.move_cursors_with(|map, _, _| {
3316 let row = rows[index];
3317 index += 1;
3318
3319 let point = Point::new(row, 0);
3320 let boundary = map.next_line_boundary(point).1;
3321 let clipped = map.clip_point(boundary, Bias::Left);
3322
3323 (clipped, SelectionGoal::None)
3324 });
3325 });
3326
3327 let mut indent_edits = Vec::new();
3328 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3329 for row in rows {
3330 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3331 for (row, indent) in indents {
3332 if indent.len == 0 {
3333 continue;
3334 }
3335
3336 let text = match indent.kind {
3337 IndentKind::Space => " ".repeat(indent.len as usize),
3338 IndentKind::Tab => "\t".repeat(indent.len as usize),
3339 };
3340 let point = Point::new(row.0, 0);
3341 indent_edits.push((point..point, text));
3342 }
3343 }
3344 editor.edit(indent_edits, cx);
3345 });
3346 }
3347
3348 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3349 let buffer = self.buffer.read(cx);
3350 let snapshot = buffer.snapshot(cx);
3351
3352 let mut edits = Vec::new();
3353 let mut rows = Vec::new();
3354 let mut rows_inserted = 0;
3355
3356 for selection in self.selections.all_adjusted(cx) {
3357 let cursor = selection.head();
3358 let row = cursor.row;
3359
3360 let point = Point::new(row + 1, 0);
3361 let start_of_line = snapshot.clip_point(point, Bias::Left);
3362
3363 let newline = "\n".to_string();
3364 edits.push((start_of_line..start_of_line, newline));
3365
3366 rows_inserted += 1;
3367 rows.push(row + rows_inserted);
3368 }
3369
3370 self.transact(window, cx, |editor, window, cx| {
3371 editor.edit(edits, cx);
3372
3373 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3374 let mut index = 0;
3375 s.move_cursors_with(|map, _, _| {
3376 let row = rows[index];
3377 index += 1;
3378
3379 let point = Point::new(row, 0);
3380 let boundary = map.next_line_boundary(point).1;
3381 let clipped = map.clip_point(boundary, Bias::Left);
3382
3383 (clipped, SelectionGoal::None)
3384 });
3385 });
3386
3387 let mut indent_edits = Vec::new();
3388 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3389 for row in rows {
3390 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3391 for (row, indent) in indents {
3392 if indent.len == 0 {
3393 continue;
3394 }
3395
3396 let text = match indent.kind {
3397 IndentKind::Space => " ".repeat(indent.len as usize),
3398 IndentKind::Tab => "\t".repeat(indent.len as usize),
3399 };
3400 let point = Point::new(row.0, 0);
3401 indent_edits.push((point..point, text));
3402 }
3403 }
3404 editor.edit(indent_edits, cx);
3405 });
3406 }
3407
3408 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3409 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3410 original_indent_columns: Vec::new(),
3411 });
3412 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3413 }
3414
3415 fn insert_with_autoindent_mode(
3416 &mut self,
3417 text: &str,
3418 autoindent_mode: Option<AutoindentMode>,
3419 window: &mut Window,
3420 cx: &mut Context<Self>,
3421 ) {
3422 if self.read_only(cx) {
3423 return;
3424 }
3425
3426 let text: Arc<str> = text.into();
3427 self.transact(window, cx, |this, window, cx| {
3428 let old_selections = this.selections.all_adjusted(cx);
3429 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3430 let anchors = {
3431 let snapshot = buffer.read(cx);
3432 old_selections
3433 .iter()
3434 .map(|s| {
3435 let anchor = snapshot.anchor_after(s.head());
3436 s.map(|_| anchor)
3437 })
3438 .collect::<Vec<_>>()
3439 };
3440 buffer.edit(
3441 old_selections
3442 .iter()
3443 .map(|s| (s.start..s.end, text.clone())),
3444 autoindent_mode,
3445 cx,
3446 );
3447 anchors
3448 });
3449
3450 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3451 s.select_anchors(selection_anchors);
3452 });
3453
3454 cx.notify();
3455 });
3456 }
3457
3458 fn trigger_completion_on_input(
3459 &mut self,
3460 text: &str,
3461 trigger_in_words: bool,
3462 window: &mut Window,
3463 cx: &mut Context<Self>,
3464 ) {
3465 if self.is_completion_trigger(text, trigger_in_words, cx) {
3466 self.show_completions(
3467 &ShowCompletions {
3468 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3469 },
3470 window,
3471 cx,
3472 );
3473 } else {
3474 self.hide_context_menu(window, cx);
3475 }
3476 }
3477
3478 fn is_completion_trigger(
3479 &self,
3480 text: &str,
3481 trigger_in_words: bool,
3482 cx: &mut Context<Self>,
3483 ) -> bool {
3484 let position = self.selections.newest_anchor().head();
3485 let multibuffer = self.buffer.read(cx);
3486 let Some(buffer) = position
3487 .buffer_id
3488 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3489 else {
3490 return false;
3491 };
3492
3493 if let Some(completion_provider) = &self.completion_provider {
3494 completion_provider.is_completion_trigger(
3495 &buffer,
3496 position.text_anchor,
3497 text,
3498 trigger_in_words,
3499 cx,
3500 )
3501 } else {
3502 false
3503 }
3504 }
3505
3506 /// If any empty selections is touching the start of its innermost containing autoclose
3507 /// region, expand it to select the brackets.
3508 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3509 let selections = self.selections.all::<usize>(cx);
3510 let buffer = self.buffer.read(cx).read(cx);
3511 let new_selections = self
3512 .selections_with_autoclose_regions(selections, &buffer)
3513 .map(|(mut selection, region)| {
3514 if !selection.is_empty() {
3515 return selection;
3516 }
3517
3518 if let Some(region) = region {
3519 let mut range = region.range.to_offset(&buffer);
3520 if selection.start == range.start && range.start >= region.pair.start.len() {
3521 range.start -= region.pair.start.len();
3522 if buffer.contains_str_at(range.start, ®ion.pair.start)
3523 && buffer.contains_str_at(range.end, ®ion.pair.end)
3524 {
3525 range.end += region.pair.end.len();
3526 selection.start = range.start;
3527 selection.end = range.end;
3528
3529 return selection;
3530 }
3531 }
3532 }
3533
3534 let always_treat_brackets_as_autoclosed = buffer
3535 .settings_at(selection.start, cx)
3536 .always_treat_brackets_as_autoclosed;
3537
3538 if !always_treat_brackets_as_autoclosed {
3539 return selection;
3540 }
3541
3542 if let Some(scope) = buffer.language_scope_at(selection.start) {
3543 for (pair, enabled) in scope.brackets() {
3544 if !enabled || !pair.close {
3545 continue;
3546 }
3547
3548 if buffer.contains_str_at(selection.start, &pair.end) {
3549 let pair_start_len = pair.start.len();
3550 if buffer.contains_str_at(
3551 selection.start.saturating_sub(pair_start_len),
3552 &pair.start,
3553 ) {
3554 selection.start -= pair_start_len;
3555 selection.end += pair.end.len();
3556
3557 return selection;
3558 }
3559 }
3560 }
3561 }
3562
3563 selection
3564 })
3565 .collect();
3566
3567 drop(buffer);
3568 self.change_selections(None, window, cx, |selections| {
3569 selections.select(new_selections)
3570 });
3571 }
3572
3573 /// Iterate the given selections, and for each one, find the smallest surrounding
3574 /// autoclose region. This uses the ordering of the selections and the autoclose
3575 /// regions to avoid repeated comparisons.
3576 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3577 &'a self,
3578 selections: impl IntoIterator<Item = Selection<D>>,
3579 buffer: &'a MultiBufferSnapshot,
3580 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3581 let mut i = 0;
3582 let mut regions = self.autoclose_regions.as_slice();
3583 selections.into_iter().map(move |selection| {
3584 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3585
3586 let mut enclosing = None;
3587 while let Some(pair_state) = regions.get(i) {
3588 if pair_state.range.end.to_offset(buffer) < range.start {
3589 regions = ®ions[i + 1..];
3590 i = 0;
3591 } else if pair_state.range.start.to_offset(buffer) > range.end {
3592 break;
3593 } else {
3594 if pair_state.selection_id == selection.id {
3595 enclosing = Some(pair_state);
3596 }
3597 i += 1;
3598 }
3599 }
3600
3601 (selection, enclosing)
3602 })
3603 }
3604
3605 /// Remove any autoclose regions that no longer contain their selection.
3606 fn invalidate_autoclose_regions(
3607 &mut self,
3608 mut selections: &[Selection<Anchor>],
3609 buffer: &MultiBufferSnapshot,
3610 ) {
3611 self.autoclose_regions.retain(|state| {
3612 let mut i = 0;
3613 while let Some(selection) = selections.get(i) {
3614 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3615 selections = &selections[1..];
3616 continue;
3617 }
3618 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3619 break;
3620 }
3621 if selection.id == state.selection_id {
3622 return true;
3623 } else {
3624 i += 1;
3625 }
3626 }
3627 false
3628 });
3629 }
3630
3631 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3632 let offset = position.to_offset(buffer);
3633 let (word_range, kind) = buffer.surrounding_word(offset, true);
3634 if offset > word_range.start && kind == Some(CharKind::Word) {
3635 Some(
3636 buffer
3637 .text_for_range(word_range.start..offset)
3638 .collect::<String>(),
3639 )
3640 } else {
3641 None
3642 }
3643 }
3644
3645 pub fn toggle_inlay_hints(
3646 &mut self,
3647 _: &ToggleInlayHints,
3648 _: &mut Window,
3649 cx: &mut Context<Self>,
3650 ) {
3651 self.refresh_inlay_hints(
3652 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3653 cx,
3654 );
3655 }
3656
3657 pub fn inlay_hints_enabled(&self) -> bool {
3658 self.inlay_hint_cache.enabled
3659 }
3660
3661 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3662 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3663 return;
3664 }
3665
3666 let reason_description = reason.description();
3667 let ignore_debounce = matches!(
3668 reason,
3669 InlayHintRefreshReason::SettingsChange(_)
3670 | InlayHintRefreshReason::Toggle(_)
3671 | InlayHintRefreshReason::ExcerptsRemoved(_)
3672 );
3673 let (invalidate_cache, required_languages) = match reason {
3674 InlayHintRefreshReason::Toggle(enabled) => {
3675 self.inlay_hint_cache.enabled = enabled;
3676 if enabled {
3677 (InvalidationStrategy::RefreshRequested, None)
3678 } else {
3679 self.inlay_hint_cache.clear();
3680 self.splice_inlays(
3681 &self
3682 .visible_inlay_hints(cx)
3683 .iter()
3684 .map(|inlay| inlay.id)
3685 .collect::<Vec<InlayId>>(),
3686 Vec::new(),
3687 cx,
3688 );
3689 return;
3690 }
3691 }
3692 InlayHintRefreshReason::SettingsChange(new_settings) => {
3693 match self.inlay_hint_cache.update_settings(
3694 &self.buffer,
3695 new_settings,
3696 self.visible_inlay_hints(cx),
3697 cx,
3698 ) {
3699 ControlFlow::Break(Some(InlaySplice {
3700 to_remove,
3701 to_insert,
3702 })) => {
3703 self.splice_inlays(&to_remove, to_insert, cx);
3704 return;
3705 }
3706 ControlFlow::Break(None) => return,
3707 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3708 }
3709 }
3710 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3711 if let Some(InlaySplice {
3712 to_remove,
3713 to_insert,
3714 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3715 {
3716 self.splice_inlays(&to_remove, to_insert, cx);
3717 }
3718 return;
3719 }
3720 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3721 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3722 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3723 }
3724 InlayHintRefreshReason::RefreshRequested => {
3725 (InvalidationStrategy::RefreshRequested, None)
3726 }
3727 };
3728
3729 if let Some(InlaySplice {
3730 to_remove,
3731 to_insert,
3732 }) = self.inlay_hint_cache.spawn_hint_refresh(
3733 reason_description,
3734 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3735 invalidate_cache,
3736 ignore_debounce,
3737 cx,
3738 ) {
3739 self.splice_inlays(&to_remove, to_insert, cx);
3740 }
3741 }
3742
3743 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3744 self.display_map
3745 .read(cx)
3746 .current_inlays()
3747 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3748 .cloned()
3749 .collect()
3750 }
3751
3752 pub fn excerpts_for_inlay_hints_query(
3753 &self,
3754 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3755 cx: &mut Context<Editor>,
3756 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3757 let Some(project) = self.project.as_ref() else {
3758 return HashMap::default();
3759 };
3760 let project = project.read(cx);
3761 let multi_buffer = self.buffer().read(cx);
3762 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3763 let multi_buffer_visible_start = self
3764 .scroll_manager
3765 .anchor()
3766 .anchor
3767 .to_point(&multi_buffer_snapshot);
3768 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3769 multi_buffer_visible_start
3770 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3771 Bias::Left,
3772 );
3773 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3774 multi_buffer_snapshot
3775 .range_to_buffer_ranges(multi_buffer_visible_range)
3776 .into_iter()
3777 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3778 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3779 let buffer_file = project::File::from_dyn(buffer.file())?;
3780 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3781 let worktree_entry = buffer_worktree
3782 .read(cx)
3783 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3784 if worktree_entry.is_ignored {
3785 return None;
3786 }
3787
3788 let language = buffer.language()?;
3789 if let Some(restrict_to_languages) = restrict_to_languages {
3790 if !restrict_to_languages.contains(language) {
3791 return None;
3792 }
3793 }
3794 Some((
3795 excerpt_id,
3796 (
3797 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3798 buffer.version().clone(),
3799 excerpt_visible_range,
3800 ),
3801 ))
3802 })
3803 .collect()
3804 }
3805
3806 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3807 TextLayoutDetails {
3808 text_system: window.text_system().clone(),
3809 editor_style: self.style.clone().unwrap(),
3810 rem_size: window.rem_size(),
3811 scroll_anchor: self.scroll_manager.anchor(),
3812 visible_rows: self.visible_line_count(),
3813 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3814 }
3815 }
3816
3817 pub fn splice_inlays(
3818 &self,
3819 to_remove: &[InlayId],
3820 to_insert: Vec<Inlay>,
3821 cx: &mut Context<Self>,
3822 ) {
3823 self.display_map.update(cx, |display_map, cx| {
3824 display_map.splice_inlays(to_remove, to_insert, cx)
3825 });
3826 cx.notify();
3827 }
3828
3829 fn trigger_on_type_formatting(
3830 &self,
3831 input: String,
3832 window: &mut Window,
3833 cx: &mut Context<Self>,
3834 ) -> Option<Task<Result<()>>> {
3835 if input.len() != 1 {
3836 return None;
3837 }
3838
3839 let project = self.project.as_ref()?;
3840 let position = self.selections.newest_anchor().head();
3841 let (buffer, buffer_position) = self
3842 .buffer
3843 .read(cx)
3844 .text_anchor_for_position(position, cx)?;
3845
3846 let settings = language_settings::language_settings(
3847 buffer
3848 .read(cx)
3849 .language_at(buffer_position)
3850 .map(|l| l.name()),
3851 buffer.read(cx).file(),
3852 cx,
3853 );
3854 if !settings.use_on_type_format {
3855 return None;
3856 }
3857
3858 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3859 // hence we do LSP request & edit on host side only — add formats to host's history.
3860 let push_to_lsp_host_history = true;
3861 // If this is not the host, append its history with new edits.
3862 let push_to_client_history = project.read(cx).is_via_collab();
3863
3864 let on_type_formatting = project.update(cx, |project, cx| {
3865 project.on_type_format(
3866 buffer.clone(),
3867 buffer_position,
3868 input,
3869 push_to_lsp_host_history,
3870 cx,
3871 )
3872 });
3873 Some(cx.spawn_in(window, |editor, mut cx| async move {
3874 if let Some(transaction) = on_type_formatting.await? {
3875 if push_to_client_history {
3876 buffer
3877 .update(&mut cx, |buffer, _| {
3878 buffer.push_transaction(transaction, Instant::now());
3879 })
3880 .ok();
3881 }
3882 editor.update(&mut cx, |editor, cx| {
3883 editor.refresh_document_highlights(cx);
3884 })?;
3885 }
3886 Ok(())
3887 }))
3888 }
3889
3890 pub fn show_completions(
3891 &mut self,
3892 options: &ShowCompletions,
3893 window: &mut Window,
3894 cx: &mut Context<Self>,
3895 ) {
3896 if self.pending_rename.is_some() {
3897 return;
3898 }
3899
3900 let Some(provider) = self.completion_provider.as_ref() else {
3901 return;
3902 };
3903
3904 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3905 return;
3906 }
3907
3908 let position = self.selections.newest_anchor().head();
3909 if position.diff_base_anchor.is_some() {
3910 return;
3911 }
3912 let (buffer, buffer_position) =
3913 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3914 output
3915 } else {
3916 return;
3917 };
3918 let show_completion_documentation = buffer
3919 .read(cx)
3920 .snapshot()
3921 .settings_at(buffer_position, cx)
3922 .show_completion_documentation;
3923
3924 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3925
3926 let trigger_kind = match &options.trigger {
3927 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3928 CompletionTriggerKind::TRIGGER_CHARACTER
3929 }
3930 _ => CompletionTriggerKind::INVOKED,
3931 };
3932 let completion_context = CompletionContext {
3933 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3934 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3935 Some(String::from(trigger))
3936 } else {
3937 None
3938 }
3939 }),
3940 trigger_kind,
3941 };
3942 let completions =
3943 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3944 let sort_completions = provider.sort_completions();
3945
3946 let id = post_inc(&mut self.next_completion_id);
3947 let task = cx.spawn_in(window, |editor, mut cx| {
3948 async move {
3949 editor.update(&mut cx, |this, _| {
3950 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3951 })?;
3952 let completions = completions.await.log_err();
3953 let menu = if let Some(completions) = completions {
3954 let mut menu = CompletionsMenu::new(
3955 id,
3956 sort_completions,
3957 show_completion_documentation,
3958 position,
3959 buffer.clone(),
3960 completions.into(),
3961 );
3962
3963 menu.filter(query.as_deref(), cx.background_executor().clone())
3964 .await;
3965
3966 menu.visible().then_some(menu)
3967 } else {
3968 None
3969 };
3970
3971 editor.update_in(&mut cx, |editor, window, cx| {
3972 match editor.context_menu.borrow().as_ref() {
3973 None => {}
3974 Some(CodeContextMenu::Completions(prev_menu)) => {
3975 if prev_menu.id > id {
3976 return;
3977 }
3978 }
3979 _ => return,
3980 }
3981
3982 if editor.focus_handle.is_focused(window) && menu.is_some() {
3983 let mut menu = menu.unwrap();
3984 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3985
3986 *editor.context_menu.borrow_mut() =
3987 Some(CodeContextMenu::Completions(menu));
3988
3989 if editor.show_edit_predictions_in_menu() {
3990 editor.update_visible_inline_completion(window, cx);
3991 } else {
3992 editor.discard_inline_completion(false, cx);
3993 }
3994
3995 cx.notify();
3996 } else if editor.completion_tasks.len() <= 1 {
3997 // If there are no more completion tasks and the last menu was
3998 // empty, we should hide it.
3999 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4000 // If it was already hidden and we don't show inline
4001 // completions in the menu, we should also show the
4002 // inline-completion when available.
4003 if was_hidden && editor.show_edit_predictions_in_menu() {
4004 editor.update_visible_inline_completion(window, cx);
4005 }
4006 }
4007 })?;
4008
4009 Ok::<_, anyhow::Error>(())
4010 }
4011 .log_err()
4012 });
4013
4014 self.completion_tasks.push((id, task));
4015 }
4016
4017 pub fn confirm_completion(
4018 &mut self,
4019 action: &ConfirmCompletion,
4020 window: &mut Window,
4021 cx: &mut Context<Self>,
4022 ) -> Option<Task<Result<()>>> {
4023 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4024 }
4025
4026 pub fn compose_completion(
4027 &mut self,
4028 action: &ComposeCompletion,
4029 window: &mut Window,
4030 cx: &mut Context<Self>,
4031 ) -> Option<Task<Result<()>>> {
4032 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4033 }
4034
4035 fn do_completion(
4036 &mut self,
4037 item_ix: Option<usize>,
4038 intent: CompletionIntent,
4039 window: &mut Window,
4040 cx: &mut Context<Editor>,
4041 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4042 use language::ToOffset as _;
4043
4044 let completions_menu =
4045 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4046 menu
4047 } else {
4048 return None;
4049 };
4050
4051 let entries = completions_menu.entries.borrow();
4052 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4053 if self.show_edit_predictions_in_menu() {
4054 self.discard_inline_completion(true, cx);
4055 }
4056 let candidate_id = mat.candidate_id;
4057 drop(entries);
4058
4059 let buffer_handle = completions_menu.buffer;
4060 let completion = completions_menu
4061 .completions
4062 .borrow()
4063 .get(candidate_id)?
4064 .clone();
4065 cx.stop_propagation();
4066
4067 let snippet;
4068 let text;
4069
4070 if completion.is_snippet() {
4071 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4072 text = snippet.as_ref().unwrap().text.clone();
4073 } else {
4074 snippet = None;
4075 text = completion.new_text.clone();
4076 };
4077 let selections = self.selections.all::<usize>(cx);
4078 let buffer = buffer_handle.read(cx);
4079 let old_range = completion.old_range.to_offset(buffer);
4080 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4081
4082 let newest_selection = self.selections.newest_anchor();
4083 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4084 return None;
4085 }
4086
4087 let lookbehind = newest_selection
4088 .start
4089 .text_anchor
4090 .to_offset(buffer)
4091 .saturating_sub(old_range.start);
4092 let lookahead = old_range
4093 .end
4094 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4095 let mut common_prefix_len = old_text
4096 .bytes()
4097 .zip(text.bytes())
4098 .take_while(|(a, b)| a == b)
4099 .count();
4100
4101 let snapshot = self.buffer.read(cx).snapshot(cx);
4102 let mut range_to_replace: Option<Range<isize>> = None;
4103 let mut ranges = Vec::new();
4104 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4105 for selection in &selections {
4106 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4107 let start = selection.start.saturating_sub(lookbehind);
4108 let end = selection.end + lookahead;
4109 if selection.id == newest_selection.id {
4110 range_to_replace = Some(
4111 ((start + common_prefix_len) as isize - selection.start as isize)
4112 ..(end as isize - selection.start as isize),
4113 );
4114 }
4115 ranges.push(start + common_prefix_len..end);
4116 } else {
4117 common_prefix_len = 0;
4118 ranges.clear();
4119 ranges.extend(selections.iter().map(|s| {
4120 if s.id == newest_selection.id {
4121 range_to_replace = Some(
4122 old_range.start.to_offset_utf16(&snapshot).0 as isize
4123 - selection.start as isize
4124 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4125 - selection.start as isize,
4126 );
4127 old_range.clone()
4128 } else {
4129 s.start..s.end
4130 }
4131 }));
4132 break;
4133 }
4134 if !self.linked_edit_ranges.is_empty() {
4135 let start_anchor = snapshot.anchor_before(selection.head());
4136 let end_anchor = snapshot.anchor_after(selection.tail());
4137 if let Some(ranges) = self
4138 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4139 {
4140 for (buffer, edits) in ranges {
4141 linked_edits.entry(buffer.clone()).or_default().extend(
4142 edits
4143 .into_iter()
4144 .map(|range| (range, text[common_prefix_len..].to_owned())),
4145 );
4146 }
4147 }
4148 }
4149 }
4150 let text = &text[common_prefix_len..];
4151
4152 cx.emit(EditorEvent::InputHandled {
4153 utf16_range_to_replace: range_to_replace,
4154 text: text.into(),
4155 });
4156
4157 self.transact(window, cx, |this, window, cx| {
4158 if let Some(mut snippet) = snippet {
4159 snippet.text = text.to_string();
4160 for tabstop in snippet
4161 .tabstops
4162 .iter_mut()
4163 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4164 {
4165 tabstop.start -= common_prefix_len as isize;
4166 tabstop.end -= common_prefix_len as isize;
4167 }
4168
4169 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4170 } else {
4171 this.buffer.update(cx, |buffer, cx| {
4172 buffer.edit(
4173 ranges.iter().map(|range| (range.clone(), text)),
4174 this.autoindent_mode.clone(),
4175 cx,
4176 );
4177 });
4178 }
4179 for (buffer, edits) in linked_edits {
4180 buffer.update(cx, |buffer, cx| {
4181 let snapshot = buffer.snapshot();
4182 let edits = edits
4183 .into_iter()
4184 .map(|(range, text)| {
4185 use text::ToPoint as TP;
4186 let end_point = TP::to_point(&range.end, &snapshot);
4187 let start_point = TP::to_point(&range.start, &snapshot);
4188 (start_point..end_point, text)
4189 })
4190 .sorted_by_key(|(range, _)| range.start)
4191 .collect::<Vec<_>>();
4192 buffer.edit(edits, None, cx);
4193 })
4194 }
4195
4196 this.refresh_inline_completion(true, false, window, cx);
4197 });
4198
4199 let show_new_completions_on_confirm = completion
4200 .confirm
4201 .as_ref()
4202 .map_or(false, |confirm| confirm(intent, window, cx));
4203 if show_new_completions_on_confirm {
4204 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4205 }
4206
4207 let provider = self.completion_provider.as_ref()?;
4208 drop(completion);
4209 let apply_edits = provider.apply_additional_edits_for_completion(
4210 buffer_handle,
4211 completions_menu.completions.clone(),
4212 candidate_id,
4213 true,
4214 cx,
4215 );
4216
4217 let editor_settings = EditorSettings::get_global(cx);
4218 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4219 // After the code completion is finished, users often want to know what signatures are needed.
4220 // so we should automatically call signature_help
4221 self.show_signature_help(&ShowSignatureHelp, window, cx);
4222 }
4223
4224 Some(cx.foreground_executor().spawn(async move {
4225 apply_edits.await?;
4226 Ok(())
4227 }))
4228 }
4229
4230 pub fn toggle_code_actions(
4231 &mut self,
4232 action: &ToggleCodeActions,
4233 window: &mut Window,
4234 cx: &mut Context<Self>,
4235 ) {
4236 let mut context_menu = self.context_menu.borrow_mut();
4237 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4238 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4239 // Toggle if we're selecting the same one
4240 *context_menu = None;
4241 cx.notify();
4242 return;
4243 } else {
4244 // Otherwise, clear it and start a new one
4245 *context_menu = None;
4246 cx.notify();
4247 }
4248 }
4249 drop(context_menu);
4250 let snapshot = self.snapshot(window, cx);
4251 let deployed_from_indicator = action.deployed_from_indicator;
4252 let mut task = self.code_actions_task.take();
4253 let action = action.clone();
4254 cx.spawn_in(window, |editor, mut cx| async move {
4255 while let Some(prev_task) = task {
4256 prev_task.await.log_err();
4257 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4258 }
4259
4260 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4261 if editor.focus_handle.is_focused(window) {
4262 let multibuffer_point = action
4263 .deployed_from_indicator
4264 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4265 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4266 let (buffer, buffer_row) = snapshot
4267 .buffer_snapshot
4268 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4269 .and_then(|(buffer_snapshot, range)| {
4270 editor
4271 .buffer
4272 .read(cx)
4273 .buffer(buffer_snapshot.remote_id())
4274 .map(|buffer| (buffer, range.start.row))
4275 })?;
4276 let (_, code_actions) = editor
4277 .available_code_actions
4278 .clone()
4279 .and_then(|(location, code_actions)| {
4280 let snapshot = location.buffer.read(cx).snapshot();
4281 let point_range = location.range.to_point(&snapshot);
4282 let point_range = point_range.start.row..=point_range.end.row;
4283 if point_range.contains(&buffer_row) {
4284 Some((location, code_actions))
4285 } else {
4286 None
4287 }
4288 })
4289 .unzip();
4290 let buffer_id = buffer.read(cx).remote_id();
4291 let tasks = editor
4292 .tasks
4293 .get(&(buffer_id, buffer_row))
4294 .map(|t| Arc::new(t.to_owned()));
4295 if tasks.is_none() && code_actions.is_none() {
4296 return None;
4297 }
4298
4299 editor.completion_tasks.clear();
4300 editor.discard_inline_completion(false, cx);
4301 let task_context =
4302 tasks
4303 .as_ref()
4304 .zip(editor.project.clone())
4305 .map(|(tasks, project)| {
4306 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4307 });
4308
4309 Some(cx.spawn_in(window, |editor, mut cx| async move {
4310 let task_context = match task_context {
4311 Some(task_context) => task_context.await,
4312 None => None,
4313 };
4314 let resolved_tasks =
4315 tasks.zip(task_context).map(|(tasks, task_context)| {
4316 Rc::new(ResolvedTasks {
4317 templates: tasks.resolve(&task_context).collect(),
4318 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4319 multibuffer_point.row,
4320 tasks.column,
4321 )),
4322 })
4323 });
4324 let spawn_straight_away = resolved_tasks
4325 .as_ref()
4326 .map_or(false, |tasks| tasks.templates.len() == 1)
4327 && code_actions
4328 .as_ref()
4329 .map_or(true, |actions| actions.is_empty());
4330 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4331 *editor.context_menu.borrow_mut() =
4332 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4333 buffer,
4334 actions: CodeActionContents {
4335 tasks: resolved_tasks,
4336 actions: code_actions,
4337 },
4338 selected_item: Default::default(),
4339 scroll_handle: UniformListScrollHandle::default(),
4340 deployed_from_indicator,
4341 }));
4342 if spawn_straight_away {
4343 if let Some(task) = editor.confirm_code_action(
4344 &ConfirmCodeAction { item_ix: Some(0) },
4345 window,
4346 cx,
4347 ) {
4348 cx.notify();
4349 return task;
4350 }
4351 }
4352 cx.notify();
4353 Task::ready(Ok(()))
4354 }) {
4355 task.await
4356 } else {
4357 Ok(())
4358 }
4359 }))
4360 } else {
4361 Some(Task::ready(Ok(())))
4362 }
4363 })?;
4364 if let Some(task) = spawned_test_task {
4365 task.await?;
4366 }
4367
4368 Ok::<_, anyhow::Error>(())
4369 })
4370 .detach_and_log_err(cx);
4371 }
4372
4373 pub fn confirm_code_action(
4374 &mut self,
4375 action: &ConfirmCodeAction,
4376 window: &mut Window,
4377 cx: &mut Context<Self>,
4378 ) -> Option<Task<Result<()>>> {
4379 let actions_menu =
4380 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4381 menu
4382 } else {
4383 return None;
4384 };
4385 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4386 let action = actions_menu.actions.get(action_ix)?;
4387 let title = action.label();
4388 let buffer = actions_menu.buffer;
4389 let workspace = self.workspace()?;
4390
4391 match action {
4392 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4393 workspace.update(cx, |workspace, cx| {
4394 workspace::tasks::schedule_resolved_task(
4395 workspace,
4396 task_source_kind,
4397 resolved_task,
4398 false,
4399 cx,
4400 );
4401
4402 Some(Task::ready(Ok(())))
4403 })
4404 }
4405 CodeActionsItem::CodeAction {
4406 excerpt_id,
4407 action,
4408 provider,
4409 } => {
4410 let apply_code_action =
4411 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4412 let workspace = workspace.downgrade();
4413 Some(cx.spawn_in(window, |editor, cx| async move {
4414 let project_transaction = apply_code_action.await?;
4415 Self::open_project_transaction(
4416 &editor,
4417 workspace,
4418 project_transaction,
4419 title,
4420 cx,
4421 )
4422 .await
4423 }))
4424 }
4425 }
4426 }
4427
4428 pub async fn open_project_transaction(
4429 this: &WeakEntity<Editor>,
4430 workspace: WeakEntity<Workspace>,
4431 transaction: ProjectTransaction,
4432 title: String,
4433 mut cx: AsyncWindowContext,
4434 ) -> Result<()> {
4435 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4436 cx.update(|_, cx| {
4437 entries.sort_unstable_by_key(|(buffer, _)| {
4438 buffer.read(cx).file().map(|f| f.path().clone())
4439 });
4440 })?;
4441
4442 // If the project transaction's edits are all contained within this editor, then
4443 // avoid opening a new editor to display them.
4444
4445 if let Some((buffer, transaction)) = entries.first() {
4446 if entries.len() == 1 {
4447 let excerpt = this.update(&mut cx, |editor, cx| {
4448 editor
4449 .buffer()
4450 .read(cx)
4451 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4452 })?;
4453 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4454 if excerpted_buffer == *buffer {
4455 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4456 let excerpt_range = excerpt_range.to_offset(buffer);
4457 buffer
4458 .edited_ranges_for_transaction::<usize>(transaction)
4459 .all(|range| {
4460 excerpt_range.start <= range.start
4461 && excerpt_range.end >= range.end
4462 })
4463 })?;
4464
4465 if all_edits_within_excerpt {
4466 return Ok(());
4467 }
4468 }
4469 }
4470 }
4471 } else {
4472 return Ok(());
4473 }
4474
4475 let mut ranges_to_highlight = Vec::new();
4476 let excerpt_buffer = cx.new(|cx| {
4477 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4478 for (buffer_handle, transaction) in &entries {
4479 let buffer = buffer_handle.read(cx);
4480 ranges_to_highlight.extend(
4481 multibuffer.push_excerpts_with_context_lines(
4482 buffer_handle.clone(),
4483 buffer
4484 .edited_ranges_for_transaction::<usize>(transaction)
4485 .collect(),
4486 DEFAULT_MULTIBUFFER_CONTEXT,
4487 cx,
4488 ),
4489 );
4490 }
4491 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4492 multibuffer
4493 })?;
4494
4495 workspace.update_in(&mut cx, |workspace, window, cx| {
4496 let project = workspace.project().clone();
4497 let editor = cx
4498 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4499 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4500 editor.update(cx, |editor, cx| {
4501 editor.highlight_background::<Self>(
4502 &ranges_to_highlight,
4503 |theme| theme.editor_highlighted_line_background,
4504 cx,
4505 );
4506 });
4507 })?;
4508
4509 Ok(())
4510 }
4511
4512 pub fn clear_code_action_providers(&mut self) {
4513 self.code_action_providers.clear();
4514 self.available_code_actions.take();
4515 }
4516
4517 pub fn add_code_action_provider(
4518 &mut self,
4519 provider: Rc<dyn CodeActionProvider>,
4520 window: &mut Window,
4521 cx: &mut Context<Self>,
4522 ) {
4523 if self
4524 .code_action_providers
4525 .iter()
4526 .any(|existing_provider| existing_provider.id() == provider.id())
4527 {
4528 return;
4529 }
4530
4531 self.code_action_providers.push(provider);
4532 self.refresh_code_actions(window, cx);
4533 }
4534
4535 pub fn remove_code_action_provider(
4536 &mut self,
4537 id: Arc<str>,
4538 window: &mut Window,
4539 cx: &mut Context<Self>,
4540 ) {
4541 self.code_action_providers
4542 .retain(|provider| provider.id() != id);
4543 self.refresh_code_actions(window, cx);
4544 }
4545
4546 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4547 let buffer = self.buffer.read(cx);
4548 let newest_selection = self.selections.newest_anchor().clone();
4549 if newest_selection.head().diff_base_anchor.is_some() {
4550 return None;
4551 }
4552 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4553 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4554 if start_buffer != end_buffer {
4555 return None;
4556 }
4557
4558 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4559 cx.background_executor()
4560 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4561 .await;
4562
4563 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4564 let providers = this.code_action_providers.clone();
4565 let tasks = this
4566 .code_action_providers
4567 .iter()
4568 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4569 .collect::<Vec<_>>();
4570 (providers, tasks)
4571 })?;
4572
4573 let mut actions = Vec::new();
4574 for (provider, provider_actions) in
4575 providers.into_iter().zip(future::join_all(tasks).await)
4576 {
4577 if let Some(provider_actions) = provider_actions.log_err() {
4578 actions.extend(provider_actions.into_iter().map(|action| {
4579 AvailableCodeAction {
4580 excerpt_id: newest_selection.start.excerpt_id,
4581 action,
4582 provider: provider.clone(),
4583 }
4584 }));
4585 }
4586 }
4587
4588 this.update(&mut cx, |this, cx| {
4589 this.available_code_actions = if actions.is_empty() {
4590 None
4591 } else {
4592 Some((
4593 Location {
4594 buffer: start_buffer,
4595 range: start..end,
4596 },
4597 actions.into(),
4598 ))
4599 };
4600 cx.notify();
4601 })
4602 }));
4603 None
4604 }
4605
4606 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4607 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4608 self.show_git_blame_inline = false;
4609
4610 self.show_git_blame_inline_delay_task =
4611 Some(cx.spawn_in(window, |this, mut cx| async move {
4612 cx.background_executor().timer(delay).await;
4613
4614 this.update(&mut cx, |this, cx| {
4615 this.show_git_blame_inline = true;
4616 cx.notify();
4617 })
4618 .log_err();
4619 }));
4620 }
4621 }
4622
4623 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4624 if self.pending_rename.is_some() {
4625 return None;
4626 }
4627
4628 let provider = self.semantics_provider.clone()?;
4629 let buffer = self.buffer.read(cx);
4630 let newest_selection = self.selections.newest_anchor().clone();
4631 let cursor_position = newest_selection.head();
4632 let (cursor_buffer, cursor_buffer_position) =
4633 buffer.text_anchor_for_position(cursor_position, cx)?;
4634 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4635 if cursor_buffer != tail_buffer {
4636 return None;
4637 }
4638 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4639 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4640 cx.background_executor()
4641 .timer(Duration::from_millis(debounce))
4642 .await;
4643
4644 let highlights = if let Some(highlights) = cx
4645 .update(|cx| {
4646 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4647 })
4648 .ok()
4649 .flatten()
4650 {
4651 highlights.await.log_err()
4652 } else {
4653 None
4654 };
4655
4656 if let Some(highlights) = highlights {
4657 this.update(&mut cx, |this, cx| {
4658 if this.pending_rename.is_some() {
4659 return;
4660 }
4661
4662 let buffer_id = cursor_position.buffer_id;
4663 let buffer = this.buffer.read(cx);
4664 if !buffer
4665 .text_anchor_for_position(cursor_position, cx)
4666 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4667 {
4668 return;
4669 }
4670
4671 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4672 let mut write_ranges = Vec::new();
4673 let mut read_ranges = Vec::new();
4674 for highlight in highlights {
4675 for (excerpt_id, excerpt_range) in
4676 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4677 {
4678 let start = highlight
4679 .range
4680 .start
4681 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4682 let end = highlight
4683 .range
4684 .end
4685 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4686 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4687 continue;
4688 }
4689
4690 let range = Anchor {
4691 buffer_id,
4692 excerpt_id,
4693 text_anchor: start,
4694 diff_base_anchor: None,
4695 }..Anchor {
4696 buffer_id,
4697 excerpt_id,
4698 text_anchor: end,
4699 diff_base_anchor: None,
4700 };
4701 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4702 write_ranges.push(range);
4703 } else {
4704 read_ranges.push(range);
4705 }
4706 }
4707 }
4708
4709 this.highlight_background::<DocumentHighlightRead>(
4710 &read_ranges,
4711 |theme| theme.editor_document_highlight_read_background,
4712 cx,
4713 );
4714 this.highlight_background::<DocumentHighlightWrite>(
4715 &write_ranges,
4716 |theme| theme.editor_document_highlight_write_background,
4717 cx,
4718 );
4719 cx.notify();
4720 })
4721 .log_err();
4722 }
4723 }));
4724 None
4725 }
4726
4727 pub fn refresh_inline_completion(
4728 &mut self,
4729 debounce: bool,
4730 user_requested: bool,
4731 window: &mut Window,
4732 cx: &mut Context<Self>,
4733 ) -> Option<()> {
4734 let provider = self.edit_prediction_provider()?;
4735 let cursor = self.selections.newest_anchor().head();
4736 let (buffer, cursor_buffer_position) =
4737 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4738
4739 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4740 self.discard_inline_completion(false, cx);
4741 return None;
4742 }
4743
4744 if !user_requested
4745 && (!self.should_show_edit_predictions()
4746 || !self.is_focused(window)
4747 || buffer.read(cx).is_empty())
4748 {
4749 self.discard_inline_completion(false, cx);
4750 return None;
4751 }
4752
4753 self.update_visible_inline_completion(window, cx);
4754 provider.refresh(
4755 self.project.clone(),
4756 buffer,
4757 cursor_buffer_position,
4758 debounce,
4759 cx,
4760 );
4761 Some(())
4762 }
4763
4764 fn show_edit_predictions_in_menu(&self) -> bool {
4765 match self.edit_prediction_settings {
4766 EditPredictionSettings::Disabled => false,
4767 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4768 }
4769 }
4770
4771 pub fn edit_predictions_enabled(&self) -> bool {
4772 match self.edit_prediction_settings {
4773 EditPredictionSettings::Disabled => false,
4774 EditPredictionSettings::Enabled { .. } => true,
4775 }
4776 }
4777
4778 fn edit_prediction_requires_modifier(&self) -> bool {
4779 match self.edit_prediction_settings {
4780 EditPredictionSettings::Disabled => false,
4781 EditPredictionSettings::Enabled {
4782 preview_requires_modifier,
4783 ..
4784 } => preview_requires_modifier,
4785 }
4786 }
4787
4788 fn edit_prediction_settings_at_position(
4789 &self,
4790 buffer: &Entity<Buffer>,
4791 buffer_position: language::Anchor,
4792 cx: &App,
4793 ) -> EditPredictionSettings {
4794 if self.mode != EditorMode::Full
4795 || !self.show_inline_completions_override.unwrap_or(true)
4796 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4797 {
4798 return EditPredictionSettings::Disabled;
4799 }
4800
4801 let buffer = buffer.read(cx);
4802
4803 let file = buffer.file();
4804
4805 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4806 return EditPredictionSettings::Disabled;
4807 };
4808
4809 let by_provider = matches!(
4810 self.menu_inline_completions_policy,
4811 MenuInlineCompletionsPolicy::ByProvider
4812 );
4813
4814 let show_in_menu = by_provider
4815 && self
4816 .edit_prediction_provider
4817 .as_ref()
4818 .map_or(false, |provider| {
4819 provider.provider.show_completions_in_menu()
4820 });
4821
4822 let preview_requires_modifier =
4823 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4824
4825 EditPredictionSettings::Enabled {
4826 show_in_menu,
4827 preview_requires_modifier,
4828 }
4829 }
4830
4831 fn should_show_edit_predictions(&self) -> bool {
4832 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4833 }
4834
4835 pub fn edit_prediction_preview_is_active(&self) -> bool {
4836 matches!(
4837 self.edit_prediction_preview,
4838 EditPredictionPreview::Active { .. }
4839 )
4840 }
4841
4842 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4843 let cursor = self.selections.newest_anchor().head();
4844 if let Some((buffer, cursor_position)) =
4845 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4846 {
4847 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4848 } else {
4849 false
4850 }
4851 }
4852
4853 fn inline_completions_enabled_in_buffer(
4854 &self,
4855 buffer: &Entity<Buffer>,
4856 buffer_position: language::Anchor,
4857 cx: &App,
4858 ) -> bool {
4859 maybe!({
4860 let provider = self.edit_prediction_provider()?;
4861 if !provider.is_enabled(&buffer, buffer_position, cx) {
4862 return Some(false);
4863 }
4864 let buffer = buffer.read(cx);
4865 let Some(file) = buffer.file() else {
4866 return Some(true);
4867 };
4868 let settings = all_language_settings(Some(file), cx);
4869 Some(settings.inline_completions_enabled_for_path(file.path()))
4870 })
4871 .unwrap_or(false)
4872 }
4873
4874 fn cycle_inline_completion(
4875 &mut self,
4876 direction: Direction,
4877 window: &mut Window,
4878 cx: &mut Context<Self>,
4879 ) -> Option<()> {
4880 let provider = self.edit_prediction_provider()?;
4881 let cursor = self.selections.newest_anchor().head();
4882 let (buffer, cursor_buffer_position) =
4883 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4884 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4885 return None;
4886 }
4887
4888 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4889 self.update_visible_inline_completion(window, cx);
4890
4891 Some(())
4892 }
4893
4894 pub fn show_inline_completion(
4895 &mut self,
4896 _: &ShowEditPrediction,
4897 window: &mut Window,
4898 cx: &mut Context<Self>,
4899 ) {
4900 if !self.has_active_inline_completion() {
4901 self.refresh_inline_completion(false, true, window, cx);
4902 return;
4903 }
4904
4905 self.update_visible_inline_completion(window, cx);
4906 }
4907
4908 pub fn display_cursor_names(
4909 &mut self,
4910 _: &DisplayCursorNames,
4911 window: &mut Window,
4912 cx: &mut Context<Self>,
4913 ) {
4914 self.show_cursor_names(window, cx);
4915 }
4916
4917 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4918 self.show_cursor_names = true;
4919 cx.notify();
4920 cx.spawn_in(window, |this, mut cx| async move {
4921 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4922 this.update(&mut cx, |this, cx| {
4923 this.show_cursor_names = false;
4924 cx.notify()
4925 })
4926 .ok()
4927 })
4928 .detach();
4929 }
4930
4931 pub fn next_edit_prediction(
4932 &mut self,
4933 _: &NextEditPrediction,
4934 window: &mut Window,
4935 cx: &mut Context<Self>,
4936 ) {
4937 if self.has_active_inline_completion() {
4938 self.cycle_inline_completion(Direction::Next, window, cx);
4939 } else {
4940 let is_copilot_disabled = self
4941 .refresh_inline_completion(false, true, window, cx)
4942 .is_none();
4943 if is_copilot_disabled {
4944 cx.propagate();
4945 }
4946 }
4947 }
4948
4949 pub fn previous_edit_prediction(
4950 &mut self,
4951 _: &PreviousEditPrediction,
4952 window: &mut Window,
4953 cx: &mut Context<Self>,
4954 ) {
4955 if self.has_active_inline_completion() {
4956 self.cycle_inline_completion(Direction::Prev, window, cx);
4957 } else {
4958 let is_copilot_disabled = self
4959 .refresh_inline_completion(false, true, window, cx)
4960 .is_none();
4961 if is_copilot_disabled {
4962 cx.propagate();
4963 }
4964 }
4965 }
4966
4967 pub fn accept_edit_prediction(
4968 &mut self,
4969 _: &AcceptEditPrediction,
4970 window: &mut Window,
4971 cx: &mut Context<Self>,
4972 ) {
4973 if self.show_edit_predictions_in_menu() {
4974 self.hide_context_menu(window, cx);
4975 }
4976
4977 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4978 return;
4979 };
4980
4981 self.report_inline_completion_event(
4982 active_inline_completion.completion_id.clone(),
4983 true,
4984 cx,
4985 );
4986
4987 match &active_inline_completion.completion {
4988 InlineCompletion::Move { target, .. } => {
4989 let target = *target;
4990
4991 if let Some(position_map) = &self.last_position_map {
4992 if position_map
4993 .visible_row_range
4994 .contains(&target.to_display_point(&position_map.snapshot).row())
4995 || !self.edit_prediction_requires_modifier()
4996 {
4997 // Note that this is also done in vim's handler of the Tab action.
4998 self.change_selections(
4999 Some(Autoscroll::newest()),
5000 window,
5001 cx,
5002 |selections| {
5003 selections.select_anchor_ranges([target..target]);
5004 },
5005 );
5006 self.clear_row_highlights::<EditPredictionPreview>();
5007
5008 self.edit_prediction_preview = EditPredictionPreview::Active {
5009 previous_scroll_position: None,
5010 };
5011 } else {
5012 self.edit_prediction_preview = EditPredictionPreview::Active {
5013 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5014 };
5015 self.highlight_rows::<EditPredictionPreview>(
5016 target..target,
5017 cx.theme().colors().editor_highlighted_line_background,
5018 true,
5019 cx,
5020 );
5021 self.request_autoscroll(Autoscroll::fit(), cx);
5022 }
5023 }
5024 }
5025 InlineCompletion::Edit { edits, .. } => {
5026 if let Some(provider) = self.edit_prediction_provider() {
5027 provider.accept(cx);
5028 }
5029
5030 let snapshot = self.buffer.read(cx).snapshot(cx);
5031 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5032
5033 self.buffer.update(cx, |buffer, cx| {
5034 buffer.edit(edits.iter().cloned(), None, cx)
5035 });
5036
5037 self.change_selections(None, window, cx, |s| {
5038 s.select_anchor_ranges([last_edit_end..last_edit_end])
5039 });
5040
5041 self.update_visible_inline_completion(window, cx);
5042 if self.active_inline_completion.is_none() {
5043 self.refresh_inline_completion(true, true, window, cx);
5044 }
5045
5046 cx.notify();
5047 }
5048 }
5049
5050 self.edit_prediction_requires_modifier_in_leading_space = false;
5051 }
5052
5053 pub fn accept_partial_inline_completion(
5054 &mut self,
5055 _: &AcceptPartialEditPrediction,
5056 window: &mut Window,
5057 cx: &mut Context<Self>,
5058 ) {
5059 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5060 return;
5061 };
5062 if self.selections.count() != 1 {
5063 return;
5064 }
5065
5066 self.report_inline_completion_event(
5067 active_inline_completion.completion_id.clone(),
5068 true,
5069 cx,
5070 );
5071
5072 match &active_inline_completion.completion {
5073 InlineCompletion::Move { target, .. } => {
5074 let target = *target;
5075 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5076 selections.select_anchor_ranges([target..target]);
5077 });
5078 }
5079 InlineCompletion::Edit { edits, .. } => {
5080 // Find an insertion that starts at the cursor position.
5081 let snapshot = self.buffer.read(cx).snapshot(cx);
5082 let cursor_offset = self.selections.newest::<usize>(cx).head();
5083 let insertion = edits.iter().find_map(|(range, text)| {
5084 let range = range.to_offset(&snapshot);
5085 if range.is_empty() && range.start == cursor_offset {
5086 Some(text)
5087 } else {
5088 None
5089 }
5090 });
5091
5092 if let Some(text) = insertion {
5093 let mut partial_completion = text
5094 .chars()
5095 .by_ref()
5096 .take_while(|c| c.is_alphabetic())
5097 .collect::<String>();
5098 if partial_completion.is_empty() {
5099 partial_completion = text
5100 .chars()
5101 .by_ref()
5102 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5103 .collect::<String>();
5104 }
5105
5106 cx.emit(EditorEvent::InputHandled {
5107 utf16_range_to_replace: None,
5108 text: partial_completion.clone().into(),
5109 });
5110
5111 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5112
5113 self.refresh_inline_completion(true, true, window, cx);
5114 cx.notify();
5115 } else {
5116 self.accept_edit_prediction(&Default::default(), window, cx);
5117 }
5118 }
5119 }
5120 }
5121
5122 fn discard_inline_completion(
5123 &mut self,
5124 should_report_inline_completion_event: bool,
5125 cx: &mut Context<Self>,
5126 ) -> bool {
5127 if should_report_inline_completion_event {
5128 let completion_id = self
5129 .active_inline_completion
5130 .as_ref()
5131 .and_then(|active_completion| active_completion.completion_id.clone());
5132
5133 self.report_inline_completion_event(completion_id, false, cx);
5134 }
5135
5136 if let Some(provider) = self.edit_prediction_provider() {
5137 provider.discard(cx);
5138 }
5139
5140 self.take_active_inline_completion(cx)
5141 }
5142
5143 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5144 let Some(provider) = self.edit_prediction_provider() else {
5145 return;
5146 };
5147
5148 let Some((_, buffer, _)) = self
5149 .buffer
5150 .read(cx)
5151 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5152 else {
5153 return;
5154 };
5155
5156 let extension = buffer
5157 .read(cx)
5158 .file()
5159 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5160
5161 let event_type = match accepted {
5162 true => "Edit Prediction Accepted",
5163 false => "Edit Prediction Discarded",
5164 };
5165 telemetry::event!(
5166 event_type,
5167 provider = provider.name(),
5168 prediction_id = id,
5169 suggestion_accepted = accepted,
5170 file_extension = extension,
5171 );
5172 }
5173
5174 pub fn has_active_inline_completion(&self) -> bool {
5175 self.active_inline_completion.is_some()
5176 }
5177
5178 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5179 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5180 return false;
5181 };
5182
5183 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5184 self.clear_highlights::<InlineCompletionHighlight>(cx);
5185 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5186 true
5187 }
5188
5189 /// Returns true when we're displaying the edit prediction popover below the cursor
5190 /// like we are not previewing and the LSP autocomplete menu is visible
5191 /// or we are in `when_holding_modifier` mode.
5192 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5193 if self.edit_prediction_preview_is_active()
5194 || !self.show_edit_predictions_in_menu()
5195 || !self.edit_predictions_enabled()
5196 {
5197 return false;
5198 }
5199
5200 if self.has_visible_completions_menu() {
5201 return true;
5202 }
5203
5204 has_completion && self.edit_prediction_requires_modifier()
5205 }
5206
5207 fn handle_modifiers_changed(
5208 &mut self,
5209 modifiers: Modifiers,
5210 position_map: &PositionMap,
5211 window: &mut Window,
5212 cx: &mut Context<Self>,
5213 ) {
5214 if self.show_edit_predictions_in_menu() {
5215 self.update_edit_prediction_preview(&modifiers, window, cx);
5216 }
5217
5218 let mouse_position = window.mouse_position();
5219 if !position_map.text_hitbox.is_hovered(window) {
5220 return;
5221 }
5222
5223 self.update_hovered_link(
5224 position_map.point_for_position(mouse_position),
5225 &position_map.snapshot,
5226 modifiers,
5227 window,
5228 cx,
5229 )
5230 }
5231
5232 fn update_edit_prediction_preview(
5233 &mut self,
5234 modifiers: &Modifiers,
5235 window: &mut Window,
5236 cx: &mut Context<Self>,
5237 ) {
5238 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5239 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5240 return;
5241 };
5242
5243 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5244 if matches!(
5245 self.edit_prediction_preview,
5246 EditPredictionPreview::Inactive
5247 ) {
5248 self.edit_prediction_preview = EditPredictionPreview::Active {
5249 previous_scroll_position: None,
5250 };
5251
5252 self.update_visible_inline_completion(window, cx);
5253 cx.notify();
5254 }
5255 } else if let EditPredictionPreview::Active {
5256 previous_scroll_position,
5257 } = self.edit_prediction_preview
5258 {
5259 if let (Some(previous_scroll_position), Some(position_map)) =
5260 (previous_scroll_position, self.last_position_map.as_ref())
5261 {
5262 self.set_scroll_position(
5263 previous_scroll_position
5264 .scroll_position(&position_map.snapshot.display_snapshot),
5265 window,
5266 cx,
5267 );
5268 }
5269
5270 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5271 self.clear_row_highlights::<EditPredictionPreview>();
5272 self.update_visible_inline_completion(window, cx);
5273 cx.notify();
5274 }
5275 }
5276
5277 fn update_visible_inline_completion(
5278 &mut self,
5279 _window: &mut Window,
5280 cx: &mut Context<Self>,
5281 ) -> Option<()> {
5282 let selection = self.selections.newest_anchor();
5283 let cursor = selection.head();
5284 let multibuffer = self.buffer.read(cx).snapshot(cx);
5285 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5286 let excerpt_id = cursor.excerpt_id;
5287
5288 let show_in_menu = self.show_edit_predictions_in_menu();
5289 let completions_menu_has_precedence = !show_in_menu
5290 && (self.context_menu.borrow().is_some()
5291 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5292
5293 if completions_menu_has_precedence
5294 || !offset_selection.is_empty()
5295 || self
5296 .active_inline_completion
5297 .as_ref()
5298 .map_or(false, |completion| {
5299 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5300 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5301 !invalidation_range.contains(&offset_selection.head())
5302 })
5303 {
5304 self.discard_inline_completion(false, cx);
5305 return None;
5306 }
5307
5308 self.take_active_inline_completion(cx);
5309 let Some(provider) = self.edit_prediction_provider() else {
5310 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5311 return None;
5312 };
5313
5314 let (buffer, cursor_buffer_position) =
5315 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5316
5317 self.edit_prediction_settings =
5318 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5319
5320 if !self.edit_prediction_settings.is_enabled() {
5321 self.discard_inline_completion(false, cx);
5322 return None;
5323 }
5324
5325 self.edit_prediction_cursor_on_leading_whitespace =
5326 multibuffer.is_line_whitespace_upto(cursor);
5327
5328 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5329 let edits = inline_completion
5330 .edits
5331 .into_iter()
5332 .flat_map(|(range, new_text)| {
5333 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5334 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5335 Some((start..end, new_text))
5336 })
5337 .collect::<Vec<_>>();
5338 if edits.is_empty() {
5339 return None;
5340 }
5341
5342 let first_edit_start = edits.first().unwrap().0.start;
5343 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5344 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5345
5346 let last_edit_end = edits.last().unwrap().0.end;
5347 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5348 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5349
5350 let cursor_row = cursor.to_point(&multibuffer).row;
5351
5352 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5353
5354 let mut inlay_ids = Vec::new();
5355 let invalidation_row_range;
5356 let move_invalidation_row_range = if cursor_row < edit_start_row {
5357 Some(cursor_row..edit_end_row)
5358 } else if cursor_row > edit_end_row {
5359 Some(edit_start_row..cursor_row)
5360 } else {
5361 None
5362 };
5363 let is_move =
5364 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5365 let completion = if is_move {
5366 invalidation_row_range =
5367 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5368 let target = first_edit_start;
5369 InlineCompletion::Move { target, snapshot }
5370 } else {
5371 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5372 && !self.inline_completions_hidden_for_vim_mode;
5373
5374 if show_completions_in_buffer {
5375 if edits
5376 .iter()
5377 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5378 {
5379 let mut inlays = Vec::new();
5380 for (range, new_text) in &edits {
5381 let inlay = Inlay::inline_completion(
5382 post_inc(&mut self.next_inlay_id),
5383 range.start,
5384 new_text.as_str(),
5385 );
5386 inlay_ids.push(inlay.id);
5387 inlays.push(inlay);
5388 }
5389
5390 self.splice_inlays(&[], inlays, cx);
5391 } else {
5392 let background_color = cx.theme().status().deleted_background;
5393 self.highlight_text::<InlineCompletionHighlight>(
5394 edits.iter().map(|(range, _)| range.clone()).collect(),
5395 HighlightStyle {
5396 background_color: Some(background_color),
5397 ..Default::default()
5398 },
5399 cx,
5400 );
5401 }
5402 }
5403
5404 invalidation_row_range = edit_start_row..edit_end_row;
5405
5406 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5407 if provider.show_tab_accept_marker() {
5408 EditDisplayMode::TabAccept
5409 } else {
5410 EditDisplayMode::Inline
5411 }
5412 } else {
5413 EditDisplayMode::DiffPopover
5414 };
5415
5416 InlineCompletion::Edit {
5417 edits,
5418 edit_preview: inline_completion.edit_preview,
5419 display_mode,
5420 snapshot,
5421 }
5422 };
5423
5424 let invalidation_range = multibuffer
5425 .anchor_before(Point::new(invalidation_row_range.start, 0))
5426 ..multibuffer.anchor_after(Point::new(
5427 invalidation_row_range.end,
5428 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5429 ));
5430
5431 self.stale_inline_completion_in_menu = None;
5432 self.active_inline_completion = Some(InlineCompletionState {
5433 inlay_ids,
5434 completion,
5435 completion_id: inline_completion.id,
5436 invalidation_range,
5437 });
5438
5439 cx.notify();
5440
5441 Some(())
5442 }
5443
5444 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5445 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5446 }
5447
5448 fn render_code_actions_indicator(
5449 &self,
5450 _style: &EditorStyle,
5451 row: DisplayRow,
5452 is_active: bool,
5453 cx: &mut Context<Self>,
5454 ) -> Option<IconButton> {
5455 if self.available_code_actions.is_some() {
5456 Some(
5457 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5458 .shape(ui::IconButtonShape::Square)
5459 .icon_size(IconSize::XSmall)
5460 .icon_color(Color::Muted)
5461 .toggle_state(is_active)
5462 .tooltip({
5463 let focus_handle = self.focus_handle.clone();
5464 move |window, cx| {
5465 Tooltip::for_action_in(
5466 "Toggle Code Actions",
5467 &ToggleCodeActions {
5468 deployed_from_indicator: None,
5469 },
5470 &focus_handle,
5471 window,
5472 cx,
5473 )
5474 }
5475 })
5476 .on_click(cx.listener(move |editor, _e, window, cx| {
5477 window.focus(&editor.focus_handle(cx));
5478 editor.toggle_code_actions(
5479 &ToggleCodeActions {
5480 deployed_from_indicator: Some(row),
5481 },
5482 window,
5483 cx,
5484 );
5485 })),
5486 )
5487 } else {
5488 None
5489 }
5490 }
5491
5492 fn clear_tasks(&mut self) {
5493 self.tasks.clear()
5494 }
5495
5496 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5497 if self.tasks.insert(key, value).is_some() {
5498 // This case should hopefully be rare, but just in case...
5499 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5500 }
5501 }
5502
5503 fn build_tasks_context(
5504 project: &Entity<Project>,
5505 buffer: &Entity<Buffer>,
5506 buffer_row: u32,
5507 tasks: &Arc<RunnableTasks>,
5508 cx: &mut Context<Self>,
5509 ) -> Task<Option<task::TaskContext>> {
5510 let position = Point::new(buffer_row, tasks.column);
5511 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5512 let location = Location {
5513 buffer: buffer.clone(),
5514 range: range_start..range_start,
5515 };
5516 // Fill in the environmental variables from the tree-sitter captures
5517 let mut captured_task_variables = TaskVariables::default();
5518 for (capture_name, value) in tasks.extra_variables.clone() {
5519 captured_task_variables.insert(
5520 task::VariableName::Custom(capture_name.into()),
5521 value.clone(),
5522 );
5523 }
5524 project.update(cx, |project, cx| {
5525 project.task_store().update(cx, |task_store, cx| {
5526 task_store.task_context_for_location(captured_task_variables, location, cx)
5527 })
5528 })
5529 }
5530
5531 pub fn spawn_nearest_task(
5532 &mut self,
5533 action: &SpawnNearestTask,
5534 window: &mut Window,
5535 cx: &mut Context<Self>,
5536 ) {
5537 let Some((workspace, _)) = self.workspace.clone() else {
5538 return;
5539 };
5540 let Some(project) = self.project.clone() else {
5541 return;
5542 };
5543
5544 // Try to find a closest, enclosing node using tree-sitter that has a
5545 // task
5546 let Some((buffer, buffer_row, tasks)) = self
5547 .find_enclosing_node_task(cx)
5548 // Or find the task that's closest in row-distance.
5549 .or_else(|| self.find_closest_task(cx))
5550 else {
5551 return;
5552 };
5553
5554 let reveal_strategy = action.reveal;
5555 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5556 cx.spawn_in(window, |_, mut cx| async move {
5557 let context = task_context.await?;
5558 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5559
5560 let resolved = resolved_task.resolved.as_mut()?;
5561 resolved.reveal = reveal_strategy;
5562
5563 workspace
5564 .update(&mut cx, |workspace, cx| {
5565 workspace::tasks::schedule_resolved_task(
5566 workspace,
5567 task_source_kind,
5568 resolved_task,
5569 false,
5570 cx,
5571 );
5572 })
5573 .ok()
5574 })
5575 .detach();
5576 }
5577
5578 fn find_closest_task(
5579 &mut self,
5580 cx: &mut Context<Self>,
5581 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5582 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5583
5584 let ((buffer_id, row), tasks) = self
5585 .tasks
5586 .iter()
5587 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5588
5589 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5590 let tasks = Arc::new(tasks.to_owned());
5591 Some((buffer, *row, tasks))
5592 }
5593
5594 fn find_enclosing_node_task(
5595 &mut self,
5596 cx: &mut Context<Self>,
5597 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5598 let snapshot = self.buffer.read(cx).snapshot(cx);
5599 let offset = self.selections.newest::<usize>(cx).head();
5600 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5601 let buffer_id = excerpt.buffer().remote_id();
5602
5603 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5604 let mut cursor = layer.node().walk();
5605
5606 while cursor.goto_first_child_for_byte(offset).is_some() {
5607 if cursor.node().end_byte() == offset {
5608 cursor.goto_next_sibling();
5609 }
5610 }
5611
5612 // Ascend to the smallest ancestor that contains the range and has a task.
5613 loop {
5614 let node = cursor.node();
5615 let node_range = node.byte_range();
5616 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5617
5618 // Check if this node contains our offset
5619 if node_range.start <= offset && node_range.end >= offset {
5620 // If it contains offset, check for task
5621 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5622 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5623 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5624 }
5625 }
5626
5627 if !cursor.goto_parent() {
5628 break;
5629 }
5630 }
5631 None
5632 }
5633
5634 fn render_run_indicator(
5635 &self,
5636 _style: &EditorStyle,
5637 is_active: bool,
5638 row: DisplayRow,
5639 cx: &mut Context<Self>,
5640 ) -> IconButton {
5641 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5642 .shape(ui::IconButtonShape::Square)
5643 .icon_size(IconSize::XSmall)
5644 .icon_color(Color::Muted)
5645 .toggle_state(is_active)
5646 .on_click(cx.listener(move |editor, _e, window, cx| {
5647 window.focus(&editor.focus_handle(cx));
5648 editor.toggle_code_actions(
5649 &ToggleCodeActions {
5650 deployed_from_indicator: Some(row),
5651 },
5652 window,
5653 cx,
5654 );
5655 }))
5656 }
5657
5658 pub fn context_menu_visible(&self) -> bool {
5659 !self.edit_prediction_preview_is_active()
5660 && self
5661 .context_menu
5662 .borrow()
5663 .as_ref()
5664 .map_or(false, |menu| menu.visible())
5665 }
5666
5667 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5668 self.context_menu
5669 .borrow()
5670 .as_ref()
5671 .map(|menu| menu.origin())
5672 }
5673
5674 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5675 px(30.)
5676 }
5677
5678 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5679 if self.read_only(cx) {
5680 cx.theme().players().read_only()
5681 } else {
5682 self.style.as_ref().unwrap().local_player
5683 }
5684 }
5685
5686 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5687 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5688 let accept_keystroke = accept_binding.keystroke()?;
5689
5690 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5691
5692 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5693 Color::Accent
5694 } else {
5695 Color::Muted
5696 };
5697
5698 h_flex()
5699 .px_0p5()
5700 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5701 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5702 .text_size(TextSize::XSmall.rems(cx))
5703 .child(h_flex().children(ui::render_modifiers(
5704 &accept_keystroke.modifiers,
5705 PlatformStyle::platform(),
5706 Some(modifiers_color),
5707 Some(IconSize::XSmall.rems().into()),
5708 true,
5709 )))
5710 .when(is_platform_style_mac, |parent| {
5711 parent.child(accept_keystroke.key.clone())
5712 })
5713 .when(!is_platform_style_mac, |parent| {
5714 parent.child(
5715 Key::new(
5716 util::capitalize(&accept_keystroke.key),
5717 Some(Color::Default),
5718 )
5719 .size(Some(IconSize::XSmall.rems().into())),
5720 )
5721 })
5722 .into()
5723 }
5724
5725 fn render_edit_prediction_line_popover(
5726 &self,
5727 label: impl Into<SharedString>,
5728 icon: Option<IconName>,
5729 window: &mut Window,
5730 cx: &App,
5731 ) -> Option<Div> {
5732 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5733
5734 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5735
5736 let result = h_flex()
5737 .gap_1()
5738 .border_1()
5739 .rounded_lg()
5740 .shadow_sm()
5741 .bg(bg_color)
5742 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5743 .py_0p5()
5744 .pl_1()
5745 .pr(padding_right)
5746 .children(self.render_edit_prediction_accept_keybind(window, cx))
5747 .child(Label::new(label).size(LabelSize::Small))
5748 .when_some(icon, |element, icon| {
5749 element.child(
5750 div()
5751 .mt(px(1.5))
5752 .child(Icon::new(icon).size(IconSize::Small)),
5753 )
5754 });
5755
5756 Some(result)
5757 }
5758
5759 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5760 let accent_color = cx.theme().colors().text_accent;
5761 let editor_bg_color = cx.theme().colors().editor_background;
5762 editor_bg_color.blend(accent_color.opacity(0.1))
5763 }
5764
5765 #[allow(clippy::too_many_arguments)]
5766 fn render_edit_prediction_cursor_popover(
5767 &self,
5768 min_width: Pixels,
5769 max_width: Pixels,
5770 cursor_point: Point,
5771 style: &EditorStyle,
5772 accept_keystroke: &gpui::Keystroke,
5773 _window: &Window,
5774 cx: &mut Context<Editor>,
5775 ) -> Option<AnyElement> {
5776 let provider = self.edit_prediction_provider.as_ref()?;
5777
5778 if provider.provider.needs_terms_acceptance(cx) {
5779 return Some(
5780 h_flex()
5781 .min_w(min_width)
5782 .flex_1()
5783 .px_2()
5784 .py_1()
5785 .gap_3()
5786 .elevation_2(cx)
5787 .hover(|style| style.bg(cx.theme().colors().element_hover))
5788 .id("accept-terms")
5789 .cursor_pointer()
5790 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5791 .on_click(cx.listener(|this, _event, window, cx| {
5792 cx.stop_propagation();
5793 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5794 window.dispatch_action(
5795 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5796 cx,
5797 );
5798 }))
5799 .child(
5800 h_flex()
5801 .flex_1()
5802 .gap_2()
5803 .child(Icon::new(IconName::ZedPredict))
5804 .child(Label::new("Accept Terms of Service"))
5805 .child(div().w_full())
5806 .child(
5807 Icon::new(IconName::ArrowUpRight)
5808 .color(Color::Muted)
5809 .size(IconSize::Small),
5810 )
5811 .into_any_element(),
5812 )
5813 .into_any(),
5814 );
5815 }
5816
5817 let is_refreshing = provider.provider.is_refreshing(cx);
5818
5819 fn pending_completion_container() -> Div {
5820 h_flex()
5821 .h_full()
5822 .flex_1()
5823 .gap_2()
5824 .child(Icon::new(IconName::ZedPredict))
5825 }
5826
5827 let completion = match &self.active_inline_completion {
5828 Some(completion) => match &completion.completion {
5829 InlineCompletion::Move {
5830 target, snapshot, ..
5831 } if !self.has_visible_completions_menu() => {
5832 use text::ToPoint as _;
5833
5834 return Some(
5835 h_flex()
5836 .px_2()
5837 .py_1()
5838 .elevation_2(cx)
5839 .border_color(cx.theme().colors().border)
5840 .rounded_tl(px(0.))
5841 .gap_2()
5842 .child(
5843 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5844 Icon::new(IconName::ZedPredictDown)
5845 } else {
5846 Icon::new(IconName::ZedPredictUp)
5847 },
5848 )
5849 .child(Label::new("Hold").size(LabelSize::Small))
5850 .child(h_flex().children(ui::render_modifiers(
5851 &accept_keystroke.modifiers,
5852 PlatformStyle::platform(),
5853 Some(Color::Default),
5854 Some(IconSize::Small.rems().into()),
5855 false,
5856 )))
5857 .into_any(),
5858 );
5859 }
5860 _ => self.render_edit_prediction_cursor_popover_preview(
5861 completion,
5862 cursor_point,
5863 style,
5864 cx,
5865 )?,
5866 },
5867
5868 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5869 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5870 stale_completion,
5871 cursor_point,
5872 style,
5873 cx,
5874 )?,
5875
5876 None => {
5877 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5878 }
5879 },
5880
5881 None => pending_completion_container().child(Label::new("No Prediction")),
5882 };
5883
5884 let completion = if is_refreshing {
5885 completion
5886 .with_animation(
5887 "loading-completion",
5888 Animation::new(Duration::from_secs(2))
5889 .repeat()
5890 .with_easing(pulsating_between(0.4, 0.8)),
5891 |label, delta| label.opacity(delta),
5892 )
5893 .into_any_element()
5894 } else {
5895 completion.into_any_element()
5896 };
5897
5898 let has_completion = self.active_inline_completion.is_some();
5899
5900 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5901 Some(
5902 h_flex()
5903 .min_w(min_width)
5904 .max_w(max_width)
5905 .flex_1()
5906 .elevation_2(cx)
5907 .border_color(cx.theme().colors().border)
5908 .child(
5909 div()
5910 .flex_1()
5911 .py_1()
5912 .px_2()
5913 .overflow_hidden()
5914 .child(completion),
5915 )
5916 .child(
5917 h_flex()
5918 .h_full()
5919 .border_l_1()
5920 .rounded_r_lg()
5921 .border_color(cx.theme().colors().border)
5922 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5923 .gap_1()
5924 .py_1()
5925 .px_2()
5926 .child(
5927 h_flex()
5928 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5929 .when(is_platform_style_mac, |parent| parent.gap_1())
5930 .child(h_flex().children(ui::render_modifiers(
5931 &accept_keystroke.modifiers,
5932 PlatformStyle::platform(),
5933 Some(if !has_completion {
5934 Color::Muted
5935 } else {
5936 Color::Default
5937 }),
5938 None,
5939 false,
5940 ))),
5941 )
5942 .child(Label::new("Preview").into_any_element())
5943 .opacity(if has_completion { 1.0 } else { 0.4 }),
5944 )
5945 .into_any(),
5946 )
5947 }
5948
5949 fn render_edit_prediction_cursor_popover_preview(
5950 &self,
5951 completion: &InlineCompletionState,
5952 cursor_point: Point,
5953 style: &EditorStyle,
5954 cx: &mut Context<Editor>,
5955 ) -> Option<Div> {
5956 use text::ToPoint as _;
5957
5958 fn render_relative_row_jump(
5959 prefix: impl Into<String>,
5960 current_row: u32,
5961 target_row: u32,
5962 ) -> Div {
5963 let (row_diff, arrow) = if target_row < current_row {
5964 (current_row - target_row, IconName::ArrowUp)
5965 } else {
5966 (target_row - current_row, IconName::ArrowDown)
5967 };
5968
5969 h_flex()
5970 .child(
5971 Label::new(format!("{}{}", prefix.into(), row_diff))
5972 .color(Color::Muted)
5973 .size(LabelSize::Small),
5974 )
5975 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5976 }
5977
5978 match &completion.completion {
5979 InlineCompletion::Move {
5980 target, snapshot, ..
5981 } => Some(
5982 h_flex()
5983 .px_2()
5984 .gap_2()
5985 .flex_1()
5986 .child(
5987 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5988 Icon::new(IconName::ZedPredictDown)
5989 } else {
5990 Icon::new(IconName::ZedPredictUp)
5991 },
5992 )
5993 .child(Label::new("Jump to Edit")),
5994 ),
5995
5996 InlineCompletion::Edit {
5997 edits,
5998 edit_preview,
5999 snapshot,
6000 display_mode: _,
6001 } => {
6002 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6003
6004 let highlighted_edits = crate::inline_completion_edit_text(
6005 &snapshot,
6006 &edits,
6007 edit_preview.as_ref()?,
6008 true,
6009 cx,
6010 );
6011
6012 let len_total = highlighted_edits.text.len();
6013 let first_line = &highlighted_edits.text
6014 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
6015 let first_line_len = first_line.len();
6016
6017 let first_highlight_start = highlighted_edits
6018 .highlights
6019 .first()
6020 .map_or(0, |(range, _)| range.start);
6021 let drop_prefix_len = first_line
6022 .char_indices()
6023 .find(|(_, c)| !c.is_whitespace())
6024 .map_or(first_highlight_start, |(ix, _)| {
6025 ix.min(first_highlight_start)
6026 });
6027
6028 let preview_text = &first_line[drop_prefix_len..];
6029 let preview_len = preview_text.len();
6030 let highlights = highlighted_edits
6031 .highlights
6032 .into_iter()
6033 .take_until(|(range, _)| range.start > first_line_len)
6034 .map(|(range, style)| {
6035 (
6036 range.start - drop_prefix_len
6037 ..(range.end - drop_prefix_len).min(preview_len),
6038 style,
6039 )
6040 });
6041
6042 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
6043 .with_highlights(&style.text, highlights);
6044
6045 let preview = h_flex()
6046 .gap_1()
6047 .min_w_16()
6048 .child(styled_text)
6049 .when(len_total > first_line_len, |parent| parent.child("…"));
6050
6051 let left = if first_edit_row != cursor_point.row {
6052 render_relative_row_jump("", cursor_point.row, first_edit_row)
6053 .into_any_element()
6054 } else {
6055 Icon::new(IconName::ZedPredict).into_any_element()
6056 };
6057
6058 Some(
6059 h_flex()
6060 .h_full()
6061 .flex_1()
6062 .gap_2()
6063 .pr_1()
6064 .overflow_x_hidden()
6065 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6066 .child(left)
6067 .child(preview),
6068 )
6069 }
6070 }
6071 }
6072
6073 fn render_context_menu(
6074 &self,
6075 style: &EditorStyle,
6076 max_height_in_lines: u32,
6077 y_flipped: bool,
6078 window: &mut Window,
6079 cx: &mut Context<Editor>,
6080 ) -> Option<AnyElement> {
6081 let menu = self.context_menu.borrow();
6082 let menu = menu.as_ref()?;
6083 if !menu.visible() {
6084 return None;
6085 };
6086 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6087 }
6088
6089 fn render_context_menu_aside(
6090 &self,
6091 style: &EditorStyle,
6092 max_size: Size<Pixels>,
6093 cx: &mut Context<Editor>,
6094 ) -> Option<AnyElement> {
6095 self.context_menu.borrow().as_ref().and_then(|menu| {
6096 if menu.visible() {
6097 menu.render_aside(
6098 style,
6099 max_size,
6100 self.workspace.as_ref().map(|(w, _)| w.clone()),
6101 cx,
6102 )
6103 } else {
6104 None
6105 }
6106 })
6107 }
6108
6109 fn hide_context_menu(
6110 &mut self,
6111 window: &mut Window,
6112 cx: &mut Context<Self>,
6113 ) -> Option<CodeContextMenu> {
6114 cx.notify();
6115 self.completion_tasks.clear();
6116 let context_menu = self.context_menu.borrow_mut().take();
6117 self.stale_inline_completion_in_menu.take();
6118 self.update_visible_inline_completion(window, cx);
6119 context_menu
6120 }
6121
6122 fn show_snippet_choices(
6123 &mut self,
6124 choices: &Vec<String>,
6125 selection: Range<Anchor>,
6126 cx: &mut Context<Self>,
6127 ) {
6128 if selection.start.buffer_id.is_none() {
6129 return;
6130 }
6131 let buffer_id = selection.start.buffer_id.unwrap();
6132 let buffer = self.buffer().read(cx).buffer(buffer_id);
6133 let id = post_inc(&mut self.next_completion_id);
6134
6135 if let Some(buffer) = buffer {
6136 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6137 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6138 ));
6139 }
6140 }
6141
6142 pub fn insert_snippet(
6143 &mut self,
6144 insertion_ranges: &[Range<usize>],
6145 snippet: Snippet,
6146 window: &mut Window,
6147 cx: &mut Context<Self>,
6148 ) -> Result<()> {
6149 struct Tabstop<T> {
6150 is_end_tabstop: bool,
6151 ranges: Vec<Range<T>>,
6152 choices: Option<Vec<String>>,
6153 }
6154
6155 let tabstops = self.buffer.update(cx, |buffer, cx| {
6156 let snippet_text: Arc<str> = snippet.text.clone().into();
6157 buffer.edit(
6158 insertion_ranges
6159 .iter()
6160 .cloned()
6161 .map(|range| (range, snippet_text.clone())),
6162 Some(AutoindentMode::EachLine),
6163 cx,
6164 );
6165
6166 let snapshot = &*buffer.read(cx);
6167 let snippet = &snippet;
6168 snippet
6169 .tabstops
6170 .iter()
6171 .map(|tabstop| {
6172 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6173 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6174 });
6175 let mut tabstop_ranges = tabstop
6176 .ranges
6177 .iter()
6178 .flat_map(|tabstop_range| {
6179 let mut delta = 0_isize;
6180 insertion_ranges.iter().map(move |insertion_range| {
6181 let insertion_start = insertion_range.start as isize + delta;
6182 delta +=
6183 snippet.text.len() as isize - insertion_range.len() as isize;
6184
6185 let start = ((insertion_start + tabstop_range.start) as usize)
6186 .min(snapshot.len());
6187 let end = ((insertion_start + tabstop_range.end) as usize)
6188 .min(snapshot.len());
6189 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6190 })
6191 })
6192 .collect::<Vec<_>>();
6193 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6194
6195 Tabstop {
6196 is_end_tabstop,
6197 ranges: tabstop_ranges,
6198 choices: tabstop.choices.clone(),
6199 }
6200 })
6201 .collect::<Vec<_>>()
6202 });
6203 if let Some(tabstop) = tabstops.first() {
6204 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6205 s.select_ranges(tabstop.ranges.iter().cloned());
6206 });
6207
6208 if let Some(choices) = &tabstop.choices {
6209 if let Some(selection) = tabstop.ranges.first() {
6210 self.show_snippet_choices(choices, selection.clone(), cx)
6211 }
6212 }
6213
6214 // If we're already at the last tabstop and it's at the end of the snippet,
6215 // we're done, we don't need to keep the state around.
6216 if !tabstop.is_end_tabstop {
6217 let choices = tabstops
6218 .iter()
6219 .map(|tabstop| tabstop.choices.clone())
6220 .collect();
6221
6222 let ranges = tabstops
6223 .into_iter()
6224 .map(|tabstop| tabstop.ranges)
6225 .collect::<Vec<_>>();
6226
6227 self.snippet_stack.push(SnippetState {
6228 active_index: 0,
6229 ranges,
6230 choices,
6231 });
6232 }
6233
6234 // Check whether the just-entered snippet ends with an auto-closable bracket.
6235 if self.autoclose_regions.is_empty() {
6236 let snapshot = self.buffer.read(cx).snapshot(cx);
6237 for selection in &mut self.selections.all::<Point>(cx) {
6238 let selection_head = selection.head();
6239 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6240 continue;
6241 };
6242
6243 let mut bracket_pair = None;
6244 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6245 let prev_chars = snapshot
6246 .reversed_chars_at(selection_head)
6247 .collect::<String>();
6248 for (pair, enabled) in scope.brackets() {
6249 if enabled
6250 && pair.close
6251 && prev_chars.starts_with(pair.start.as_str())
6252 && next_chars.starts_with(pair.end.as_str())
6253 {
6254 bracket_pair = Some(pair.clone());
6255 break;
6256 }
6257 }
6258 if let Some(pair) = bracket_pair {
6259 let start = snapshot.anchor_after(selection_head);
6260 let end = snapshot.anchor_after(selection_head);
6261 self.autoclose_regions.push(AutocloseRegion {
6262 selection_id: selection.id,
6263 range: start..end,
6264 pair,
6265 });
6266 }
6267 }
6268 }
6269 }
6270 Ok(())
6271 }
6272
6273 pub fn move_to_next_snippet_tabstop(
6274 &mut self,
6275 window: &mut Window,
6276 cx: &mut Context<Self>,
6277 ) -> bool {
6278 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6279 }
6280
6281 pub fn move_to_prev_snippet_tabstop(
6282 &mut self,
6283 window: &mut Window,
6284 cx: &mut Context<Self>,
6285 ) -> bool {
6286 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6287 }
6288
6289 pub fn move_to_snippet_tabstop(
6290 &mut self,
6291 bias: Bias,
6292 window: &mut Window,
6293 cx: &mut Context<Self>,
6294 ) -> bool {
6295 if let Some(mut snippet) = self.snippet_stack.pop() {
6296 match bias {
6297 Bias::Left => {
6298 if snippet.active_index > 0 {
6299 snippet.active_index -= 1;
6300 } else {
6301 self.snippet_stack.push(snippet);
6302 return false;
6303 }
6304 }
6305 Bias::Right => {
6306 if snippet.active_index + 1 < snippet.ranges.len() {
6307 snippet.active_index += 1;
6308 } else {
6309 self.snippet_stack.push(snippet);
6310 return false;
6311 }
6312 }
6313 }
6314 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6315 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6316 s.select_anchor_ranges(current_ranges.iter().cloned())
6317 });
6318
6319 if let Some(choices) = &snippet.choices[snippet.active_index] {
6320 if let Some(selection) = current_ranges.first() {
6321 self.show_snippet_choices(&choices, selection.clone(), cx);
6322 }
6323 }
6324
6325 // If snippet state is not at the last tabstop, push it back on the stack
6326 if snippet.active_index + 1 < snippet.ranges.len() {
6327 self.snippet_stack.push(snippet);
6328 }
6329 return true;
6330 }
6331 }
6332
6333 false
6334 }
6335
6336 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6337 self.transact(window, cx, |this, window, cx| {
6338 this.select_all(&SelectAll, window, cx);
6339 this.insert("", window, cx);
6340 });
6341 }
6342
6343 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6344 self.transact(window, cx, |this, window, cx| {
6345 this.select_autoclose_pair(window, cx);
6346 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6347 if !this.linked_edit_ranges.is_empty() {
6348 let selections = this.selections.all::<MultiBufferPoint>(cx);
6349 let snapshot = this.buffer.read(cx).snapshot(cx);
6350
6351 for selection in selections.iter() {
6352 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6353 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6354 if selection_start.buffer_id != selection_end.buffer_id {
6355 continue;
6356 }
6357 if let Some(ranges) =
6358 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6359 {
6360 for (buffer, entries) in ranges {
6361 linked_ranges.entry(buffer).or_default().extend(entries);
6362 }
6363 }
6364 }
6365 }
6366
6367 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6368 if !this.selections.line_mode {
6369 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6370 for selection in &mut selections {
6371 if selection.is_empty() {
6372 let old_head = selection.head();
6373 let mut new_head =
6374 movement::left(&display_map, old_head.to_display_point(&display_map))
6375 .to_point(&display_map);
6376 if let Some((buffer, line_buffer_range)) = display_map
6377 .buffer_snapshot
6378 .buffer_line_for_row(MultiBufferRow(old_head.row))
6379 {
6380 let indent_size =
6381 buffer.indent_size_for_line(line_buffer_range.start.row);
6382 let indent_len = match indent_size.kind {
6383 IndentKind::Space => {
6384 buffer.settings_at(line_buffer_range.start, cx).tab_size
6385 }
6386 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6387 };
6388 if old_head.column <= indent_size.len && old_head.column > 0 {
6389 let indent_len = indent_len.get();
6390 new_head = cmp::min(
6391 new_head,
6392 MultiBufferPoint::new(
6393 old_head.row,
6394 ((old_head.column - 1) / indent_len) * indent_len,
6395 ),
6396 );
6397 }
6398 }
6399
6400 selection.set_head(new_head, SelectionGoal::None);
6401 }
6402 }
6403 }
6404
6405 this.signature_help_state.set_backspace_pressed(true);
6406 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6407 s.select(selections)
6408 });
6409 this.insert("", window, cx);
6410 let empty_str: Arc<str> = Arc::from("");
6411 for (buffer, edits) in linked_ranges {
6412 let snapshot = buffer.read(cx).snapshot();
6413 use text::ToPoint as TP;
6414
6415 let edits = edits
6416 .into_iter()
6417 .map(|range| {
6418 let end_point = TP::to_point(&range.end, &snapshot);
6419 let mut start_point = TP::to_point(&range.start, &snapshot);
6420
6421 if end_point == start_point {
6422 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6423 .saturating_sub(1);
6424 start_point =
6425 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6426 };
6427
6428 (start_point..end_point, empty_str.clone())
6429 })
6430 .sorted_by_key(|(range, _)| range.start)
6431 .collect::<Vec<_>>();
6432 buffer.update(cx, |this, cx| {
6433 this.edit(edits, None, cx);
6434 })
6435 }
6436 this.refresh_inline_completion(true, false, window, cx);
6437 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6438 });
6439 }
6440
6441 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6442 self.transact(window, cx, |this, window, cx| {
6443 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6444 let line_mode = s.line_mode;
6445 s.move_with(|map, selection| {
6446 if selection.is_empty() && !line_mode {
6447 let cursor = movement::right(map, selection.head());
6448 selection.end = cursor;
6449 selection.reversed = true;
6450 selection.goal = SelectionGoal::None;
6451 }
6452 })
6453 });
6454 this.insert("", window, cx);
6455 this.refresh_inline_completion(true, false, window, cx);
6456 });
6457 }
6458
6459 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6460 if self.move_to_prev_snippet_tabstop(window, cx) {
6461 return;
6462 }
6463
6464 self.outdent(&Outdent, window, cx);
6465 }
6466
6467 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6468 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6469 return;
6470 }
6471
6472 let mut selections = self.selections.all_adjusted(cx);
6473 let buffer = self.buffer.read(cx);
6474 let snapshot = buffer.snapshot(cx);
6475 let rows_iter = selections.iter().map(|s| s.head().row);
6476 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6477
6478 let mut edits = Vec::new();
6479 let mut prev_edited_row = 0;
6480 let mut row_delta = 0;
6481 for selection in &mut selections {
6482 if selection.start.row != prev_edited_row {
6483 row_delta = 0;
6484 }
6485 prev_edited_row = selection.end.row;
6486
6487 // If the selection is non-empty, then increase the indentation of the selected lines.
6488 if !selection.is_empty() {
6489 row_delta =
6490 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6491 continue;
6492 }
6493
6494 // If the selection is empty and the cursor is in the leading whitespace before the
6495 // suggested indentation, then auto-indent the line.
6496 let cursor = selection.head();
6497 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6498 if let Some(suggested_indent) =
6499 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6500 {
6501 if cursor.column < suggested_indent.len
6502 && cursor.column <= current_indent.len
6503 && current_indent.len <= suggested_indent.len
6504 {
6505 selection.start = Point::new(cursor.row, suggested_indent.len);
6506 selection.end = selection.start;
6507 if row_delta == 0 {
6508 edits.extend(Buffer::edit_for_indent_size_adjustment(
6509 cursor.row,
6510 current_indent,
6511 suggested_indent,
6512 ));
6513 row_delta = suggested_indent.len - current_indent.len;
6514 }
6515 continue;
6516 }
6517 }
6518
6519 // Otherwise, insert a hard or soft tab.
6520 let settings = buffer.settings_at(cursor, cx);
6521 let tab_size = if settings.hard_tabs {
6522 IndentSize::tab()
6523 } else {
6524 let tab_size = settings.tab_size.get();
6525 let char_column = snapshot
6526 .text_for_range(Point::new(cursor.row, 0)..cursor)
6527 .flat_map(str::chars)
6528 .count()
6529 + row_delta as usize;
6530 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6531 IndentSize::spaces(chars_to_next_tab_stop)
6532 };
6533 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6534 selection.end = selection.start;
6535 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6536 row_delta += tab_size.len;
6537 }
6538
6539 self.transact(window, cx, |this, window, cx| {
6540 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6541 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6542 s.select(selections)
6543 });
6544 this.refresh_inline_completion(true, false, window, cx);
6545 });
6546 }
6547
6548 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6549 if self.read_only(cx) {
6550 return;
6551 }
6552 let mut selections = self.selections.all::<Point>(cx);
6553 let mut prev_edited_row = 0;
6554 let mut row_delta = 0;
6555 let mut edits = Vec::new();
6556 let buffer = self.buffer.read(cx);
6557 let snapshot = buffer.snapshot(cx);
6558 for selection in &mut selections {
6559 if selection.start.row != prev_edited_row {
6560 row_delta = 0;
6561 }
6562 prev_edited_row = selection.end.row;
6563
6564 row_delta =
6565 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6566 }
6567
6568 self.transact(window, cx, |this, window, cx| {
6569 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6570 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6571 s.select(selections)
6572 });
6573 });
6574 }
6575
6576 fn indent_selection(
6577 buffer: &MultiBuffer,
6578 snapshot: &MultiBufferSnapshot,
6579 selection: &mut Selection<Point>,
6580 edits: &mut Vec<(Range<Point>, String)>,
6581 delta_for_start_row: u32,
6582 cx: &App,
6583 ) -> u32 {
6584 let settings = buffer.settings_at(selection.start, cx);
6585 let tab_size = settings.tab_size.get();
6586 let indent_kind = if settings.hard_tabs {
6587 IndentKind::Tab
6588 } else {
6589 IndentKind::Space
6590 };
6591 let mut start_row = selection.start.row;
6592 let mut end_row = selection.end.row + 1;
6593
6594 // If a selection ends at the beginning of a line, don't indent
6595 // that last line.
6596 if selection.end.column == 0 && selection.end.row > selection.start.row {
6597 end_row -= 1;
6598 }
6599
6600 // Avoid re-indenting a row that has already been indented by a
6601 // previous selection, but still update this selection's column
6602 // to reflect that indentation.
6603 if delta_for_start_row > 0 {
6604 start_row += 1;
6605 selection.start.column += delta_for_start_row;
6606 if selection.end.row == selection.start.row {
6607 selection.end.column += delta_for_start_row;
6608 }
6609 }
6610
6611 let mut delta_for_end_row = 0;
6612 let has_multiple_rows = start_row + 1 != end_row;
6613 for row in start_row..end_row {
6614 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6615 let indent_delta = match (current_indent.kind, indent_kind) {
6616 (IndentKind::Space, IndentKind::Space) => {
6617 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6618 IndentSize::spaces(columns_to_next_tab_stop)
6619 }
6620 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6621 (_, IndentKind::Tab) => IndentSize::tab(),
6622 };
6623
6624 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6625 0
6626 } else {
6627 selection.start.column
6628 };
6629 let row_start = Point::new(row, start);
6630 edits.push((
6631 row_start..row_start,
6632 indent_delta.chars().collect::<String>(),
6633 ));
6634
6635 // Update this selection's endpoints to reflect the indentation.
6636 if row == selection.start.row {
6637 selection.start.column += indent_delta.len;
6638 }
6639 if row == selection.end.row {
6640 selection.end.column += indent_delta.len;
6641 delta_for_end_row = indent_delta.len;
6642 }
6643 }
6644
6645 if selection.start.row == selection.end.row {
6646 delta_for_start_row + delta_for_end_row
6647 } else {
6648 delta_for_end_row
6649 }
6650 }
6651
6652 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6653 if self.read_only(cx) {
6654 return;
6655 }
6656 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6657 let selections = self.selections.all::<Point>(cx);
6658 let mut deletion_ranges = Vec::new();
6659 let mut last_outdent = None;
6660 {
6661 let buffer = self.buffer.read(cx);
6662 let snapshot = buffer.snapshot(cx);
6663 for selection in &selections {
6664 let settings = buffer.settings_at(selection.start, cx);
6665 let tab_size = settings.tab_size.get();
6666 let mut rows = selection.spanned_rows(false, &display_map);
6667
6668 // Avoid re-outdenting a row that has already been outdented by a
6669 // previous selection.
6670 if let Some(last_row) = last_outdent {
6671 if last_row == rows.start {
6672 rows.start = rows.start.next_row();
6673 }
6674 }
6675 let has_multiple_rows = rows.len() > 1;
6676 for row in rows.iter_rows() {
6677 let indent_size = snapshot.indent_size_for_line(row);
6678 if indent_size.len > 0 {
6679 let deletion_len = match indent_size.kind {
6680 IndentKind::Space => {
6681 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6682 if columns_to_prev_tab_stop == 0 {
6683 tab_size
6684 } else {
6685 columns_to_prev_tab_stop
6686 }
6687 }
6688 IndentKind::Tab => 1,
6689 };
6690 let start = if has_multiple_rows
6691 || deletion_len > selection.start.column
6692 || indent_size.len < selection.start.column
6693 {
6694 0
6695 } else {
6696 selection.start.column - deletion_len
6697 };
6698 deletion_ranges.push(
6699 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6700 );
6701 last_outdent = Some(row);
6702 }
6703 }
6704 }
6705 }
6706
6707 self.transact(window, cx, |this, window, cx| {
6708 this.buffer.update(cx, |buffer, cx| {
6709 let empty_str: Arc<str> = Arc::default();
6710 buffer.edit(
6711 deletion_ranges
6712 .into_iter()
6713 .map(|range| (range, empty_str.clone())),
6714 None,
6715 cx,
6716 );
6717 });
6718 let selections = this.selections.all::<usize>(cx);
6719 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6720 s.select(selections)
6721 });
6722 });
6723 }
6724
6725 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6726 if self.read_only(cx) {
6727 return;
6728 }
6729 let selections = self
6730 .selections
6731 .all::<usize>(cx)
6732 .into_iter()
6733 .map(|s| s.range());
6734
6735 self.transact(window, cx, |this, window, cx| {
6736 this.buffer.update(cx, |buffer, cx| {
6737 buffer.autoindent_ranges(selections, cx);
6738 });
6739 let selections = this.selections.all::<usize>(cx);
6740 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6741 s.select(selections)
6742 });
6743 });
6744 }
6745
6746 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6747 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6748 let selections = self.selections.all::<Point>(cx);
6749
6750 let mut new_cursors = Vec::new();
6751 let mut edit_ranges = Vec::new();
6752 let mut selections = selections.iter().peekable();
6753 while let Some(selection) = selections.next() {
6754 let mut rows = selection.spanned_rows(false, &display_map);
6755 let goal_display_column = selection.head().to_display_point(&display_map).column();
6756
6757 // Accumulate contiguous regions of rows that we want to delete.
6758 while let Some(next_selection) = selections.peek() {
6759 let next_rows = next_selection.spanned_rows(false, &display_map);
6760 if next_rows.start <= rows.end {
6761 rows.end = next_rows.end;
6762 selections.next().unwrap();
6763 } else {
6764 break;
6765 }
6766 }
6767
6768 let buffer = &display_map.buffer_snapshot;
6769 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6770 let edit_end;
6771 let cursor_buffer_row;
6772 if buffer.max_point().row >= rows.end.0 {
6773 // If there's a line after the range, delete the \n from the end of the row range
6774 // and position the cursor on the next line.
6775 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6776 cursor_buffer_row = rows.end;
6777 } else {
6778 // If there isn't a line after the range, delete the \n from the line before the
6779 // start of the row range and position the cursor there.
6780 edit_start = edit_start.saturating_sub(1);
6781 edit_end = buffer.len();
6782 cursor_buffer_row = rows.start.previous_row();
6783 }
6784
6785 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6786 *cursor.column_mut() =
6787 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6788
6789 new_cursors.push((
6790 selection.id,
6791 buffer.anchor_after(cursor.to_point(&display_map)),
6792 ));
6793 edit_ranges.push(edit_start..edit_end);
6794 }
6795
6796 self.transact(window, cx, |this, window, cx| {
6797 let buffer = this.buffer.update(cx, |buffer, cx| {
6798 let empty_str: Arc<str> = Arc::default();
6799 buffer.edit(
6800 edit_ranges
6801 .into_iter()
6802 .map(|range| (range, empty_str.clone())),
6803 None,
6804 cx,
6805 );
6806 buffer.snapshot(cx)
6807 });
6808 let new_selections = new_cursors
6809 .into_iter()
6810 .map(|(id, cursor)| {
6811 let cursor = cursor.to_point(&buffer);
6812 Selection {
6813 id,
6814 start: cursor,
6815 end: cursor,
6816 reversed: false,
6817 goal: SelectionGoal::None,
6818 }
6819 })
6820 .collect();
6821
6822 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6823 s.select(new_selections);
6824 });
6825 });
6826 }
6827
6828 pub fn join_lines_impl(
6829 &mut self,
6830 insert_whitespace: bool,
6831 window: &mut Window,
6832 cx: &mut Context<Self>,
6833 ) {
6834 if self.read_only(cx) {
6835 return;
6836 }
6837 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6838 for selection in self.selections.all::<Point>(cx) {
6839 let start = MultiBufferRow(selection.start.row);
6840 // Treat single line selections as if they include the next line. Otherwise this action
6841 // would do nothing for single line selections individual cursors.
6842 let end = if selection.start.row == selection.end.row {
6843 MultiBufferRow(selection.start.row + 1)
6844 } else {
6845 MultiBufferRow(selection.end.row)
6846 };
6847
6848 if let Some(last_row_range) = row_ranges.last_mut() {
6849 if start <= last_row_range.end {
6850 last_row_range.end = end;
6851 continue;
6852 }
6853 }
6854 row_ranges.push(start..end);
6855 }
6856
6857 let snapshot = self.buffer.read(cx).snapshot(cx);
6858 let mut cursor_positions = Vec::new();
6859 for row_range in &row_ranges {
6860 let anchor = snapshot.anchor_before(Point::new(
6861 row_range.end.previous_row().0,
6862 snapshot.line_len(row_range.end.previous_row()),
6863 ));
6864 cursor_positions.push(anchor..anchor);
6865 }
6866
6867 self.transact(window, cx, |this, window, cx| {
6868 for row_range in row_ranges.into_iter().rev() {
6869 for row in row_range.iter_rows().rev() {
6870 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6871 let next_line_row = row.next_row();
6872 let indent = snapshot.indent_size_for_line(next_line_row);
6873 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6874
6875 let replace =
6876 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6877 " "
6878 } else {
6879 ""
6880 };
6881
6882 this.buffer.update(cx, |buffer, cx| {
6883 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6884 });
6885 }
6886 }
6887
6888 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6889 s.select_anchor_ranges(cursor_positions)
6890 });
6891 });
6892 }
6893
6894 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6895 self.join_lines_impl(true, window, cx);
6896 }
6897
6898 pub fn sort_lines_case_sensitive(
6899 &mut self,
6900 _: &SortLinesCaseSensitive,
6901 window: &mut Window,
6902 cx: &mut Context<Self>,
6903 ) {
6904 self.manipulate_lines(window, cx, |lines| lines.sort())
6905 }
6906
6907 pub fn sort_lines_case_insensitive(
6908 &mut self,
6909 _: &SortLinesCaseInsensitive,
6910 window: &mut Window,
6911 cx: &mut Context<Self>,
6912 ) {
6913 self.manipulate_lines(window, cx, |lines| {
6914 lines.sort_by_key(|line| line.to_lowercase())
6915 })
6916 }
6917
6918 pub fn unique_lines_case_insensitive(
6919 &mut self,
6920 _: &UniqueLinesCaseInsensitive,
6921 window: &mut Window,
6922 cx: &mut Context<Self>,
6923 ) {
6924 self.manipulate_lines(window, cx, |lines| {
6925 let mut seen = HashSet::default();
6926 lines.retain(|line| seen.insert(line.to_lowercase()));
6927 })
6928 }
6929
6930 pub fn unique_lines_case_sensitive(
6931 &mut self,
6932 _: &UniqueLinesCaseSensitive,
6933 window: &mut Window,
6934 cx: &mut Context<Self>,
6935 ) {
6936 self.manipulate_lines(window, cx, |lines| {
6937 let mut seen = HashSet::default();
6938 lines.retain(|line| seen.insert(*line));
6939 })
6940 }
6941
6942 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6943 let mut revert_changes = HashMap::default();
6944 let snapshot = self.snapshot(window, cx);
6945 for hunk in snapshot
6946 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6947 {
6948 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6949 }
6950 if !revert_changes.is_empty() {
6951 self.transact(window, cx, |editor, window, cx| {
6952 editor.revert(revert_changes, window, cx);
6953 });
6954 }
6955 }
6956
6957 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6958 let Some(project) = self.project.clone() else {
6959 return;
6960 };
6961 self.reload(project, window, cx)
6962 .detach_and_notify_err(window, cx);
6963 }
6964
6965 pub fn revert_selected_hunks(
6966 &mut self,
6967 _: &RevertSelectedHunks,
6968 window: &mut Window,
6969 cx: &mut Context<Self>,
6970 ) {
6971 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6972 self.revert_hunks_in_ranges(selections, window, cx);
6973 }
6974
6975 fn revert_hunks_in_ranges(
6976 &mut self,
6977 ranges: impl Iterator<Item = Range<Point>>,
6978 window: &mut Window,
6979 cx: &mut Context<Editor>,
6980 ) {
6981 let mut revert_changes = HashMap::default();
6982 let snapshot = self.snapshot(window, cx);
6983 for hunk in &snapshot.hunks_for_ranges(ranges) {
6984 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6985 }
6986 if !revert_changes.is_empty() {
6987 self.transact(window, cx, |editor, window, cx| {
6988 editor.revert(revert_changes, window, cx);
6989 });
6990 }
6991 }
6992
6993 pub fn open_active_item_in_terminal(
6994 &mut self,
6995 _: &OpenInTerminal,
6996 window: &mut Window,
6997 cx: &mut Context<Self>,
6998 ) {
6999 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7000 let project_path = buffer.read(cx).project_path(cx)?;
7001 let project = self.project.as_ref()?.read(cx);
7002 let entry = project.entry_for_path(&project_path, cx)?;
7003 let parent = match &entry.canonical_path {
7004 Some(canonical_path) => canonical_path.to_path_buf(),
7005 None => project.absolute_path(&project_path, cx)?,
7006 }
7007 .parent()?
7008 .to_path_buf();
7009 Some(parent)
7010 }) {
7011 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7012 }
7013 }
7014
7015 pub fn prepare_revert_change(
7016 &self,
7017 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7018 hunk: &MultiBufferDiffHunk,
7019 cx: &mut App,
7020 ) -> Option<()> {
7021 let buffer = self.buffer.read(cx);
7022 let diff = buffer.diff_for(hunk.buffer_id)?;
7023 let buffer = buffer.buffer(hunk.buffer_id)?;
7024 let buffer = buffer.read(cx);
7025 let original_text = diff
7026 .read(cx)
7027 .base_text()
7028 .as_ref()?
7029 .as_rope()
7030 .slice(hunk.diff_base_byte_range.clone());
7031 let buffer_snapshot = buffer.snapshot();
7032 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7033 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7034 probe
7035 .0
7036 .start
7037 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7038 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7039 }) {
7040 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7041 Some(())
7042 } else {
7043 None
7044 }
7045 }
7046
7047 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7048 self.manipulate_lines(window, cx, |lines| lines.reverse())
7049 }
7050
7051 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7052 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7053 }
7054
7055 fn manipulate_lines<Fn>(
7056 &mut self,
7057 window: &mut Window,
7058 cx: &mut Context<Self>,
7059 mut callback: Fn,
7060 ) where
7061 Fn: FnMut(&mut Vec<&str>),
7062 {
7063 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7064 let buffer = self.buffer.read(cx).snapshot(cx);
7065
7066 let mut edits = Vec::new();
7067
7068 let selections = self.selections.all::<Point>(cx);
7069 let mut selections = selections.iter().peekable();
7070 let mut contiguous_row_selections = Vec::new();
7071 let mut new_selections = Vec::new();
7072 let mut added_lines = 0;
7073 let mut removed_lines = 0;
7074
7075 while let Some(selection) = selections.next() {
7076 let (start_row, end_row) = consume_contiguous_rows(
7077 &mut contiguous_row_selections,
7078 selection,
7079 &display_map,
7080 &mut selections,
7081 );
7082
7083 let start_point = Point::new(start_row.0, 0);
7084 let end_point = Point::new(
7085 end_row.previous_row().0,
7086 buffer.line_len(end_row.previous_row()),
7087 );
7088 let text = buffer
7089 .text_for_range(start_point..end_point)
7090 .collect::<String>();
7091
7092 let mut lines = text.split('\n').collect_vec();
7093
7094 let lines_before = lines.len();
7095 callback(&mut lines);
7096 let lines_after = lines.len();
7097
7098 edits.push((start_point..end_point, lines.join("\n")));
7099
7100 // Selections must change based on added and removed line count
7101 let start_row =
7102 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7103 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7104 new_selections.push(Selection {
7105 id: selection.id,
7106 start: start_row,
7107 end: end_row,
7108 goal: SelectionGoal::None,
7109 reversed: selection.reversed,
7110 });
7111
7112 if lines_after > lines_before {
7113 added_lines += lines_after - lines_before;
7114 } else if lines_before > lines_after {
7115 removed_lines += lines_before - lines_after;
7116 }
7117 }
7118
7119 self.transact(window, cx, |this, window, cx| {
7120 let buffer = this.buffer.update(cx, |buffer, cx| {
7121 buffer.edit(edits, None, cx);
7122 buffer.snapshot(cx)
7123 });
7124
7125 // Recalculate offsets on newly edited buffer
7126 let new_selections = new_selections
7127 .iter()
7128 .map(|s| {
7129 let start_point = Point::new(s.start.0, 0);
7130 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7131 Selection {
7132 id: s.id,
7133 start: buffer.point_to_offset(start_point),
7134 end: buffer.point_to_offset(end_point),
7135 goal: s.goal,
7136 reversed: s.reversed,
7137 }
7138 })
7139 .collect();
7140
7141 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7142 s.select(new_selections);
7143 });
7144
7145 this.request_autoscroll(Autoscroll::fit(), cx);
7146 });
7147 }
7148
7149 pub fn convert_to_upper_case(
7150 &mut self,
7151 _: &ConvertToUpperCase,
7152 window: &mut Window,
7153 cx: &mut Context<Self>,
7154 ) {
7155 self.manipulate_text(window, cx, |text| text.to_uppercase())
7156 }
7157
7158 pub fn convert_to_lower_case(
7159 &mut self,
7160 _: &ConvertToLowerCase,
7161 window: &mut Window,
7162 cx: &mut Context<Self>,
7163 ) {
7164 self.manipulate_text(window, cx, |text| text.to_lowercase())
7165 }
7166
7167 pub fn convert_to_title_case(
7168 &mut self,
7169 _: &ConvertToTitleCase,
7170 window: &mut Window,
7171 cx: &mut Context<Self>,
7172 ) {
7173 self.manipulate_text(window, cx, |text| {
7174 text.split('\n')
7175 .map(|line| line.to_case(Case::Title))
7176 .join("\n")
7177 })
7178 }
7179
7180 pub fn convert_to_snake_case(
7181 &mut self,
7182 _: &ConvertToSnakeCase,
7183 window: &mut Window,
7184 cx: &mut Context<Self>,
7185 ) {
7186 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7187 }
7188
7189 pub fn convert_to_kebab_case(
7190 &mut self,
7191 _: &ConvertToKebabCase,
7192 window: &mut Window,
7193 cx: &mut Context<Self>,
7194 ) {
7195 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7196 }
7197
7198 pub fn convert_to_upper_camel_case(
7199 &mut self,
7200 _: &ConvertToUpperCamelCase,
7201 window: &mut Window,
7202 cx: &mut Context<Self>,
7203 ) {
7204 self.manipulate_text(window, cx, |text| {
7205 text.split('\n')
7206 .map(|line| line.to_case(Case::UpperCamel))
7207 .join("\n")
7208 })
7209 }
7210
7211 pub fn convert_to_lower_camel_case(
7212 &mut self,
7213 _: &ConvertToLowerCamelCase,
7214 window: &mut Window,
7215 cx: &mut Context<Self>,
7216 ) {
7217 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7218 }
7219
7220 pub fn convert_to_opposite_case(
7221 &mut self,
7222 _: &ConvertToOppositeCase,
7223 window: &mut Window,
7224 cx: &mut Context<Self>,
7225 ) {
7226 self.manipulate_text(window, cx, |text| {
7227 text.chars()
7228 .fold(String::with_capacity(text.len()), |mut t, c| {
7229 if c.is_uppercase() {
7230 t.extend(c.to_lowercase());
7231 } else {
7232 t.extend(c.to_uppercase());
7233 }
7234 t
7235 })
7236 })
7237 }
7238
7239 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7240 where
7241 Fn: FnMut(&str) -> String,
7242 {
7243 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7244 let buffer = self.buffer.read(cx).snapshot(cx);
7245
7246 let mut new_selections = Vec::new();
7247 let mut edits = Vec::new();
7248 let mut selection_adjustment = 0i32;
7249
7250 for selection in self.selections.all::<usize>(cx) {
7251 let selection_is_empty = selection.is_empty();
7252
7253 let (start, end) = if selection_is_empty {
7254 let word_range = movement::surrounding_word(
7255 &display_map,
7256 selection.start.to_display_point(&display_map),
7257 );
7258 let start = word_range.start.to_offset(&display_map, Bias::Left);
7259 let end = word_range.end.to_offset(&display_map, Bias::Left);
7260 (start, end)
7261 } else {
7262 (selection.start, selection.end)
7263 };
7264
7265 let text = buffer.text_for_range(start..end).collect::<String>();
7266 let old_length = text.len() as i32;
7267 let text = callback(&text);
7268
7269 new_selections.push(Selection {
7270 start: (start as i32 - selection_adjustment) as usize,
7271 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7272 goal: SelectionGoal::None,
7273 ..selection
7274 });
7275
7276 selection_adjustment += old_length - text.len() as i32;
7277
7278 edits.push((start..end, text));
7279 }
7280
7281 self.transact(window, cx, |this, window, cx| {
7282 this.buffer.update(cx, |buffer, cx| {
7283 buffer.edit(edits, None, cx);
7284 });
7285
7286 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7287 s.select(new_selections);
7288 });
7289
7290 this.request_autoscroll(Autoscroll::fit(), cx);
7291 });
7292 }
7293
7294 pub fn duplicate(
7295 &mut self,
7296 upwards: bool,
7297 whole_lines: bool,
7298 window: &mut Window,
7299 cx: &mut Context<Self>,
7300 ) {
7301 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7302 let buffer = &display_map.buffer_snapshot;
7303 let selections = self.selections.all::<Point>(cx);
7304
7305 let mut edits = Vec::new();
7306 let mut selections_iter = selections.iter().peekable();
7307 while let Some(selection) = selections_iter.next() {
7308 let mut rows = selection.spanned_rows(false, &display_map);
7309 // duplicate line-wise
7310 if whole_lines || selection.start == selection.end {
7311 // Avoid duplicating the same lines twice.
7312 while let Some(next_selection) = selections_iter.peek() {
7313 let next_rows = next_selection.spanned_rows(false, &display_map);
7314 if next_rows.start < rows.end {
7315 rows.end = next_rows.end;
7316 selections_iter.next().unwrap();
7317 } else {
7318 break;
7319 }
7320 }
7321
7322 // Copy the text from the selected row region and splice it either at the start
7323 // or end of the region.
7324 let start = Point::new(rows.start.0, 0);
7325 let end = Point::new(
7326 rows.end.previous_row().0,
7327 buffer.line_len(rows.end.previous_row()),
7328 );
7329 let text = buffer
7330 .text_for_range(start..end)
7331 .chain(Some("\n"))
7332 .collect::<String>();
7333 let insert_location = if upwards {
7334 Point::new(rows.end.0, 0)
7335 } else {
7336 start
7337 };
7338 edits.push((insert_location..insert_location, text));
7339 } else {
7340 // duplicate character-wise
7341 let start = selection.start;
7342 let end = selection.end;
7343 let text = buffer.text_for_range(start..end).collect::<String>();
7344 edits.push((selection.end..selection.end, text));
7345 }
7346 }
7347
7348 self.transact(window, cx, |this, _, cx| {
7349 this.buffer.update(cx, |buffer, cx| {
7350 buffer.edit(edits, None, cx);
7351 });
7352
7353 this.request_autoscroll(Autoscroll::fit(), cx);
7354 });
7355 }
7356
7357 pub fn duplicate_line_up(
7358 &mut self,
7359 _: &DuplicateLineUp,
7360 window: &mut Window,
7361 cx: &mut Context<Self>,
7362 ) {
7363 self.duplicate(true, true, window, cx);
7364 }
7365
7366 pub fn duplicate_line_down(
7367 &mut self,
7368 _: &DuplicateLineDown,
7369 window: &mut Window,
7370 cx: &mut Context<Self>,
7371 ) {
7372 self.duplicate(false, true, window, cx);
7373 }
7374
7375 pub fn duplicate_selection(
7376 &mut self,
7377 _: &DuplicateSelection,
7378 window: &mut Window,
7379 cx: &mut Context<Self>,
7380 ) {
7381 self.duplicate(false, false, window, cx);
7382 }
7383
7384 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7385 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7386 let buffer = self.buffer.read(cx).snapshot(cx);
7387
7388 let mut edits = Vec::new();
7389 let mut unfold_ranges = Vec::new();
7390 let mut refold_creases = Vec::new();
7391
7392 let selections = self.selections.all::<Point>(cx);
7393 let mut selections = selections.iter().peekable();
7394 let mut contiguous_row_selections = Vec::new();
7395 let mut new_selections = Vec::new();
7396
7397 while let Some(selection) = selections.next() {
7398 // Find all the selections that span a contiguous row range
7399 let (start_row, end_row) = consume_contiguous_rows(
7400 &mut contiguous_row_selections,
7401 selection,
7402 &display_map,
7403 &mut selections,
7404 );
7405
7406 // Move the text spanned by the row range to be before the line preceding the row range
7407 if start_row.0 > 0 {
7408 let range_to_move = Point::new(
7409 start_row.previous_row().0,
7410 buffer.line_len(start_row.previous_row()),
7411 )
7412 ..Point::new(
7413 end_row.previous_row().0,
7414 buffer.line_len(end_row.previous_row()),
7415 );
7416 let insertion_point = display_map
7417 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7418 .0;
7419
7420 // Don't move lines across excerpts
7421 if buffer
7422 .excerpt_containing(insertion_point..range_to_move.end)
7423 .is_some()
7424 {
7425 let text = buffer
7426 .text_for_range(range_to_move.clone())
7427 .flat_map(|s| s.chars())
7428 .skip(1)
7429 .chain(['\n'])
7430 .collect::<String>();
7431
7432 edits.push((
7433 buffer.anchor_after(range_to_move.start)
7434 ..buffer.anchor_before(range_to_move.end),
7435 String::new(),
7436 ));
7437 let insertion_anchor = buffer.anchor_after(insertion_point);
7438 edits.push((insertion_anchor..insertion_anchor, text));
7439
7440 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7441
7442 // Move selections up
7443 new_selections.extend(contiguous_row_selections.drain(..).map(
7444 |mut selection| {
7445 selection.start.row -= row_delta;
7446 selection.end.row -= row_delta;
7447 selection
7448 },
7449 ));
7450
7451 // Move folds up
7452 unfold_ranges.push(range_to_move.clone());
7453 for fold in display_map.folds_in_range(
7454 buffer.anchor_before(range_to_move.start)
7455 ..buffer.anchor_after(range_to_move.end),
7456 ) {
7457 let mut start = fold.range.start.to_point(&buffer);
7458 let mut end = fold.range.end.to_point(&buffer);
7459 start.row -= row_delta;
7460 end.row -= row_delta;
7461 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7462 }
7463 }
7464 }
7465
7466 // If we didn't move line(s), preserve the existing selections
7467 new_selections.append(&mut contiguous_row_selections);
7468 }
7469
7470 self.transact(window, cx, |this, window, cx| {
7471 this.unfold_ranges(&unfold_ranges, true, true, cx);
7472 this.buffer.update(cx, |buffer, cx| {
7473 for (range, text) in edits {
7474 buffer.edit([(range, text)], None, cx);
7475 }
7476 });
7477 this.fold_creases(refold_creases, true, window, cx);
7478 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7479 s.select(new_selections);
7480 })
7481 });
7482 }
7483
7484 pub fn move_line_down(
7485 &mut self,
7486 _: &MoveLineDown,
7487 window: &mut Window,
7488 cx: &mut Context<Self>,
7489 ) {
7490 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7491 let buffer = self.buffer.read(cx).snapshot(cx);
7492
7493 let mut edits = Vec::new();
7494 let mut unfold_ranges = Vec::new();
7495 let mut refold_creases = Vec::new();
7496
7497 let selections = self.selections.all::<Point>(cx);
7498 let mut selections = selections.iter().peekable();
7499 let mut contiguous_row_selections = Vec::new();
7500 let mut new_selections = Vec::new();
7501
7502 while let Some(selection) = selections.next() {
7503 // Find all the selections that span a contiguous row range
7504 let (start_row, end_row) = consume_contiguous_rows(
7505 &mut contiguous_row_selections,
7506 selection,
7507 &display_map,
7508 &mut selections,
7509 );
7510
7511 // Move the text spanned by the row range to be after the last line of the row range
7512 if end_row.0 <= buffer.max_point().row {
7513 let range_to_move =
7514 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7515 let insertion_point = display_map
7516 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7517 .0;
7518
7519 // Don't move lines across excerpt boundaries
7520 if buffer
7521 .excerpt_containing(range_to_move.start..insertion_point)
7522 .is_some()
7523 {
7524 let mut text = String::from("\n");
7525 text.extend(buffer.text_for_range(range_to_move.clone()));
7526 text.pop(); // Drop trailing newline
7527 edits.push((
7528 buffer.anchor_after(range_to_move.start)
7529 ..buffer.anchor_before(range_to_move.end),
7530 String::new(),
7531 ));
7532 let insertion_anchor = buffer.anchor_after(insertion_point);
7533 edits.push((insertion_anchor..insertion_anchor, text));
7534
7535 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7536
7537 // Move selections down
7538 new_selections.extend(contiguous_row_selections.drain(..).map(
7539 |mut selection| {
7540 selection.start.row += row_delta;
7541 selection.end.row += row_delta;
7542 selection
7543 },
7544 ));
7545
7546 // Move folds down
7547 unfold_ranges.push(range_to_move.clone());
7548 for fold in display_map.folds_in_range(
7549 buffer.anchor_before(range_to_move.start)
7550 ..buffer.anchor_after(range_to_move.end),
7551 ) {
7552 let mut start = fold.range.start.to_point(&buffer);
7553 let mut end = fold.range.end.to_point(&buffer);
7554 start.row += row_delta;
7555 end.row += row_delta;
7556 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7557 }
7558 }
7559 }
7560
7561 // If we didn't move line(s), preserve the existing selections
7562 new_selections.append(&mut contiguous_row_selections);
7563 }
7564
7565 self.transact(window, cx, |this, window, cx| {
7566 this.unfold_ranges(&unfold_ranges, true, true, cx);
7567 this.buffer.update(cx, |buffer, cx| {
7568 for (range, text) in edits {
7569 buffer.edit([(range, text)], None, cx);
7570 }
7571 });
7572 this.fold_creases(refold_creases, true, window, cx);
7573 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7574 s.select(new_selections)
7575 });
7576 });
7577 }
7578
7579 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7580 let text_layout_details = &self.text_layout_details(window);
7581 self.transact(window, cx, |this, window, cx| {
7582 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7583 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7584 let line_mode = s.line_mode;
7585 s.move_with(|display_map, selection| {
7586 if !selection.is_empty() || line_mode {
7587 return;
7588 }
7589
7590 let mut head = selection.head();
7591 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7592 if head.column() == display_map.line_len(head.row()) {
7593 transpose_offset = display_map
7594 .buffer_snapshot
7595 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7596 }
7597
7598 if transpose_offset == 0 {
7599 return;
7600 }
7601
7602 *head.column_mut() += 1;
7603 head = display_map.clip_point(head, Bias::Right);
7604 let goal = SelectionGoal::HorizontalPosition(
7605 display_map
7606 .x_for_display_point(head, text_layout_details)
7607 .into(),
7608 );
7609 selection.collapse_to(head, goal);
7610
7611 let transpose_start = display_map
7612 .buffer_snapshot
7613 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7614 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7615 let transpose_end = display_map
7616 .buffer_snapshot
7617 .clip_offset(transpose_offset + 1, Bias::Right);
7618 if let Some(ch) =
7619 display_map.buffer_snapshot.chars_at(transpose_start).next()
7620 {
7621 edits.push((transpose_start..transpose_offset, String::new()));
7622 edits.push((transpose_end..transpose_end, ch.to_string()));
7623 }
7624 }
7625 });
7626 edits
7627 });
7628 this.buffer
7629 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7630 let selections = this.selections.all::<usize>(cx);
7631 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7632 s.select(selections);
7633 });
7634 });
7635 }
7636
7637 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7638 self.rewrap_impl(IsVimMode::No, cx)
7639 }
7640
7641 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7642 let buffer = self.buffer.read(cx).snapshot(cx);
7643 let selections = self.selections.all::<Point>(cx);
7644 let mut selections = selections.iter().peekable();
7645
7646 let mut edits = Vec::new();
7647 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7648
7649 while let Some(selection) = selections.next() {
7650 let mut start_row = selection.start.row;
7651 let mut end_row = selection.end.row;
7652
7653 // Skip selections that overlap with a range that has already been rewrapped.
7654 let selection_range = start_row..end_row;
7655 if rewrapped_row_ranges
7656 .iter()
7657 .any(|range| range.overlaps(&selection_range))
7658 {
7659 continue;
7660 }
7661
7662 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7663
7664 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7665 match language_scope.language_name().as_ref() {
7666 "Markdown" | "Plain Text" => {
7667 should_rewrap = true;
7668 }
7669 _ => {}
7670 }
7671 }
7672
7673 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7674
7675 // Since not all lines in the selection may be at the same indent
7676 // level, choose the indent size that is the most common between all
7677 // of the lines.
7678 //
7679 // If there is a tie, we use the deepest indent.
7680 let (indent_size, indent_end) = {
7681 let mut indent_size_occurrences = HashMap::default();
7682 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7683
7684 for row in start_row..=end_row {
7685 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7686 rows_by_indent_size.entry(indent).or_default().push(row);
7687 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7688 }
7689
7690 let indent_size = indent_size_occurrences
7691 .into_iter()
7692 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7693 .map(|(indent, _)| indent)
7694 .unwrap_or_default();
7695 let row = rows_by_indent_size[&indent_size][0];
7696 let indent_end = Point::new(row, indent_size.len);
7697
7698 (indent_size, indent_end)
7699 };
7700
7701 let mut line_prefix = indent_size.chars().collect::<String>();
7702
7703 if let Some(comment_prefix) =
7704 buffer
7705 .language_scope_at(selection.head())
7706 .and_then(|language| {
7707 language
7708 .line_comment_prefixes()
7709 .iter()
7710 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7711 .cloned()
7712 })
7713 {
7714 line_prefix.push_str(&comment_prefix);
7715 should_rewrap = true;
7716 }
7717
7718 if !should_rewrap {
7719 continue;
7720 }
7721
7722 if selection.is_empty() {
7723 'expand_upwards: while start_row > 0 {
7724 let prev_row = start_row - 1;
7725 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7726 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7727 {
7728 start_row = prev_row;
7729 } else {
7730 break 'expand_upwards;
7731 }
7732 }
7733
7734 'expand_downwards: while end_row < buffer.max_point().row {
7735 let next_row = end_row + 1;
7736 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7737 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7738 {
7739 end_row = next_row;
7740 } else {
7741 break 'expand_downwards;
7742 }
7743 }
7744 }
7745
7746 let start = Point::new(start_row, 0);
7747 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7748 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7749 let Some(lines_without_prefixes) = selection_text
7750 .lines()
7751 .map(|line| {
7752 line.strip_prefix(&line_prefix)
7753 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7754 .ok_or_else(|| {
7755 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7756 })
7757 })
7758 .collect::<Result<Vec<_>, _>>()
7759 .log_err()
7760 else {
7761 continue;
7762 };
7763
7764 let wrap_column = buffer
7765 .settings_at(Point::new(start_row, 0), cx)
7766 .preferred_line_length as usize;
7767 let wrapped_text = wrap_with_prefix(
7768 line_prefix,
7769 lines_without_prefixes.join(" "),
7770 wrap_column,
7771 tab_size,
7772 );
7773
7774 // TODO: should always use char-based diff while still supporting cursor behavior that
7775 // matches vim.
7776 let diff = match is_vim_mode {
7777 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7778 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7779 };
7780 let mut offset = start.to_offset(&buffer);
7781 let mut moved_since_edit = true;
7782
7783 for change in diff.iter_all_changes() {
7784 let value = change.value();
7785 match change.tag() {
7786 ChangeTag::Equal => {
7787 offset += value.len();
7788 moved_since_edit = true;
7789 }
7790 ChangeTag::Delete => {
7791 let start = buffer.anchor_after(offset);
7792 let end = buffer.anchor_before(offset + value.len());
7793
7794 if moved_since_edit {
7795 edits.push((start..end, String::new()));
7796 } else {
7797 edits.last_mut().unwrap().0.end = end;
7798 }
7799
7800 offset += value.len();
7801 moved_since_edit = false;
7802 }
7803 ChangeTag::Insert => {
7804 if moved_since_edit {
7805 let anchor = buffer.anchor_after(offset);
7806 edits.push((anchor..anchor, value.to_string()));
7807 } else {
7808 edits.last_mut().unwrap().1.push_str(value);
7809 }
7810
7811 moved_since_edit = false;
7812 }
7813 }
7814 }
7815
7816 rewrapped_row_ranges.push(start_row..=end_row);
7817 }
7818
7819 self.buffer
7820 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7821 }
7822
7823 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7824 let mut text = String::new();
7825 let buffer = self.buffer.read(cx).snapshot(cx);
7826 let mut selections = self.selections.all::<Point>(cx);
7827 let mut clipboard_selections = Vec::with_capacity(selections.len());
7828 {
7829 let max_point = buffer.max_point();
7830 let mut is_first = true;
7831 for selection in &mut selections {
7832 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7833 if is_entire_line {
7834 selection.start = Point::new(selection.start.row, 0);
7835 if !selection.is_empty() && selection.end.column == 0 {
7836 selection.end = cmp::min(max_point, selection.end);
7837 } else {
7838 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7839 }
7840 selection.goal = SelectionGoal::None;
7841 }
7842 if is_first {
7843 is_first = false;
7844 } else {
7845 text += "\n";
7846 }
7847 let mut len = 0;
7848 for chunk in buffer.text_for_range(selection.start..selection.end) {
7849 text.push_str(chunk);
7850 len += chunk.len();
7851 }
7852 clipboard_selections.push(ClipboardSelection {
7853 len,
7854 is_entire_line,
7855 first_line_indent: buffer
7856 .indent_size_for_line(MultiBufferRow(selection.start.row))
7857 .len,
7858 });
7859 }
7860 }
7861
7862 self.transact(window, cx, |this, window, cx| {
7863 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7864 s.select(selections);
7865 });
7866 this.insert("", window, cx);
7867 });
7868 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7869 }
7870
7871 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7872 let item = self.cut_common(window, cx);
7873 cx.write_to_clipboard(item);
7874 }
7875
7876 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7877 self.change_selections(None, window, cx, |s| {
7878 s.move_with(|snapshot, sel| {
7879 if sel.is_empty() {
7880 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7881 }
7882 });
7883 });
7884 let item = self.cut_common(window, cx);
7885 cx.set_global(KillRing(item))
7886 }
7887
7888 pub fn kill_ring_yank(
7889 &mut self,
7890 _: &KillRingYank,
7891 window: &mut Window,
7892 cx: &mut Context<Self>,
7893 ) {
7894 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7895 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7896 (kill_ring.text().to_string(), kill_ring.metadata_json())
7897 } else {
7898 return;
7899 }
7900 } else {
7901 return;
7902 };
7903 self.do_paste(&text, metadata, false, window, cx);
7904 }
7905
7906 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7907 let selections = self.selections.all::<Point>(cx);
7908 let buffer = self.buffer.read(cx).read(cx);
7909 let mut text = String::new();
7910
7911 let mut clipboard_selections = Vec::with_capacity(selections.len());
7912 {
7913 let max_point = buffer.max_point();
7914 let mut is_first = true;
7915 for selection in selections.iter() {
7916 let mut start = selection.start;
7917 let mut end = selection.end;
7918 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7919 if is_entire_line {
7920 start = Point::new(start.row, 0);
7921 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7922 }
7923 if is_first {
7924 is_first = false;
7925 } else {
7926 text += "\n";
7927 }
7928 let mut len = 0;
7929 for chunk in buffer.text_for_range(start..end) {
7930 text.push_str(chunk);
7931 len += chunk.len();
7932 }
7933 clipboard_selections.push(ClipboardSelection {
7934 len,
7935 is_entire_line,
7936 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7937 });
7938 }
7939 }
7940
7941 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7942 text,
7943 clipboard_selections,
7944 ));
7945 }
7946
7947 pub fn do_paste(
7948 &mut self,
7949 text: &String,
7950 clipboard_selections: Option<Vec<ClipboardSelection>>,
7951 handle_entire_lines: bool,
7952 window: &mut Window,
7953 cx: &mut Context<Self>,
7954 ) {
7955 if self.read_only(cx) {
7956 return;
7957 }
7958
7959 let clipboard_text = Cow::Borrowed(text);
7960
7961 self.transact(window, cx, |this, window, cx| {
7962 if let Some(mut clipboard_selections) = clipboard_selections {
7963 let old_selections = this.selections.all::<usize>(cx);
7964 let all_selections_were_entire_line =
7965 clipboard_selections.iter().all(|s| s.is_entire_line);
7966 let first_selection_indent_column =
7967 clipboard_selections.first().map(|s| s.first_line_indent);
7968 if clipboard_selections.len() != old_selections.len() {
7969 clipboard_selections.drain(..);
7970 }
7971 let cursor_offset = this.selections.last::<usize>(cx).head();
7972 let mut auto_indent_on_paste = true;
7973
7974 this.buffer.update(cx, |buffer, cx| {
7975 let snapshot = buffer.read(cx);
7976 auto_indent_on_paste =
7977 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7978
7979 let mut start_offset = 0;
7980 let mut edits = Vec::new();
7981 let mut original_indent_columns = Vec::new();
7982 for (ix, selection) in old_selections.iter().enumerate() {
7983 let to_insert;
7984 let entire_line;
7985 let original_indent_column;
7986 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7987 let end_offset = start_offset + clipboard_selection.len;
7988 to_insert = &clipboard_text[start_offset..end_offset];
7989 entire_line = clipboard_selection.is_entire_line;
7990 start_offset = end_offset + 1;
7991 original_indent_column = Some(clipboard_selection.first_line_indent);
7992 } else {
7993 to_insert = clipboard_text.as_str();
7994 entire_line = all_selections_were_entire_line;
7995 original_indent_column = first_selection_indent_column
7996 }
7997
7998 // If the corresponding selection was empty when this slice of the
7999 // clipboard text was written, then the entire line containing the
8000 // selection was copied. If this selection is also currently empty,
8001 // then paste the line before the current line of the buffer.
8002 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8003 let column = selection.start.to_point(&snapshot).column as usize;
8004 let line_start = selection.start - column;
8005 line_start..line_start
8006 } else {
8007 selection.range()
8008 };
8009
8010 edits.push((range, to_insert));
8011 original_indent_columns.extend(original_indent_column);
8012 }
8013 drop(snapshot);
8014
8015 buffer.edit(
8016 edits,
8017 if auto_indent_on_paste {
8018 Some(AutoindentMode::Block {
8019 original_indent_columns,
8020 })
8021 } else {
8022 None
8023 },
8024 cx,
8025 );
8026 });
8027
8028 let selections = this.selections.all::<usize>(cx);
8029 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8030 s.select(selections)
8031 });
8032 } else {
8033 this.insert(&clipboard_text, window, cx);
8034 }
8035 });
8036 }
8037
8038 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8039 if let Some(item) = cx.read_from_clipboard() {
8040 let entries = item.entries();
8041
8042 match entries.first() {
8043 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8044 // of all the pasted entries.
8045 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8046 .do_paste(
8047 clipboard_string.text(),
8048 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8049 true,
8050 window,
8051 cx,
8052 ),
8053 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8054 }
8055 }
8056 }
8057
8058 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8059 if self.read_only(cx) {
8060 return;
8061 }
8062
8063 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8064 if let Some((selections, _)) =
8065 self.selection_history.transaction(transaction_id).cloned()
8066 {
8067 self.change_selections(None, window, cx, |s| {
8068 s.select_anchors(selections.to_vec());
8069 });
8070 }
8071 self.request_autoscroll(Autoscroll::fit(), cx);
8072 self.unmark_text(window, cx);
8073 self.refresh_inline_completion(true, false, window, cx);
8074 cx.emit(EditorEvent::Edited { transaction_id });
8075 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8076 }
8077 }
8078
8079 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8080 if self.read_only(cx) {
8081 return;
8082 }
8083
8084 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8085 if let Some((_, Some(selections))) =
8086 self.selection_history.transaction(transaction_id).cloned()
8087 {
8088 self.change_selections(None, window, cx, |s| {
8089 s.select_anchors(selections.to_vec());
8090 });
8091 }
8092 self.request_autoscroll(Autoscroll::fit(), cx);
8093 self.unmark_text(window, cx);
8094 self.refresh_inline_completion(true, false, window, cx);
8095 cx.emit(EditorEvent::Edited { transaction_id });
8096 }
8097 }
8098
8099 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8100 self.buffer
8101 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8102 }
8103
8104 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8105 self.buffer
8106 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8107 }
8108
8109 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8111 let line_mode = s.line_mode;
8112 s.move_with(|map, selection| {
8113 let cursor = if selection.is_empty() && !line_mode {
8114 movement::left(map, selection.start)
8115 } else {
8116 selection.start
8117 };
8118 selection.collapse_to(cursor, SelectionGoal::None);
8119 });
8120 })
8121 }
8122
8123 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8124 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8125 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8126 })
8127 }
8128
8129 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8130 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8131 let line_mode = s.line_mode;
8132 s.move_with(|map, selection| {
8133 let cursor = if selection.is_empty() && !line_mode {
8134 movement::right(map, selection.end)
8135 } else {
8136 selection.end
8137 };
8138 selection.collapse_to(cursor, SelectionGoal::None)
8139 });
8140 })
8141 }
8142
8143 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8144 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8145 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8146 })
8147 }
8148
8149 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8150 if self.take_rename(true, window, cx).is_some() {
8151 return;
8152 }
8153
8154 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8155 cx.propagate();
8156 return;
8157 }
8158
8159 let text_layout_details = &self.text_layout_details(window);
8160 let selection_count = self.selections.count();
8161 let first_selection = self.selections.first_anchor();
8162
8163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8164 let line_mode = s.line_mode;
8165 s.move_with(|map, selection| {
8166 if !selection.is_empty() && !line_mode {
8167 selection.goal = SelectionGoal::None;
8168 }
8169 let (cursor, goal) = movement::up(
8170 map,
8171 selection.start,
8172 selection.goal,
8173 false,
8174 text_layout_details,
8175 );
8176 selection.collapse_to(cursor, goal);
8177 });
8178 });
8179
8180 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8181 {
8182 cx.propagate();
8183 }
8184 }
8185
8186 pub fn move_up_by_lines(
8187 &mut self,
8188 action: &MoveUpByLines,
8189 window: &mut Window,
8190 cx: &mut Context<Self>,
8191 ) {
8192 if self.take_rename(true, window, cx).is_some() {
8193 return;
8194 }
8195
8196 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8197 cx.propagate();
8198 return;
8199 }
8200
8201 let text_layout_details = &self.text_layout_details(window);
8202
8203 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8204 let line_mode = s.line_mode;
8205 s.move_with(|map, selection| {
8206 if !selection.is_empty() && !line_mode {
8207 selection.goal = SelectionGoal::None;
8208 }
8209 let (cursor, goal) = movement::up_by_rows(
8210 map,
8211 selection.start,
8212 action.lines,
8213 selection.goal,
8214 false,
8215 text_layout_details,
8216 );
8217 selection.collapse_to(cursor, goal);
8218 });
8219 })
8220 }
8221
8222 pub fn move_down_by_lines(
8223 &mut self,
8224 action: &MoveDownByLines,
8225 window: &mut Window,
8226 cx: &mut Context<Self>,
8227 ) {
8228 if self.take_rename(true, window, cx).is_some() {
8229 return;
8230 }
8231
8232 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8233 cx.propagate();
8234 return;
8235 }
8236
8237 let text_layout_details = &self.text_layout_details(window);
8238
8239 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8240 let line_mode = s.line_mode;
8241 s.move_with(|map, selection| {
8242 if !selection.is_empty() && !line_mode {
8243 selection.goal = SelectionGoal::None;
8244 }
8245 let (cursor, goal) = movement::down_by_rows(
8246 map,
8247 selection.start,
8248 action.lines,
8249 selection.goal,
8250 false,
8251 text_layout_details,
8252 );
8253 selection.collapse_to(cursor, goal);
8254 });
8255 })
8256 }
8257
8258 pub fn select_down_by_lines(
8259 &mut self,
8260 action: &SelectDownByLines,
8261 window: &mut Window,
8262 cx: &mut Context<Self>,
8263 ) {
8264 let text_layout_details = &self.text_layout_details(window);
8265 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8266 s.move_heads_with(|map, head, goal| {
8267 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8268 })
8269 })
8270 }
8271
8272 pub fn select_up_by_lines(
8273 &mut self,
8274 action: &SelectUpByLines,
8275 window: &mut Window,
8276 cx: &mut Context<Self>,
8277 ) {
8278 let text_layout_details = &self.text_layout_details(window);
8279 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8280 s.move_heads_with(|map, head, goal| {
8281 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8282 })
8283 })
8284 }
8285
8286 pub fn select_page_up(
8287 &mut self,
8288 _: &SelectPageUp,
8289 window: &mut Window,
8290 cx: &mut Context<Self>,
8291 ) {
8292 let Some(row_count) = self.visible_row_count() else {
8293 return;
8294 };
8295
8296 let text_layout_details = &self.text_layout_details(window);
8297
8298 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8299 s.move_heads_with(|map, head, goal| {
8300 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8301 })
8302 })
8303 }
8304
8305 pub fn move_page_up(
8306 &mut self,
8307 action: &MovePageUp,
8308 window: &mut Window,
8309 cx: &mut Context<Self>,
8310 ) {
8311 if self.take_rename(true, window, cx).is_some() {
8312 return;
8313 }
8314
8315 if self
8316 .context_menu
8317 .borrow_mut()
8318 .as_mut()
8319 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8320 .unwrap_or(false)
8321 {
8322 return;
8323 }
8324
8325 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8326 cx.propagate();
8327 return;
8328 }
8329
8330 let Some(row_count) = self.visible_row_count() else {
8331 return;
8332 };
8333
8334 let autoscroll = if action.center_cursor {
8335 Autoscroll::center()
8336 } else {
8337 Autoscroll::fit()
8338 };
8339
8340 let text_layout_details = &self.text_layout_details(window);
8341
8342 self.change_selections(Some(autoscroll), window, cx, |s| {
8343 let line_mode = s.line_mode;
8344 s.move_with(|map, selection| {
8345 if !selection.is_empty() && !line_mode {
8346 selection.goal = SelectionGoal::None;
8347 }
8348 let (cursor, goal) = movement::up_by_rows(
8349 map,
8350 selection.end,
8351 row_count,
8352 selection.goal,
8353 false,
8354 text_layout_details,
8355 );
8356 selection.collapse_to(cursor, goal);
8357 });
8358 });
8359 }
8360
8361 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8362 let text_layout_details = &self.text_layout_details(window);
8363 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8364 s.move_heads_with(|map, head, goal| {
8365 movement::up(map, head, goal, false, text_layout_details)
8366 })
8367 })
8368 }
8369
8370 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8371 self.take_rename(true, window, cx);
8372
8373 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8374 cx.propagate();
8375 return;
8376 }
8377
8378 let text_layout_details = &self.text_layout_details(window);
8379 let selection_count = self.selections.count();
8380 let first_selection = self.selections.first_anchor();
8381
8382 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8383 let line_mode = s.line_mode;
8384 s.move_with(|map, selection| {
8385 if !selection.is_empty() && !line_mode {
8386 selection.goal = SelectionGoal::None;
8387 }
8388 let (cursor, goal) = movement::down(
8389 map,
8390 selection.end,
8391 selection.goal,
8392 false,
8393 text_layout_details,
8394 );
8395 selection.collapse_to(cursor, goal);
8396 });
8397 });
8398
8399 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8400 {
8401 cx.propagate();
8402 }
8403 }
8404
8405 pub fn select_page_down(
8406 &mut self,
8407 _: &SelectPageDown,
8408 window: &mut Window,
8409 cx: &mut Context<Self>,
8410 ) {
8411 let Some(row_count) = self.visible_row_count() else {
8412 return;
8413 };
8414
8415 let text_layout_details = &self.text_layout_details(window);
8416
8417 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8418 s.move_heads_with(|map, head, goal| {
8419 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8420 })
8421 })
8422 }
8423
8424 pub fn move_page_down(
8425 &mut self,
8426 action: &MovePageDown,
8427 window: &mut Window,
8428 cx: &mut Context<Self>,
8429 ) {
8430 if self.take_rename(true, window, cx).is_some() {
8431 return;
8432 }
8433
8434 if self
8435 .context_menu
8436 .borrow_mut()
8437 .as_mut()
8438 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8439 .unwrap_or(false)
8440 {
8441 return;
8442 }
8443
8444 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8445 cx.propagate();
8446 return;
8447 }
8448
8449 let Some(row_count) = self.visible_row_count() else {
8450 return;
8451 };
8452
8453 let autoscroll = if action.center_cursor {
8454 Autoscroll::center()
8455 } else {
8456 Autoscroll::fit()
8457 };
8458
8459 let text_layout_details = &self.text_layout_details(window);
8460 self.change_selections(Some(autoscroll), window, cx, |s| {
8461 let line_mode = s.line_mode;
8462 s.move_with(|map, selection| {
8463 if !selection.is_empty() && !line_mode {
8464 selection.goal = SelectionGoal::None;
8465 }
8466 let (cursor, goal) = movement::down_by_rows(
8467 map,
8468 selection.end,
8469 row_count,
8470 selection.goal,
8471 false,
8472 text_layout_details,
8473 );
8474 selection.collapse_to(cursor, goal);
8475 });
8476 });
8477 }
8478
8479 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8480 let text_layout_details = &self.text_layout_details(window);
8481 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8482 s.move_heads_with(|map, head, goal| {
8483 movement::down(map, head, goal, false, text_layout_details)
8484 })
8485 });
8486 }
8487
8488 pub fn context_menu_first(
8489 &mut self,
8490 _: &ContextMenuFirst,
8491 _window: &mut Window,
8492 cx: &mut Context<Self>,
8493 ) {
8494 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8495 context_menu.select_first(self.completion_provider.as_deref(), cx);
8496 }
8497 }
8498
8499 pub fn context_menu_prev(
8500 &mut self,
8501 _: &ContextMenuPrev,
8502 _window: &mut Window,
8503 cx: &mut Context<Self>,
8504 ) {
8505 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8506 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8507 }
8508 }
8509
8510 pub fn context_menu_next(
8511 &mut self,
8512 _: &ContextMenuNext,
8513 _window: &mut Window,
8514 cx: &mut Context<Self>,
8515 ) {
8516 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8517 context_menu.select_next(self.completion_provider.as_deref(), cx);
8518 }
8519 }
8520
8521 pub fn context_menu_last(
8522 &mut self,
8523 _: &ContextMenuLast,
8524 _window: &mut Window,
8525 cx: &mut Context<Self>,
8526 ) {
8527 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8528 context_menu.select_last(self.completion_provider.as_deref(), cx);
8529 }
8530 }
8531
8532 pub fn move_to_previous_word_start(
8533 &mut self,
8534 _: &MoveToPreviousWordStart,
8535 window: &mut Window,
8536 cx: &mut Context<Self>,
8537 ) {
8538 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8539 s.move_cursors_with(|map, head, _| {
8540 (
8541 movement::previous_word_start(map, head),
8542 SelectionGoal::None,
8543 )
8544 });
8545 })
8546 }
8547
8548 pub fn move_to_previous_subword_start(
8549 &mut self,
8550 _: &MoveToPreviousSubwordStart,
8551 window: &mut Window,
8552 cx: &mut Context<Self>,
8553 ) {
8554 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8555 s.move_cursors_with(|map, head, _| {
8556 (
8557 movement::previous_subword_start(map, head),
8558 SelectionGoal::None,
8559 )
8560 });
8561 })
8562 }
8563
8564 pub fn select_to_previous_word_start(
8565 &mut self,
8566 _: &SelectToPreviousWordStart,
8567 window: &mut Window,
8568 cx: &mut Context<Self>,
8569 ) {
8570 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8571 s.move_heads_with(|map, head, _| {
8572 (
8573 movement::previous_word_start(map, head),
8574 SelectionGoal::None,
8575 )
8576 });
8577 })
8578 }
8579
8580 pub fn select_to_previous_subword_start(
8581 &mut self,
8582 _: &SelectToPreviousSubwordStart,
8583 window: &mut Window,
8584 cx: &mut Context<Self>,
8585 ) {
8586 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8587 s.move_heads_with(|map, head, _| {
8588 (
8589 movement::previous_subword_start(map, head),
8590 SelectionGoal::None,
8591 )
8592 });
8593 })
8594 }
8595
8596 pub fn delete_to_previous_word_start(
8597 &mut self,
8598 action: &DeleteToPreviousWordStart,
8599 window: &mut Window,
8600 cx: &mut Context<Self>,
8601 ) {
8602 self.transact(window, cx, |this, window, cx| {
8603 this.select_autoclose_pair(window, cx);
8604 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8605 let line_mode = s.line_mode;
8606 s.move_with(|map, selection| {
8607 if selection.is_empty() && !line_mode {
8608 let cursor = if action.ignore_newlines {
8609 movement::previous_word_start(map, selection.head())
8610 } else {
8611 movement::previous_word_start_or_newline(map, selection.head())
8612 };
8613 selection.set_head(cursor, SelectionGoal::None);
8614 }
8615 });
8616 });
8617 this.insert("", window, cx);
8618 });
8619 }
8620
8621 pub fn delete_to_previous_subword_start(
8622 &mut self,
8623 _: &DeleteToPreviousSubwordStart,
8624 window: &mut Window,
8625 cx: &mut Context<Self>,
8626 ) {
8627 self.transact(window, cx, |this, window, cx| {
8628 this.select_autoclose_pair(window, cx);
8629 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8630 let line_mode = s.line_mode;
8631 s.move_with(|map, selection| {
8632 if selection.is_empty() && !line_mode {
8633 let cursor = movement::previous_subword_start(map, selection.head());
8634 selection.set_head(cursor, SelectionGoal::None);
8635 }
8636 });
8637 });
8638 this.insert("", window, cx);
8639 });
8640 }
8641
8642 pub fn move_to_next_word_end(
8643 &mut self,
8644 _: &MoveToNextWordEnd,
8645 window: &mut Window,
8646 cx: &mut Context<Self>,
8647 ) {
8648 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8649 s.move_cursors_with(|map, head, _| {
8650 (movement::next_word_end(map, head), SelectionGoal::None)
8651 });
8652 })
8653 }
8654
8655 pub fn move_to_next_subword_end(
8656 &mut self,
8657 _: &MoveToNextSubwordEnd,
8658 window: &mut Window,
8659 cx: &mut Context<Self>,
8660 ) {
8661 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8662 s.move_cursors_with(|map, head, _| {
8663 (movement::next_subword_end(map, head), SelectionGoal::None)
8664 });
8665 })
8666 }
8667
8668 pub fn select_to_next_word_end(
8669 &mut self,
8670 _: &SelectToNextWordEnd,
8671 window: &mut Window,
8672 cx: &mut Context<Self>,
8673 ) {
8674 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8675 s.move_heads_with(|map, head, _| {
8676 (movement::next_word_end(map, head), SelectionGoal::None)
8677 });
8678 })
8679 }
8680
8681 pub fn select_to_next_subword_end(
8682 &mut self,
8683 _: &SelectToNextSubwordEnd,
8684 window: &mut Window,
8685 cx: &mut Context<Self>,
8686 ) {
8687 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8688 s.move_heads_with(|map, head, _| {
8689 (movement::next_subword_end(map, head), SelectionGoal::None)
8690 });
8691 })
8692 }
8693
8694 pub fn delete_to_next_word_end(
8695 &mut self,
8696 action: &DeleteToNextWordEnd,
8697 window: &mut Window,
8698 cx: &mut Context<Self>,
8699 ) {
8700 self.transact(window, cx, |this, 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::next_word_end(map, selection.head())
8707 } else {
8708 movement::next_word_end_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_next_subword_end(
8719 &mut self,
8720 _: &DeleteToNextSubwordEnd,
8721 window: &mut Window,
8722 cx: &mut Context<Self>,
8723 ) {
8724 self.transact(window, cx, |this, window, cx| {
8725 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8726 s.move_with(|map, selection| {
8727 if selection.is_empty() {
8728 let cursor = movement::next_subword_end(map, selection.head());
8729 selection.set_head(cursor, SelectionGoal::None);
8730 }
8731 });
8732 });
8733 this.insert("", window, cx);
8734 });
8735 }
8736
8737 pub fn move_to_beginning_of_line(
8738 &mut self,
8739 action: &MoveToBeginningOfLine,
8740 window: &mut Window,
8741 cx: &mut Context<Self>,
8742 ) {
8743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8744 s.move_cursors_with(|map, head, _| {
8745 (
8746 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8747 SelectionGoal::None,
8748 )
8749 });
8750 })
8751 }
8752
8753 pub fn select_to_beginning_of_line(
8754 &mut self,
8755 action: &SelectToBeginningOfLine,
8756 window: &mut Window,
8757 cx: &mut Context<Self>,
8758 ) {
8759 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8760 s.move_heads_with(|map, head, _| {
8761 (
8762 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8763 SelectionGoal::None,
8764 )
8765 });
8766 });
8767 }
8768
8769 pub fn delete_to_beginning_of_line(
8770 &mut self,
8771 _: &DeleteToBeginningOfLine,
8772 window: &mut Window,
8773 cx: &mut Context<Self>,
8774 ) {
8775 self.transact(window, cx, |this, window, cx| {
8776 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8777 s.move_with(|_, selection| {
8778 selection.reversed = true;
8779 });
8780 });
8781
8782 this.select_to_beginning_of_line(
8783 &SelectToBeginningOfLine {
8784 stop_at_soft_wraps: false,
8785 },
8786 window,
8787 cx,
8788 );
8789 this.backspace(&Backspace, window, cx);
8790 });
8791 }
8792
8793 pub fn move_to_end_of_line(
8794 &mut self,
8795 action: &MoveToEndOfLine,
8796 window: &mut Window,
8797 cx: &mut Context<Self>,
8798 ) {
8799 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8800 s.move_cursors_with(|map, head, _| {
8801 (
8802 movement::line_end(map, head, action.stop_at_soft_wraps),
8803 SelectionGoal::None,
8804 )
8805 });
8806 })
8807 }
8808
8809 pub fn select_to_end_of_line(
8810 &mut self,
8811 action: &SelectToEndOfLine,
8812 window: &mut Window,
8813 cx: &mut Context<Self>,
8814 ) {
8815 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8816 s.move_heads_with(|map, head, _| {
8817 (
8818 movement::line_end(map, head, action.stop_at_soft_wraps),
8819 SelectionGoal::None,
8820 )
8821 });
8822 })
8823 }
8824
8825 pub fn delete_to_end_of_line(
8826 &mut self,
8827 _: &DeleteToEndOfLine,
8828 window: &mut Window,
8829 cx: &mut Context<Self>,
8830 ) {
8831 self.transact(window, cx, |this, window, cx| {
8832 this.select_to_end_of_line(
8833 &SelectToEndOfLine {
8834 stop_at_soft_wraps: false,
8835 },
8836 window,
8837 cx,
8838 );
8839 this.delete(&Delete, window, cx);
8840 });
8841 }
8842
8843 pub fn cut_to_end_of_line(
8844 &mut self,
8845 _: &CutToEndOfLine,
8846 window: &mut Window,
8847 cx: &mut Context<Self>,
8848 ) {
8849 self.transact(window, cx, |this, window, cx| {
8850 this.select_to_end_of_line(
8851 &SelectToEndOfLine {
8852 stop_at_soft_wraps: false,
8853 },
8854 window,
8855 cx,
8856 );
8857 this.cut(&Cut, window, cx);
8858 });
8859 }
8860
8861 pub fn move_to_start_of_paragraph(
8862 &mut self,
8863 _: &MoveToStartOfParagraph,
8864 window: &mut Window,
8865 cx: &mut Context<Self>,
8866 ) {
8867 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8868 cx.propagate();
8869 return;
8870 }
8871
8872 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8873 s.move_with(|map, selection| {
8874 selection.collapse_to(
8875 movement::start_of_paragraph(map, selection.head(), 1),
8876 SelectionGoal::None,
8877 )
8878 });
8879 })
8880 }
8881
8882 pub fn move_to_end_of_paragraph(
8883 &mut self,
8884 _: &MoveToEndOfParagraph,
8885 window: &mut Window,
8886 cx: &mut Context<Self>,
8887 ) {
8888 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8889 cx.propagate();
8890 return;
8891 }
8892
8893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8894 s.move_with(|map, selection| {
8895 selection.collapse_to(
8896 movement::end_of_paragraph(map, selection.head(), 1),
8897 SelectionGoal::None,
8898 )
8899 });
8900 })
8901 }
8902
8903 pub fn select_to_start_of_paragraph(
8904 &mut self,
8905 _: &SelectToStartOfParagraph,
8906 window: &mut Window,
8907 cx: &mut Context<Self>,
8908 ) {
8909 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8910 cx.propagate();
8911 return;
8912 }
8913
8914 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8915 s.move_heads_with(|map, head, _| {
8916 (
8917 movement::start_of_paragraph(map, head, 1),
8918 SelectionGoal::None,
8919 )
8920 });
8921 })
8922 }
8923
8924 pub fn select_to_end_of_paragraph(
8925 &mut self,
8926 _: &SelectToEndOfParagraph,
8927 window: &mut Window,
8928 cx: &mut Context<Self>,
8929 ) {
8930 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8931 cx.propagate();
8932 return;
8933 }
8934
8935 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8936 s.move_heads_with(|map, head, _| {
8937 (
8938 movement::end_of_paragraph(map, head, 1),
8939 SelectionGoal::None,
8940 )
8941 });
8942 })
8943 }
8944
8945 pub fn move_to_beginning(
8946 &mut self,
8947 _: &MoveToBeginning,
8948 window: &mut Window,
8949 cx: &mut Context<Self>,
8950 ) {
8951 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8952 cx.propagate();
8953 return;
8954 }
8955
8956 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8957 s.select_ranges(vec![0..0]);
8958 });
8959 }
8960
8961 pub fn select_to_beginning(
8962 &mut self,
8963 _: &SelectToBeginning,
8964 window: &mut Window,
8965 cx: &mut Context<Self>,
8966 ) {
8967 let mut selection = self.selections.last::<Point>(cx);
8968 selection.set_head(Point::zero(), SelectionGoal::None);
8969
8970 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8971 s.select(vec![selection]);
8972 });
8973 }
8974
8975 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8976 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8977 cx.propagate();
8978 return;
8979 }
8980
8981 let cursor = self.buffer.read(cx).read(cx).len();
8982 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8983 s.select_ranges(vec![cursor..cursor])
8984 });
8985 }
8986
8987 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8988 self.nav_history = nav_history;
8989 }
8990
8991 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8992 self.nav_history.as_ref()
8993 }
8994
8995 fn push_to_nav_history(
8996 &mut self,
8997 cursor_anchor: Anchor,
8998 new_position: Option<Point>,
8999 cx: &mut Context<Self>,
9000 ) {
9001 if let Some(nav_history) = self.nav_history.as_mut() {
9002 let buffer = self.buffer.read(cx).read(cx);
9003 let cursor_position = cursor_anchor.to_point(&buffer);
9004 let scroll_state = self.scroll_manager.anchor();
9005 let scroll_top_row = scroll_state.top_row(&buffer);
9006 drop(buffer);
9007
9008 if let Some(new_position) = new_position {
9009 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9010 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9011 return;
9012 }
9013 }
9014
9015 nav_history.push(
9016 Some(NavigationData {
9017 cursor_anchor,
9018 cursor_position,
9019 scroll_anchor: scroll_state,
9020 scroll_top_row,
9021 }),
9022 cx,
9023 );
9024 }
9025 }
9026
9027 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9028 let buffer = self.buffer.read(cx).snapshot(cx);
9029 let mut selection = self.selections.first::<usize>(cx);
9030 selection.set_head(buffer.len(), SelectionGoal::None);
9031 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9032 s.select(vec![selection]);
9033 });
9034 }
9035
9036 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9037 let end = self.buffer.read(cx).read(cx).len();
9038 self.change_selections(None, window, cx, |s| {
9039 s.select_ranges(vec![0..end]);
9040 });
9041 }
9042
9043 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9044 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9045 let mut selections = self.selections.all::<Point>(cx);
9046 let max_point = display_map.buffer_snapshot.max_point();
9047 for selection in &mut selections {
9048 let rows = selection.spanned_rows(true, &display_map);
9049 selection.start = Point::new(rows.start.0, 0);
9050 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9051 selection.reversed = false;
9052 }
9053 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9054 s.select(selections);
9055 });
9056 }
9057
9058 pub fn split_selection_into_lines(
9059 &mut self,
9060 _: &SplitSelectionIntoLines,
9061 window: &mut Window,
9062 cx: &mut Context<Self>,
9063 ) {
9064 let mut to_unfold = Vec::new();
9065 let mut new_selection_ranges = Vec::new();
9066 {
9067 let selections = self.selections.all::<Point>(cx);
9068 let buffer = self.buffer.read(cx).read(cx);
9069 for selection in selections {
9070 for row in selection.start.row..selection.end.row {
9071 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9072 new_selection_ranges.push(cursor..cursor);
9073 }
9074 new_selection_ranges.push(selection.end..selection.end);
9075 to_unfold.push(selection.start..selection.end);
9076 }
9077 }
9078 self.unfold_ranges(&to_unfold, true, true, cx);
9079 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9080 s.select_ranges(new_selection_ranges);
9081 });
9082 }
9083
9084 pub fn add_selection_above(
9085 &mut self,
9086 _: &AddSelectionAbove,
9087 window: &mut Window,
9088 cx: &mut Context<Self>,
9089 ) {
9090 self.add_selection(true, window, cx);
9091 }
9092
9093 pub fn add_selection_below(
9094 &mut self,
9095 _: &AddSelectionBelow,
9096 window: &mut Window,
9097 cx: &mut Context<Self>,
9098 ) {
9099 self.add_selection(false, window, cx);
9100 }
9101
9102 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9103 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9104 let mut selections = self.selections.all::<Point>(cx);
9105 let text_layout_details = self.text_layout_details(window);
9106 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9107 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9108 let range = oldest_selection.display_range(&display_map).sorted();
9109
9110 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9111 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9112 let positions = start_x.min(end_x)..start_x.max(end_x);
9113
9114 selections.clear();
9115 let mut stack = Vec::new();
9116 for row in range.start.row().0..=range.end.row().0 {
9117 if let Some(selection) = self.selections.build_columnar_selection(
9118 &display_map,
9119 DisplayRow(row),
9120 &positions,
9121 oldest_selection.reversed,
9122 &text_layout_details,
9123 ) {
9124 stack.push(selection.id);
9125 selections.push(selection);
9126 }
9127 }
9128
9129 if above {
9130 stack.reverse();
9131 }
9132
9133 AddSelectionsState { above, stack }
9134 });
9135
9136 let last_added_selection = *state.stack.last().unwrap();
9137 let mut new_selections = Vec::new();
9138 if above == state.above {
9139 let end_row = if above {
9140 DisplayRow(0)
9141 } else {
9142 display_map.max_point().row()
9143 };
9144
9145 'outer: for selection in selections {
9146 if selection.id == last_added_selection {
9147 let range = selection.display_range(&display_map).sorted();
9148 debug_assert_eq!(range.start.row(), range.end.row());
9149 let mut row = range.start.row();
9150 let positions =
9151 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9152 px(start)..px(end)
9153 } else {
9154 let start_x =
9155 display_map.x_for_display_point(range.start, &text_layout_details);
9156 let end_x =
9157 display_map.x_for_display_point(range.end, &text_layout_details);
9158 start_x.min(end_x)..start_x.max(end_x)
9159 };
9160
9161 while row != end_row {
9162 if above {
9163 row.0 -= 1;
9164 } else {
9165 row.0 += 1;
9166 }
9167
9168 if let Some(new_selection) = self.selections.build_columnar_selection(
9169 &display_map,
9170 row,
9171 &positions,
9172 selection.reversed,
9173 &text_layout_details,
9174 ) {
9175 state.stack.push(new_selection.id);
9176 if above {
9177 new_selections.push(new_selection);
9178 new_selections.push(selection);
9179 } else {
9180 new_selections.push(selection);
9181 new_selections.push(new_selection);
9182 }
9183
9184 continue 'outer;
9185 }
9186 }
9187 }
9188
9189 new_selections.push(selection);
9190 }
9191 } else {
9192 new_selections = selections;
9193 new_selections.retain(|s| s.id != last_added_selection);
9194 state.stack.pop();
9195 }
9196
9197 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9198 s.select(new_selections);
9199 });
9200 if state.stack.len() > 1 {
9201 self.add_selections_state = Some(state);
9202 }
9203 }
9204
9205 pub fn select_next_match_internal(
9206 &mut self,
9207 display_map: &DisplaySnapshot,
9208 replace_newest: bool,
9209 autoscroll: Option<Autoscroll>,
9210 window: &mut Window,
9211 cx: &mut Context<Self>,
9212 ) -> Result<()> {
9213 fn select_next_match_ranges(
9214 this: &mut Editor,
9215 range: Range<usize>,
9216 replace_newest: bool,
9217 auto_scroll: Option<Autoscroll>,
9218 window: &mut Window,
9219 cx: &mut Context<Editor>,
9220 ) {
9221 this.unfold_ranges(&[range.clone()], false, true, cx);
9222 this.change_selections(auto_scroll, window, cx, |s| {
9223 if replace_newest {
9224 s.delete(s.newest_anchor().id);
9225 }
9226 s.insert_range(range.clone());
9227 });
9228 }
9229
9230 let buffer = &display_map.buffer_snapshot;
9231 let mut selections = self.selections.all::<usize>(cx);
9232 if let Some(mut select_next_state) = self.select_next_state.take() {
9233 let query = &select_next_state.query;
9234 if !select_next_state.done {
9235 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9236 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9237 let mut next_selected_range = None;
9238
9239 let bytes_after_last_selection =
9240 buffer.bytes_in_range(last_selection.end..buffer.len());
9241 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9242 let query_matches = query
9243 .stream_find_iter(bytes_after_last_selection)
9244 .map(|result| (last_selection.end, result))
9245 .chain(
9246 query
9247 .stream_find_iter(bytes_before_first_selection)
9248 .map(|result| (0, result)),
9249 );
9250
9251 for (start_offset, query_match) in query_matches {
9252 let query_match = query_match.unwrap(); // can only fail due to I/O
9253 let offset_range =
9254 start_offset + query_match.start()..start_offset + query_match.end();
9255 let display_range = offset_range.start.to_display_point(display_map)
9256 ..offset_range.end.to_display_point(display_map);
9257
9258 if !select_next_state.wordwise
9259 || (!movement::is_inside_word(display_map, display_range.start)
9260 && !movement::is_inside_word(display_map, display_range.end))
9261 {
9262 // TODO: This is n^2, because we might check all the selections
9263 if !selections
9264 .iter()
9265 .any(|selection| selection.range().overlaps(&offset_range))
9266 {
9267 next_selected_range = Some(offset_range);
9268 break;
9269 }
9270 }
9271 }
9272
9273 if let Some(next_selected_range) = next_selected_range {
9274 select_next_match_ranges(
9275 self,
9276 next_selected_range,
9277 replace_newest,
9278 autoscroll,
9279 window,
9280 cx,
9281 );
9282 } else {
9283 select_next_state.done = true;
9284 }
9285 }
9286
9287 self.select_next_state = Some(select_next_state);
9288 } else {
9289 let mut only_carets = true;
9290 let mut same_text_selected = true;
9291 let mut selected_text = None;
9292
9293 let mut selections_iter = selections.iter().peekable();
9294 while let Some(selection) = selections_iter.next() {
9295 if selection.start != selection.end {
9296 only_carets = false;
9297 }
9298
9299 if same_text_selected {
9300 if selected_text.is_none() {
9301 selected_text =
9302 Some(buffer.text_for_range(selection.range()).collect::<String>());
9303 }
9304
9305 if let Some(next_selection) = selections_iter.peek() {
9306 if next_selection.range().len() == selection.range().len() {
9307 let next_selected_text = buffer
9308 .text_for_range(next_selection.range())
9309 .collect::<String>();
9310 if Some(next_selected_text) != selected_text {
9311 same_text_selected = false;
9312 selected_text = None;
9313 }
9314 } else {
9315 same_text_selected = false;
9316 selected_text = None;
9317 }
9318 }
9319 }
9320 }
9321
9322 if only_carets {
9323 for selection in &mut selections {
9324 let word_range = movement::surrounding_word(
9325 display_map,
9326 selection.start.to_display_point(display_map),
9327 );
9328 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9329 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9330 selection.goal = SelectionGoal::None;
9331 selection.reversed = false;
9332 select_next_match_ranges(
9333 self,
9334 selection.start..selection.end,
9335 replace_newest,
9336 autoscroll,
9337 window,
9338 cx,
9339 );
9340 }
9341
9342 if selections.len() == 1 {
9343 let selection = selections
9344 .last()
9345 .expect("ensured that there's only one selection");
9346 let query = buffer
9347 .text_for_range(selection.start..selection.end)
9348 .collect::<String>();
9349 let is_empty = query.is_empty();
9350 let select_state = SelectNextState {
9351 query: AhoCorasick::new(&[query])?,
9352 wordwise: true,
9353 done: is_empty,
9354 };
9355 self.select_next_state = Some(select_state);
9356 } else {
9357 self.select_next_state = None;
9358 }
9359 } else if let Some(selected_text) = selected_text {
9360 self.select_next_state = Some(SelectNextState {
9361 query: AhoCorasick::new(&[selected_text])?,
9362 wordwise: false,
9363 done: false,
9364 });
9365 self.select_next_match_internal(
9366 display_map,
9367 replace_newest,
9368 autoscroll,
9369 window,
9370 cx,
9371 )?;
9372 }
9373 }
9374 Ok(())
9375 }
9376
9377 pub fn select_all_matches(
9378 &mut self,
9379 _action: &SelectAllMatches,
9380 window: &mut Window,
9381 cx: &mut Context<Self>,
9382 ) -> Result<()> {
9383 self.push_to_selection_history();
9384 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9385
9386 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9387 let Some(select_next_state) = self.select_next_state.as_mut() else {
9388 return Ok(());
9389 };
9390 if select_next_state.done {
9391 return Ok(());
9392 }
9393
9394 let mut new_selections = self.selections.all::<usize>(cx);
9395
9396 let buffer = &display_map.buffer_snapshot;
9397 let query_matches = select_next_state
9398 .query
9399 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9400
9401 for query_match in query_matches {
9402 let query_match = query_match.unwrap(); // can only fail due to I/O
9403 let offset_range = query_match.start()..query_match.end();
9404 let display_range = offset_range.start.to_display_point(&display_map)
9405 ..offset_range.end.to_display_point(&display_map);
9406
9407 if !select_next_state.wordwise
9408 || (!movement::is_inside_word(&display_map, display_range.start)
9409 && !movement::is_inside_word(&display_map, display_range.end))
9410 {
9411 self.selections.change_with(cx, |selections| {
9412 new_selections.push(Selection {
9413 id: selections.new_selection_id(),
9414 start: offset_range.start,
9415 end: offset_range.end,
9416 reversed: false,
9417 goal: SelectionGoal::None,
9418 });
9419 });
9420 }
9421 }
9422
9423 new_selections.sort_by_key(|selection| selection.start);
9424 let mut ix = 0;
9425 while ix + 1 < new_selections.len() {
9426 let current_selection = &new_selections[ix];
9427 let next_selection = &new_selections[ix + 1];
9428 if current_selection.range().overlaps(&next_selection.range()) {
9429 if current_selection.id < next_selection.id {
9430 new_selections.remove(ix + 1);
9431 } else {
9432 new_selections.remove(ix);
9433 }
9434 } else {
9435 ix += 1;
9436 }
9437 }
9438
9439 let reversed = self.selections.oldest::<usize>(cx).reversed;
9440
9441 for selection in new_selections.iter_mut() {
9442 selection.reversed = reversed;
9443 }
9444
9445 select_next_state.done = true;
9446 self.unfold_ranges(
9447 &new_selections
9448 .iter()
9449 .map(|selection| selection.range())
9450 .collect::<Vec<_>>(),
9451 false,
9452 false,
9453 cx,
9454 );
9455 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9456 selections.select(new_selections)
9457 });
9458
9459 Ok(())
9460 }
9461
9462 pub fn select_next(
9463 &mut self,
9464 action: &SelectNext,
9465 window: &mut Window,
9466 cx: &mut Context<Self>,
9467 ) -> Result<()> {
9468 self.push_to_selection_history();
9469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9470 self.select_next_match_internal(
9471 &display_map,
9472 action.replace_newest,
9473 Some(Autoscroll::newest()),
9474 window,
9475 cx,
9476 )?;
9477 Ok(())
9478 }
9479
9480 pub fn select_previous(
9481 &mut self,
9482 action: &SelectPrevious,
9483 window: &mut Window,
9484 cx: &mut Context<Self>,
9485 ) -> Result<()> {
9486 self.push_to_selection_history();
9487 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9488 let buffer = &display_map.buffer_snapshot;
9489 let mut selections = self.selections.all::<usize>(cx);
9490 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9491 let query = &select_prev_state.query;
9492 if !select_prev_state.done {
9493 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9494 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9495 let mut next_selected_range = None;
9496 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9497 let bytes_before_last_selection =
9498 buffer.reversed_bytes_in_range(0..last_selection.start);
9499 let bytes_after_first_selection =
9500 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9501 let query_matches = query
9502 .stream_find_iter(bytes_before_last_selection)
9503 .map(|result| (last_selection.start, result))
9504 .chain(
9505 query
9506 .stream_find_iter(bytes_after_first_selection)
9507 .map(|result| (buffer.len(), result)),
9508 );
9509 for (end_offset, query_match) in query_matches {
9510 let query_match = query_match.unwrap(); // can only fail due to I/O
9511 let offset_range =
9512 end_offset - query_match.end()..end_offset - query_match.start();
9513 let display_range = offset_range.start.to_display_point(&display_map)
9514 ..offset_range.end.to_display_point(&display_map);
9515
9516 if !select_prev_state.wordwise
9517 || (!movement::is_inside_word(&display_map, display_range.start)
9518 && !movement::is_inside_word(&display_map, display_range.end))
9519 {
9520 next_selected_range = Some(offset_range);
9521 break;
9522 }
9523 }
9524
9525 if let Some(next_selected_range) = next_selected_range {
9526 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9527 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9528 if action.replace_newest {
9529 s.delete(s.newest_anchor().id);
9530 }
9531 s.insert_range(next_selected_range);
9532 });
9533 } else {
9534 select_prev_state.done = true;
9535 }
9536 }
9537
9538 self.select_prev_state = Some(select_prev_state);
9539 } else {
9540 let mut only_carets = true;
9541 let mut same_text_selected = true;
9542 let mut selected_text = None;
9543
9544 let mut selections_iter = selections.iter().peekable();
9545 while let Some(selection) = selections_iter.next() {
9546 if selection.start != selection.end {
9547 only_carets = false;
9548 }
9549
9550 if same_text_selected {
9551 if selected_text.is_none() {
9552 selected_text =
9553 Some(buffer.text_for_range(selection.range()).collect::<String>());
9554 }
9555
9556 if let Some(next_selection) = selections_iter.peek() {
9557 if next_selection.range().len() == selection.range().len() {
9558 let next_selected_text = buffer
9559 .text_for_range(next_selection.range())
9560 .collect::<String>();
9561 if Some(next_selected_text) != selected_text {
9562 same_text_selected = false;
9563 selected_text = None;
9564 }
9565 } else {
9566 same_text_selected = false;
9567 selected_text = None;
9568 }
9569 }
9570 }
9571 }
9572
9573 if only_carets {
9574 for selection in &mut selections {
9575 let word_range = movement::surrounding_word(
9576 &display_map,
9577 selection.start.to_display_point(&display_map),
9578 );
9579 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9580 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9581 selection.goal = SelectionGoal::None;
9582 selection.reversed = false;
9583 }
9584 if selections.len() == 1 {
9585 let selection = selections
9586 .last()
9587 .expect("ensured that there's only one selection");
9588 let query = buffer
9589 .text_for_range(selection.start..selection.end)
9590 .collect::<String>();
9591 let is_empty = query.is_empty();
9592 let select_state = SelectNextState {
9593 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9594 wordwise: true,
9595 done: is_empty,
9596 };
9597 self.select_prev_state = Some(select_state);
9598 } else {
9599 self.select_prev_state = None;
9600 }
9601
9602 self.unfold_ranges(
9603 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9604 false,
9605 true,
9606 cx,
9607 );
9608 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9609 s.select(selections);
9610 });
9611 } else if let Some(selected_text) = selected_text {
9612 self.select_prev_state = Some(SelectNextState {
9613 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9614 wordwise: false,
9615 done: false,
9616 });
9617 self.select_previous(action, window, cx)?;
9618 }
9619 }
9620 Ok(())
9621 }
9622
9623 pub fn toggle_comments(
9624 &mut self,
9625 action: &ToggleComments,
9626 window: &mut Window,
9627 cx: &mut Context<Self>,
9628 ) {
9629 if self.read_only(cx) {
9630 return;
9631 }
9632 let text_layout_details = &self.text_layout_details(window);
9633 self.transact(window, cx, |this, window, cx| {
9634 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9635 let mut edits = Vec::new();
9636 let mut selection_edit_ranges = Vec::new();
9637 let mut last_toggled_row = None;
9638 let snapshot = this.buffer.read(cx).read(cx);
9639 let empty_str: Arc<str> = Arc::default();
9640 let mut suffixes_inserted = Vec::new();
9641 let ignore_indent = action.ignore_indent;
9642
9643 fn comment_prefix_range(
9644 snapshot: &MultiBufferSnapshot,
9645 row: MultiBufferRow,
9646 comment_prefix: &str,
9647 comment_prefix_whitespace: &str,
9648 ignore_indent: bool,
9649 ) -> Range<Point> {
9650 let indent_size = if ignore_indent {
9651 0
9652 } else {
9653 snapshot.indent_size_for_line(row).len
9654 };
9655
9656 let start = Point::new(row.0, indent_size);
9657
9658 let mut line_bytes = snapshot
9659 .bytes_in_range(start..snapshot.max_point())
9660 .flatten()
9661 .copied();
9662
9663 // If this line currently begins with the line comment prefix, then record
9664 // the range containing the prefix.
9665 if line_bytes
9666 .by_ref()
9667 .take(comment_prefix.len())
9668 .eq(comment_prefix.bytes())
9669 {
9670 // Include any whitespace that matches the comment prefix.
9671 let matching_whitespace_len = line_bytes
9672 .zip(comment_prefix_whitespace.bytes())
9673 .take_while(|(a, b)| a == b)
9674 .count() as u32;
9675 let end = Point::new(
9676 start.row,
9677 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9678 );
9679 start..end
9680 } else {
9681 start..start
9682 }
9683 }
9684
9685 fn comment_suffix_range(
9686 snapshot: &MultiBufferSnapshot,
9687 row: MultiBufferRow,
9688 comment_suffix: &str,
9689 comment_suffix_has_leading_space: bool,
9690 ) -> Range<Point> {
9691 let end = Point::new(row.0, snapshot.line_len(row));
9692 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9693
9694 let mut line_end_bytes = snapshot
9695 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9696 .flatten()
9697 .copied();
9698
9699 let leading_space_len = if suffix_start_column > 0
9700 && line_end_bytes.next() == Some(b' ')
9701 && comment_suffix_has_leading_space
9702 {
9703 1
9704 } else {
9705 0
9706 };
9707
9708 // If this line currently begins with the line comment prefix, then record
9709 // the range containing the prefix.
9710 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9711 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9712 start..end
9713 } else {
9714 end..end
9715 }
9716 }
9717
9718 // TODO: Handle selections that cross excerpts
9719 for selection in &mut selections {
9720 let start_column = snapshot
9721 .indent_size_for_line(MultiBufferRow(selection.start.row))
9722 .len;
9723 let language = if let Some(language) =
9724 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9725 {
9726 language
9727 } else {
9728 continue;
9729 };
9730
9731 selection_edit_ranges.clear();
9732
9733 // If multiple selections contain a given row, avoid processing that
9734 // row more than once.
9735 let mut start_row = MultiBufferRow(selection.start.row);
9736 if last_toggled_row == Some(start_row) {
9737 start_row = start_row.next_row();
9738 }
9739 let end_row =
9740 if selection.end.row > selection.start.row && selection.end.column == 0 {
9741 MultiBufferRow(selection.end.row - 1)
9742 } else {
9743 MultiBufferRow(selection.end.row)
9744 };
9745 last_toggled_row = Some(end_row);
9746
9747 if start_row > end_row {
9748 continue;
9749 }
9750
9751 // If the language has line comments, toggle those.
9752 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9753
9754 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9755 if ignore_indent {
9756 full_comment_prefixes = full_comment_prefixes
9757 .into_iter()
9758 .map(|s| Arc::from(s.trim_end()))
9759 .collect();
9760 }
9761
9762 if !full_comment_prefixes.is_empty() {
9763 let first_prefix = full_comment_prefixes
9764 .first()
9765 .expect("prefixes is non-empty");
9766 let prefix_trimmed_lengths = full_comment_prefixes
9767 .iter()
9768 .map(|p| p.trim_end_matches(' ').len())
9769 .collect::<SmallVec<[usize; 4]>>();
9770
9771 let mut all_selection_lines_are_comments = true;
9772
9773 for row in start_row.0..=end_row.0 {
9774 let row = MultiBufferRow(row);
9775 if start_row < end_row && snapshot.is_line_blank(row) {
9776 continue;
9777 }
9778
9779 let prefix_range = full_comment_prefixes
9780 .iter()
9781 .zip(prefix_trimmed_lengths.iter().copied())
9782 .map(|(prefix, trimmed_prefix_len)| {
9783 comment_prefix_range(
9784 snapshot.deref(),
9785 row,
9786 &prefix[..trimmed_prefix_len],
9787 &prefix[trimmed_prefix_len..],
9788 ignore_indent,
9789 )
9790 })
9791 .max_by_key(|range| range.end.column - range.start.column)
9792 .expect("prefixes is non-empty");
9793
9794 if prefix_range.is_empty() {
9795 all_selection_lines_are_comments = false;
9796 }
9797
9798 selection_edit_ranges.push(prefix_range);
9799 }
9800
9801 if all_selection_lines_are_comments {
9802 edits.extend(
9803 selection_edit_ranges
9804 .iter()
9805 .cloned()
9806 .map(|range| (range, empty_str.clone())),
9807 );
9808 } else {
9809 let min_column = selection_edit_ranges
9810 .iter()
9811 .map(|range| range.start.column)
9812 .min()
9813 .unwrap_or(0);
9814 edits.extend(selection_edit_ranges.iter().map(|range| {
9815 let position = Point::new(range.start.row, min_column);
9816 (position..position, first_prefix.clone())
9817 }));
9818 }
9819 } else if let Some((full_comment_prefix, comment_suffix)) =
9820 language.block_comment_delimiters()
9821 {
9822 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9823 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9824 let prefix_range = comment_prefix_range(
9825 snapshot.deref(),
9826 start_row,
9827 comment_prefix,
9828 comment_prefix_whitespace,
9829 ignore_indent,
9830 );
9831 let suffix_range = comment_suffix_range(
9832 snapshot.deref(),
9833 end_row,
9834 comment_suffix.trim_start_matches(' '),
9835 comment_suffix.starts_with(' '),
9836 );
9837
9838 if prefix_range.is_empty() || suffix_range.is_empty() {
9839 edits.push((
9840 prefix_range.start..prefix_range.start,
9841 full_comment_prefix.clone(),
9842 ));
9843 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9844 suffixes_inserted.push((end_row, comment_suffix.len()));
9845 } else {
9846 edits.push((prefix_range, empty_str.clone()));
9847 edits.push((suffix_range, empty_str.clone()));
9848 }
9849 } else {
9850 continue;
9851 }
9852 }
9853
9854 drop(snapshot);
9855 this.buffer.update(cx, |buffer, cx| {
9856 buffer.edit(edits, None, cx);
9857 });
9858
9859 // Adjust selections so that they end before any comment suffixes that
9860 // were inserted.
9861 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9862 let mut selections = this.selections.all::<Point>(cx);
9863 let snapshot = this.buffer.read(cx).read(cx);
9864 for selection in &mut selections {
9865 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9866 match row.cmp(&MultiBufferRow(selection.end.row)) {
9867 Ordering::Less => {
9868 suffixes_inserted.next();
9869 continue;
9870 }
9871 Ordering::Greater => break,
9872 Ordering::Equal => {
9873 if selection.end.column == snapshot.line_len(row) {
9874 if selection.is_empty() {
9875 selection.start.column -= suffix_len as u32;
9876 }
9877 selection.end.column -= suffix_len as u32;
9878 }
9879 break;
9880 }
9881 }
9882 }
9883 }
9884
9885 drop(snapshot);
9886 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9887 s.select(selections)
9888 });
9889
9890 let selections = this.selections.all::<Point>(cx);
9891 let selections_on_single_row = selections.windows(2).all(|selections| {
9892 selections[0].start.row == selections[1].start.row
9893 && selections[0].end.row == selections[1].end.row
9894 && selections[0].start.row == selections[0].end.row
9895 });
9896 let selections_selecting = selections
9897 .iter()
9898 .any(|selection| selection.start != selection.end);
9899 let advance_downwards = action.advance_downwards
9900 && selections_on_single_row
9901 && !selections_selecting
9902 && !matches!(this.mode, EditorMode::SingleLine { .. });
9903
9904 if advance_downwards {
9905 let snapshot = this.buffer.read(cx).snapshot(cx);
9906
9907 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9908 s.move_cursors_with(|display_snapshot, display_point, _| {
9909 let mut point = display_point.to_point(display_snapshot);
9910 point.row += 1;
9911 point = snapshot.clip_point(point, Bias::Left);
9912 let display_point = point.to_display_point(display_snapshot);
9913 let goal = SelectionGoal::HorizontalPosition(
9914 display_snapshot
9915 .x_for_display_point(display_point, text_layout_details)
9916 .into(),
9917 );
9918 (display_point, goal)
9919 })
9920 });
9921 }
9922 });
9923 }
9924
9925 pub fn select_enclosing_symbol(
9926 &mut self,
9927 _: &SelectEnclosingSymbol,
9928 window: &mut Window,
9929 cx: &mut Context<Self>,
9930 ) {
9931 let buffer = self.buffer.read(cx).snapshot(cx);
9932 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9933
9934 fn update_selection(
9935 selection: &Selection<usize>,
9936 buffer_snap: &MultiBufferSnapshot,
9937 ) -> Option<Selection<usize>> {
9938 let cursor = selection.head();
9939 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9940 for symbol in symbols.iter().rev() {
9941 let start = symbol.range.start.to_offset(buffer_snap);
9942 let end = symbol.range.end.to_offset(buffer_snap);
9943 let new_range = start..end;
9944 if start < selection.start || end > selection.end {
9945 return Some(Selection {
9946 id: selection.id,
9947 start: new_range.start,
9948 end: new_range.end,
9949 goal: SelectionGoal::None,
9950 reversed: selection.reversed,
9951 });
9952 }
9953 }
9954 None
9955 }
9956
9957 let mut selected_larger_symbol = false;
9958 let new_selections = old_selections
9959 .iter()
9960 .map(|selection| match update_selection(selection, &buffer) {
9961 Some(new_selection) => {
9962 if new_selection.range() != selection.range() {
9963 selected_larger_symbol = true;
9964 }
9965 new_selection
9966 }
9967 None => selection.clone(),
9968 })
9969 .collect::<Vec<_>>();
9970
9971 if selected_larger_symbol {
9972 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9973 s.select(new_selections);
9974 });
9975 }
9976 }
9977
9978 pub fn select_larger_syntax_node(
9979 &mut self,
9980 _: &SelectLargerSyntaxNode,
9981 window: &mut Window,
9982 cx: &mut Context<Self>,
9983 ) {
9984 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9985 let buffer = self.buffer.read(cx).snapshot(cx);
9986 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9987
9988 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9989 let mut selected_larger_node = false;
9990 let new_selections = old_selections
9991 .iter()
9992 .map(|selection| {
9993 let old_range = selection.start..selection.end;
9994 let mut new_range = old_range.clone();
9995 let mut new_node = None;
9996 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9997 {
9998 new_node = Some(node);
9999 new_range = containing_range;
10000 if !display_map.intersects_fold(new_range.start)
10001 && !display_map.intersects_fold(new_range.end)
10002 {
10003 break;
10004 }
10005 }
10006
10007 if let Some(node) = new_node {
10008 // Log the ancestor, to support using this action as a way to explore TreeSitter
10009 // nodes. Parent and grandparent are also logged because this operation will not
10010 // visit nodes that have the same range as their parent.
10011 log::info!("Node: {node:?}");
10012 let parent = node.parent();
10013 log::info!("Parent: {parent:?}");
10014 let grandparent = parent.and_then(|x| x.parent());
10015 log::info!("Grandparent: {grandparent:?}");
10016 }
10017
10018 selected_larger_node |= new_range != old_range;
10019 Selection {
10020 id: selection.id,
10021 start: new_range.start,
10022 end: new_range.end,
10023 goal: SelectionGoal::None,
10024 reversed: selection.reversed,
10025 }
10026 })
10027 .collect::<Vec<_>>();
10028
10029 if selected_larger_node {
10030 stack.push(old_selections);
10031 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10032 s.select(new_selections);
10033 });
10034 }
10035 self.select_larger_syntax_node_stack = stack;
10036 }
10037
10038 pub fn select_smaller_syntax_node(
10039 &mut self,
10040 _: &SelectSmallerSyntaxNode,
10041 window: &mut Window,
10042 cx: &mut Context<Self>,
10043 ) {
10044 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10045 if let Some(selections) = stack.pop() {
10046 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10047 s.select(selections.to_vec());
10048 });
10049 }
10050 self.select_larger_syntax_node_stack = stack;
10051 }
10052
10053 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10054 if !EditorSettings::get_global(cx).gutter.runnables {
10055 self.clear_tasks();
10056 return Task::ready(());
10057 }
10058 let project = self.project.as_ref().map(Entity::downgrade);
10059 cx.spawn_in(window, |this, mut cx| async move {
10060 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10061 let Some(project) = project.and_then(|p| p.upgrade()) else {
10062 return;
10063 };
10064 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10065 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10066 }) else {
10067 return;
10068 };
10069
10070 let hide_runnables = project
10071 .update(&mut cx, |project, cx| {
10072 // Do not display any test indicators in non-dev server remote projects.
10073 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10074 })
10075 .unwrap_or(true);
10076 if hide_runnables {
10077 return;
10078 }
10079 let new_rows =
10080 cx.background_executor()
10081 .spawn({
10082 let snapshot = display_snapshot.clone();
10083 async move {
10084 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10085 }
10086 })
10087 .await;
10088
10089 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10090 this.update(&mut cx, |this, _| {
10091 this.clear_tasks();
10092 for (key, value) in rows {
10093 this.insert_tasks(key, value);
10094 }
10095 })
10096 .ok();
10097 })
10098 }
10099 fn fetch_runnable_ranges(
10100 snapshot: &DisplaySnapshot,
10101 range: Range<Anchor>,
10102 ) -> Vec<language::RunnableRange> {
10103 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10104 }
10105
10106 fn runnable_rows(
10107 project: Entity<Project>,
10108 snapshot: DisplaySnapshot,
10109 runnable_ranges: Vec<RunnableRange>,
10110 mut cx: AsyncWindowContext,
10111 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10112 runnable_ranges
10113 .into_iter()
10114 .filter_map(|mut runnable| {
10115 let tasks = cx
10116 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10117 .ok()?;
10118 if tasks.is_empty() {
10119 return None;
10120 }
10121
10122 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10123
10124 let row = snapshot
10125 .buffer_snapshot
10126 .buffer_line_for_row(MultiBufferRow(point.row))?
10127 .1
10128 .start
10129 .row;
10130
10131 let context_range =
10132 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10133 Some((
10134 (runnable.buffer_id, row),
10135 RunnableTasks {
10136 templates: tasks,
10137 offset: MultiBufferOffset(runnable.run_range.start),
10138 context_range,
10139 column: point.column,
10140 extra_variables: runnable.extra_captures,
10141 },
10142 ))
10143 })
10144 .collect()
10145 }
10146
10147 fn templates_with_tags(
10148 project: &Entity<Project>,
10149 runnable: &mut Runnable,
10150 cx: &mut App,
10151 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10152 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10153 let (worktree_id, file) = project
10154 .buffer_for_id(runnable.buffer, cx)
10155 .and_then(|buffer| buffer.read(cx).file())
10156 .map(|file| (file.worktree_id(cx), file.clone()))
10157 .unzip();
10158
10159 (
10160 project.task_store().read(cx).task_inventory().cloned(),
10161 worktree_id,
10162 file,
10163 )
10164 });
10165
10166 let tags = mem::take(&mut runnable.tags);
10167 let mut tags: Vec<_> = tags
10168 .into_iter()
10169 .flat_map(|tag| {
10170 let tag = tag.0.clone();
10171 inventory
10172 .as_ref()
10173 .into_iter()
10174 .flat_map(|inventory| {
10175 inventory.read(cx).list_tasks(
10176 file.clone(),
10177 Some(runnable.language.clone()),
10178 worktree_id,
10179 cx,
10180 )
10181 })
10182 .filter(move |(_, template)| {
10183 template.tags.iter().any(|source_tag| source_tag == &tag)
10184 })
10185 })
10186 .sorted_by_key(|(kind, _)| kind.to_owned())
10187 .collect();
10188 if let Some((leading_tag_source, _)) = tags.first() {
10189 // Strongest source wins; if we have worktree tag binding, prefer that to
10190 // global and language bindings;
10191 // if we have a global binding, prefer that to language binding.
10192 let first_mismatch = tags
10193 .iter()
10194 .position(|(tag_source, _)| tag_source != leading_tag_source);
10195 if let Some(index) = first_mismatch {
10196 tags.truncate(index);
10197 }
10198 }
10199
10200 tags
10201 }
10202
10203 pub fn move_to_enclosing_bracket(
10204 &mut self,
10205 _: &MoveToEnclosingBracket,
10206 window: &mut Window,
10207 cx: &mut Context<Self>,
10208 ) {
10209 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10210 s.move_offsets_with(|snapshot, selection| {
10211 let Some(enclosing_bracket_ranges) =
10212 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10213 else {
10214 return;
10215 };
10216
10217 let mut best_length = usize::MAX;
10218 let mut best_inside = false;
10219 let mut best_in_bracket_range = false;
10220 let mut best_destination = None;
10221 for (open, close) in enclosing_bracket_ranges {
10222 let close = close.to_inclusive();
10223 let length = close.end() - open.start;
10224 let inside = selection.start >= open.end && selection.end <= *close.start();
10225 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10226 || close.contains(&selection.head());
10227
10228 // If best is next to a bracket and current isn't, skip
10229 if !in_bracket_range && best_in_bracket_range {
10230 continue;
10231 }
10232
10233 // Prefer smaller lengths unless best is inside and current isn't
10234 if length > best_length && (best_inside || !inside) {
10235 continue;
10236 }
10237
10238 best_length = length;
10239 best_inside = inside;
10240 best_in_bracket_range = in_bracket_range;
10241 best_destination = Some(
10242 if close.contains(&selection.start) && close.contains(&selection.end) {
10243 if inside {
10244 open.end
10245 } else {
10246 open.start
10247 }
10248 } else if inside {
10249 *close.start()
10250 } else {
10251 *close.end()
10252 },
10253 );
10254 }
10255
10256 if let Some(destination) = best_destination {
10257 selection.collapse_to(destination, SelectionGoal::None);
10258 }
10259 })
10260 });
10261 }
10262
10263 pub fn undo_selection(
10264 &mut self,
10265 _: &UndoSelection,
10266 window: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) {
10269 self.end_selection(window, cx);
10270 self.selection_history.mode = SelectionHistoryMode::Undoing;
10271 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10272 self.change_selections(None, window, cx, |s| {
10273 s.select_anchors(entry.selections.to_vec())
10274 });
10275 self.select_next_state = entry.select_next_state;
10276 self.select_prev_state = entry.select_prev_state;
10277 self.add_selections_state = entry.add_selections_state;
10278 self.request_autoscroll(Autoscroll::newest(), cx);
10279 }
10280 self.selection_history.mode = SelectionHistoryMode::Normal;
10281 }
10282
10283 pub fn redo_selection(
10284 &mut self,
10285 _: &RedoSelection,
10286 window: &mut Window,
10287 cx: &mut Context<Self>,
10288 ) {
10289 self.end_selection(window, cx);
10290 self.selection_history.mode = SelectionHistoryMode::Redoing;
10291 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10292 self.change_selections(None, window, cx, |s| {
10293 s.select_anchors(entry.selections.to_vec())
10294 });
10295 self.select_next_state = entry.select_next_state;
10296 self.select_prev_state = entry.select_prev_state;
10297 self.add_selections_state = entry.add_selections_state;
10298 self.request_autoscroll(Autoscroll::newest(), cx);
10299 }
10300 self.selection_history.mode = SelectionHistoryMode::Normal;
10301 }
10302
10303 pub fn expand_excerpts(
10304 &mut self,
10305 action: &ExpandExcerpts,
10306 _: &mut Window,
10307 cx: &mut Context<Self>,
10308 ) {
10309 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10310 }
10311
10312 pub fn expand_excerpts_down(
10313 &mut self,
10314 action: &ExpandExcerptsDown,
10315 _: &mut Window,
10316 cx: &mut Context<Self>,
10317 ) {
10318 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10319 }
10320
10321 pub fn expand_excerpts_up(
10322 &mut self,
10323 action: &ExpandExcerptsUp,
10324 _: &mut Window,
10325 cx: &mut Context<Self>,
10326 ) {
10327 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10328 }
10329
10330 pub fn expand_excerpts_for_direction(
10331 &mut self,
10332 lines: u32,
10333 direction: ExpandExcerptDirection,
10334
10335 cx: &mut Context<Self>,
10336 ) {
10337 let selections = self.selections.disjoint_anchors();
10338
10339 let lines = if lines == 0 {
10340 EditorSettings::get_global(cx).expand_excerpt_lines
10341 } else {
10342 lines
10343 };
10344
10345 self.buffer.update(cx, |buffer, cx| {
10346 let snapshot = buffer.snapshot(cx);
10347 let mut excerpt_ids = selections
10348 .iter()
10349 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10350 .collect::<Vec<_>>();
10351 excerpt_ids.sort();
10352 excerpt_ids.dedup();
10353 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10354 })
10355 }
10356
10357 pub fn expand_excerpt(
10358 &mut self,
10359 excerpt: ExcerptId,
10360 direction: ExpandExcerptDirection,
10361 cx: &mut Context<Self>,
10362 ) {
10363 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10364 self.buffer.update(cx, |buffer, cx| {
10365 buffer.expand_excerpts([excerpt], lines, direction, cx)
10366 })
10367 }
10368
10369 pub fn go_to_singleton_buffer_point(
10370 &mut self,
10371 point: Point,
10372 window: &mut Window,
10373 cx: &mut Context<Self>,
10374 ) {
10375 self.go_to_singleton_buffer_range(point..point, window, cx);
10376 }
10377
10378 pub fn go_to_singleton_buffer_range(
10379 &mut self,
10380 range: Range<Point>,
10381 window: &mut Window,
10382 cx: &mut Context<Self>,
10383 ) {
10384 let multibuffer = self.buffer().read(cx);
10385 let Some(buffer) = multibuffer.as_singleton() else {
10386 return;
10387 };
10388 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10389 return;
10390 };
10391 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10392 return;
10393 };
10394 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10395 s.select_anchor_ranges([start..end])
10396 });
10397 }
10398
10399 fn go_to_diagnostic(
10400 &mut self,
10401 _: &GoToDiagnostic,
10402 window: &mut Window,
10403 cx: &mut Context<Self>,
10404 ) {
10405 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10406 }
10407
10408 fn go_to_prev_diagnostic(
10409 &mut self,
10410 _: &GoToPrevDiagnostic,
10411 window: &mut Window,
10412 cx: &mut Context<Self>,
10413 ) {
10414 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10415 }
10416
10417 pub fn go_to_diagnostic_impl(
10418 &mut self,
10419 direction: Direction,
10420 window: &mut Window,
10421 cx: &mut Context<Self>,
10422 ) {
10423 let buffer = self.buffer.read(cx).snapshot(cx);
10424 let selection = self.selections.newest::<usize>(cx);
10425
10426 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10427 if direction == Direction::Next {
10428 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10429 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10430 return;
10431 };
10432 self.activate_diagnostics(
10433 buffer_id,
10434 popover.local_diagnostic.diagnostic.group_id,
10435 window,
10436 cx,
10437 );
10438 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10439 let primary_range_start = active_diagnostics.primary_range.start;
10440 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10441 let mut new_selection = s.newest_anchor().clone();
10442 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10443 s.select_anchors(vec![new_selection.clone()]);
10444 });
10445 self.refresh_inline_completion(false, true, window, cx);
10446 }
10447 return;
10448 }
10449 }
10450
10451 let active_group_id = self
10452 .active_diagnostics
10453 .as_ref()
10454 .map(|active_group| active_group.group_id);
10455 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10456 active_diagnostics
10457 .primary_range
10458 .to_offset(&buffer)
10459 .to_inclusive()
10460 });
10461 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10462 if active_primary_range.contains(&selection.head()) {
10463 *active_primary_range.start()
10464 } else {
10465 selection.head()
10466 }
10467 } else {
10468 selection.head()
10469 };
10470
10471 let snapshot = self.snapshot(window, cx);
10472 let primary_diagnostics_before = buffer
10473 .diagnostics_in_range::<usize>(0..search_start)
10474 .filter(|entry| entry.diagnostic.is_primary)
10475 .filter(|entry| entry.range.start != entry.range.end)
10476 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10477 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10478 .collect::<Vec<_>>();
10479 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10480 primary_diagnostics_before
10481 .iter()
10482 .position(|entry| entry.diagnostic.group_id == active_group_id)
10483 });
10484
10485 let primary_diagnostics_after = buffer
10486 .diagnostics_in_range::<usize>(search_start..buffer.len())
10487 .filter(|entry| entry.diagnostic.is_primary)
10488 .filter(|entry| entry.range.start != entry.range.end)
10489 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10490 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10491 .collect::<Vec<_>>();
10492 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10493 primary_diagnostics_after
10494 .iter()
10495 .enumerate()
10496 .rev()
10497 .find_map(|(i, entry)| {
10498 if entry.diagnostic.group_id == active_group_id {
10499 Some(i)
10500 } else {
10501 None
10502 }
10503 })
10504 });
10505
10506 let next_primary_diagnostic = match direction {
10507 Direction::Prev => primary_diagnostics_before
10508 .iter()
10509 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10510 .rev()
10511 .next(),
10512 Direction::Next => primary_diagnostics_after
10513 .iter()
10514 .skip(
10515 last_same_group_diagnostic_after
10516 .map(|index| index + 1)
10517 .unwrap_or(0),
10518 )
10519 .next(),
10520 };
10521
10522 // Cycle around to the start of the buffer, potentially moving back to the start of
10523 // the currently active diagnostic.
10524 let cycle_around = || match direction {
10525 Direction::Prev => primary_diagnostics_after
10526 .iter()
10527 .rev()
10528 .chain(primary_diagnostics_before.iter().rev())
10529 .next(),
10530 Direction::Next => primary_diagnostics_before
10531 .iter()
10532 .chain(primary_diagnostics_after.iter())
10533 .next(),
10534 };
10535
10536 if let Some((primary_range, group_id)) = next_primary_diagnostic
10537 .or_else(cycle_around)
10538 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10539 {
10540 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10541 return;
10542 };
10543 self.activate_diagnostics(buffer_id, group_id, window, cx);
10544 if self.active_diagnostics.is_some() {
10545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10546 s.select(vec![Selection {
10547 id: selection.id,
10548 start: primary_range.start,
10549 end: primary_range.start,
10550 reversed: false,
10551 goal: SelectionGoal::None,
10552 }]);
10553 });
10554 self.refresh_inline_completion(false, true, window, cx);
10555 }
10556 }
10557 }
10558
10559 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10560 let snapshot = self.snapshot(window, cx);
10561 let selection = self.selections.newest::<Point>(cx);
10562 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10563 }
10564
10565 fn go_to_hunk_after_position(
10566 &mut self,
10567 snapshot: &EditorSnapshot,
10568 position: Point,
10569 window: &mut Window,
10570 cx: &mut Context<Editor>,
10571 ) -> Option<MultiBufferDiffHunk> {
10572 let mut hunk = snapshot
10573 .buffer_snapshot
10574 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10575 .find(|hunk| hunk.row_range.start.0 > position.row);
10576 if hunk.is_none() {
10577 hunk = snapshot
10578 .buffer_snapshot
10579 .diff_hunks_in_range(Point::zero()..position)
10580 .find(|hunk| hunk.row_range.end.0 < position.row)
10581 }
10582 if let Some(hunk) = &hunk {
10583 let destination = Point::new(hunk.row_range.start.0, 0);
10584 self.unfold_ranges(&[destination..destination], false, false, cx);
10585 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10586 s.select_ranges(vec![destination..destination]);
10587 });
10588 }
10589
10590 hunk
10591 }
10592
10593 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10594 let snapshot = self.snapshot(window, cx);
10595 let selection = self.selections.newest::<Point>(cx);
10596 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10597 }
10598
10599 fn go_to_hunk_before_position(
10600 &mut self,
10601 snapshot: &EditorSnapshot,
10602 position: Point,
10603 window: &mut Window,
10604 cx: &mut Context<Editor>,
10605 ) -> Option<MultiBufferDiffHunk> {
10606 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10607 if hunk.is_none() {
10608 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10609 }
10610 if let Some(hunk) = &hunk {
10611 let destination = Point::new(hunk.row_range.start.0, 0);
10612 self.unfold_ranges(&[destination..destination], false, false, cx);
10613 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10614 s.select_ranges(vec![destination..destination]);
10615 });
10616 }
10617
10618 hunk
10619 }
10620
10621 pub fn go_to_definition(
10622 &mut self,
10623 _: &GoToDefinition,
10624 window: &mut Window,
10625 cx: &mut Context<Self>,
10626 ) -> Task<Result<Navigated>> {
10627 let definition =
10628 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10629 cx.spawn_in(window, |editor, mut cx| async move {
10630 if definition.await? == Navigated::Yes {
10631 return Ok(Navigated::Yes);
10632 }
10633 match editor.update_in(&mut cx, |editor, window, cx| {
10634 editor.find_all_references(&FindAllReferences, window, cx)
10635 })? {
10636 Some(references) => references.await,
10637 None => Ok(Navigated::No),
10638 }
10639 })
10640 }
10641
10642 pub fn go_to_declaration(
10643 &mut self,
10644 _: &GoToDeclaration,
10645 window: &mut Window,
10646 cx: &mut Context<Self>,
10647 ) -> Task<Result<Navigated>> {
10648 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10649 }
10650
10651 pub fn go_to_declaration_split(
10652 &mut self,
10653 _: &GoToDeclaration,
10654 window: &mut Window,
10655 cx: &mut Context<Self>,
10656 ) -> Task<Result<Navigated>> {
10657 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10658 }
10659
10660 pub fn go_to_implementation(
10661 &mut self,
10662 _: &GoToImplementation,
10663 window: &mut Window,
10664 cx: &mut Context<Self>,
10665 ) -> Task<Result<Navigated>> {
10666 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10667 }
10668
10669 pub fn go_to_implementation_split(
10670 &mut self,
10671 _: &GoToImplementationSplit,
10672 window: &mut Window,
10673 cx: &mut Context<Self>,
10674 ) -> Task<Result<Navigated>> {
10675 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10676 }
10677
10678 pub fn go_to_type_definition(
10679 &mut self,
10680 _: &GoToTypeDefinition,
10681 window: &mut Window,
10682 cx: &mut Context<Self>,
10683 ) -> Task<Result<Navigated>> {
10684 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10685 }
10686
10687 pub fn go_to_definition_split(
10688 &mut self,
10689 _: &GoToDefinitionSplit,
10690 window: &mut Window,
10691 cx: &mut Context<Self>,
10692 ) -> Task<Result<Navigated>> {
10693 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10694 }
10695
10696 pub fn go_to_type_definition_split(
10697 &mut self,
10698 _: &GoToTypeDefinitionSplit,
10699 window: &mut Window,
10700 cx: &mut Context<Self>,
10701 ) -> Task<Result<Navigated>> {
10702 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10703 }
10704
10705 fn go_to_definition_of_kind(
10706 &mut self,
10707 kind: GotoDefinitionKind,
10708 split: bool,
10709 window: &mut Window,
10710 cx: &mut Context<Self>,
10711 ) -> Task<Result<Navigated>> {
10712 let Some(provider) = self.semantics_provider.clone() else {
10713 return Task::ready(Ok(Navigated::No));
10714 };
10715 let head = self.selections.newest::<usize>(cx).head();
10716 let buffer = self.buffer.read(cx);
10717 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10718 text_anchor
10719 } else {
10720 return Task::ready(Ok(Navigated::No));
10721 };
10722
10723 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10724 return Task::ready(Ok(Navigated::No));
10725 };
10726
10727 cx.spawn_in(window, |editor, mut cx| async move {
10728 let definitions = definitions.await?;
10729 let navigated = editor
10730 .update_in(&mut cx, |editor, window, cx| {
10731 editor.navigate_to_hover_links(
10732 Some(kind),
10733 definitions
10734 .into_iter()
10735 .filter(|location| {
10736 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10737 })
10738 .map(HoverLink::Text)
10739 .collect::<Vec<_>>(),
10740 split,
10741 window,
10742 cx,
10743 )
10744 })?
10745 .await?;
10746 anyhow::Ok(navigated)
10747 })
10748 }
10749
10750 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10751 let selection = self.selections.newest_anchor();
10752 let head = selection.head();
10753 let tail = selection.tail();
10754
10755 let Some((buffer, start_position)) =
10756 self.buffer.read(cx).text_anchor_for_position(head, cx)
10757 else {
10758 return;
10759 };
10760
10761 let end_position = if head != tail {
10762 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10763 return;
10764 };
10765 Some(pos)
10766 } else {
10767 None
10768 };
10769
10770 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10771 let url = if let Some(end_pos) = end_position {
10772 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10773 } else {
10774 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10775 };
10776
10777 if let Some(url) = url {
10778 editor.update(&mut cx, |_, cx| {
10779 cx.open_url(&url);
10780 })
10781 } else {
10782 Ok(())
10783 }
10784 });
10785
10786 url_finder.detach();
10787 }
10788
10789 pub fn open_selected_filename(
10790 &mut self,
10791 _: &OpenSelectedFilename,
10792 window: &mut Window,
10793 cx: &mut Context<Self>,
10794 ) {
10795 let Some(workspace) = self.workspace() else {
10796 return;
10797 };
10798
10799 let position = self.selections.newest_anchor().head();
10800
10801 let Some((buffer, buffer_position)) =
10802 self.buffer.read(cx).text_anchor_for_position(position, cx)
10803 else {
10804 return;
10805 };
10806
10807 let project = self.project.clone();
10808
10809 cx.spawn_in(window, |_, mut cx| async move {
10810 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10811
10812 if let Some((_, path)) = result {
10813 workspace
10814 .update_in(&mut cx, |workspace, window, cx| {
10815 workspace.open_resolved_path(path, window, cx)
10816 })?
10817 .await?;
10818 }
10819 anyhow::Ok(())
10820 })
10821 .detach();
10822 }
10823
10824 pub(crate) fn navigate_to_hover_links(
10825 &mut self,
10826 kind: Option<GotoDefinitionKind>,
10827 mut definitions: Vec<HoverLink>,
10828 split: bool,
10829 window: &mut Window,
10830 cx: &mut Context<Editor>,
10831 ) -> Task<Result<Navigated>> {
10832 // If there is one definition, just open it directly
10833 if definitions.len() == 1 {
10834 let definition = definitions.pop().unwrap();
10835
10836 enum TargetTaskResult {
10837 Location(Option<Location>),
10838 AlreadyNavigated,
10839 }
10840
10841 let target_task = match definition {
10842 HoverLink::Text(link) => {
10843 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10844 }
10845 HoverLink::InlayHint(lsp_location, server_id) => {
10846 let computation =
10847 self.compute_target_location(lsp_location, server_id, window, cx);
10848 cx.background_executor().spawn(async move {
10849 let location = computation.await?;
10850 Ok(TargetTaskResult::Location(location))
10851 })
10852 }
10853 HoverLink::Url(url) => {
10854 cx.open_url(&url);
10855 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10856 }
10857 HoverLink::File(path) => {
10858 if let Some(workspace) = self.workspace() {
10859 cx.spawn_in(window, |_, mut cx| async move {
10860 workspace
10861 .update_in(&mut cx, |workspace, window, cx| {
10862 workspace.open_resolved_path(path, window, cx)
10863 })?
10864 .await
10865 .map(|_| TargetTaskResult::AlreadyNavigated)
10866 })
10867 } else {
10868 Task::ready(Ok(TargetTaskResult::Location(None)))
10869 }
10870 }
10871 };
10872 cx.spawn_in(window, |editor, mut cx| async move {
10873 let target = match target_task.await.context("target resolution task")? {
10874 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10875 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10876 TargetTaskResult::Location(Some(target)) => target,
10877 };
10878
10879 editor.update_in(&mut cx, |editor, window, cx| {
10880 let Some(workspace) = editor.workspace() else {
10881 return Navigated::No;
10882 };
10883 let pane = workspace.read(cx).active_pane().clone();
10884
10885 let range = target.range.to_point(target.buffer.read(cx));
10886 let range = editor.range_for_match(&range);
10887 let range = collapse_multiline_range(range);
10888
10889 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10890 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10891 } else {
10892 window.defer(cx, move |window, cx| {
10893 let target_editor: Entity<Self> =
10894 workspace.update(cx, |workspace, cx| {
10895 let pane = if split {
10896 workspace.adjacent_pane(window, cx)
10897 } else {
10898 workspace.active_pane().clone()
10899 };
10900
10901 workspace.open_project_item(
10902 pane,
10903 target.buffer.clone(),
10904 true,
10905 true,
10906 window,
10907 cx,
10908 )
10909 });
10910 target_editor.update(cx, |target_editor, cx| {
10911 // When selecting a definition in a different buffer, disable the nav history
10912 // to avoid creating a history entry at the previous cursor location.
10913 pane.update(cx, |pane, _| pane.disable_history());
10914 target_editor.go_to_singleton_buffer_range(range, window, cx);
10915 pane.update(cx, |pane, _| pane.enable_history());
10916 });
10917 });
10918 }
10919 Navigated::Yes
10920 })
10921 })
10922 } else if !definitions.is_empty() {
10923 cx.spawn_in(window, |editor, mut cx| async move {
10924 let (title, location_tasks, workspace) = editor
10925 .update_in(&mut cx, |editor, window, cx| {
10926 let tab_kind = match kind {
10927 Some(GotoDefinitionKind::Implementation) => "Implementations",
10928 _ => "Definitions",
10929 };
10930 let title = definitions
10931 .iter()
10932 .find_map(|definition| match definition {
10933 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10934 let buffer = origin.buffer.read(cx);
10935 format!(
10936 "{} for {}",
10937 tab_kind,
10938 buffer
10939 .text_for_range(origin.range.clone())
10940 .collect::<String>()
10941 )
10942 }),
10943 HoverLink::InlayHint(_, _) => None,
10944 HoverLink::Url(_) => None,
10945 HoverLink::File(_) => None,
10946 })
10947 .unwrap_or(tab_kind.to_string());
10948 let location_tasks = definitions
10949 .into_iter()
10950 .map(|definition| match definition {
10951 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10952 HoverLink::InlayHint(lsp_location, server_id) => editor
10953 .compute_target_location(lsp_location, server_id, window, cx),
10954 HoverLink::Url(_) => Task::ready(Ok(None)),
10955 HoverLink::File(_) => Task::ready(Ok(None)),
10956 })
10957 .collect::<Vec<_>>();
10958 (title, location_tasks, editor.workspace().clone())
10959 })
10960 .context("location tasks preparation")?;
10961
10962 let locations = future::join_all(location_tasks)
10963 .await
10964 .into_iter()
10965 .filter_map(|location| location.transpose())
10966 .collect::<Result<_>>()
10967 .context("location tasks")?;
10968
10969 let Some(workspace) = workspace else {
10970 return Ok(Navigated::No);
10971 };
10972 let opened = workspace
10973 .update_in(&mut cx, |workspace, window, cx| {
10974 Self::open_locations_in_multibuffer(
10975 workspace,
10976 locations,
10977 title,
10978 split,
10979 MultibufferSelectionMode::First,
10980 window,
10981 cx,
10982 )
10983 })
10984 .ok();
10985
10986 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10987 })
10988 } else {
10989 Task::ready(Ok(Navigated::No))
10990 }
10991 }
10992
10993 fn compute_target_location(
10994 &self,
10995 lsp_location: lsp::Location,
10996 server_id: LanguageServerId,
10997 window: &mut Window,
10998 cx: &mut Context<Self>,
10999 ) -> Task<anyhow::Result<Option<Location>>> {
11000 let Some(project) = self.project.clone() else {
11001 return Task::ready(Ok(None));
11002 };
11003
11004 cx.spawn_in(window, move |editor, mut cx| async move {
11005 let location_task = editor.update(&mut cx, |_, cx| {
11006 project.update(cx, |project, cx| {
11007 let language_server_name = project
11008 .language_server_statuses(cx)
11009 .find(|(id, _)| server_id == *id)
11010 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11011 language_server_name.map(|language_server_name| {
11012 project.open_local_buffer_via_lsp(
11013 lsp_location.uri.clone(),
11014 server_id,
11015 language_server_name,
11016 cx,
11017 )
11018 })
11019 })
11020 })?;
11021 let location = match location_task {
11022 Some(task) => Some({
11023 let target_buffer_handle = task.await.context("open local buffer")?;
11024 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11025 let target_start = target_buffer
11026 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11027 let target_end = target_buffer
11028 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11029 target_buffer.anchor_after(target_start)
11030 ..target_buffer.anchor_before(target_end)
11031 })?;
11032 Location {
11033 buffer: target_buffer_handle,
11034 range,
11035 }
11036 }),
11037 None => None,
11038 };
11039 Ok(location)
11040 })
11041 }
11042
11043 pub fn find_all_references(
11044 &mut self,
11045 _: &FindAllReferences,
11046 window: &mut Window,
11047 cx: &mut Context<Self>,
11048 ) -> Option<Task<Result<Navigated>>> {
11049 let selection = self.selections.newest::<usize>(cx);
11050 let multi_buffer = self.buffer.read(cx);
11051 let head = selection.head();
11052
11053 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11054 let head_anchor = multi_buffer_snapshot.anchor_at(
11055 head,
11056 if head < selection.tail() {
11057 Bias::Right
11058 } else {
11059 Bias::Left
11060 },
11061 );
11062
11063 match self
11064 .find_all_references_task_sources
11065 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11066 {
11067 Ok(_) => {
11068 log::info!(
11069 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11070 );
11071 return None;
11072 }
11073 Err(i) => {
11074 self.find_all_references_task_sources.insert(i, head_anchor);
11075 }
11076 }
11077
11078 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11079 let workspace = self.workspace()?;
11080 let project = workspace.read(cx).project().clone();
11081 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11082 Some(cx.spawn_in(window, |editor, mut cx| async move {
11083 let _cleanup = defer({
11084 let mut cx = cx.clone();
11085 move || {
11086 let _ = editor.update(&mut cx, |editor, _| {
11087 if let Ok(i) =
11088 editor
11089 .find_all_references_task_sources
11090 .binary_search_by(|anchor| {
11091 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11092 })
11093 {
11094 editor.find_all_references_task_sources.remove(i);
11095 }
11096 });
11097 }
11098 });
11099
11100 let locations = references.await?;
11101 if locations.is_empty() {
11102 return anyhow::Ok(Navigated::No);
11103 }
11104
11105 workspace.update_in(&mut cx, |workspace, window, cx| {
11106 let title = locations
11107 .first()
11108 .as_ref()
11109 .map(|location| {
11110 let buffer = location.buffer.read(cx);
11111 format!(
11112 "References to `{}`",
11113 buffer
11114 .text_for_range(location.range.clone())
11115 .collect::<String>()
11116 )
11117 })
11118 .unwrap();
11119 Self::open_locations_in_multibuffer(
11120 workspace,
11121 locations,
11122 title,
11123 false,
11124 MultibufferSelectionMode::First,
11125 window,
11126 cx,
11127 );
11128 Navigated::Yes
11129 })
11130 }))
11131 }
11132
11133 /// Opens a multibuffer with the given project locations in it
11134 pub fn open_locations_in_multibuffer(
11135 workspace: &mut Workspace,
11136 mut locations: Vec<Location>,
11137 title: String,
11138 split: bool,
11139 multibuffer_selection_mode: MultibufferSelectionMode,
11140 window: &mut Window,
11141 cx: &mut Context<Workspace>,
11142 ) {
11143 // If there are multiple definitions, open them in a multibuffer
11144 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11145 let mut locations = locations.into_iter().peekable();
11146 let mut ranges = Vec::new();
11147 let capability = workspace.project().read(cx).capability();
11148
11149 let excerpt_buffer = cx.new(|cx| {
11150 let mut multibuffer = MultiBuffer::new(capability);
11151 while let Some(location) = locations.next() {
11152 let buffer = location.buffer.read(cx);
11153 let mut ranges_for_buffer = Vec::new();
11154 let range = location.range.to_offset(buffer);
11155 ranges_for_buffer.push(range.clone());
11156
11157 while let Some(next_location) = locations.peek() {
11158 if next_location.buffer == location.buffer {
11159 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11160 locations.next();
11161 } else {
11162 break;
11163 }
11164 }
11165
11166 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11167 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11168 location.buffer.clone(),
11169 ranges_for_buffer,
11170 DEFAULT_MULTIBUFFER_CONTEXT,
11171 cx,
11172 ))
11173 }
11174
11175 multibuffer.with_title(title)
11176 });
11177
11178 let editor = cx.new(|cx| {
11179 Editor::for_multibuffer(
11180 excerpt_buffer,
11181 Some(workspace.project().clone()),
11182 true,
11183 window,
11184 cx,
11185 )
11186 });
11187 editor.update(cx, |editor, cx| {
11188 match multibuffer_selection_mode {
11189 MultibufferSelectionMode::First => {
11190 if let Some(first_range) = ranges.first() {
11191 editor.change_selections(None, window, cx, |selections| {
11192 selections.clear_disjoint();
11193 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11194 });
11195 }
11196 editor.highlight_background::<Self>(
11197 &ranges,
11198 |theme| theme.editor_highlighted_line_background,
11199 cx,
11200 );
11201 }
11202 MultibufferSelectionMode::All => {
11203 editor.change_selections(None, window, cx, |selections| {
11204 selections.clear_disjoint();
11205 selections.select_anchor_ranges(ranges);
11206 });
11207 }
11208 }
11209 editor.register_buffers_with_language_servers(cx);
11210 });
11211
11212 let item = Box::new(editor);
11213 let item_id = item.item_id();
11214
11215 if split {
11216 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11217 } else {
11218 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11219 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11220 pane.close_current_preview_item(window, cx)
11221 } else {
11222 None
11223 }
11224 });
11225 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11226 }
11227 workspace.active_pane().update(cx, |pane, cx| {
11228 pane.set_preview_item_id(Some(item_id), cx);
11229 });
11230 }
11231
11232 pub fn rename(
11233 &mut self,
11234 _: &Rename,
11235 window: &mut Window,
11236 cx: &mut Context<Self>,
11237 ) -> Option<Task<Result<()>>> {
11238 use language::ToOffset as _;
11239
11240 let provider = self.semantics_provider.clone()?;
11241 let selection = self.selections.newest_anchor().clone();
11242 let (cursor_buffer, cursor_buffer_position) = self
11243 .buffer
11244 .read(cx)
11245 .text_anchor_for_position(selection.head(), cx)?;
11246 let (tail_buffer, cursor_buffer_position_end) = self
11247 .buffer
11248 .read(cx)
11249 .text_anchor_for_position(selection.tail(), cx)?;
11250 if tail_buffer != cursor_buffer {
11251 return None;
11252 }
11253
11254 let snapshot = cursor_buffer.read(cx).snapshot();
11255 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11256 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11257 let prepare_rename = provider
11258 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11259 .unwrap_or_else(|| Task::ready(Ok(None)));
11260 drop(snapshot);
11261
11262 Some(cx.spawn_in(window, |this, mut cx| async move {
11263 let rename_range = if let Some(range) = prepare_rename.await? {
11264 Some(range)
11265 } else {
11266 this.update(&mut cx, |this, cx| {
11267 let buffer = this.buffer.read(cx).snapshot(cx);
11268 let mut buffer_highlights = this
11269 .document_highlights_for_position(selection.head(), &buffer)
11270 .filter(|highlight| {
11271 highlight.start.excerpt_id == selection.head().excerpt_id
11272 && highlight.end.excerpt_id == selection.head().excerpt_id
11273 });
11274 buffer_highlights
11275 .next()
11276 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11277 })?
11278 };
11279 if let Some(rename_range) = rename_range {
11280 this.update_in(&mut cx, |this, window, cx| {
11281 let snapshot = cursor_buffer.read(cx).snapshot();
11282 let rename_buffer_range = rename_range.to_offset(&snapshot);
11283 let cursor_offset_in_rename_range =
11284 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11285 let cursor_offset_in_rename_range_end =
11286 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11287
11288 this.take_rename(false, window, cx);
11289 let buffer = this.buffer.read(cx).read(cx);
11290 let cursor_offset = selection.head().to_offset(&buffer);
11291 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11292 let rename_end = rename_start + rename_buffer_range.len();
11293 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11294 let mut old_highlight_id = None;
11295 let old_name: Arc<str> = buffer
11296 .chunks(rename_start..rename_end, true)
11297 .map(|chunk| {
11298 if old_highlight_id.is_none() {
11299 old_highlight_id = chunk.syntax_highlight_id;
11300 }
11301 chunk.text
11302 })
11303 .collect::<String>()
11304 .into();
11305
11306 drop(buffer);
11307
11308 // Position the selection in the rename editor so that it matches the current selection.
11309 this.show_local_selections = false;
11310 let rename_editor = cx.new(|cx| {
11311 let mut editor = Editor::single_line(window, cx);
11312 editor.buffer.update(cx, |buffer, cx| {
11313 buffer.edit([(0..0, old_name.clone())], None, cx)
11314 });
11315 let rename_selection_range = match cursor_offset_in_rename_range
11316 .cmp(&cursor_offset_in_rename_range_end)
11317 {
11318 Ordering::Equal => {
11319 editor.select_all(&SelectAll, window, cx);
11320 return editor;
11321 }
11322 Ordering::Less => {
11323 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11324 }
11325 Ordering::Greater => {
11326 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11327 }
11328 };
11329 if rename_selection_range.end > old_name.len() {
11330 editor.select_all(&SelectAll, window, cx);
11331 } else {
11332 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11333 s.select_ranges([rename_selection_range]);
11334 });
11335 }
11336 editor
11337 });
11338 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11339 if e == &EditorEvent::Focused {
11340 cx.emit(EditorEvent::FocusedIn)
11341 }
11342 })
11343 .detach();
11344
11345 let write_highlights =
11346 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11347 let read_highlights =
11348 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11349 let ranges = write_highlights
11350 .iter()
11351 .flat_map(|(_, ranges)| ranges.iter())
11352 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11353 .cloned()
11354 .collect();
11355
11356 this.highlight_text::<Rename>(
11357 ranges,
11358 HighlightStyle {
11359 fade_out: Some(0.6),
11360 ..Default::default()
11361 },
11362 cx,
11363 );
11364 let rename_focus_handle = rename_editor.focus_handle(cx);
11365 window.focus(&rename_focus_handle);
11366 let block_id = this.insert_blocks(
11367 [BlockProperties {
11368 style: BlockStyle::Flex,
11369 placement: BlockPlacement::Below(range.start),
11370 height: 1,
11371 render: Arc::new({
11372 let rename_editor = rename_editor.clone();
11373 move |cx: &mut BlockContext| {
11374 let mut text_style = cx.editor_style.text.clone();
11375 if let Some(highlight_style) = old_highlight_id
11376 .and_then(|h| h.style(&cx.editor_style.syntax))
11377 {
11378 text_style = text_style.highlight(highlight_style);
11379 }
11380 div()
11381 .block_mouse_down()
11382 .pl(cx.anchor_x)
11383 .child(EditorElement::new(
11384 &rename_editor,
11385 EditorStyle {
11386 background: cx.theme().system().transparent,
11387 local_player: cx.editor_style.local_player,
11388 text: text_style,
11389 scrollbar_width: cx.editor_style.scrollbar_width,
11390 syntax: cx.editor_style.syntax.clone(),
11391 status: cx.editor_style.status.clone(),
11392 inlay_hints_style: HighlightStyle {
11393 font_weight: Some(FontWeight::BOLD),
11394 ..make_inlay_hints_style(cx.app)
11395 },
11396 inline_completion_styles: make_suggestion_styles(
11397 cx.app,
11398 ),
11399 ..EditorStyle::default()
11400 },
11401 ))
11402 .into_any_element()
11403 }
11404 }),
11405 priority: 0,
11406 }],
11407 Some(Autoscroll::fit()),
11408 cx,
11409 )[0];
11410 this.pending_rename = Some(RenameState {
11411 range,
11412 old_name,
11413 editor: rename_editor,
11414 block_id,
11415 });
11416 })?;
11417 }
11418
11419 Ok(())
11420 }))
11421 }
11422
11423 pub fn confirm_rename(
11424 &mut self,
11425 _: &ConfirmRename,
11426 window: &mut Window,
11427 cx: &mut Context<Self>,
11428 ) -> Option<Task<Result<()>>> {
11429 let rename = self.take_rename(false, window, cx)?;
11430 let workspace = self.workspace()?.downgrade();
11431 let (buffer, start) = self
11432 .buffer
11433 .read(cx)
11434 .text_anchor_for_position(rename.range.start, cx)?;
11435 let (end_buffer, _) = self
11436 .buffer
11437 .read(cx)
11438 .text_anchor_for_position(rename.range.end, cx)?;
11439 if buffer != end_buffer {
11440 return None;
11441 }
11442
11443 let old_name = rename.old_name;
11444 let new_name = rename.editor.read(cx).text(cx);
11445
11446 let rename = self.semantics_provider.as_ref()?.perform_rename(
11447 &buffer,
11448 start,
11449 new_name.clone(),
11450 cx,
11451 )?;
11452
11453 Some(cx.spawn_in(window, |editor, mut cx| async move {
11454 let project_transaction = rename.await?;
11455 Self::open_project_transaction(
11456 &editor,
11457 workspace,
11458 project_transaction,
11459 format!("Rename: {} → {}", old_name, new_name),
11460 cx.clone(),
11461 )
11462 .await?;
11463
11464 editor.update(&mut cx, |editor, cx| {
11465 editor.refresh_document_highlights(cx);
11466 })?;
11467 Ok(())
11468 }))
11469 }
11470
11471 fn take_rename(
11472 &mut self,
11473 moving_cursor: bool,
11474 window: &mut Window,
11475 cx: &mut Context<Self>,
11476 ) -> Option<RenameState> {
11477 let rename = self.pending_rename.take()?;
11478 if rename.editor.focus_handle(cx).is_focused(window) {
11479 window.focus(&self.focus_handle);
11480 }
11481
11482 self.remove_blocks(
11483 [rename.block_id].into_iter().collect(),
11484 Some(Autoscroll::fit()),
11485 cx,
11486 );
11487 self.clear_highlights::<Rename>(cx);
11488 self.show_local_selections = true;
11489
11490 if moving_cursor {
11491 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11492 editor.selections.newest::<usize>(cx).head()
11493 });
11494
11495 // Update the selection to match the position of the selection inside
11496 // the rename editor.
11497 let snapshot = self.buffer.read(cx).read(cx);
11498 let rename_range = rename.range.to_offset(&snapshot);
11499 let cursor_in_editor = snapshot
11500 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11501 .min(rename_range.end);
11502 drop(snapshot);
11503
11504 self.change_selections(None, window, cx, |s| {
11505 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11506 });
11507 } else {
11508 self.refresh_document_highlights(cx);
11509 }
11510
11511 Some(rename)
11512 }
11513
11514 pub fn pending_rename(&self) -> Option<&RenameState> {
11515 self.pending_rename.as_ref()
11516 }
11517
11518 fn format(
11519 &mut self,
11520 _: &Format,
11521 window: &mut Window,
11522 cx: &mut Context<Self>,
11523 ) -> Option<Task<Result<()>>> {
11524 let project = match &self.project {
11525 Some(project) => project.clone(),
11526 None => return None,
11527 };
11528
11529 Some(self.perform_format(
11530 project,
11531 FormatTrigger::Manual,
11532 FormatTarget::Buffers,
11533 window,
11534 cx,
11535 ))
11536 }
11537
11538 fn format_selections(
11539 &mut self,
11540 _: &FormatSelections,
11541 window: &mut Window,
11542 cx: &mut Context<Self>,
11543 ) -> Option<Task<Result<()>>> {
11544 let project = match &self.project {
11545 Some(project) => project.clone(),
11546 None => return None,
11547 };
11548
11549 let ranges = self
11550 .selections
11551 .all_adjusted(cx)
11552 .into_iter()
11553 .map(|selection| selection.range())
11554 .collect_vec();
11555
11556 Some(self.perform_format(
11557 project,
11558 FormatTrigger::Manual,
11559 FormatTarget::Ranges(ranges),
11560 window,
11561 cx,
11562 ))
11563 }
11564
11565 fn perform_format(
11566 &mut self,
11567 project: Entity<Project>,
11568 trigger: FormatTrigger,
11569 target: FormatTarget,
11570 window: &mut Window,
11571 cx: &mut Context<Self>,
11572 ) -> Task<Result<()>> {
11573 let buffer = self.buffer.clone();
11574 let (buffers, target) = match target {
11575 FormatTarget::Buffers => {
11576 let mut buffers = buffer.read(cx).all_buffers();
11577 if trigger == FormatTrigger::Save {
11578 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11579 }
11580 (buffers, LspFormatTarget::Buffers)
11581 }
11582 FormatTarget::Ranges(selection_ranges) => {
11583 let multi_buffer = buffer.read(cx);
11584 let snapshot = multi_buffer.read(cx);
11585 let mut buffers = HashSet::default();
11586 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11587 BTreeMap::new();
11588 for selection_range in selection_ranges {
11589 for (buffer, buffer_range, _) in
11590 snapshot.range_to_buffer_ranges(selection_range)
11591 {
11592 let buffer_id = buffer.remote_id();
11593 let start = buffer.anchor_before(buffer_range.start);
11594 let end = buffer.anchor_after(buffer_range.end);
11595 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11596 buffer_id_to_ranges
11597 .entry(buffer_id)
11598 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11599 .or_insert_with(|| vec![start..end]);
11600 }
11601 }
11602 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11603 }
11604 };
11605
11606 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11607 let format = project.update(cx, |project, cx| {
11608 project.format(buffers, target, true, trigger, cx)
11609 });
11610
11611 cx.spawn_in(window, |_, mut cx| async move {
11612 let transaction = futures::select_biased! {
11613 () = timeout => {
11614 log::warn!("timed out waiting for formatting");
11615 None
11616 }
11617 transaction = format.log_err().fuse() => transaction,
11618 };
11619
11620 buffer
11621 .update(&mut cx, |buffer, cx| {
11622 if let Some(transaction) = transaction {
11623 if !buffer.is_singleton() {
11624 buffer.push_transaction(&transaction.0, cx);
11625 }
11626 }
11627
11628 cx.notify();
11629 })
11630 .ok();
11631
11632 Ok(())
11633 })
11634 }
11635
11636 fn restart_language_server(
11637 &mut self,
11638 _: &RestartLanguageServer,
11639 _: &mut Window,
11640 cx: &mut Context<Self>,
11641 ) {
11642 if let Some(project) = self.project.clone() {
11643 self.buffer.update(cx, |multi_buffer, cx| {
11644 project.update(cx, |project, cx| {
11645 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11646 });
11647 })
11648 }
11649 }
11650
11651 fn cancel_language_server_work(
11652 workspace: &mut Workspace,
11653 _: &actions::CancelLanguageServerWork,
11654 _: &mut Window,
11655 cx: &mut Context<Workspace>,
11656 ) {
11657 let project = workspace.project();
11658 let buffers = workspace
11659 .active_item(cx)
11660 .and_then(|item| item.act_as::<Editor>(cx))
11661 .map_or(HashSet::default(), |editor| {
11662 editor.read(cx).buffer.read(cx).all_buffers()
11663 });
11664 project.update(cx, |project, cx| {
11665 project.cancel_language_server_work_for_buffers(buffers, cx);
11666 });
11667 }
11668
11669 fn show_character_palette(
11670 &mut self,
11671 _: &ShowCharacterPalette,
11672 window: &mut Window,
11673 _: &mut Context<Self>,
11674 ) {
11675 window.show_character_palette();
11676 }
11677
11678 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11679 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11680 let buffer = self.buffer.read(cx).snapshot(cx);
11681 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11682 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11683 let is_valid = buffer
11684 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11685 .any(|entry| {
11686 entry.diagnostic.is_primary
11687 && !entry.range.is_empty()
11688 && entry.range.start == primary_range_start
11689 && entry.diagnostic.message == active_diagnostics.primary_message
11690 });
11691
11692 if is_valid != active_diagnostics.is_valid {
11693 active_diagnostics.is_valid = is_valid;
11694 let mut new_styles = HashMap::default();
11695 for (block_id, diagnostic) in &active_diagnostics.blocks {
11696 new_styles.insert(
11697 *block_id,
11698 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11699 );
11700 }
11701 self.display_map.update(cx, |display_map, _cx| {
11702 display_map.replace_blocks(new_styles)
11703 });
11704 }
11705 }
11706 }
11707
11708 fn activate_diagnostics(
11709 &mut self,
11710 buffer_id: BufferId,
11711 group_id: usize,
11712 window: &mut Window,
11713 cx: &mut Context<Self>,
11714 ) {
11715 self.dismiss_diagnostics(cx);
11716 let snapshot = self.snapshot(window, cx);
11717 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11718 let buffer = self.buffer.read(cx).snapshot(cx);
11719
11720 let mut primary_range = None;
11721 let mut primary_message = None;
11722 let diagnostic_group = buffer
11723 .diagnostic_group(buffer_id, group_id)
11724 .filter_map(|entry| {
11725 let start = entry.range.start;
11726 let end = entry.range.end;
11727 if snapshot.is_line_folded(MultiBufferRow(start.row))
11728 && (start.row == end.row
11729 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11730 {
11731 return None;
11732 }
11733 if entry.diagnostic.is_primary {
11734 primary_range = Some(entry.range.clone());
11735 primary_message = Some(entry.diagnostic.message.clone());
11736 }
11737 Some(entry)
11738 })
11739 .collect::<Vec<_>>();
11740 let primary_range = primary_range?;
11741 let primary_message = primary_message?;
11742
11743 let blocks = display_map
11744 .insert_blocks(
11745 diagnostic_group.iter().map(|entry| {
11746 let diagnostic = entry.diagnostic.clone();
11747 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11748 BlockProperties {
11749 style: BlockStyle::Fixed,
11750 placement: BlockPlacement::Below(
11751 buffer.anchor_after(entry.range.start),
11752 ),
11753 height: message_height,
11754 render: diagnostic_block_renderer(diagnostic, None, true, true),
11755 priority: 0,
11756 }
11757 }),
11758 cx,
11759 )
11760 .into_iter()
11761 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11762 .collect();
11763
11764 Some(ActiveDiagnosticGroup {
11765 primary_range: buffer.anchor_before(primary_range.start)
11766 ..buffer.anchor_after(primary_range.end),
11767 primary_message,
11768 group_id,
11769 blocks,
11770 is_valid: true,
11771 })
11772 });
11773 }
11774
11775 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11776 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11777 self.display_map.update(cx, |display_map, cx| {
11778 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11779 });
11780 cx.notify();
11781 }
11782 }
11783
11784 pub fn set_selections_from_remote(
11785 &mut self,
11786 selections: Vec<Selection<Anchor>>,
11787 pending_selection: Option<Selection<Anchor>>,
11788 window: &mut Window,
11789 cx: &mut Context<Self>,
11790 ) {
11791 let old_cursor_position = self.selections.newest_anchor().head();
11792 self.selections.change_with(cx, |s| {
11793 s.select_anchors(selections);
11794 if let Some(pending_selection) = pending_selection {
11795 s.set_pending(pending_selection, SelectMode::Character);
11796 } else {
11797 s.clear_pending();
11798 }
11799 });
11800 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11801 }
11802
11803 fn push_to_selection_history(&mut self) {
11804 self.selection_history.push(SelectionHistoryEntry {
11805 selections: self.selections.disjoint_anchors(),
11806 select_next_state: self.select_next_state.clone(),
11807 select_prev_state: self.select_prev_state.clone(),
11808 add_selections_state: self.add_selections_state.clone(),
11809 });
11810 }
11811
11812 pub fn transact(
11813 &mut self,
11814 window: &mut Window,
11815 cx: &mut Context<Self>,
11816 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11817 ) -> Option<TransactionId> {
11818 self.start_transaction_at(Instant::now(), window, cx);
11819 update(self, window, cx);
11820 self.end_transaction_at(Instant::now(), cx)
11821 }
11822
11823 pub fn start_transaction_at(
11824 &mut self,
11825 now: Instant,
11826 window: &mut Window,
11827 cx: &mut Context<Self>,
11828 ) {
11829 self.end_selection(window, cx);
11830 if let Some(tx_id) = self
11831 .buffer
11832 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11833 {
11834 self.selection_history
11835 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11836 cx.emit(EditorEvent::TransactionBegun {
11837 transaction_id: tx_id,
11838 })
11839 }
11840 }
11841
11842 pub fn end_transaction_at(
11843 &mut self,
11844 now: Instant,
11845 cx: &mut Context<Self>,
11846 ) -> Option<TransactionId> {
11847 if let Some(transaction_id) = self
11848 .buffer
11849 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11850 {
11851 if let Some((_, end_selections)) =
11852 self.selection_history.transaction_mut(transaction_id)
11853 {
11854 *end_selections = Some(self.selections.disjoint_anchors());
11855 } else {
11856 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11857 }
11858
11859 cx.emit(EditorEvent::Edited { transaction_id });
11860 Some(transaction_id)
11861 } else {
11862 None
11863 }
11864 }
11865
11866 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11867 if self.selection_mark_mode {
11868 self.change_selections(None, window, cx, |s| {
11869 s.move_with(|_, sel| {
11870 sel.collapse_to(sel.head(), SelectionGoal::None);
11871 });
11872 })
11873 }
11874 self.selection_mark_mode = true;
11875 cx.notify();
11876 }
11877
11878 pub fn swap_selection_ends(
11879 &mut self,
11880 _: &actions::SwapSelectionEnds,
11881 window: &mut Window,
11882 cx: &mut Context<Self>,
11883 ) {
11884 self.change_selections(None, window, cx, |s| {
11885 s.move_with(|_, sel| {
11886 if sel.start != sel.end {
11887 sel.reversed = !sel.reversed
11888 }
11889 });
11890 });
11891 self.request_autoscroll(Autoscroll::newest(), cx);
11892 cx.notify();
11893 }
11894
11895 pub fn toggle_fold(
11896 &mut self,
11897 _: &actions::ToggleFold,
11898 window: &mut Window,
11899 cx: &mut Context<Self>,
11900 ) {
11901 if self.is_singleton(cx) {
11902 let selection = self.selections.newest::<Point>(cx);
11903
11904 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11905 let range = if selection.is_empty() {
11906 let point = selection.head().to_display_point(&display_map);
11907 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11908 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11909 .to_point(&display_map);
11910 start..end
11911 } else {
11912 selection.range()
11913 };
11914 if display_map.folds_in_range(range).next().is_some() {
11915 self.unfold_lines(&Default::default(), window, cx)
11916 } else {
11917 self.fold(&Default::default(), window, cx)
11918 }
11919 } else {
11920 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11921 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11922 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11923 .map(|(snapshot, _, _)| snapshot.remote_id())
11924 .collect();
11925
11926 for buffer_id in buffer_ids {
11927 if self.is_buffer_folded(buffer_id, cx) {
11928 self.unfold_buffer(buffer_id, cx);
11929 } else {
11930 self.fold_buffer(buffer_id, cx);
11931 }
11932 }
11933 }
11934 }
11935
11936 pub fn toggle_fold_recursive(
11937 &mut self,
11938 _: &actions::ToggleFoldRecursive,
11939 window: &mut Window,
11940 cx: &mut Context<Self>,
11941 ) {
11942 let selection = self.selections.newest::<Point>(cx);
11943
11944 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11945 let range = if selection.is_empty() {
11946 let point = selection.head().to_display_point(&display_map);
11947 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11948 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11949 .to_point(&display_map);
11950 start..end
11951 } else {
11952 selection.range()
11953 };
11954 if display_map.folds_in_range(range).next().is_some() {
11955 self.unfold_recursive(&Default::default(), window, cx)
11956 } else {
11957 self.fold_recursive(&Default::default(), window, cx)
11958 }
11959 }
11960
11961 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11962 if self.is_singleton(cx) {
11963 let mut to_fold = Vec::new();
11964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11965 let selections = self.selections.all_adjusted(cx);
11966
11967 for selection in selections {
11968 let range = selection.range().sorted();
11969 let buffer_start_row = range.start.row;
11970
11971 if range.start.row != range.end.row {
11972 let mut found = false;
11973 let mut row = range.start.row;
11974 while row <= range.end.row {
11975 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11976 {
11977 found = true;
11978 row = crease.range().end.row + 1;
11979 to_fold.push(crease);
11980 } else {
11981 row += 1
11982 }
11983 }
11984 if found {
11985 continue;
11986 }
11987 }
11988
11989 for row in (0..=range.start.row).rev() {
11990 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11991 if crease.range().end.row >= buffer_start_row {
11992 to_fold.push(crease);
11993 if row <= range.start.row {
11994 break;
11995 }
11996 }
11997 }
11998 }
11999 }
12000
12001 self.fold_creases(to_fold, true, window, cx);
12002 } else {
12003 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12004
12005 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12006 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12007 .map(|(snapshot, _, _)| snapshot.remote_id())
12008 .collect();
12009 for buffer_id in buffer_ids {
12010 self.fold_buffer(buffer_id, cx);
12011 }
12012 }
12013 }
12014
12015 fn fold_at_level(
12016 &mut self,
12017 fold_at: &FoldAtLevel,
12018 window: &mut Window,
12019 cx: &mut Context<Self>,
12020 ) {
12021 if !self.buffer.read(cx).is_singleton() {
12022 return;
12023 }
12024
12025 let fold_at_level = fold_at.0;
12026 let snapshot = self.buffer.read(cx).snapshot(cx);
12027 let mut to_fold = Vec::new();
12028 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12029
12030 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12031 while start_row < end_row {
12032 match self
12033 .snapshot(window, cx)
12034 .crease_for_buffer_row(MultiBufferRow(start_row))
12035 {
12036 Some(crease) => {
12037 let nested_start_row = crease.range().start.row + 1;
12038 let nested_end_row = crease.range().end.row;
12039
12040 if current_level < fold_at_level {
12041 stack.push((nested_start_row, nested_end_row, current_level + 1));
12042 } else if current_level == fold_at_level {
12043 to_fold.push(crease);
12044 }
12045
12046 start_row = nested_end_row + 1;
12047 }
12048 None => start_row += 1,
12049 }
12050 }
12051 }
12052
12053 self.fold_creases(to_fold, true, window, cx);
12054 }
12055
12056 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12057 if self.buffer.read(cx).is_singleton() {
12058 let mut fold_ranges = Vec::new();
12059 let snapshot = self.buffer.read(cx).snapshot(cx);
12060
12061 for row in 0..snapshot.max_row().0 {
12062 if let Some(foldable_range) = self
12063 .snapshot(window, cx)
12064 .crease_for_buffer_row(MultiBufferRow(row))
12065 {
12066 fold_ranges.push(foldable_range);
12067 }
12068 }
12069
12070 self.fold_creases(fold_ranges, true, window, cx);
12071 } else {
12072 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12073 editor
12074 .update_in(&mut cx, |editor, _, cx| {
12075 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12076 editor.fold_buffer(buffer_id, cx);
12077 }
12078 })
12079 .ok();
12080 });
12081 }
12082 }
12083
12084 pub fn fold_function_bodies(
12085 &mut self,
12086 _: &actions::FoldFunctionBodies,
12087 window: &mut Window,
12088 cx: &mut Context<Self>,
12089 ) {
12090 let snapshot = self.buffer.read(cx).snapshot(cx);
12091
12092 let ranges = snapshot
12093 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12094 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12095 .collect::<Vec<_>>();
12096
12097 let creases = ranges
12098 .into_iter()
12099 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12100 .collect();
12101
12102 self.fold_creases(creases, true, window, cx);
12103 }
12104
12105 pub fn fold_recursive(
12106 &mut self,
12107 _: &actions::FoldRecursive,
12108 window: &mut Window,
12109 cx: &mut Context<Self>,
12110 ) {
12111 let mut to_fold = Vec::new();
12112 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12113 let selections = self.selections.all_adjusted(cx);
12114
12115 for selection in selections {
12116 let range = selection.range().sorted();
12117 let buffer_start_row = range.start.row;
12118
12119 if range.start.row != range.end.row {
12120 let mut found = false;
12121 for row in range.start.row..=range.end.row {
12122 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12123 found = true;
12124 to_fold.push(crease);
12125 }
12126 }
12127 if found {
12128 continue;
12129 }
12130 }
12131
12132 for row in (0..=range.start.row).rev() {
12133 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12134 if crease.range().end.row >= buffer_start_row {
12135 to_fold.push(crease);
12136 } else {
12137 break;
12138 }
12139 }
12140 }
12141 }
12142
12143 self.fold_creases(to_fold, true, window, cx);
12144 }
12145
12146 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12147 let buffer_row = fold_at.buffer_row;
12148 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12149
12150 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12151 let autoscroll = self
12152 .selections
12153 .all::<Point>(cx)
12154 .iter()
12155 .any(|selection| crease.range().overlaps(&selection.range()));
12156
12157 self.fold_creases(vec![crease], autoscroll, window, cx);
12158 }
12159 }
12160
12161 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12162 if self.is_singleton(cx) {
12163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12164 let buffer = &display_map.buffer_snapshot;
12165 let selections = self.selections.all::<Point>(cx);
12166 let ranges = selections
12167 .iter()
12168 .map(|s| {
12169 let range = s.display_range(&display_map).sorted();
12170 let mut start = range.start.to_point(&display_map);
12171 let mut end = range.end.to_point(&display_map);
12172 start.column = 0;
12173 end.column = buffer.line_len(MultiBufferRow(end.row));
12174 start..end
12175 })
12176 .collect::<Vec<_>>();
12177
12178 self.unfold_ranges(&ranges, true, true, cx);
12179 } else {
12180 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12181 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12182 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12183 .map(|(snapshot, _, _)| snapshot.remote_id())
12184 .collect();
12185 for buffer_id in buffer_ids {
12186 self.unfold_buffer(buffer_id, cx);
12187 }
12188 }
12189 }
12190
12191 pub fn unfold_recursive(
12192 &mut self,
12193 _: &UnfoldRecursive,
12194 _window: &mut Window,
12195 cx: &mut Context<Self>,
12196 ) {
12197 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12198 let selections = self.selections.all::<Point>(cx);
12199 let ranges = selections
12200 .iter()
12201 .map(|s| {
12202 let mut range = s.display_range(&display_map).sorted();
12203 *range.start.column_mut() = 0;
12204 *range.end.column_mut() = display_map.line_len(range.end.row());
12205 let start = range.start.to_point(&display_map);
12206 let end = range.end.to_point(&display_map);
12207 start..end
12208 })
12209 .collect::<Vec<_>>();
12210
12211 self.unfold_ranges(&ranges, true, true, cx);
12212 }
12213
12214 pub fn unfold_at(
12215 &mut self,
12216 unfold_at: &UnfoldAt,
12217 _window: &mut Window,
12218 cx: &mut Context<Self>,
12219 ) {
12220 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12221
12222 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12223 ..Point::new(
12224 unfold_at.buffer_row.0,
12225 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12226 );
12227
12228 let autoscroll = self
12229 .selections
12230 .all::<Point>(cx)
12231 .iter()
12232 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12233
12234 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12235 }
12236
12237 pub fn unfold_all(
12238 &mut self,
12239 _: &actions::UnfoldAll,
12240 _window: &mut Window,
12241 cx: &mut Context<Self>,
12242 ) {
12243 if self.buffer.read(cx).is_singleton() {
12244 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12245 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12246 } else {
12247 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12248 editor
12249 .update(&mut cx, |editor, cx| {
12250 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12251 editor.unfold_buffer(buffer_id, cx);
12252 }
12253 })
12254 .ok();
12255 });
12256 }
12257 }
12258
12259 pub fn fold_selected_ranges(
12260 &mut self,
12261 _: &FoldSelectedRanges,
12262 window: &mut Window,
12263 cx: &mut Context<Self>,
12264 ) {
12265 let selections = self.selections.all::<Point>(cx);
12266 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12267 let line_mode = self.selections.line_mode;
12268 let ranges = selections
12269 .into_iter()
12270 .map(|s| {
12271 if line_mode {
12272 let start = Point::new(s.start.row, 0);
12273 let end = Point::new(
12274 s.end.row,
12275 display_map
12276 .buffer_snapshot
12277 .line_len(MultiBufferRow(s.end.row)),
12278 );
12279 Crease::simple(start..end, display_map.fold_placeholder.clone())
12280 } else {
12281 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12282 }
12283 })
12284 .collect::<Vec<_>>();
12285 self.fold_creases(ranges, true, window, cx);
12286 }
12287
12288 pub fn fold_ranges<T: ToOffset + Clone>(
12289 &mut self,
12290 ranges: Vec<Range<T>>,
12291 auto_scroll: bool,
12292 window: &mut Window,
12293 cx: &mut Context<Self>,
12294 ) {
12295 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12296 let ranges = ranges
12297 .into_iter()
12298 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12299 .collect::<Vec<_>>();
12300 self.fold_creases(ranges, auto_scroll, window, cx);
12301 }
12302
12303 pub fn fold_creases<T: ToOffset + Clone>(
12304 &mut self,
12305 creases: Vec<Crease<T>>,
12306 auto_scroll: bool,
12307 window: &mut Window,
12308 cx: &mut Context<Self>,
12309 ) {
12310 if creases.is_empty() {
12311 return;
12312 }
12313
12314 let mut buffers_affected = HashSet::default();
12315 let multi_buffer = self.buffer().read(cx);
12316 for crease in &creases {
12317 if let Some((_, buffer, _)) =
12318 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12319 {
12320 buffers_affected.insert(buffer.read(cx).remote_id());
12321 };
12322 }
12323
12324 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12325
12326 if auto_scroll {
12327 self.request_autoscroll(Autoscroll::fit(), cx);
12328 }
12329
12330 cx.notify();
12331
12332 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12333 // Clear diagnostics block when folding a range that contains it.
12334 let snapshot = self.snapshot(window, cx);
12335 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12336 drop(snapshot);
12337 self.active_diagnostics = Some(active_diagnostics);
12338 self.dismiss_diagnostics(cx);
12339 } else {
12340 self.active_diagnostics = Some(active_diagnostics);
12341 }
12342 }
12343
12344 self.scrollbar_marker_state.dirty = true;
12345 }
12346
12347 /// Removes any folds whose ranges intersect any of the given ranges.
12348 pub fn unfold_ranges<T: ToOffset + Clone>(
12349 &mut self,
12350 ranges: &[Range<T>],
12351 inclusive: bool,
12352 auto_scroll: bool,
12353 cx: &mut Context<Self>,
12354 ) {
12355 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12356 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12357 });
12358 }
12359
12360 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12361 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12362 return;
12363 }
12364 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12365 self.display_map
12366 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12367 cx.emit(EditorEvent::BufferFoldToggled {
12368 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12369 folded: true,
12370 });
12371 cx.notify();
12372 }
12373
12374 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12375 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12376 return;
12377 }
12378 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12379 self.display_map.update(cx, |display_map, cx| {
12380 display_map.unfold_buffer(buffer_id, cx);
12381 });
12382 cx.emit(EditorEvent::BufferFoldToggled {
12383 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12384 folded: false,
12385 });
12386 cx.notify();
12387 }
12388
12389 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12390 self.display_map.read(cx).is_buffer_folded(buffer)
12391 }
12392
12393 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12394 self.display_map.read(cx).folded_buffers()
12395 }
12396
12397 /// Removes any folds with the given ranges.
12398 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12399 &mut self,
12400 ranges: &[Range<T>],
12401 type_id: TypeId,
12402 auto_scroll: bool,
12403 cx: &mut Context<Self>,
12404 ) {
12405 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12406 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12407 });
12408 }
12409
12410 fn remove_folds_with<T: ToOffset + Clone>(
12411 &mut self,
12412 ranges: &[Range<T>],
12413 auto_scroll: bool,
12414 cx: &mut Context<Self>,
12415 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12416 ) {
12417 if ranges.is_empty() {
12418 return;
12419 }
12420
12421 let mut buffers_affected = HashSet::default();
12422 let multi_buffer = self.buffer().read(cx);
12423 for range in ranges {
12424 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12425 buffers_affected.insert(buffer.read(cx).remote_id());
12426 };
12427 }
12428
12429 self.display_map.update(cx, update);
12430
12431 if auto_scroll {
12432 self.request_autoscroll(Autoscroll::fit(), cx);
12433 }
12434
12435 cx.notify();
12436 self.scrollbar_marker_state.dirty = true;
12437 self.active_indent_guides_state.dirty = true;
12438 }
12439
12440 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12441 self.display_map.read(cx).fold_placeholder.clone()
12442 }
12443
12444 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12445 self.buffer.update(cx, |buffer, cx| {
12446 buffer.set_all_diff_hunks_expanded(cx);
12447 });
12448 }
12449
12450 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12451 self.distinguish_unstaged_diff_hunks = true;
12452 }
12453
12454 pub fn expand_all_diff_hunks(
12455 &mut self,
12456 _: &ExpandAllHunkDiffs,
12457 _window: &mut Window,
12458 cx: &mut Context<Self>,
12459 ) {
12460 self.buffer.update(cx, |buffer, cx| {
12461 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12462 });
12463 }
12464
12465 pub fn toggle_selected_diff_hunks(
12466 &mut self,
12467 _: &ToggleSelectedDiffHunks,
12468 _window: &mut Window,
12469 cx: &mut Context<Self>,
12470 ) {
12471 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12472 self.toggle_diff_hunks_in_ranges(ranges, cx);
12473 }
12474
12475 fn diff_hunks_in_ranges<'a>(
12476 &'a self,
12477 ranges: &'a [Range<Anchor>],
12478 buffer: &'a MultiBufferSnapshot,
12479 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12480 ranges.iter().flat_map(move |range| {
12481 let end_excerpt_id = range.end.excerpt_id;
12482 let range = range.to_point(buffer);
12483 let mut peek_end = range.end;
12484 if range.end.row < buffer.max_row().0 {
12485 peek_end = Point::new(range.end.row + 1, 0);
12486 }
12487 buffer
12488 .diff_hunks_in_range(range.start..peek_end)
12489 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12490 })
12491 }
12492
12493 pub fn has_stageable_diff_hunks_in_ranges(
12494 &self,
12495 ranges: &[Range<Anchor>],
12496 snapshot: &MultiBufferSnapshot,
12497 ) -> bool {
12498 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12499 hunks.any(|hunk| {
12500 log::debug!("considering {hunk:?}");
12501 hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12502 })
12503 }
12504
12505 pub fn toggle_staged_selected_diff_hunks(
12506 &mut self,
12507 _: &ToggleStagedSelectedDiffHunks,
12508 _window: &mut Window,
12509 cx: &mut Context<Self>,
12510 ) {
12511 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12512 self.stage_or_unstage_diff_hunks(&ranges, cx);
12513 }
12514
12515 pub fn stage_or_unstage_diff_hunks(
12516 &mut self,
12517 ranges: &[Range<Anchor>],
12518 cx: &mut Context<Self>,
12519 ) {
12520 let Some(project) = &self.project else {
12521 return;
12522 };
12523 let snapshot = self.buffer.read(cx).snapshot(cx);
12524 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12525
12526 let chunk_by = self
12527 .diff_hunks_in_ranges(&ranges, &snapshot)
12528 .chunk_by(|hunk| hunk.buffer_id);
12529 for (buffer_id, hunks) in &chunk_by {
12530 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12531 log::debug!("no buffer for id");
12532 continue;
12533 };
12534 let buffer = buffer.read(cx).snapshot();
12535 let Some((repo, path)) = project
12536 .read(cx)
12537 .repository_and_path_for_buffer_id(buffer_id, cx)
12538 else {
12539 log::debug!("no git repo for buffer id");
12540 continue;
12541 };
12542 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12543 log::debug!("no diff for buffer id");
12544 continue;
12545 };
12546 let Some(secondary_diff) = diff.secondary_diff() else {
12547 log::debug!("no secondary diff for buffer id");
12548 continue;
12549 };
12550
12551 let edits = diff.secondary_edits_for_stage_or_unstage(
12552 stage,
12553 hunks.map(|hunk| {
12554 (
12555 hunk.diff_base_byte_range.clone(),
12556 hunk.secondary_diff_base_byte_range.clone(),
12557 hunk.buffer_range.clone(),
12558 )
12559 }),
12560 &buffer,
12561 );
12562
12563 let index_base = secondary_diff.base_text().map_or_else(
12564 || Rope::from(""),
12565 |snapshot| snapshot.text.as_rope().clone(),
12566 );
12567 let index_buffer = cx.new(|cx| {
12568 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12569 });
12570 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12571 index_buffer.edit(edits, None, cx);
12572 index_buffer.snapshot().as_rope().to_string()
12573 });
12574 let new_index_text = if new_index_text.is_empty()
12575 && (diff.is_single_insertion
12576 || buffer
12577 .file()
12578 .map_or(false, |file| file.disk_state() == DiskState::New))
12579 {
12580 log::debug!("removing from index");
12581 None
12582 } else {
12583 Some(new_index_text)
12584 };
12585
12586 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12587 }
12588 }
12589
12590 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12591 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12592 self.buffer
12593 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12594 }
12595
12596 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12597 self.buffer.update(cx, |buffer, cx| {
12598 let ranges = vec![Anchor::min()..Anchor::max()];
12599 if !buffer.all_diff_hunks_expanded()
12600 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12601 {
12602 buffer.collapse_diff_hunks(ranges, cx);
12603 true
12604 } else {
12605 false
12606 }
12607 })
12608 }
12609
12610 fn toggle_diff_hunks_in_ranges(
12611 &mut self,
12612 ranges: Vec<Range<Anchor>>,
12613 cx: &mut Context<'_, Editor>,
12614 ) {
12615 self.buffer.update(cx, |buffer, cx| {
12616 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12617 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12618 })
12619 }
12620
12621 fn toggle_diff_hunks_in_ranges_narrow(
12622 &mut self,
12623 ranges: Vec<Range<Anchor>>,
12624 cx: &mut Context<'_, Editor>,
12625 ) {
12626 self.buffer.update(cx, |buffer, cx| {
12627 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12628 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12629 })
12630 }
12631
12632 pub(crate) fn apply_all_diff_hunks(
12633 &mut self,
12634 _: &ApplyAllDiffHunks,
12635 window: &mut Window,
12636 cx: &mut Context<Self>,
12637 ) {
12638 let buffers = self.buffer.read(cx).all_buffers();
12639 for branch_buffer in buffers {
12640 branch_buffer.update(cx, |branch_buffer, cx| {
12641 branch_buffer.merge_into_base(Vec::new(), cx);
12642 });
12643 }
12644
12645 if let Some(project) = self.project.clone() {
12646 self.save(true, project, window, cx).detach_and_log_err(cx);
12647 }
12648 }
12649
12650 pub(crate) fn apply_selected_diff_hunks(
12651 &mut self,
12652 _: &ApplyDiffHunk,
12653 window: &mut Window,
12654 cx: &mut Context<Self>,
12655 ) {
12656 let snapshot = self.snapshot(window, cx);
12657 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12658 let mut ranges_by_buffer = HashMap::default();
12659 self.transact(window, cx, |editor, _window, cx| {
12660 for hunk in hunks {
12661 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12662 ranges_by_buffer
12663 .entry(buffer.clone())
12664 .or_insert_with(Vec::new)
12665 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12666 }
12667 }
12668
12669 for (buffer, ranges) in ranges_by_buffer {
12670 buffer.update(cx, |buffer, cx| {
12671 buffer.merge_into_base(ranges, cx);
12672 });
12673 }
12674 });
12675
12676 if let Some(project) = self.project.clone() {
12677 self.save(true, project, window, cx).detach_and_log_err(cx);
12678 }
12679 }
12680
12681 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12682 if hovered != self.gutter_hovered {
12683 self.gutter_hovered = hovered;
12684 cx.notify();
12685 }
12686 }
12687
12688 pub fn insert_blocks(
12689 &mut self,
12690 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12691 autoscroll: Option<Autoscroll>,
12692 cx: &mut Context<Self>,
12693 ) -> Vec<CustomBlockId> {
12694 let blocks = self
12695 .display_map
12696 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12697 if let Some(autoscroll) = autoscroll {
12698 self.request_autoscroll(autoscroll, cx);
12699 }
12700 cx.notify();
12701 blocks
12702 }
12703
12704 pub fn resize_blocks(
12705 &mut self,
12706 heights: HashMap<CustomBlockId, u32>,
12707 autoscroll: Option<Autoscroll>,
12708 cx: &mut Context<Self>,
12709 ) {
12710 self.display_map
12711 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12712 if let Some(autoscroll) = autoscroll {
12713 self.request_autoscroll(autoscroll, cx);
12714 }
12715 cx.notify();
12716 }
12717
12718 pub fn replace_blocks(
12719 &mut self,
12720 renderers: HashMap<CustomBlockId, RenderBlock>,
12721 autoscroll: Option<Autoscroll>,
12722 cx: &mut Context<Self>,
12723 ) {
12724 self.display_map
12725 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12726 if let Some(autoscroll) = autoscroll {
12727 self.request_autoscroll(autoscroll, cx);
12728 }
12729 cx.notify();
12730 }
12731
12732 pub fn remove_blocks(
12733 &mut self,
12734 block_ids: HashSet<CustomBlockId>,
12735 autoscroll: Option<Autoscroll>,
12736 cx: &mut Context<Self>,
12737 ) {
12738 self.display_map.update(cx, |display_map, cx| {
12739 display_map.remove_blocks(block_ids, cx)
12740 });
12741 if let Some(autoscroll) = autoscroll {
12742 self.request_autoscroll(autoscroll, cx);
12743 }
12744 cx.notify();
12745 }
12746
12747 pub fn row_for_block(
12748 &self,
12749 block_id: CustomBlockId,
12750 cx: &mut Context<Self>,
12751 ) -> Option<DisplayRow> {
12752 self.display_map
12753 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12754 }
12755
12756 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12757 self.focused_block = Some(focused_block);
12758 }
12759
12760 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12761 self.focused_block.take()
12762 }
12763
12764 pub fn insert_creases(
12765 &mut self,
12766 creases: impl IntoIterator<Item = Crease<Anchor>>,
12767 cx: &mut Context<Self>,
12768 ) -> Vec<CreaseId> {
12769 self.display_map
12770 .update(cx, |map, cx| map.insert_creases(creases, cx))
12771 }
12772
12773 pub fn remove_creases(
12774 &mut self,
12775 ids: impl IntoIterator<Item = CreaseId>,
12776 cx: &mut Context<Self>,
12777 ) {
12778 self.display_map
12779 .update(cx, |map, cx| map.remove_creases(ids, cx));
12780 }
12781
12782 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12783 self.display_map
12784 .update(cx, |map, cx| map.snapshot(cx))
12785 .longest_row()
12786 }
12787
12788 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12789 self.display_map
12790 .update(cx, |map, cx| map.snapshot(cx))
12791 .max_point()
12792 }
12793
12794 pub fn text(&self, cx: &App) -> String {
12795 self.buffer.read(cx).read(cx).text()
12796 }
12797
12798 pub fn is_empty(&self, cx: &App) -> bool {
12799 self.buffer.read(cx).read(cx).is_empty()
12800 }
12801
12802 pub fn text_option(&self, cx: &App) -> Option<String> {
12803 let text = self.text(cx);
12804 let text = text.trim();
12805
12806 if text.is_empty() {
12807 return None;
12808 }
12809
12810 Some(text.to_string())
12811 }
12812
12813 pub fn set_text(
12814 &mut self,
12815 text: impl Into<Arc<str>>,
12816 window: &mut Window,
12817 cx: &mut Context<Self>,
12818 ) {
12819 self.transact(window, cx, |this, _, cx| {
12820 this.buffer
12821 .read(cx)
12822 .as_singleton()
12823 .expect("you can only call set_text on editors for singleton buffers")
12824 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12825 });
12826 }
12827
12828 pub fn display_text(&self, cx: &mut App) -> String {
12829 self.display_map
12830 .update(cx, |map, cx| map.snapshot(cx))
12831 .text()
12832 }
12833
12834 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12835 let mut wrap_guides = smallvec::smallvec![];
12836
12837 if self.show_wrap_guides == Some(false) {
12838 return wrap_guides;
12839 }
12840
12841 let settings = self.buffer.read(cx).settings_at(0, cx);
12842 if settings.show_wrap_guides {
12843 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12844 wrap_guides.push((soft_wrap as usize, true));
12845 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12846 wrap_guides.push((soft_wrap as usize, true));
12847 }
12848 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12849 }
12850
12851 wrap_guides
12852 }
12853
12854 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12855 let settings = self.buffer.read(cx).settings_at(0, cx);
12856 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12857 match mode {
12858 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12859 SoftWrap::None
12860 }
12861 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12862 language_settings::SoftWrap::PreferredLineLength => {
12863 SoftWrap::Column(settings.preferred_line_length)
12864 }
12865 language_settings::SoftWrap::Bounded => {
12866 SoftWrap::Bounded(settings.preferred_line_length)
12867 }
12868 }
12869 }
12870
12871 pub fn set_soft_wrap_mode(
12872 &mut self,
12873 mode: language_settings::SoftWrap,
12874
12875 cx: &mut Context<Self>,
12876 ) {
12877 self.soft_wrap_mode_override = Some(mode);
12878 cx.notify();
12879 }
12880
12881 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12882 self.text_style_refinement = Some(style);
12883 }
12884
12885 /// called by the Element so we know what style we were most recently rendered with.
12886 pub(crate) fn set_style(
12887 &mut self,
12888 style: EditorStyle,
12889 window: &mut Window,
12890 cx: &mut Context<Self>,
12891 ) {
12892 let rem_size = window.rem_size();
12893 self.display_map.update(cx, |map, cx| {
12894 map.set_font(
12895 style.text.font(),
12896 style.text.font_size.to_pixels(rem_size),
12897 cx,
12898 )
12899 });
12900 self.style = Some(style);
12901 }
12902
12903 pub fn style(&self) -> Option<&EditorStyle> {
12904 self.style.as_ref()
12905 }
12906
12907 // Called by the element. This method is not designed to be called outside of the editor
12908 // element's layout code because it does not notify when rewrapping is computed synchronously.
12909 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12910 self.display_map
12911 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12912 }
12913
12914 pub fn set_soft_wrap(&mut self) {
12915 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12916 }
12917
12918 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12919 if self.soft_wrap_mode_override.is_some() {
12920 self.soft_wrap_mode_override.take();
12921 } else {
12922 let soft_wrap = match self.soft_wrap_mode(cx) {
12923 SoftWrap::GitDiff => return,
12924 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12925 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12926 language_settings::SoftWrap::None
12927 }
12928 };
12929 self.soft_wrap_mode_override = Some(soft_wrap);
12930 }
12931 cx.notify();
12932 }
12933
12934 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12935 let Some(workspace) = self.workspace() else {
12936 return;
12937 };
12938 let fs = workspace.read(cx).app_state().fs.clone();
12939 let current_show = TabBarSettings::get_global(cx).show;
12940 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12941 setting.show = Some(!current_show);
12942 });
12943 }
12944
12945 pub fn toggle_indent_guides(
12946 &mut self,
12947 _: &ToggleIndentGuides,
12948 _: &mut Window,
12949 cx: &mut Context<Self>,
12950 ) {
12951 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12952 self.buffer
12953 .read(cx)
12954 .settings_at(0, cx)
12955 .indent_guides
12956 .enabled
12957 });
12958 self.show_indent_guides = Some(!currently_enabled);
12959 cx.notify();
12960 }
12961
12962 fn should_show_indent_guides(&self) -> Option<bool> {
12963 self.show_indent_guides
12964 }
12965
12966 pub fn toggle_line_numbers(
12967 &mut self,
12968 _: &ToggleLineNumbers,
12969 _: &mut Window,
12970 cx: &mut Context<Self>,
12971 ) {
12972 let mut editor_settings = EditorSettings::get_global(cx).clone();
12973 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12974 EditorSettings::override_global(editor_settings, cx);
12975 }
12976
12977 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12978 self.use_relative_line_numbers
12979 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12980 }
12981
12982 pub fn toggle_relative_line_numbers(
12983 &mut self,
12984 _: &ToggleRelativeLineNumbers,
12985 _: &mut Window,
12986 cx: &mut Context<Self>,
12987 ) {
12988 let is_relative = self.should_use_relative_line_numbers(cx);
12989 self.set_relative_line_number(Some(!is_relative), cx)
12990 }
12991
12992 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12993 self.use_relative_line_numbers = is_relative;
12994 cx.notify();
12995 }
12996
12997 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12998 self.show_gutter = show_gutter;
12999 cx.notify();
13000 }
13001
13002 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13003 self.show_scrollbars = show_scrollbars;
13004 cx.notify();
13005 }
13006
13007 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13008 self.show_line_numbers = Some(show_line_numbers);
13009 cx.notify();
13010 }
13011
13012 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13013 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13014 cx.notify();
13015 }
13016
13017 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13018 self.show_code_actions = Some(show_code_actions);
13019 cx.notify();
13020 }
13021
13022 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13023 self.show_runnables = Some(show_runnables);
13024 cx.notify();
13025 }
13026
13027 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13028 if self.display_map.read(cx).masked != masked {
13029 self.display_map.update(cx, |map, _| map.masked = masked);
13030 }
13031 cx.notify()
13032 }
13033
13034 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13035 self.show_wrap_guides = Some(show_wrap_guides);
13036 cx.notify();
13037 }
13038
13039 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13040 self.show_indent_guides = Some(show_indent_guides);
13041 cx.notify();
13042 }
13043
13044 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13045 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13046 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13047 if let Some(dir) = file.abs_path(cx).parent() {
13048 return Some(dir.to_owned());
13049 }
13050 }
13051
13052 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13053 return Some(project_path.path.to_path_buf());
13054 }
13055 }
13056
13057 None
13058 }
13059
13060 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13061 self.active_excerpt(cx)?
13062 .1
13063 .read(cx)
13064 .file()
13065 .and_then(|f| f.as_local())
13066 }
13067
13068 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13069 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13070 let buffer = buffer.read(cx);
13071 if let Some(project_path) = buffer.project_path(cx) {
13072 let project = self.project.as_ref()?.read(cx);
13073 project.absolute_path(&project_path, cx)
13074 } else {
13075 buffer
13076 .file()
13077 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13078 }
13079 })
13080 }
13081
13082 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13083 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13084 let project_path = buffer.read(cx).project_path(cx)?;
13085 let project = self.project.as_ref()?.read(cx);
13086 let entry = project.entry_for_path(&project_path, cx)?;
13087 let path = entry.path.to_path_buf();
13088 Some(path)
13089 })
13090 }
13091
13092 pub fn reveal_in_finder(
13093 &mut self,
13094 _: &RevealInFileManager,
13095 _window: &mut Window,
13096 cx: &mut Context<Self>,
13097 ) {
13098 if let Some(target) = self.target_file(cx) {
13099 cx.reveal_path(&target.abs_path(cx));
13100 }
13101 }
13102
13103 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13104 if let Some(path) = self.target_file_abs_path(cx) {
13105 if let Some(path) = path.to_str() {
13106 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13107 }
13108 }
13109 }
13110
13111 pub fn copy_relative_path(
13112 &mut self,
13113 _: &CopyRelativePath,
13114 _window: &mut Window,
13115 cx: &mut Context<Self>,
13116 ) {
13117 if let Some(path) = self.target_file_path(cx) {
13118 if let Some(path) = path.to_str() {
13119 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13120 }
13121 }
13122 }
13123
13124 pub fn copy_file_name_without_extension(
13125 &mut self,
13126 _: &CopyFileNameWithoutExtension,
13127 _: &mut Window,
13128 cx: &mut Context<Self>,
13129 ) {
13130 if let Some(file) = self.target_file(cx) {
13131 if let Some(file_stem) = file.path().file_stem() {
13132 if let Some(name) = file_stem.to_str() {
13133 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13134 }
13135 }
13136 }
13137 }
13138
13139 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13140 if let Some(file) = self.target_file(cx) {
13141 if let Some(file_name) = file.path().file_name() {
13142 if let Some(name) = file_name.to_str() {
13143 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13144 }
13145 }
13146 }
13147 }
13148
13149 pub fn toggle_git_blame(
13150 &mut self,
13151 _: &ToggleGitBlame,
13152 window: &mut Window,
13153 cx: &mut Context<Self>,
13154 ) {
13155 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13156
13157 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13158 self.start_git_blame(true, window, cx);
13159 }
13160
13161 cx.notify();
13162 }
13163
13164 pub fn toggle_git_blame_inline(
13165 &mut self,
13166 _: &ToggleGitBlameInline,
13167 window: &mut Window,
13168 cx: &mut Context<Self>,
13169 ) {
13170 self.toggle_git_blame_inline_internal(true, window, cx);
13171 cx.notify();
13172 }
13173
13174 pub fn git_blame_inline_enabled(&self) -> bool {
13175 self.git_blame_inline_enabled
13176 }
13177
13178 pub fn toggle_selection_menu(
13179 &mut self,
13180 _: &ToggleSelectionMenu,
13181 _: &mut Window,
13182 cx: &mut Context<Self>,
13183 ) {
13184 self.show_selection_menu = self
13185 .show_selection_menu
13186 .map(|show_selections_menu| !show_selections_menu)
13187 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13188
13189 cx.notify();
13190 }
13191
13192 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13193 self.show_selection_menu
13194 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13195 }
13196
13197 fn start_git_blame(
13198 &mut self,
13199 user_triggered: bool,
13200 window: &mut Window,
13201 cx: &mut Context<Self>,
13202 ) {
13203 if let Some(project) = self.project.as_ref() {
13204 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13205 return;
13206 };
13207
13208 if buffer.read(cx).file().is_none() {
13209 return;
13210 }
13211
13212 let focused = self.focus_handle(cx).contains_focused(window, cx);
13213
13214 let project = project.clone();
13215 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13216 self.blame_subscription =
13217 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13218 self.blame = Some(blame);
13219 }
13220 }
13221
13222 fn toggle_git_blame_inline_internal(
13223 &mut self,
13224 user_triggered: bool,
13225 window: &mut Window,
13226 cx: &mut Context<Self>,
13227 ) {
13228 if self.git_blame_inline_enabled {
13229 self.git_blame_inline_enabled = false;
13230 self.show_git_blame_inline = false;
13231 self.show_git_blame_inline_delay_task.take();
13232 } else {
13233 self.git_blame_inline_enabled = true;
13234 self.start_git_blame_inline(user_triggered, window, cx);
13235 }
13236
13237 cx.notify();
13238 }
13239
13240 fn start_git_blame_inline(
13241 &mut self,
13242 user_triggered: bool,
13243 window: &mut Window,
13244 cx: &mut Context<Self>,
13245 ) {
13246 self.start_git_blame(user_triggered, window, cx);
13247
13248 if ProjectSettings::get_global(cx)
13249 .git
13250 .inline_blame_delay()
13251 .is_some()
13252 {
13253 self.start_inline_blame_timer(window, cx);
13254 } else {
13255 self.show_git_blame_inline = true
13256 }
13257 }
13258
13259 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13260 self.blame.as_ref()
13261 }
13262
13263 pub fn show_git_blame_gutter(&self) -> bool {
13264 self.show_git_blame_gutter
13265 }
13266
13267 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13268 self.show_git_blame_gutter && self.has_blame_entries(cx)
13269 }
13270
13271 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13272 self.show_git_blame_inline
13273 && self.focus_handle.is_focused(window)
13274 && !self.newest_selection_head_on_empty_line(cx)
13275 && self.has_blame_entries(cx)
13276 }
13277
13278 fn has_blame_entries(&self, cx: &App) -> bool {
13279 self.blame()
13280 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13281 }
13282
13283 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13284 let cursor_anchor = self.selections.newest_anchor().head();
13285
13286 let snapshot = self.buffer.read(cx).snapshot(cx);
13287 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13288
13289 snapshot.line_len(buffer_row) == 0
13290 }
13291
13292 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13293 let buffer_and_selection = maybe!({
13294 let selection = self.selections.newest::<Point>(cx);
13295 let selection_range = selection.range();
13296
13297 let multi_buffer = self.buffer().read(cx);
13298 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13299 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13300
13301 let (buffer, range, _) = if selection.reversed {
13302 buffer_ranges.first()
13303 } else {
13304 buffer_ranges.last()
13305 }?;
13306
13307 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13308 ..text::ToPoint::to_point(&range.end, &buffer).row;
13309 Some((
13310 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13311 selection,
13312 ))
13313 });
13314
13315 let Some((buffer, selection)) = buffer_and_selection else {
13316 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13317 };
13318
13319 let Some(project) = self.project.as_ref() else {
13320 return Task::ready(Err(anyhow!("editor does not have project")));
13321 };
13322
13323 project.update(cx, |project, cx| {
13324 project.get_permalink_to_line(&buffer, selection, cx)
13325 })
13326 }
13327
13328 pub fn copy_permalink_to_line(
13329 &mut self,
13330 _: &CopyPermalinkToLine,
13331 window: &mut Window,
13332 cx: &mut Context<Self>,
13333 ) {
13334 let permalink_task = self.get_permalink_to_line(cx);
13335 let workspace = self.workspace();
13336
13337 cx.spawn_in(window, |_, mut cx| async move {
13338 match permalink_task.await {
13339 Ok(permalink) => {
13340 cx.update(|_, cx| {
13341 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13342 })
13343 .ok();
13344 }
13345 Err(err) => {
13346 let message = format!("Failed to copy permalink: {err}");
13347
13348 Err::<(), anyhow::Error>(err).log_err();
13349
13350 if let Some(workspace) = workspace {
13351 workspace
13352 .update_in(&mut cx, |workspace, _, cx| {
13353 struct CopyPermalinkToLine;
13354
13355 workspace.show_toast(
13356 Toast::new(
13357 NotificationId::unique::<CopyPermalinkToLine>(),
13358 message,
13359 ),
13360 cx,
13361 )
13362 })
13363 .ok();
13364 }
13365 }
13366 }
13367 })
13368 .detach();
13369 }
13370
13371 pub fn copy_file_location(
13372 &mut self,
13373 _: &CopyFileLocation,
13374 _: &mut Window,
13375 cx: &mut Context<Self>,
13376 ) {
13377 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13378 if let Some(file) = self.target_file(cx) {
13379 if let Some(path) = file.path().to_str() {
13380 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13381 }
13382 }
13383 }
13384
13385 pub fn open_permalink_to_line(
13386 &mut self,
13387 _: &OpenPermalinkToLine,
13388 window: &mut Window,
13389 cx: &mut Context<Self>,
13390 ) {
13391 let permalink_task = self.get_permalink_to_line(cx);
13392 let workspace = self.workspace();
13393
13394 cx.spawn_in(window, |_, mut cx| async move {
13395 match permalink_task.await {
13396 Ok(permalink) => {
13397 cx.update(|_, cx| {
13398 cx.open_url(permalink.as_ref());
13399 })
13400 .ok();
13401 }
13402 Err(err) => {
13403 let message = format!("Failed to open permalink: {err}");
13404
13405 Err::<(), anyhow::Error>(err).log_err();
13406
13407 if let Some(workspace) = workspace {
13408 workspace
13409 .update(&mut cx, |workspace, cx| {
13410 struct OpenPermalinkToLine;
13411
13412 workspace.show_toast(
13413 Toast::new(
13414 NotificationId::unique::<OpenPermalinkToLine>(),
13415 message,
13416 ),
13417 cx,
13418 )
13419 })
13420 .ok();
13421 }
13422 }
13423 }
13424 })
13425 .detach();
13426 }
13427
13428 pub fn insert_uuid_v4(
13429 &mut self,
13430 _: &InsertUuidV4,
13431 window: &mut Window,
13432 cx: &mut Context<Self>,
13433 ) {
13434 self.insert_uuid(UuidVersion::V4, window, cx);
13435 }
13436
13437 pub fn insert_uuid_v7(
13438 &mut self,
13439 _: &InsertUuidV7,
13440 window: &mut Window,
13441 cx: &mut Context<Self>,
13442 ) {
13443 self.insert_uuid(UuidVersion::V7, window, cx);
13444 }
13445
13446 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13447 self.transact(window, cx, |this, window, cx| {
13448 let edits = this
13449 .selections
13450 .all::<Point>(cx)
13451 .into_iter()
13452 .map(|selection| {
13453 let uuid = match version {
13454 UuidVersion::V4 => uuid::Uuid::new_v4(),
13455 UuidVersion::V7 => uuid::Uuid::now_v7(),
13456 };
13457
13458 (selection.range(), uuid.to_string())
13459 });
13460 this.edit(edits, cx);
13461 this.refresh_inline_completion(true, false, window, cx);
13462 });
13463 }
13464
13465 pub fn open_selections_in_multibuffer(
13466 &mut self,
13467 _: &OpenSelectionsInMultibuffer,
13468 window: &mut Window,
13469 cx: &mut Context<Self>,
13470 ) {
13471 let multibuffer = self.buffer.read(cx);
13472
13473 let Some(buffer) = multibuffer.as_singleton() else {
13474 return;
13475 };
13476
13477 let Some(workspace) = self.workspace() else {
13478 return;
13479 };
13480
13481 let locations = self
13482 .selections
13483 .disjoint_anchors()
13484 .iter()
13485 .map(|range| Location {
13486 buffer: buffer.clone(),
13487 range: range.start.text_anchor..range.end.text_anchor,
13488 })
13489 .collect::<Vec<_>>();
13490
13491 let title = multibuffer.title(cx).to_string();
13492
13493 cx.spawn_in(window, |_, mut cx| async move {
13494 workspace.update_in(&mut cx, |workspace, window, cx| {
13495 Self::open_locations_in_multibuffer(
13496 workspace,
13497 locations,
13498 format!("Selections for '{title}'"),
13499 false,
13500 MultibufferSelectionMode::All,
13501 window,
13502 cx,
13503 );
13504 })
13505 })
13506 .detach();
13507 }
13508
13509 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13510 /// last highlight added will be used.
13511 ///
13512 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13513 pub fn highlight_rows<T: 'static>(
13514 &mut self,
13515 range: Range<Anchor>,
13516 color: Hsla,
13517 should_autoscroll: bool,
13518 cx: &mut Context<Self>,
13519 ) {
13520 let snapshot = self.buffer().read(cx).snapshot(cx);
13521 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13522 let ix = row_highlights.binary_search_by(|highlight| {
13523 Ordering::Equal
13524 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13525 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13526 });
13527
13528 if let Err(mut ix) = ix {
13529 let index = post_inc(&mut self.highlight_order);
13530
13531 // If this range intersects with the preceding highlight, then merge it with
13532 // the preceding highlight. Otherwise insert a new highlight.
13533 let mut merged = false;
13534 if ix > 0 {
13535 let prev_highlight = &mut row_highlights[ix - 1];
13536 if prev_highlight
13537 .range
13538 .end
13539 .cmp(&range.start, &snapshot)
13540 .is_ge()
13541 {
13542 ix -= 1;
13543 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13544 prev_highlight.range.end = range.end;
13545 }
13546 merged = true;
13547 prev_highlight.index = index;
13548 prev_highlight.color = color;
13549 prev_highlight.should_autoscroll = should_autoscroll;
13550 }
13551 }
13552
13553 if !merged {
13554 row_highlights.insert(
13555 ix,
13556 RowHighlight {
13557 range: range.clone(),
13558 index,
13559 color,
13560 should_autoscroll,
13561 },
13562 );
13563 }
13564
13565 // If any of the following highlights intersect with this one, merge them.
13566 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13567 let highlight = &row_highlights[ix];
13568 if next_highlight
13569 .range
13570 .start
13571 .cmp(&highlight.range.end, &snapshot)
13572 .is_le()
13573 {
13574 if next_highlight
13575 .range
13576 .end
13577 .cmp(&highlight.range.end, &snapshot)
13578 .is_gt()
13579 {
13580 row_highlights[ix].range.end = next_highlight.range.end;
13581 }
13582 row_highlights.remove(ix + 1);
13583 } else {
13584 break;
13585 }
13586 }
13587 }
13588 }
13589
13590 /// Remove any highlighted row ranges of the given type that intersect the
13591 /// given ranges.
13592 pub fn remove_highlighted_rows<T: 'static>(
13593 &mut self,
13594 ranges_to_remove: Vec<Range<Anchor>>,
13595 cx: &mut Context<Self>,
13596 ) {
13597 let snapshot = self.buffer().read(cx).snapshot(cx);
13598 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13599 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13600 row_highlights.retain(|highlight| {
13601 while let Some(range_to_remove) = ranges_to_remove.peek() {
13602 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13603 Ordering::Less | Ordering::Equal => {
13604 ranges_to_remove.next();
13605 }
13606 Ordering::Greater => {
13607 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13608 Ordering::Less | Ordering::Equal => {
13609 return false;
13610 }
13611 Ordering::Greater => break,
13612 }
13613 }
13614 }
13615 }
13616
13617 true
13618 })
13619 }
13620
13621 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13622 pub fn clear_row_highlights<T: 'static>(&mut self) {
13623 self.highlighted_rows.remove(&TypeId::of::<T>());
13624 }
13625
13626 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13627 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13628 self.highlighted_rows
13629 .get(&TypeId::of::<T>())
13630 .map_or(&[] as &[_], |vec| vec.as_slice())
13631 .iter()
13632 .map(|highlight| (highlight.range.clone(), highlight.color))
13633 }
13634
13635 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13636 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13637 /// Allows to ignore certain kinds of highlights.
13638 pub fn highlighted_display_rows(
13639 &self,
13640 window: &mut Window,
13641 cx: &mut App,
13642 ) -> BTreeMap<DisplayRow, Background> {
13643 let snapshot = self.snapshot(window, cx);
13644 let mut used_highlight_orders = HashMap::default();
13645 self.highlighted_rows
13646 .iter()
13647 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13648 .fold(
13649 BTreeMap::<DisplayRow, Background>::new(),
13650 |mut unique_rows, highlight| {
13651 let start = highlight.range.start.to_display_point(&snapshot);
13652 let end = highlight.range.end.to_display_point(&snapshot);
13653 let start_row = start.row().0;
13654 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13655 && end.column() == 0
13656 {
13657 end.row().0.saturating_sub(1)
13658 } else {
13659 end.row().0
13660 };
13661 for row in start_row..=end_row {
13662 let used_index =
13663 used_highlight_orders.entry(row).or_insert(highlight.index);
13664 if highlight.index >= *used_index {
13665 *used_index = highlight.index;
13666 unique_rows.insert(DisplayRow(row), highlight.color.into());
13667 }
13668 }
13669 unique_rows
13670 },
13671 )
13672 }
13673
13674 pub fn highlighted_display_row_for_autoscroll(
13675 &self,
13676 snapshot: &DisplaySnapshot,
13677 ) -> Option<DisplayRow> {
13678 self.highlighted_rows
13679 .values()
13680 .flat_map(|highlighted_rows| highlighted_rows.iter())
13681 .filter_map(|highlight| {
13682 if highlight.should_autoscroll {
13683 Some(highlight.range.start.to_display_point(snapshot).row())
13684 } else {
13685 None
13686 }
13687 })
13688 .min()
13689 }
13690
13691 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13692 self.highlight_background::<SearchWithinRange>(
13693 ranges,
13694 |colors| colors.editor_document_highlight_read_background,
13695 cx,
13696 )
13697 }
13698
13699 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13700 self.breadcrumb_header = Some(new_header);
13701 }
13702
13703 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13704 self.clear_background_highlights::<SearchWithinRange>(cx);
13705 }
13706
13707 pub fn highlight_background<T: 'static>(
13708 &mut self,
13709 ranges: &[Range<Anchor>],
13710 color_fetcher: fn(&ThemeColors) -> Hsla,
13711 cx: &mut Context<Self>,
13712 ) {
13713 self.background_highlights
13714 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13715 self.scrollbar_marker_state.dirty = true;
13716 cx.notify();
13717 }
13718
13719 pub fn clear_background_highlights<T: 'static>(
13720 &mut self,
13721 cx: &mut Context<Self>,
13722 ) -> Option<BackgroundHighlight> {
13723 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13724 if !text_highlights.1.is_empty() {
13725 self.scrollbar_marker_state.dirty = true;
13726 cx.notify();
13727 }
13728 Some(text_highlights)
13729 }
13730
13731 pub fn highlight_gutter<T: 'static>(
13732 &mut self,
13733 ranges: &[Range<Anchor>],
13734 color_fetcher: fn(&App) -> Hsla,
13735 cx: &mut Context<Self>,
13736 ) {
13737 self.gutter_highlights
13738 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13739 cx.notify();
13740 }
13741
13742 pub fn clear_gutter_highlights<T: 'static>(
13743 &mut self,
13744 cx: &mut Context<Self>,
13745 ) -> Option<GutterHighlight> {
13746 cx.notify();
13747 self.gutter_highlights.remove(&TypeId::of::<T>())
13748 }
13749
13750 #[cfg(feature = "test-support")]
13751 pub fn all_text_background_highlights(
13752 &self,
13753 window: &mut Window,
13754 cx: &mut Context<Self>,
13755 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13756 let snapshot = self.snapshot(window, cx);
13757 let buffer = &snapshot.buffer_snapshot;
13758 let start = buffer.anchor_before(0);
13759 let end = buffer.anchor_after(buffer.len());
13760 let theme = cx.theme().colors();
13761 self.background_highlights_in_range(start..end, &snapshot, theme)
13762 }
13763
13764 #[cfg(feature = "test-support")]
13765 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13766 let snapshot = self.buffer().read(cx).snapshot(cx);
13767
13768 let highlights = self
13769 .background_highlights
13770 .get(&TypeId::of::<items::BufferSearchHighlights>());
13771
13772 if let Some((_color, ranges)) = highlights {
13773 ranges
13774 .iter()
13775 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13776 .collect_vec()
13777 } else {
13778 vec![]
13779 }
13780 }
13781
13782 fn document_highlights_for_position<'a>(
13783 &'a self,
13784 position: Anchor,
13785 buffer: &'a MultiBufferSnapshot,
13786 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13787 let read_highlights = self
13788 .background_highlights
13789 .get(&TypeId::of::<DocumentHighlightRead>())
13790 .map(|h| &h.1);
13791 let write_highlights = self
13792 .background_highlights
13793 .get(&TypeId::of::<DocumentHighlightWrite>())
13794 .map(|h| &h.1);
13795 let left_position = position.bias_left(buffer);
13796 let right_position = position.bias_right(buffer);
13797 read_highlights
13798 .into_iter()
13799 .chain(write_highlights)
13800 .flat_map(move |ranges| {
13801 let start_ix = match ranges.binary_search_by(|probe| {
13802 let cmp = probe.end.cmp(&left_position, buffer);
13803 if cmp.is_ge() {
13804 Ordering::Greater
13805 } else {
13806 Ordering::Less
13807 }
13808 }) {
13809 Ok(i) | Err(i) => i,
13810 };
13811
13812 ranges[start_ix..]
13813 .iter()
13814 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13815 })
13816 }
13817
13818 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13819 self.background_highlights
13820 .get(&TypeId::of::<T>())
13821 .map_or(false, |(_, highlights)| !highlights.is_empty())
13822 }
13823
13824 pub fn background_highlights_in_range(
13825 &self,
13826 search_range: Range<Anchor>,
13827 display_snapshot: &DisplaySnapshot,
13828 theme: &ThemeColors,
13829 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13830 let mut results = Vec::new();
13831 for (color_fetcher, ranges) in self.background_highlights.values() {
13832 let color = color_fetcher(theme);
13833 let start_ix = match ranges.binary_search_by(|probe| {
13834 let cmp = probe
13835 .end
13836 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13837 if cmp.is_gt() {
13838 Ordering::Greater
13839 } else {
13840 Ordering::Less
13841 }
13842 }) {
13843 Ok(i) | Err(i) => i,
13844 };
13845 for range in &ranges[start_ix..] {
13846 if range
13847 .start
13848 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13849 .is_ge()
13850 {
13851 break;
13852 }
13853
13854 let start = range.start.to_display_point(display_snapshot);
13855 let end = range.end.to_display_point(display_snapshot);
13856 results.push((start..end, color))
13857 }
13858 }
13859 results
13860 }
13861
13862 pub fn background_highlight_row_ranges<T: 'static>(
13863 &self,
13864 search_range: Range<Anchor>,
13865 display_snapshot: &DisplaySnapshot,
13866 count: usize,
13867 ) -> Vec<RangeInclusive<DisplayPoint>> {
13868 let mut results = Vec::new();
13869 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13870 return vec![];
13871 };
13872
13873 let start_ix = match ranges.binary_search_by(|probe| {
13874 let cmp = probe
13875 .end
13876 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13877 if cmp.is_gt() {
13878 Ordering::Greater
13879 } else {
13880 Ordering::Less
13881 }
13882 }) {
13883 Ok(i) | Err(i) => i,
13884 };
13885 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13886 if let (Some(start_display), Some(end_display)) = (start, end) {
13887 results.push(
13888 start_display.to_display_point(display_snapshot)
13889 ..=end_display.to_display_point(display_snapshot),
13890 );
13891 }
13892 };
13893 let mut start_row: Option<Point> = None;
13894 let mut end_row: Option<Point> = None;
13895 if ranges.len() > count {
13896 return Vec::new();
13897 }
13898 for range in &ranges[start_ix..] {
13899 if range
13900 .start
13901 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13902 .is_ge()
13903 {
13904 break;
13905 }
13906 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13907 if let Some(current_row) = &end_row {
13908 if end.row == current_row.row {
13909 continue;
13910 }
13911 }
13912 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13913 if start_row.is_none() {
13914 assert_eq!(end_row, None);
13915 start_row = Some(start);
13916 end_row = Some(end);
13917 continue;
13918 }
13919 if let Some(current_end) = end_row.as_mut() {
13920 if start.row > current_end.row + 1 {
13921 push_region(start_row, end_row);
13922 start_row = Some(start);
13923 end_row = Some(end);
13924 } else {
13925 // Merge two hunks.
13926 *current_end = end;
13927 }
13928 } else {
13929 unreachable!();
13930 }
13931 }
13932 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13933 push_region(start_row, end_row);
13934 results
13935 }
13936
13937 pub fn gutter_highlights_in_range(
13938 &self,
13939 search_range: Range<Anchor>,
13940 display_snapshot: &DisplaySnapshot,
13941 cx: &App,
13942 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13943 let mut results = Vec::new();
13944 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13945 let color = color_fetcher(cx);
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 /// Get the text ranges corresponding to the redaction query
13976 pub fn redacted_ranges(
13977 &self,
13978 search_range: Range<Anchor>,
13979 display_snapshot: &DisplaySnapshot,
13980 cx: &App,
13981 ) -> Vec<Range<DisplayPoint>> {
13982 display_snapshot
13983 .buffer_snapshot
13984 .redacted_ranges(search_range, |file| {
13985 if let Some(file) = file {
13986 file.is_private()
13987 && EditorSettings::get(
13988 Some(SettingsLocation {
13989 worktree_id: file.worktree_id(cx),
13990 path: file.path().as_ref(),
13991 }),
13992 cx,
13993 )
13994 .redact_private_values
13995 } else {
13996 false
13997 }
13998 })
13999 .map(|range| {
14000 range.start.to_display_point(display_snapshot)
14001 ..range.end.to_display_point(display_snapshot)
14002 })
14003 .collect()
14004 }
14005
14006 pub fn highlight_text<T: 'static>(
14007 &mut self,
14008 ranges: Vec<Range<Anchor>>,
14009 style: HighlightStyle,
14010 cx: &mut Context<Self>,
14011 ) {
14012 self.display_map.update(cx, |map, _| {
14013 map.highlight_text(TypeId::of::<T>(), ranges, style)
14014 });
14015 cx.notify();
14016 }
14017
14018 pub(crate) fn highlight_inlays<T: 'static>(
14019 &mut self,
14020 highlights: Vec<InlayHighlight>,
14021 style: HighlightStyle,
14022 cx: &mut Context<Self>,
14023 ) {
14024 self.display_map.update(cx, |map, _| {
14025 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14026 });
14027 cx.notify();
14028 }
14029
14030 pub fn text_highlights<'a, T: 'static>(
14031 &'a self,
14032 cx: &'a App,
14033 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14034 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14035 }
14036
14037 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14038 let cleared = self
14039 .display_map
14040 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14041 if cleared {
14042 cx.notify();
14043 }
14044 }
14045
14046 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14047 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14048 && self.focus_handle.is_focused(window)
14049 }
14050
14051 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14052 self.show_cursor_when_unfocused = is_enabled;
14053 cx.notify();
14054 }
14055
14056 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14057 self.project
14058 .as_ref()
14059 .map(|project| project.read(cx).lsp_store())
14060 }
14061
14062 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14063 cx.notify();
14064 }
14065
14066 fn on_buffer_event(
14067 &mut self,
14068 multibuffer: &Entity<MultiBuffer>,
14069 event: &multi_buffer::Event,
14070 window: &mut Window,
14071 cx: &mut Context<Self>,
14072 ) {
14073 match event {
14074 multi_buffer::Event::Edited {
14075 singleton_buffer_edited,
14076 edited_buffer: buffer_edited,
14077 } => {
14078 self.scrollbar_marker_state.dirty = true;
14079 self.active_indent_guides_state.dirty = true;
14080 self.refresh_active_diagnostics(cx);
14081 self.refresh_code_actions(window, cx);
14082 if self.has_active_inline_completion() {
14083 self.update_visible_inline_completion(window, cx);
14084 }
14085 if let Some(buffer) = buffer_edited {
14086 let buffer_id = buffer.read(cx).remote_id();
14087 if !self.registered_buffers.contains_key(&buffer_id) {
14088 if let Some(lsp_store) = self.lsp_store(cx) {
14089 lsp_store.update(cx, |lsp_store, cx| {
14090 self.registered_buffers.insert(
14091 buffer_id,
14092 lsp_store.register_buffer_with_language_servers(&buffer, cx),
14093 );
14094 })
14095 }
14096 }
14097 }
14098 cx.emit(EditorEvent::BufferEdited);
14099 cx.emit(SearchEvent::MatchesInvalidated);
14100 if *singleton_buffer_edited {
14101 if let Some(project) = &self.project {
14102 let project = project.read(cx);
14103 #[allow(clippy::mutable_key_type)]
14104 let languages_affected = multibuffer
14105 .read(cx)
14106 .all_buffers()
14107 .into_iter()
14108 .filter_map(|buffer| {
14109 let buffer = buffer.read(cx);
14110 let language = buffer.language()?;
14111 if project.is_local()
14112 && project
14113 .language_servers_for_local_buffer(buffer, cx)
14114 .count()
14115 == 0
14116 {
14117 None
14118 } else {
14119 Some(language)
14120 }
14121 })
14122 .cloned()
14123 .collect::<HashSet<_>>();
14124 if !languages_affected.is_empty() {
14125 self.refresh_inlay_hints(
14126 InlayHintRefreshReason::BufferEdited(languages_affected),
14127 cx,
14128 );
14129 }
14130 }
14131 }
14132
14133 let Some(project) = &self.project else { return };
14134 let (telemetry, is_via_ssh) = {
14135 let project = project.read(cx);
14136 let telemetry = project.client().telemetry().clone();
14137 let is_via_ssh = project.is_via_ssh();
14138 (telemetry, is_via_ssh)
14139 };
14140 refresh_linked_ranges(self, window, cx);
14141 telemetry.log_edit_event("editor", is_via_ssh);
14142 }
14143 multi_buffer::Event::ExcerptsAdded {
14144 buffer,
14145 predecessor,
14146 excerpts,
14147 } => {
14148 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14149 let buffer_id = buffer.read(cx).remote_id();
14150 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14151 if let Some(project) = &self.project {
14152 self.load_diff_task = Some(
14153 get_uncommitted_diff_for_buffer(
14154 project,
14155 [buffer.clone()],
14156 self.buffer.clone(),
14157 cx,
14158 )
14159 .shared(),
14160 );
14161 }
14162 }
14163 cx.emit(EditorEvent::ExcerptsAdded {
14164 buffer: buffer.clone(),
14165 predecessor: *predecessor,
14166 excerpts: excerpts.clone(),
14167 });
14168 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14169 }
14170 multi_buffer::Event::ExcerptsRemoved { ids } => {
14171 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14172 let buffer = self.buffer.read(cx);
14173 self.registered_buffers
14174 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14175 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14176 }
14177 multi_buffer::Event::ExcerptsEdited { ids } => {
14178 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14179 }
14180 multi_buffer::Event::ExcerptsExpanded { ids } => {
14181 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14182 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14183 }
14184 multi_buffer::Event::Reparsed(buffer_id) => {
14185 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14186
14187 cx.emit(EditorEvent::Reparsed(*buffer_id));
14188 }
14189 multi_buffer::Event::DiffHunksToggled => {
14190 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14191 }
14192 multi_buffer::Event::LanguageChanged(buffer_id) => {
14193 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14194 cx.emit(EditorEvent::Reparsed(*buffer_id));
14195 cx.notify();
14196 }
14197 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14198 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14199 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14200 cx.emit(EditorEvent::TitleChanged)
14201 }
14202 // multi_buffer::Event::DiffBaseChanged => {
14203 // self.scrollbar_marker_state.dirty = true;
14204 // cx.emit(EditorEvent::DiffBaseChanged);
14205 // cx.notify();
14206 // }
14207 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14208 multi_buffer::Event::DiagnosticsUpdated => {
14209 self.refresh_active_diagnostics(cx);
14210 self.scrollbar_marker_state.dirty = true;
14211 cx.notify();
14212 }
14213 _ => {}
14214 };
14215 }
14216
14217 fn on_display_map_changed(
14218 &mut self,
14219 _: Entity<DisplayMap>,
14220 _: &mut Window,
14221 cx: &mut Context<Self>,
14222 ) {
14223 cx.notify();
14224 }
14225
14226 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14227 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14228 self.refresh_inline_completion(true, false, window, cx);
14229 self.refresh_inlay_hints(
14230 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14231 self.selections.newest_anchor().head(),
14232 &self.buffer.read(cx).snapshot(cx),
14233 cx,
14234 )),
14235 cx,
14236 );
14237
14238 let old_cursor_shape = self.cursor_shape;
14239
14240 {
14241 let editor_settings = EditorSettings::get_global(cx);
14242 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14243 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14244 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14245 }
14246
14247 if old_cursor_shape != self.cursor_shape {
14248 cx.emit(EditorEvent::CursorShapeChanged);
14249 }
14250
14251 let project_settings = ProjectSettings::get_global(cx);
14252 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14253
14254 if self.mode == EditorMode::Full {
14255 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14256 if self.git_blame_inline_enabled != inline_blame_enabled {
14257 self.toggle_git_blame_inline_internal(false, window, cx);
14258 }
14259 }
14260
14261 cx.notify();
14262 }
14263
14264 pub fn set_searchable(&mut self, searchable: bool) {
14265 self.searchable = searchable;
14266 }
14267
14268 pub fn searchable(&self) -> bool {
14269 self.searchable
14270 }
14271
14272 fn open_proposed_changes_editor(
14273 &mut self,
14274 _: &OpenProposedChangesEditor,
14275 window: &mut Window,
14276 cx: &mut Context<Self>,
14277 ) {
14278 let Some(workspace) = self.workspace() else {
14279 cx.propagate();
14280 return;
14281 };
14282
14283 let selections = self.selections.all::<usize>(cx);
14284 let multi_buffer = self.buffer.read(cx);
14285 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14286 let mut new_selections_by_buffer = HashMap::default();
14287 for selection in selections {
14288 for (buffer, range, _) in
14289 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14290 {
14291 let mut range = range.to_point(buffer);
14292 range.start.column = 0;
14293 range.end.column = buffer.line_len(range.end.row);
14294 new_selections_by_buffer
14295 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14296 .or_insert(Vec::new())
14297 .push(range)
14298 }
14299 }
14300
14301 let proposed_changes_buffers = new_selections_by_buffer
14302 .into_iter()
14303 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14304 .collect::<Vec<_>>();
14305 let proposed_changes_editor = cx.new(|cx| {
14306 ProposedChangesEditor::new(
14307 "Proposed changes",
14308 proposed_changes_buffers,
14309 self.project.clone(),
14310 window,
14311 cx,
14312 )
14313 });
14314
14315 window.defer(cx, move |window, cx| {
14316 workspace.update(cx, |workspace, cx| {
14317 workspace.active_pane().update(cx, |pane, cx| {
14318 pane.add_item(
14319 Box::new(proposed_changes_editor),
14320 true,
14321 true,
14322 None,
14323 window,
14324 cx,
14325 );
14326 });
14327 });
14328 });
14329 }
14330
14331 pub fn open_excerpts_in_split(
14332 &mut self,
14333 _: &OpenExcerptsSplit,
14334 window: &mut Window,
14335 cx: &mut Context<Self>,
14336 ) {
14337 self.open_excerpts_common(None, true, window, cx)
14338 }
14339
14340 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14341 self.open_excerpts_common(None, false, window, cx)
14342 }
14343
14344 fn open_excerpts_common(
14345 &mut self,
14346 jump_data: Option<JumpData>,
14347 split: bool,
14348 window: &mut Window,
14349 cx: &mut Context<Self>,
14350 ) {
14351 let Some(workspace) = self.workspace() else {
14352 cx.propagate();
14353 return;
14354 };
14355
14356 if self.buffer.read(cx).is_singleton() {
14357 cx.propagate();
14358 return;
14359 }
14360
14361 let mut new_selections_by_buffer = HashMap::default();
14362 match &jump_data {
14363 Some(JumpData::MultiBufferPoint {
14364 excerpt_id,
14365 position,
14366 anchor,
14367 line_offset_from_top,
14368 }) => {
14369 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14370 if let Some(buffer) = multi_buffer_snapshot
14371 .buffer_id_for_excerpt(*excerpt_id)
14372 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14373 {
14374 let buffer_snapshot = buffer.read(cx).snapshot();
14375 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14376 language::ToPoint::to_point(anchor, &buffer_snapshot)
14377 } else {
14378 buffer_snapshot.clip_point(*position, Bias::Left)
14379 };
14380 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14381 new_selections_by_buffer.insert(
14382 buffer,
14383 (
14384 vec![jump_to_offset..jump_to_offset],
14385 Some(*line_offset_from_top),
14386 ),
14387 );
14388 }
14389 }
14390 Some(JumpData::MultiBufferRow {
14391 row,
14392 line_offset_from_top,
14393 }) => {
14394 let point = MultiBufferPoint::new(row.0, 0);
14395 if let Some((buffer, buffer_point, _)) =
14396 self.buffer.read(cx).point_to_buffer_point(point, cx)
14397 {
14398 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14399 new_selections_by_buffer
14400 .entry(buffer)
14401 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14402 .0
14403 .push(buffer_offset..buffer_offset)
14404 }
14405 }
14406 None => {
14407 let selections = self.selections.all::<usize>(cx);
14408 let multi_buffer = self.buffer.read(cx);
14409 for selection in selections {
14410 for (buffer, mut range, _) in multi_buffer
14411 .snapshot(cx)
14412 .range_to_buffer_ranges(selection.range())
14413 {
14414 // When editing branch buffers, jump to the corresponding location
14415 // in their base buffer.
14416 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14417 let buffer = buffer_handle.read(cx);
14418 if let Some(base_buffer) = buffer.base_buffer() {
14419 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14420 buffer_handle = base_buffer;
14421 }
14422
14423 if selection.reversed {
14424 mem::swap(&mut range.start, &mut range.end);
14425 }
14426 new_selections_by_buffer
14427 .entry(buffer_handle)
14428 .or_insert((Vec::new(), None))
14429 .0
14430 .push(range)
14431 }
14432 }
14433 }
14434 }
14435
14436 if new_selections_by_buffer.is_empty() {
14437 return;
14438 }
14439
14440 // We defer the pane interaction because we ourselves are a workspace item
14441 // and activating a new item causes the pane to call a method on us reentrantly,
14442 // which panics if we're on the stack.
14443 window.defer(cx, move |window, cx| {
14444 workspace.update(cx, |workspace, cx| {
14445 let pane = if split {
14446 workspace.adjacent_pane(window, cx)
14447 } else {
14448 workspace.active_pane().clone()
14449 };
14450
14451 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14452 let editor = buffer
14453 .read(cx)
14454 .file()
14455 .is_none()
14456 .then(|| {
14457 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14458 // so `workspace.open_project_item` will never find them, always opening a new editor.
14459 // Instead, we try to activate the existing editor in the pane first.
14460 let (editor, pane_item_index) =
14461 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14462 let editor = item.downcast::<Editor>()?;
14463 let singleton_buffer =
14464 editor.read(cx).buffer().read(cx).as_singleton()?;
14465 if singleton_buffer == buffer {
14466 Some((editor, i))
14467 } else {
14468 None
14469 }
14470 })?;
14471 pane.update(cx, |pane, cx| {
14472 pane.activate_item(pane_item_index, true, true, window, cx)
14473 });
14474 Some(editor)
14475 })
14476 .flatten()
14477 .unwrap_or_else(|| {
14478 workspace.open_project_item::<Self>(
14479 pane.clone(),
14480 buffer,
14481 true,
14482 true,
14483 window,
14484 cx,
14485 )
14486 });
14487
14488 editor.update(cx, |editor, cx| {
14489 let autoscroll = match scroll_offset {
14490 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14491 None => Autoscroll::newest(),
14492 };
14493 let nav_history = editor.nav_history.take();
14494 editor.change_selections(Some(autoscroll), window, cx, |s| {
14495 s.select_ranges(ranges);
14496 });
14497 editor.nav_history = nav_history;
14498 });
14499 }
14500 })
14501 });
14502 }
14503
14504 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14505 let snapshot = self.buffer.read(cx).read(cx);
14506 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14507 Some(
14508 ranges
14509 .iter()
14510 .map(move |range| {
14511 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14512 })
14513 .collect(),
14514 )
14515 }
14516
14517 fn selection_replacement_ranges(
14518 &self,
14519 range: Range<OffsetUtf16>,
14520 cx: &mut App,
14521 ) -> Vec<Range<OffsetUtf16>> {
14522 let selections = self.selections.all::<OffsetUtf16>(cx);
14523 let newest_selection = selections
14524 .iter()
14525 .max_by_key(|selection| selection.id)
14526 .unwrap();
14527 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14528 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14529 let snapshot = self.buffer.read(cx).read(cx);
14530 selections
14531 .into_iter()
14532 .map(|mut selection| {
14533 selection.start.0 =
14534 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14535 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14536 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14537 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14538 })
14539 .collect()
14540 }
14541
14542 fn report_editor_event(
14543 &self,
14544 event_type: &'static str,
14545 file_extension: Option<String>,
14546 cx: &App,
14547 ) {
14548 if cfg!(any(test, feature = "test-support")) {
14549 return;
14550 }
14551
14552 let Some(project) = &self.project else { return };
14553
14554 // If None, we are in a file without an extension
14555 let file = self
14556 .buffer
14557 .read(cx)
14558 .as_singleton()
14559 .and_then(|b| b.read(cx).file());
14560 let file_extension = file_extension.or(file
14561 .as_ref()
14562 .and_then(|file| Path::new(file.file_name(cx)).extension())
14563 .and_then(|e| e.to_str())
14564 .map(|a| a.to_string()));
14565
14566 let vim_mode = cx
14567 .global::<SettingsStore>()
14568 .raw_user_settings()
14569 .get("vim_mode")
14570 == Some(&serde_json::Value::Bool(true));
14571
14572 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14573 let copilot_enabled = edit_predictions_provider
14574 == language::language_settings::EditPredictionProvider::Copilot;
14575 let copilot_enabled_for_language = self
14576 .buffer
14577 .read(cx)
14578 .settings_at(0, cx)
14579 .show_edit_predictions;
14580
14581 let project = project.read(cx);
14582 telemetry::event!(
14583 event_type,
14584 file_extension,
14585 vim_mode,
14586 copilot_enabled,
14587 copilot_enabled_for_language,
14588 edit_predictions_provider,
14589 is_via_ssh = project.is_via_ssh(),
14590 );
14591 }
14592
14593 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14594 /// with each line being an array of {text, highlight} objects.
14595 fn copy_highlight_json(
14596 &mut self,
14597 _: &CopyHighlightJson,
14598 window: &mut Window,
14599 cx: &mut Context<Self>,
14600 ) {
14601 #[derive(Serialize)]
14602 struct Chunk<'a> {
14603 text: String,
14604 highlight: Option<&'a str>,
14605 }
14606
14607 let snapshot = self.buffer.read(cx).snapshot(cx);
14608 let range = self
14609 .selected_text_range(false, window, cx)
14610 .and_then(|selection| {
14611 if selection.range.is_empty() {
14612 None
14613 } else {
14614 Some(selection.range)
14615 }
14616 })
14617 .unwrap_or_else(|| 0..snapshot.len());
14618
14619 let chunks = snapshot.chunks(range, true);
14620 let mut lines = Vec::new();
14621 let mut line: VecDeque<Chunk> = VecDeque::new();
14622
14623 let Some(style) = self.style.as_ref() else {
14624 return;
14625 };
14626
14627 for chunk in chunks {
14628 let highlight = chunk
14629 .syntax_highlight_id
14630 .and_then(|id| id.name(&style.syntax));
14631 let mut chunk_lines = chunk.text.split('\n').peekable();
14632 while let Some(text) = chunk_lines.next() {
14633 let mut merged_with_last_token = false;
14634 if let Some(last_token) = line.back_mut() {
14635 if last_token.highlight == highlight {
14636 last_token.text.push_str(text);
14637 merged_with_last_token = true;
14638 }
14639 }
14640
14641 if !merged_with_last_token {
14642 line.push_back(Chunk {
14643 text: text.into(),
14644 highlight,
14645 });
14646 }
14647
14648 if chunk_lines.peek().is_some() {
14649 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14650 line.pop_front();
14651 }
14652 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14653 line.pop_back();
14654 }
14655
14656 lines.push(mem::take(&mut line));
14657 }
14658 }
14659 }
14660
14661 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14662 return;
14663 };
14664 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14665 }
14666
14667 pub fn open_context_menu(
14668 &mut self,
14669 _: &OpenContextMenu,
14670 window: &mut Window,
14671 cx: &mut Context<Self>,
14672 ) {
14673 self.request_autoscroll(Autoscroll::newest(), cx);
14674 let position = self.selections.newest_display(cx).start;
14675 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14676 }
14677
14678 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14679 &self.inlay_hint_cache
14680 }
14681
14682 pub fn replay_insert_event(
14683 &mut self,
14684 text: &str,
14685 relative_utf16_range: Option<Range<isize>>,
14686 window: &mut Window,
14687 cx: &mut Context<Self>,
14688 ) {
14689 if !self.input_enabled {
14690 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14691 return;
14692 }
14693 if let Some(relative_utf16_range) = relative_utf16_range {
14694 let selections = self.selections.all::<OffsetUtf16>(cx);
14695 self.change_selections(None, window, cx, |s| {
14696 let new_ranges = selections.into_iter().map(|range| {
14697 let start = OffsetUtf16(
14698 range
14699 .head()
14700 .0
14701 .saturating_add_signed(relative_utf16_range.start),
14702 );
14703 let end = OffsetUtf16(
14704 range
14705 .head()
14706 .0
14707 .saturating_add_signed(relative_utf16_range.end),
14708 );
14709 start..end
14710 });
14711 s.select_ranges(new_ranges);
14712 });
14713 }
14714
14715 self.handle_input(text, window, cx);
14716 }
14717
14718 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14719 let Some(provider) = self.semantics_provider.as_ref() else {
14720 return false;
14721 };
14722
14723 let mut supports = false;
14724 self.buffer().read(cx).for_each_buffer(|buffer| {
14725 supports |= provider.supports_inlay_hints(buffer, cx);
14726 });
14727 supports
14728 }
14729
14730 pub fn is_focused(&self, window: &Window) -> bool {
14731 self.focus_handle.is_focused(window)
14732 }
14733
14734 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14735 cx.emit(EditorEvent::Focused);
14736
14737 if let Some(descendant) = self
14738 .last_focused_descendant
14739 .take()
14740 .and_then(|descendant| descendant.upgrade())
14741 {
14742 window.focus(&descendant);
14743 } else {
14744 if let Some(blame) = self.blame.as_ref() {
14745 blame.update(cx, GitBlame::focus)
14746 }
14747
14748 self.blink_manager.update(cx, BlinkManager::enable);
14749 self.show_cursor_names(window, cx);
14750 self.buffer.update(cx, |buffer, cx| {
14751 buffer.finalize_last_transaction(cx);
14752 if self.leader_peer_id.is_none() {
14753 buffer.set_active_selections(
14754 &self.selections.disjoint_anchors(),
14755 self.selections.line_mode,
14756 self.cursor_shape,
14757 cx,
14758 );
14759 }
14760 });
14761 }
14762 }
14763
14764 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14765 cx.emit(EditorEvent::FocusedIn)
14766 }
14767
14768 fn handle_focus_out(
14769 &mut self,
14770 event: FocusOutEvent,
14771 _window: &mut Window,
14772 _cx: &mut Context<Self>,
14773 ) {
14774 if event.blurred != self.focus_handle {
14775 self.last_focused_descendant = Some(event.blurred);
14776 }
14777 }
14778
14779 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14780 self.blink_manager.update(cx, BlinkManager::disable);
14781 self.buffer
14782 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14783
14784 if let Some(blame) = self.blame.as_ref() {
14785 blame.update(cx, GitBlame::blur)
14786 }
14787 if !self.hover_state.focused(window, cx) {
14788 hide_hover(self, cx);
14789 }
14790
14791 self.hide_context_menu(window, cx);
14792 self.discard_inline_completion(false, cx);
14793 cx.emit(EditorEvent::Blurred);
14794 cx.notify();
14795 }
14796
14797 pub fn register_action<A: Action>(
14798 &mut self,
14799 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14800 ) -> Subscription {
14801 let id = self.next_editor_action_id.post_inc();
14802 let listener = Arc::new(listener);
14803 self.editor_actions.borrow_mut().insert(
14804 id,
14805 Box::new(move |window, _| {
14806 let listener = listener.clone();
14807 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14808 let action = action.downcast_ref().unwrap();
14809 if phase == DispatchPhase::Bubble {
14810 listener(action, window, cx)
14811 }
14812 })
14813 }),
14814 );
14815
14816 let editor_actions = self.editor_actions.clone();
14817 Subscription::new(move || {
14818 editor_actions.borrow_mut().remove(&id);
14819 })
14820 }
14821
14822 pub fn file_header_size(&self) -> u32 {
14823 FILE_HEADER_HEIGHT
14824 }
14825
14826 pub fn revert(
14827 &mut self,
14828 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14829 window: &mut Window,
14830 cx: &mut Context<Self>,
14831 ) {
14832 self.buffer().update(cx, |multi_buffer, cx| {
14833 for (buffer_id, changes) in revert_changes {
14834 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14835 buffer.update(cx, |buffer, cx| {
14836 buffer.edit(
14837 changes.into_iter().map(|(range, text)| {
14838 (range, text.to_string().map(Arc::<str>::from))
14839 }),
14840 None,
14841 cx,
14842 );
14843 });
14844 }
14845 }
14846 });
14847 self.change_selections(None, window, cx, |selections| selections.refresh());
14848 }
14849
14850 pub fn to_pixel_point(
14851 &self,
14852 source: multi_buffer::Anchor,
14853 editor_snapshot: &EditorSnapshot,
14854 window: &mut Window,
14855 ) -> Option<gpui::Point<Pixels>> {
14856 let source_point = source.to_display_point(editor_snapshot);
14857 self.display_to_pixel_point(source_point, editor_snapshot, window)
14858 }
14859
14860 pub fn display_to_pixel_point(
14861 &self,
14862 source: DisplayPoint,
14863 editor_snapshot: &EditorSnapshot,
14864 window: &mut Window,
14865 ) -> Option<gpui::Point<Pixels>> {
14866 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14867 let text_layout_details = self.text_layout_details(window);
14868 let scroll_top = text_layout_details
14869 .scroll_anchor
14870 .scroll_position(editor_snapshot)
14871 .y;
14872
14873 if source.row().as_f32() < scroll_top.floor() {
14874 return None;
14875 }
14876 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14877 let source_y = line_height * (source.row().as_f32() - scroll_top);
14878 Some(gpui::Point::new(source_x, source_y))
14879 }
14880
14881 pub fn has_visible_completions_menu(&self) -> bool {
14882 !self.edit_prediction_preview_is_active()
14883 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14884 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14885 })
14886 }
14887
14888 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14889 self.addons
14890 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14891 }
14892
14893 pub fn unregister_addon<T: Addon>(&mut self) {
14894 self.addons.remove(&std::any::TypeId::of::<T>());
14895 }
14896
14897 pub fn addon<T: Addon>(&self) -> Option<&T> {
14898 let type_id = std::any::TypeId::of::<T>();
14899 self.addons
14900 .get(&type_id)
14901 .and_then(|item| item.to_any().downcast_ref::<T>())
14902 }
14903
14904 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14905 let text_layout_details = self.text_layout_details(window);
14906 let style = &text_layout_details.editor_style;
14907 let font_id = window.text_system().resolve_font(&style.text.font());
14908 let font_size = style.text.font_size.to_pixels(window.rem_size());
14909 let line_height = style.text.line_height_in_pixels(window.rem_size());
14910 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14911
14912 gpui::Size::new(em_width, line_height)
14913 }
14914
14915 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14916 self.load_diff_task.clone()
14917 }
14918}
14919
14920fn get_uncommitted_diff_for_buffer(
14921 project: &Entity<Project>,
14922 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14923 buffer: Entity<MultiBuffer>,
14924 cx: &mut App,
14925) -> Task<()> {
14926 let mut tasks = Vec::new();
14927 project.update(cx, |project, cx| {
14928 for buffer in buffers {
14929 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14930 }
14931 });
14932 cx.spawn(|mut cx| async move {
14933 let diffs = futures::future::join_all(tasks).await;
14934 buffer
14935 .update(&mut cx, |buffer, cx| {
14936 for diff in diffs.into_iter().flatten() {
14937 buffer.add_diff(diff, cx);
14938 }
14939 })
14940 .ok();
14941 })
14942}
14943
14944fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14945 let tab_size = tab_size.get() as usize;
14946 let mut width = offset;
14947
14948 for ch in text.chars() {
14949 width += if ch == '\t' {
14950 tab_size - (width % tab_size)
14951 } else {
14952 1
14953 };
14954 }
14955
14956 width - offset
14957}
14958
14959#[cfg(test)]
14960mod tests {
14961 use super::*;
14962
14963 #[test]
14964 fn test_string_size_with_expanded_tabs() {
14965 let nz = |val| NonZeroU32::new(val).unwrap();
14966 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14967 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14968 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14969 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14970 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14971 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14972 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14973 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14974 }
14975}
14976
14977/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14978struct WordBreakingTokenizer<'a> {
14979 input: &'a str,
14980}
14981
14982impl<'a> WordBreakingTokenizer<'a> {
14983 fn new(input: &'a str) -> Self {
14984 Self { input }
14985 }
14986}
14987
14988fn is_char_ideographic(ch: char) -> bool {
14989 use unicode_script::Script::*;
14990 use unicode_script::UnicodeScript;
14991 matches!(ch.script(), Han | Tangut | Yi)
14992}
14993
14994fn is_grapheme_ideographic(text: &str) -> bool {
14995 text.chars().any(is_char_ideographic)
14996}
14997
14998fn is_grapheme_whitespace(text: &str) -> bool {
14999 text.chars().any(|x| x.is_whitespace())
15000}
15001
15002fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15003 text.chars().next().map_or(false, |ch| {
15004 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15005 })
15006}
15007
15008#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15009struct WordBreakToken<'a> {
15010 token: &'a str,
15011 grapheme_len: usize,
15012 is_whitespace: bool,
15013}
15014
15015impl<'a> Iterator for WordBreakingTokenizer<'a> {
15016 /// Yields a span, the count of graphemes in the token, and whether it was
15017 /// whitespace. Note that it also breaks at word boundaries.
15018 type Item = WordBreakToken<'a>;
15019
15020 fn next(&mut self) -> Option<Self::Item> {
15021 use unicode_segmentation::UnicodeSegmentation;
15022 if self.input.is_empty() {
15023 return None;
15024 }
15025
15026 let mut iter = self.input.graphemes(true).peekable();
15027 let mut offset = 0;
15028 let mut graphemes = 0;
15029 if let Some(first_grapheme) = iter.next() {
15030 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15031 offset += first_grapheme.len();
15032 graphemes += 1;
15033 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15034 if let Some(grapheme) = iter.peek().copied() {
15035 if should_stay_with_preceding_ideograph(grapheme) {
15036 offset += grapheme.len();
15037 graphemes += 1;
15038 }
15039 }
15040 } else {
15041 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15042 let mut next_word_bound = words.peek().copied();
15043 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15044 next_word_bound = words.next();
15045 }
15046 while let Some(grapheme) = iter.peek().copied() {
15047 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15048 break;
15049 };
15050 if is_grapheme_whitespace(grapheme) != is_whitespace {
15051 break;
15052 };
15053 offset += grapheme.len();
15054 graphemes += 1;
15055 iter.next();
15056 }
15057 }
15058 let token = &self.input[..offset];
15059 self.input = &self.input[offset..];
15060 if is_whitespace {
15061 Some(WordBreakToken {
15062 token: " ",
15063 grapheme_len: 1,
15064 is_whitespace: true,
15065 })
15066 } else {
15067 Some(WordBreakToken {
15068 token,
15069 grapheme_len: graphemes,
15070 is_whitespace: false,
15071 })
15072 }
15073 } else {
15074 None
15075 }
15076 }
15077}
15078
15079#[test]
15080fn test_word_breaking_tokenizer() {
15081 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15082 ("", &[]),
15083 (" ", &[(" ", 1, true)]),
15084 ("Ʒ", &[("Ʒ", 1, false)]),
15085 ("Ǽ", &[("Ǽ", 1, false)]),
15086 ("⋑", &[("⋑", 1, false)]),
15087 ("⋑⋑", &[("⋑⋑", 2, false)]),
15088 (
15089 "原理,进而",
15090 &[
15091 ("原", 1, false),
15092 ("理,", 2, false),
15093 ("进", 1, false),
15094 ("而", 1, false),
15095 ],
15096 ),
15097 (
15098 "hello world",
15099 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15100 ),
15101 (
15102 "hello, world",
15103 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15104 ),
15105 (
15106 " hello world",
15107 &[
15108 (" ", 1, true),
15109 ("hello", 5, false),
15110 (" ", 1, true),
15111 ("world", 5, false),
15112 ],
15113 ),
15114 (
15115 "这是什么 \n 钢笔",
15116 &[
15117 ("这", 1, false),
15118 ("是", 1, false),
15119 ("什", 1, false),
15120 ("么", 1, false),
15121 (" ", 1, true),
15122 ("钢", 1, false),
15123 ("笔", 1, false),
15124 ],
15125 ),
15126 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15127 ];
15128
15129 for (input, result) in tests {
15130 assert_eq!(
15131 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15132 result
15133 .iter()
15134 .copied()
15135 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15136 token,
15137 grapheme_len,
15138 is_whitespace,
15139 })
15140 .collect::<Vec<_>>()
15141 );
15142 }
15143}
15144
15145fn wrap_with_prefix(
15146 line_prefix: String,
15147 unwrapped_text: String,
15148 wrap_column: usize,
15149 tab_size: NonZeroU32,
15150) -> String {
15151 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15152 let mut wrapped_text = String::new();
15153 let mut current_line = line_prefix.clone();
15154
15155 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15156 let mut current_line_len = line_prefix_len;
15157 for WordBreakToken {
15158 token,
15159 grapheme_len,
15160 is_whitespace,
15161 } in tokenizer
15162 {
15163 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15164 wrapped_text.push_str(current_line.trim_end());
15165 wrapped_text.push('\n');
15166 current_line.truncate(line_prefix.len());
15167 current_line_len = line_prefix_len;
15168 if !is_whitespace {
15169 current_line.push_str(token);
15170 current_line_len += grapheme_len;
15171 }
15172 } else if !is_whitespace {
15173 current_line.push_str(token);
15174 current_line_len += grapheme_len;
15175 } else if current_line_len != line_prefix_len {
15176 current_line.push(' ');
15177 current_line_len += 1;
15178 }
15179 }
15180
15181 if !current_line.is_empty() {
15182 wrapped_text.push_str(¤t_line);
15183 }
15184 wrapped_text
15185}
15186
15187#[test]
15188fn test_wrap_with_prefix() {
15189 assert_eq!(
15190 wrap_with_prefix(
15191 "# ".to_string(),
15192 "abcdefg".to_string(),
15193 4,
15194 NonZeroU32::new(4).unwrap()
15195 ),
15196 "# abcdefg"
15197 );
15198 assert_eq!(
15199 wrap_with_prefix(
15200 "".to_string(),
15201 "\thello world".to_string(),
15202 8,
15203 NonZeroU32::new(4).unwrap()
15204 ),
15205 "hello\nworld"
15206 );
15207 assert_eq!(
15208 wrap_with_prefix(
15209 "// ".to_string(),
15210 "xx \nyy zz aa bb cc".to_string(),
15211 12,
15212 NonZeroU32::new(4).unwrap()
15213 ),
15214 "// xx yy zz\n// aa bb cc"
15215 );
15216 assert_eq!(
15217 wrap_with_prefix(
15218 String::new(),
15219 "这是什么 \n 钢笔".to_string(),
15220 3,
15221 NonZeroU32::new(4).unwrap()
15222 ),
15223 "这是什\n么 钢\n笔"
15224 );
15225}
15226
15227pub trait CollaborationHub {
15228 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15229 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15230 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15231}
15232
15233impl CollaborationHub for Entity<Project> {
15234 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15235 self.read(cx).collaborators()
15236 }
15237
15238 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15239 self.read(cx).user_store().read(cx).participant_indices()
15240 }
15241
15242 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15243 let this = self.read(cx);
15244 let user_ids = this.collaborators().values().map(|c| c.user_id);
15245 this.user_store().read_with(cx, |user_store, cx| {
15246 user_store.participant_names(user_ids, cx)
15247 })
15248 }
15249}
15250
15251pub trait SemanticsProvider {
15252 fn hover(
15253 &self,
15254 buffer: &Entity<Buffer>,
15255 position: text::Anchor,
15256 cx: &mut App,
15257 ) -> Option<Task<Vec<project::Hover>>>;
15258
15259 fn inlay_hints(
15260 &self,
15261 buffer_handle: Entity<Buffer>,
15262 range: Range<text::Anchor>,
15263 cx: &mut App,
15264 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15265
15266 fn resolve_inlay_hint(
15267 &self,
15268 hint: InlayHint,
15269 buffer_handle: Entity<Buffer>,
15270 server_id: LanguageServerId,
15271 cx: &mut App,
15272 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15273
15274 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15275
15276 fn document_highlights(
15277 &self,
15278 buffer: &Entity<Buffer>,
15279 position: text::Anchor,
15280 cx: &mut App,
15281 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15282
15283 fn definitions(
15284 &self,
15285 buffer: &Entity<Buffer>,
15286 position: text::Anchor,
15287 kind: GotoDefinitionKind,
15288 cx: &mut App,
15289 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15290
15291 fn range_for_rename(
15292 &self,
15293 buffer: &Entity<Buffer>,
15294 position: text::Anchor,
15295 cx: &mut App,
15296 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15297
15298 fn perform_rename(
15299 &self,
15300 buffer: &Entity<Buffer>,
15301 position: text::Anchor,
15302 new_name: String,
15303 cx: &mut App,
15304 ) -> Option<Task<Result<ProjectTransaction>>>;
15305}
15306
15307pub trait CompletionProvider {
15308 fn completions(
15309 &self,
15310 buffer: &Entity<Buffer>,
15311 buffer_position: text::Anchor,
15312 trigger: CompletionContext,
15313 window: &mut Window,
15314 cx: &mut Context<Editor>,
15315 ) -> Task<Result<Vec<Completion>>>;
15316
15317 fn resolve_completions(
15318 &self,
15319 buffer: Entity<Buffer>,
15320 completion_indices: Vec<usize>,
15321 completions: Rc<RefCell<Box<[Completion]>>>,
15322 cx: &mut Context<Editor>,
15323 ) -> Task<Result<bool>>;
15324
15325 fn apply_additional_edits_for_completion(
15326 &self,
15327 _buffer: Entity<Buffer>,
15328 _completions: Rc<RefCell<Box<[Completion]>>>,
15329 _completion_index: usize,
15330 _push_to_history: bool,
15331 _cx: &mut Context<Editor>,
15332 ) -> Task<Result<Option<language::Transaction>>> {
15333 Task::ready(Ok(None))
15334 }
15335
15336 fn is_completion_trigger(
15337 &self,
15338 buffer: &Entity<Buffer>,
15339 position: language::Anchor,
15340 text: &str,
15341 trigger_in_words: bool,
15342 cx: &mut Context<Editor>,
15343 ) -> bool;
15344
15345 fn sort_completions(&self) -> bool {
15346 true
15347 }
15348}
15349
15350pub trait CodeActionProvider {
15351 fn id(&self) -> Arc<str>;
15352
15353 fn code_actions(
15354 &self,
15355 buffer: &Entity<Buffer>,
15356 range: Range<text::Anchor>,
15357 window: &mut Window,
15358 cx: &mut App,
15359 ) -> Task<Result<Vec<CodeAction>>>;
15360
15361 fn apply_code_action(
15362 &self,
15363 buffer_handle: Entity<Buffer>,
15364 action: CodeAction,
15365 excerpt_id: ExcerptId,
15366 push_to_history: bool,
15367 window: &mut Window,
15368 cx: &mut App,
15369 ) -> Task<Result<ProjectTransaction>>;
15370}
15371
15372impl CodeActionProvider for Entity<Project> {
15373 fn id(&self) -> Arc<str> {
15374 "project".into()
15375 }
15376
15377 fn code_actions(
15378 &self,
15379 buffer: &Entity<Buffer>,
15380 range: Range<text::Anchor>,
15381 _window: &mut Window,
15382 cx: &mut App,
15383 ) -> Task<Result<Vec<CodeAction>>> {
15384 self.update(cx, |project, cx| {
15385 project.code_actions(buffer, range, None, cx)
15386 })
15387 }
15388
15389 fn apply_code_action(
15390 &self,
15391 buffer_handle: Entity<Buffer>,
15392 action: CodeAction,
15393 _excerpt_id: ExcerptId,
15394 push_to_history: bool,
15395 _window: &mut Window,
15396 cx: &mut App,
15397 ) -> Task<Result<ProjectTransaction>> {
15398 self.update(cx, |project, cx| {
15399 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15400 })
15401 }
15402}
15403
15404fn snippet_completions(
15405 project: &Project,
15406 buffer: &Entity<Buffer>,
15407 buffer_position: text::Anchor,
15408 cx: &mut App,
15409) -> Task<Result<Vec<Completion>>> {
15410 let language = buffer.read(cx).language_at(buffer_position);
15411 let language_name = language.as_ref().map(|language| language.lsp_id());
15412 let snippet_store = project.snippets().read(cx);
15413 let snippets = snippet_store.snippets_for(language_name, cx);
15414
15415 if snippets.is_empty() {
15416 return Task::ready(Ok(vec![]));
15417 }
15418 let snapshot = buffer.read(cx).text_snapshot();
15419 let chars: String = snapshot
15420 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15421 .collect();
15422
15423 let scope = language.map(|language| language.default_scope());
15424 let executor = cx.background_executor().clone();
15425
15426 cx.background_executor().spawn(async move {
15427 let classifier = CharClassifier::new(scope).for_completion(true);
15428 let mut last_word = chars
15429 .chars()
15430 .take_while(|c| classifier.is_word(*c))
15431 .collect::<String>();
15432 last_word = last_word.chars().rev().collect();
15433
15434 if last_word.is_empty() {
15435 return Ok(vec![]);
15436 }
15437
15438 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15439 let to_lsp = |point: &text::Anchor| {
15440 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15441 point_to_lsp(end)
15442 };
15443 let lsp_end = to_lsp(&buffer_position);
15444
15445 let candidates = snippets
15446 .iter()
15447 .enumerate()
15448 .flat_map(|(ix, snippet)| {
15449 snippet
15450 .prefix
15451 .iter()
15452 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15453 })
15454 .collect::<Vec<StringMatchCandidate>>();
15455
15456 let mut matches = fuzzy::match_strings(
15457 &candidates,
15458 &last_word,
15459 last_word.chars().any(|c| c.is_uppercase()),
15460 100,
15461 &Default::default(),
15462 executor,
15463 )
15464 .await;
15465
15466 // Remove all candidates where the query's start does not match the start of any word in the candidate
15467 if let Some(query_start) = last_word.chars().next() {
15468 matches.retain(|string_match| {
15469 split_words(&string_match.string).any(|word| {
15470 // Check that the first codepoint of the word as lowercase matches the first
15471 // codepoint of the query as lowercase
15472 word.chars()
15473 .flat_map(|codepoint| codepoint.to_lowercase())
15474 .zip(query_start.to_lowercase())
15475 .all(|(word_cp, query_cp)| word_cp == query_cp)
15476 })
15477 });
15478 }
15479
15480 let matched_strings = matches
15481 .into_iter()
15482 .map(|m| m.string)
15483 .collect::<HashSet<_>>();
15484
15485 let result: Vec<Completion> = snippets
15486 .into_iter()
15487 .filter_map(|snippet| {
15488 let matching_prefix = snippet
15489 .prefix
15490 .iter()
15491 .find(|prefix| matched_strings.contains(*prefix))?;
15492 let start = as_offset - last_word.len();
15493 let start = snapshot.anchor_before(start);
15494 let range = start..buffer_position;
15495 let lsp_start = to_lsp(&start);
15496 let lsp_range = lsp::Range {
15497 start: lsp_start,
15498 end: lsp_end,
15499 };
15500 Some(Completion {
15501 old_range: range,
15502 new_text: snippet.body.clone(),
15503 resolved: false,
15504 label: CodeLabel {
15505 text: matching_prefix.clone(),
15506 runs: vec![],
15507 filter_range: 0..matching_prefix.len(),
15508 },
15509 server_id: LanguageServerId(usize::MAX),
15510 documentation: snippet
15511 .description
15512 .clone()
15513 .map(CompletionDocumentation::SingleLine),
15514 lsp_completion: lsp::CompletionItem {
15515 label: snippet.prefix.first().unwrap().clone(),
15516 kind: Some(CompletionItemKind::SNIPPET),
15517 label_details: snippet.description.as_ref().map(|description| {
15518 lsp::CompletionItemLabelDetails {
15519 detail: Some(description.clone()),
15520 description: None,
15521 }
15522 }),
15523 insert_text_format: Some(InsertTextFormat::SNIPPET),
15524 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15525 lsp::InsertReplaceEdit {
15526 new_text: snippet.body.clone(),
15527 insert: lsp_range,
15528 replace: lsp_range,
15529 },
15530 )),
15531 filter_text: Some(snippet.body.clone()),
15532 sort_text: Some(char::MAX.to_string()),
15533 ..Default::default()
15534 },
15535 confirm: None,
15536 })
15537 })
15538 .collect();
15539
15540 Ok(result)
15541 })
15542}
15543
15544impl CompletionProvider for Entity<Project> {
15545 fn completions(
15546 &self,
15547 buffer: &Entity<Buffer>,
15548 buffer_position: text::Anchor,
15549 options: CompletionContext,
15550 _window: &mut Window,
15551 cx: &mut Context<Editor>,
15552 ) -> Task<Result<Vec<Completion>>> {
15553 self.update(cx, |project, cx| {
15554 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15555 let project_completions = project.completions(buffer, buffer_position, options, cx);
15556 cx.background_executor().spawn(async move {
15557 let mut completions = project_completions.await?;
15558 let snippets_completions = snippets.await?;
15559 completions.extend(snippets_completions);
15560 Ok(completions)
15561 })
15562 })
15563 }
15564
15565 fn resolve_completions(
15566 &self,
15567 buffer: Entity<Buffer>,
15568 completion_indices: Vec<usize>,
15569 completions: Rc<RefCell<Box<[Completion]>>>,
15570 cx: &mut Context<Editor>,
15571 ) -> Task<Result<bool>> {
15572 self.update(cx, |project, cx| {
15573 project.lsp_store().update(cx, |lsp_store, cx| {
15574 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15575 })
15576 })
15577 }
15578
15579 fn apply_additional_edits_for_completion(
15580 &self,
15581 buffer: Entity<Buffer>,
15582 completions: Rc<RefCell<Box<[Completion]>>>,
15583 completion_index: usize,
15584 push_to_history: bool,
15585 cx: &mut Context<Editor>,
15586 ) -> Task<Result<Option<language::Transaction>>> {
15587 self.update(cx, |project, cx| {
15588 project.lsp_store().update(cx, |lsp_store, cx| {
15589 lsp_store.apply_additional_edits_for_completion(
15590 buffer,
15591 completions,
15592 completion_index,
15593 push_to_history,
15594 cx,
15595 )
15596 })
15597 })
15598 }
15599
15600 fn is_completion_trigger(
15601 &self,
15602 buffer: &Entity<Buffer>,
15603 position: language::Anchor,
15604 text: &str,
15605 trigger_in_words: bool,
15606 cx: &mut Context<Editor>,
15607 ) -> bool {
15608 let mut chars = text.chars();
15609 let char = if let Some(char) = chars.next() {
15610 char
15611 } else {
15612 return false;
15613 };
15614 if chars.next().is_some() {
15615 return false;
15616 }
15617
15618 let buffer = buffer.read(cx);
15619 let snapshot = buffer.snapshot();
15620 if !snapshot.settings_at(position, cx).show_completions_on_input {
15621 return false;
15622 }
15623 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15624 if trigger_in_words && classifier.is_word(char) {
15625 return true;
15626 }
15627
15628 buffer.completion_triggers().contains(text)
15629 }
15630}
15631
15632impl SemanticsProvider for Entity<Project> {
15633 fn hover(
15634 &self,
15635 buffer: &Entity<Buffer>,
15636 position: text::Anchor,
15637 cx: &mut App,
15638 ) -> Option<Task<Vec<project::Hover>>> {
15639 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15640 }
15641
15642 fn document_highlights(
15643 &self,
15644 buffer: &Entity<Buffer>,
15645 position: text::Anchor,
15646 cx: &mut App,
15647 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15648 Some(self.update(cx, |project, cx| {
15649 project.document_highlights(buffer, position, cx)
15650 }))
15651 }
15652
15653 fn definitions(
15654 &self,
15655 buffer: &Entity<Buffer>,
15656 position: text::Anchor,
15657 kind: GotoDefinitionKind,
15658 cx: &mut App,
15659 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15660 Some(self.update(cx, |project, cx| match kind {
15661 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15662 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15663 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15664 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15665 }))
15666 }
15667
15668 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15669 // TODO: make this work for remote projects
15670 self.read(cx)
15671 .language_servers_for_local_buffer(buffer.read(cx), cx)
15672 .any(
15673 |(_, server)| match server.capabilities().inlay_hint_provider {
15674 Some(lsp::OneOf::Left(enabled)) => enabled,
15675 Some(lsp::OneOf::Right(_)) => true,
15676 None => false,
15677 },
15678 )
15679 }
15680
15681 fn inlay_hints(
15682 &self,
15683 buffer_handle: Entity<Buffer>,
15684 range: Range<text::Anchor>,
15685 cx: &mut App,
15686 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15687 Some(self.update(cx, |project, cx| {
15688 project.inlay_hints(buffer_handle, range, cx)
15689 }))
15690 }
15691
15692 fn resolve_inlay_hint(
15693 &self,
15694 hint: InlayHint,
15695 buffer_handle: Entity<Buffer>,
15696 server_id: LanguageServerId,
15697 cx: &mut App,
15698 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15699 Some(self.update(cx, |project, cx| {
15700 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15701 }))
15702 }
15703
15704 fn range_for_rename(
15705 &self,
15706 buffer: &Entity<Buffer>,
15707 position: text::Anchor,
15708 cx: &mut App,
15709 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15710 Some(self.update(cx, |project, cx| {
15711 let buffer = buffer.clone();
15712 let task = project.prepare_rename(buffer.clone(), position, cx);
15713 cx.spawn(|_, mut cx| async move {
15714 Ok(match task.await? {
15715 PrepareRenameResponse::Success(range) => Some(range),
15716 PrepareRenameResponse::InvalidPosition => None,
15717 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15718 // Fallback on using TreeSitter info to determine identifier range
15719 buffer.update(&mut cx, |buffer, _| {
15720 let snapshot = buffer.snapshot();
15721 let (range, kind) = snapshot.surrounding_word(position);
15722 if kind != Some(CharKind::Word) {
15723 return None;
15724 }
15725 Some(
15726 snapshot.anchor_before(range.start)
15727 ..snapshot.anchor_after(range.end),
15728 )
15729 })?
15730 }
15731 })
15732 })
15733 }))
15734 }
15735
15736 fn perform_rename(
15737 &self,
15738 buffer: &Entity<Buffer>,
15739 position: text::Anchor,
15740 new_name: String,
15741 cx: &mut App,
15742 ) -> Option<Task<Result<ProjectTransaction>>> {
15743 Some(self.update(cx, |project, cx| {
15744 project.perform_rename(buffer.clone(), position, new_name, cx)
15745 }))
15746 }
15747}
15748
15749fn inlay_hint_settings(
15750 location: Anchor,
15751 snapshot: &MultiBufferSnapshot,
15752 cx: &mut Context<Editor>,
15753) -> InlayHintSettings {
15754 let file = snapshot.file_at(location);
15755 let language = snapshot.language_at(location).map(|l| l.name());
15756 language_settings(language, file, cx).inlay_hints
15757}
15758
15759fn consume_contiguous_rows(
15760 contiguous_row_selections: &mut Vec<Selection<Point>>,
15761 selection: &Selection<Point>,
15762 display_map: &DisplaySnapshot,
15763 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15764) -> (MultiBufferRow, MultiBufferRow) {
15765 contiguous_row_selections.push(selection.clone());
15766 let start_row = MultiBufferRow(selection.start.row);
15767 let mut end_row = ending_row(selection, display_map);
15768
15769 while let Some(next_selection) = selections.peek() {
15770 if next_selection.start.row <= end_row.0 {
15771 end_row = ending_row(next_selection, display_map);
15772 contiguous_row_selections.push(selections.next().unwrap().clone());
15773 } else {
15774 break;
15775 }
15776 }
15777 (start_row, end_row)
15778}
15779
15780fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15781 if next_selection.end.column > 0 || next_selection.is_empty() {
15782 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15783 } else {
15784 MultiBufferRow(next_selection.end.row)
15785 }
15786}
15787
15788impl EditorSnapshot {
15789 pub fn remote_selections_in_range<'a>(
15790 &'a self,
15791 range: &'a Range<Anchor>,
15792 collaboration_hub: &dyn CollaborationHub,
15793 cx: &'a App,
15794 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15795 let participant_names = collaboration_hub.user_names(cx);
15796 let participant_indices = collaboration_hub.user_participant_indices(cx);
15797 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15798 let collaborators_by_replica_id = collaborators_by_peer_id
15799 .iter()
15800 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15801 .collect::<HashMap<_, _>>();
15802 self.buffer_snapshot
15803 .selections_in_range(range, false)
15804 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15805 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15806 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15807 let user_name = participant_names.get(&collaborator.user_id).cloned();
15808 Some(RemoteSelection {
15809 replica_id,
15810 selection,
15811 cursor_shape,
15812 line_mode,
15813 participant_index,
15814 peer_id: collaborator.peer_id,
15815 user_name,
15816 })
15817 })
15818 }
15819
15820 pub fn hunks_for_ranges(
15821 &self,
15822 ranges: impl Iterator<Item = Range<Point>>,
15823 ) -> Vec<MultiBufferDiffHunk> {
15824 let mut hunks = Vec::new();
15825 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15826 HashMap::default();
15827 for query_range in ranges {
15828 let query_rows =
15829 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15830 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15831 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15832 ) {
15833 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15834 // when the caret is just above or just below the deleted hunk.
15835 let allow_adjacent = hunk.status().is_removed();
15836 let related_to_selection = if allow_adjacent {
15837 hunk.row_range.overlaps(&query_rows)
15838 || hunk.row_range.start == query_rows.end
15839 || hunk.row_range.end == query_rows.start
15840 } else {
15841 hunk.row_range.overlaps(&query_rows)
15842 };
15843 if related_to_selection {
15844 if !processed_buffer_rows
15845 .entry(hunk.buffer_id)
15846 .or_default()
15847 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15848 {
15849 continue;
15850 }
15851 hunks.push(hunk);
15852 }
15853 }
15854 }
15855
15856 hunks
15857 }
15858
15859 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15860 self.display_snapshot.buffer_snapshot.language_at(position)
15861 }
15862
15863 pub fn is_focused(&self) -> bool {
15864 self.is_focused
15865 }
15866
15867 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15868 self.placeholder_text.as_ref()
15869 }
15870
15871 pub fn scroll_position(&self) -> gpui::Point<f32> {
15872 self.scroll_anchor.scroll_position(&self.display_snapshot)
15873 }
15874
15875 fn gutter_dimensions(
15876 &self,
15877 font_id: FontId,
15878 font_size: Pixels,
15879 max_line_number_width: Pixels,
15880 cx: &App,
15881 ) -> Option<GutterDimensions> {
15882 if !self.show_gutter {
15883 return None;
15884 }
15885
15886 let descent = cx.text_system().descent(font_id, font_size);
15887 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15888 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15889
15890 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15891 matches!(
15892 ProjectSettings::get_global(cx).git.git_gutter,
15893 Some(GitGutterSetting::TrackedFiles)
15894 )
15895 });
15896 let gutter_settings = EditorSettings::get_global(cx).gutter;
15897 let show_line_numbers = self
15898 .show_line_numbers
15899 .unwrap_or(gutter_settings.line_numbers);
15900 let line_gutter_width = if show_line_numbers {
15901 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15902 let min_width_for_number_on_gutter = em_advance * 4.0;
15903 max_line_number_width.max(min_width_for_number_on_gutter)
15904 } else {
15905 0.0.into()
15906 };
15907
15908 let show_code_actions = self
15909 .show_code_actions
15910 .unwrap_or(gutter_settings.code_actions);
15911
15912 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15913
15914 let git_blame_entries_width =
15915 self.git_blame_gutter_max_author_length
15916 .map(|max_author_length| {
15917 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15918
15919 /// The number of characters to dedicate to gaps and margins.
15920 const SPACING_WIDTH: usize = 4;
15921
15922 let max_char_count = max_author_length
15923 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15924 + ::git::SHORT_SHA_LENGTH
15925 + MAX_RELATIVE_TIMESTAMP.len()
15926 + SPACING_WIDTH;
15927
15928 em_advance * max_char_count
15929 });
15930
15931 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15932 left_padding += if show_code_actions || show_runnables {
15933 em_width * 3.0
15934 } else if show_git_gutter && show_line_numbers {
15935 em_width * 2.0
15936 } else if show_git_gutter || show_line_numbers {
15937 em_width
15938 } else {
15939 px(0.)
15940 };
15941
15942 let right_padding = if gutter_settings.folds && show_line_numbers {
15943 em_width * 4.0
15944 } else if gutter_settings.folds {
15945 em_width * 3.0
15946 } else if show_line_numbers {
15947 em_width
15948 } else {
15949 px(0.)
15950 };
15951
15952 Some(GutterDimensions {
15953 left_padding,
15954 right_padding,
15955 width: line_gutter_width + left_padding + right_padding,
15956 margin: -descent,
15957 git_blame_entries_width,
15958 })
15959 }
15960
15961 pub fn render_crease_toggle(
15962 &self,
15963 buffer_row: MultiBufferRow,
15964 row_contains_cursor: bool,
15965 editor: Entity<Editor>,
15966 window: &mut Window,
15967 cx: &mut App,
15968 ) -> Option<AnyElement> {
15969 let folded = self.is_line_folded(buffer_row);
15970 let mut is_foldable = false;
15971
15972 if let Some(crease) = self
15973 .crease_snapshot
15974 .query_row(buffer_row, &self.buffer_snapshot)
15975 {
15976 is_foldable = true;
15977 match crease {
15978 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15979 if let Some(render_toggle) = render_toggle {
15980 let toggle_callback =
15981 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15982 if folded {
15983 editor.update(cx, |editor, cx| {
15984 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15985 });
15986 } else {
15987 editor.update(cx, |editor, cx| {
15988 editor.unfold_at(
15989 &crate::UnfoldAt { buffer_row },
15990 window,
15991 cx,
15992 )
15993 });
15994 }
15995 });
15996 return Some((render_toggle)(
15997 buffer_row,
15998 folded,
15999 toggle_callback,
16000 window,
16001 cx,
16002 ));
16003 }
16004 }
16005 }
16006 }
16007
16008 is_foldable |= self.starts_indent(buffer_row);
16009
16010 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16011 Some(
16012 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16013 .toggle_state(folded)
16014 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16015 if folded {
16016 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16017 } else {
16018 this.fold_at(&FoldAt { buffer_row }, window, cx);
16019 }
16020 }))
16021 .into_any_element(),
16022 )
16023 } else {
16024 None
16025 }
16026 }
16027
16028 pub fn render_crease_trailer(
16029 &self,
16030 buffer_row: MultiBufferRow,
16031 window: &mut Window,
16032 cx: &mut App,
16033 ) -> Option<AnyElement> {
16034 let folded = self.is_line_folded(buffer_row);
16035 if let Crease::Inline { render_trailer, .. } = self
16036 .crease_snapshot
16037 .query_row(buffer_row, &self.buffer_snapshot)?
16038 {
16039 let render_trailer = render_trailer.as_ref()?;
16040 Some(render_trailer(buffer_row, folded, window, cx))
16041 } else {
16042 None
16043 }
16044 }
16045}
16046
16047impl Deref for EditorSnapshot {
16048 type Target = DisplaySnapshot;
16049
16050 fn deref(&self) -> &Self::Target {
16051 &self.display_snapshot
16052 }
16053}
16054
16055#[derive(Clone, Debug, PartialEq, Eq)]
16056pub enum EditorEvent {
16057 InputIgnored {
16058 text: Arc<str>,
16059 },
16060 InputHandled {
16061 utf16_range_to_replace: Option<Range<isize>>,
16062 text: Arc<str>,
16063 },
16064 ExcerptsAdded {
16065 buffer: Entity<Buffer>,
16066 predecessor: ExcerptId,
16067 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16068 },
16069 ExcerptsRemoved {
16070 ids: Vec<ExcerptId>,
16071 },
16072 BufferFoldToggled {
16073 ids: Vec<ExcerptId>,
16074 folded: bool,
16075 },
16076 ExcerptsEdited {
16077 ids: Vec<ExcerptId>,
16078 },
16079 ExcerptsExpanded {
16080 ids: Vec<ExcerptId>,
16081 },
16082 BufferEdited,
16083 Edited {
16084 transaction_id: clock::Lamport,
16085 },
16086 Reparsed(BufferId),
16087 Focused,
16088 FocusedIn,
16089 Blurred,
16090 DirtyChanged,
16091 Saved,
16092 TitleChanged,
16093 DiffBaseChanged,
16094 SelectionsChanged {
16095 local: bool,
16096 },
16097 ScrollPositionChanged {
16098 local: bool,
16099 autoscroll: bool,
16100 },
16101 Closed,
16102 TransactionUndone {
16103 transaction_id: clock::Lamport,
16104 },
16105 TransactionBegun {
16106 transaction_id: clock::Lamport,
16107 },
16108 Reloaded,
16109 CursorShapeChanged,
16110}
16111
16112impl EventEmitter<EditorEvent> for Editor {}
16113
16114impl Focusable for Editor {
16115 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16116 self.focus_handle.clone()
16117 }
16118}
16119
16120impl Render for Editor {
16121 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16122 let settings = ThemeSettings::get_global(cx);
16123
16124 let mut text_style = match self.mode {
16125 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16126 color: cx.theme().colors().editor_foreground,
16127 font_family: settings.ui_font.family.clone(),
16128 font_features: settings.ui_font.features.clone(),
16129 font_fallbacks: settings.ui_font.fallbacks.clone(),
16130 font_size: rems(0.875).into(),
16131 font_weight: settings.ui_font.weight,
16132 line_height: relative(settings.buffer_line_height.value()),
16133 ..Default::default()
16134 },
16135 EditorMode::Full => TextStyle {
16136 color: cx.theme().colors().editor_foreground,
16137 font_family: settings.buffer_font.family.clone(),
16138 font_features: settings.buffer_font.features.clone(),
16139 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16140 font_size: settings.buffer_font_size().into(),
16141 font_weight: settings.buffer_font.weight,
16142 line_height: relative(settings.buffer_line_height.value()),
16143 ..Default::default()
16144 },
16145 };
16146 if let Some(text_style_refinement) = &self.text_style_refinement {
16147 text_style.refine(text_style_refinement)
16148 }
16149
16150 let background = match self.mode {
16151 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16152 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16153 EditorMode::Full => cx.theme().colors().editor_background,
16154 };
16155
16156 EditorElement::new(
16157 &cx.entity(),
16158 EditorStyle {
16159 background,
16160 local_player: cx.theme().players().local(),
16161 text: text_style,
16162 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16163 syntax: cx.theme().syntax().clone(),
16164 status: cx.theme().status().clone(),
16165 inlay_hints_style: make_inlay_hints_style(cx),
16166 inline_completion_styles: make_suggestion_styles(cx),
16167 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16168 },
16169 )
16170 }
16171}
16172
16173impl EntityInputHandler for Editor {
16174 fn text_for_range(
16175 &mut self,
16176 range_utf16: Range<usize>,
16177 adjusted_range: &mut Option<Range<usize>>,
16178 _: &mut Window,
16179 cx: &mut Context<Self>,
16180 ) -> Option<String> {
16181 let snapshot = self.buffer.read(cx).read(cx);
16182 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16183 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16184 if (start.0..end.0) != range_utf16 {
16185 adjusted_range.replace(start.0..end.0);
16186 }
16187 Some(snapshot.text_for_range(start..end).collect())
16188 }
16189
16190 fn selected_text_range(
16191 &mut self,
16192 ignore_disabled_input: bool,
16193 _: &mut Window,
16194 cx: &mut Context<Self>,
16195 ) -> Option<UTF16Selection> {
16196 // Prevent the IME menu from appearing when holding down an alphabetic key
16197 // while input is disabled.
16198 if !ignore_disabled_input && !self.input_enabled {
16199 return None;
16200 }
16201
16202 let selection = self.selections.newest::<OffsetUtf16>(cx);
16203 let range = selection.range();
16204
16205 Some(UTF16Selection {
16206 range: range.start.0..range.end.0,
16207 reversed: selection.reversed,
16208 })
16209 }
16210
16211 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16212 let snapshot = self.buffer.read(cx).read(cx);
16213 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16214 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16215 }
16216
16217 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16218 self.clear_highlights::<InputComposition>(cx);
16219 self.ime_transaction.take();
16220 }
16221
16222 fn replace_text_in_range(
16223 &mut self,
16224 range_utf16: Option<Range<usize>>,
16225 text: &str,
16226 window: &mut Window,
16227 cx: &mut Context<Self>,
16228 ) {
16229 if !self.input_enabled {
16230 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16231 return;
16232 }
16233
16234 self.transact(window, cx, |this, window, cx| {
16235 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16236 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16237 Some(this.selection_replacement_ranges(range_utf16, cx))
16238 } else {
16239 this.marked_text_ranges(cx)
16240 };
16241
16242 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16243 let newest_selection_id = this.selections.newest_anchor().id;
16244 this.selections
16245 .all::<OffsetUtf16>(cx)
16246 .iter()
16247 .zip(ranges_to_replace.iter())
16248 .find_map(|(selection, range)| {
16249 if selection.id == newest_selection_id {
16250 Some(
16251 (range.start.0 as isize - selection.head().0 as isize)
16252 ..(range.end.0 as isize - selection.head().0 as isize),
16253 )
16254 } else {
16255 None
16256 }
16257 })
16258 });
16259
16260 cx.emit(EditorEvent::InputHandled {
16261 utf16_range_to_replace: range_to_replace,
16262 text: text.into(),
16263 });
16264
16265 if let Some(new_selected_ranges) = new_selected_ranges {
16266 this.change_selections(None, window, cx, |selections| {
16267 selections.select_ranges(new_selected_ranges)
16268 });
16269 this.backspace(&Default::default(), window, cx);
16270 }
16271
16272 this.handle_input(text, window, cx);
16273 });
16274
16275 if let Some(transaction) = self.ime_transaction {
16276 self.buffer.update(cx, |buffer, cx| {
16277 buffer.group_until_transaction(transaction, cx);
16278 });
16279 }
16280
16281 self.unmark_text(window, cx);
16282 }
16283
16284 fn replace_and_mark_text_in_range(
16285 &mut self,
16286 range_utf16: Option<Range<usize>>,
16287 text: &str,
16288 new_selected_range_utf16: Option<Range<usize>>,
16289 window: &mut Window,
16290 cx: &mut Context<Self>,
16291 ) {
16292 if !self.input_enabled {
16293 return;
16294 }
16295
16296 let transaction = self.transact(window, cx, |this, window, cx| {
16297 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16298 let snapshot = this.buffer.read(cx).read(cx);
16299 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16300 for marked_range in &mut marked_ranges {
16301 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16302 marked_range.start.0 += relative_range_utf16.start;
16303 marked_range.start =
16304 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16305 marked_range.end =
16306 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16307 }
16308 }
16309 Some(marked_ranges)
16310 } else if let Some(range_utf16) = range_utf16 {
16311 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16312 Some(this.selection_replacement_ranges(range_utf16, cx))
16313 } else {
16314 None
16315 };
16316
16317 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16318 let newest_selection_id = this.selections.newest_anchor().id;
16319 this.selections
16320 .all::<OffsetUtf16>(cx)
16321 .iter()
16322 .zip(ranges_to_replace.iter())
16323 .find_map(|(selection, range)| {
16324 if selection.id == newest_selection_id {
16325 Some(
16326 (range.start.0 as isize - selection.head().0 as isize)
16327 ..(range.end.0 as isize - selection.head().0 as isize),
16328 )
16329 } else {
16330 None
16331 }
16332 })
16333 });
16334
16335 cx.emit(EditorEvent::InputHandled {
16336 utf16_range_to_replace: range_to_replace,
16337 text: text.into(),
16338 });
16339
16340 if let Some(ranges) = ranges_to_replace {
16341 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16342 }
16343
16344 let marked_ranges = {
16345 let snapshot = this.buffer.read(cx).read(cx);
16346 this.selections
16347 .disjoint_anchors()
16348 .iter()
16349 .map(|selection| {
16350 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16351 })
16352 .collect::<Vec<_>>()
16353 };
16354
16355 if text.is_empty() {
16356 this.unmark_text(window, cx);
16357 } else {
16358 this.highlight_text::<InputComposition>(
16359 marked_ranges.clone(),
16360 HighlightStyle {
16361 underline: Some(UnderlineStyle {
16362 thickness: px(1.),
16363 color: None,
16364 wavy: false,
16365 }),
16366 ..Default::default()
16367 },
16368 cx,
16369 );
16370 }
16371
16372 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16373 let use_autoclose = this.use_autoclose;
16374 let use_auto_surround = this.use_auto_surround;
16375 this.set_use_autoclose(false);
16376 this.set_use_auto_surround(false);
16377 this.handle_input(text, window, cx);
16378 this.set_use_autoclose(use_autoclose);
16379 this.set_use_auto_surround(use_auto_surround);
16380
16381 if let Some(new_selected_range) = new_selected_range_utf16 {
16382 let snapshot = this.buffer.read(cx).read(cx);
16383 let new_selected_ranges = marked_ranges
16384 .into_iter()
16385 .map(|marked_range| {
16386 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16387 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16388 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16389 snapshot.clip_offset_utf16(new_start, Bias::Left)
16390 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16391 })
16392 .collect::<Vec<_>>();
16393
16394 drop(snapshot);
16395 this.change_selections(None, window, cx, |selections| {
16396 selections.select_ranges(new_selected_ranges)
16397 });
16398 }
16399 });
16400
16401 self.ime_transaction = self.ime_transaction.or(transaction);
16402 if let Some(transaction) = self.ime_transaction {
16403 self.buffer.update(cx, |buffer, cx| {
16404 buffer.group_until_transaction(transaction, cx);
16405 });
16406 }
16407
16408 if self.text_highlights::<InputComposition>(cx).is_none() {
16409 self.ime_transaction.take();
16410 }
16411 }
16412
16413 fn bounds_for_range(
16414 &mut self,
16415 range_utf16: Range<usize>,
16416 element_bounds: gpui::Bounds<Pixels>,
16417 window: &mut Window,
16418 cx: &mut Context<Self>,
16419 ) -> Option<gpui::Bounds<Pixels>> {
16420 let text_layout_details = self.text_layout_details(window);
16421 let gpui::Size {
16422 width: em_width,
16423 height: line_height,
16424 } = self.character_size(window);
16425
16426 let snapshot = self.snapshot(window, cx);
16427 let scroll_position = snapshot.scroll_position();
16428 let scroll_left = scroll_position.x * em_width;
16429
16430 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16431 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16432 + self.gutter_dimensions.width
16433 + self.gutter_dimensions.margin;
16434 let y = line_height * (start.row().as_f32() - scroll_position.y);
16435
16436 Some(Bounds {
16437 origin: element_bounds.origin + point(x, y),
16438 size: size(em_width, line_height),
16439 })
16440 }
16441
16442 fn character_index_for_point(
16443 &mut self,
16444 point: gpui::Point<Pixels>,
16445 _window: &mut Window,
16446 _cx: &mut Context<Self>,
16447 ) -> Option<usize> {
16448 let position_map = self.last_position_map.as_ref()?;
16449 if !position_map.text_hitbox.contains(&point) {
16450 return None;
16451 }
16452 let display_point = position_map.point_for_position(point).previous_valid;
16453 let anchor = position_map
16454 .snapshot
16455 .display_point_to_anchor(display_point, Bias::Left);
16456 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16457 Some(utf16_offset.0)
16458 }
16459}
16460
16461trait SelectionExt {
16462 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16463 fn spanned_rows(
16464 &self,
16465 include_end_if_at_line_start: bool,
16466 map: &DisplaySnapshot,
16467 ) -> Range<MultiBufferRow>;
16468}
16469
16470impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16471 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16472 let start = self
16473 .start
16474 .to_point(&map.buffer_snapshot)
16475 .to_display_point(map);
16476 let end = self
16477 .end
16478 .to_point(&map.buffer_snapshot)
16479 .to_display_point(map);
16480 if self.reversed {
16481 end..start
16482 } else {
16483 start..end
16484 }
16485 }
16486
16487 fn spanned_rows(
16488 &self,
16489 include_end_if_at_line_start: bool,
16490 map: &DisplaySnapshot,
16491 ) -> Range<MultiBufferRow> {
16492 let start = self.start.to_point(&map.buffer_snapshot);
16493 let mut end = self.end.to_point(&map.buffer_snapshot);
16494 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16495 end.row -= 1;
16496 }
16497
16498 let buffer_start = map.prev_line_boundary(start).0;
16499 let buffer_end = map.next_line_boundary(end).0;
16500 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16501 }
16502}
16503
16504impl<T: InvalidationRegion> InvalidationStack<T> {
16505 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16506 where
16507 S: Clone + ToOffset,
16508 {
16509 while let Some(region) = self.last() {
16510 let all_selections_inside_invalidation_ranges =
16511 if selections.len() == region.ranges().len() {
16512 selections
16513 .iter()
16514 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16515 .all(|(selection, invalidation_range)| {
16516 let head = selection.head().to_offset(buffer);
16517 invalidation_range.start <= head && invalidation_range.end >= head
16518 })
16519 } else {
16520 false
16521 };
16522
16523 if all_selections_inside_invalidation_ranges {
16524 break;
16525 } else {
16526 self.pop();
16527 }
16528 }
16529 }
16530}
16531
16532impl<T> Default for InvalidationStack<T> {
16533 fn default() -> Self {
16534 Self(Default::default())
16535 }
16536}
16537
16538impl<T> Deref for InvalidationStack<T> {
16539 type Target = Vec<T>;
16540
16541 fn deref(&self) -> &Self::Target {
16542 &self.0
16543 }
16544}
16545
16546impl<T> DerefMut for InvalidationStack<T> {
16547 fn deref_mut(&mut self) -> &mut Self::Target {
16548 &mut self.0
16549 }
16550}
16551
16552impl InvalidationRegion for SnippetState {
16553 fn ranges(&self) -> &[Range<Anchor>] {
16554 &self.ranges[self.active_index]
16555 }
16556}
16557
16558pub fn diagnostic_block_renderer(
16559 diagnostic: Diagnostic,
16560 max_message_rows: Option<u8>,
16561 allow_closing: bool,
16562 _is_valid: bool,
16563) -> RenderBlock {
16564 let (text_without_backticks, code_ranges) =
16565 highlight_diagnostic_message(&diagnostic, max_message_rows);
16566
16567 Arc::new(move |cx: &mut BlockContext| {
16568 let group_id: SharedString = cx.block_id.to_string().into();
16569
16570 let mut text_style = cx.window.text_style().clone();
16571 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16572 let theme_settings = ThemeSettings::get_global(cx);
16573 text_style.font_family = theme_settings.buffer_font.family.clone();
16574 text_style.font_style = theme_settings.buffer_font.style;
16575 text_style.font_features = theme_settings.buffer_font.features.clone();
16576 text_style.font_weight = theme_settings.buffer_font.weight;
16577
16578 let multi_line_diagnostic = diagnostic.message.contains('\n');
16579
16580 let buttons = |diagnostic: &Diagnostic| {
16581 if multi_line_diagnostic {
16582 v_flex()
16583 } else {
16584 h_flex()
16585 }
16586 .when(allow_closing, |div| {
16587 div.children(diagnostic.is_primary.then(|| {
16588 IconButton::new("close-block", IconName::XCircle)
16589 .icon_color(Color::Muted)
16590 .size(ButtonSize::Compact)
16591 .style(ButtonStyle::Transparent)
16592 .visible_on_hover(group_id.clone())
16593 .on_click(move |_click, window, cx| {
16594 window.dispatch_action(Box::new(Cancel), cx)
16595 })
16596 .tooltip(|window, cx| {
16597 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16598 })
16599 }))
16600 })
16601 .child(
16602 IconButton::new("copy-block", IconName::Copy)
16603 .icon_color(Color::Muted)
16604 .size(ButtonSize::Compact)
16605 .style(ButtonStyle::Transparent)
16606 .visible_on_hover(group_id.clone())
16607 .on_click({
16608 let message = diagnostic.message.clone();
16609 move |_click, _, cx| {
16610 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16611 }
16612 })
16613 .tooltip(Tooltip::text("Copy diagnostic message")),
16614 )
16615 };
16616
16617 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16618 AvailableSpace::min_size(),
16619 cx.window,
16620 cx.app,
16621 );
16622
16623 h_flex()
16624 .id(cx.block_id)
16625 .group(group_id.clone())
16626 .relative()
16627 .size_full()
16628 .block_mouse_down()
16629 .pl(cx.gutter_dimensions.width)
16630 .w(cx.max_width - cx.gutter_dimensions.full_width())
16631 .child(
16632 div()
16633 .flex()
16634 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16635 .flex_shrink(),
16636 )
16637 .child(buttons(&diagnostic))
16638 .child(div().flex().flex_shrink_0().child(
16639 StyledText::new(text_without_backticks.clone()).with_highlights(
16640 &text_style,
16641 code_ranges.iter().map(|range| {
16642 (
16643 range.clone(),
16644 HighlightStyle {
16645 font_weight: Some(FontWeight::BOLD),
16646 ..Default::default()
16647 },
16648 )
16649 }),
16650 ),
16651 ))
16652 .into_any_element()
16653 })
16654}
16655
16656fn inline_completion_edit_text(
16657 current_snapshot: &BufferSnapshot,
16658 edits: &[(Range<Anchor>, String)],
16659 edit_preview: &EditPreview,
16660 include_deletions: bool,
16661 cx: &App,
16662) -> HighlightedText {
16663 let edits = edits
16664 .iter()
16665 .map(|(anchor, text)| {
16666 (
16667 anchor.start.text_anchor..anchor.end.text_anchor,
16668 text.clone(),
16669 )
16670 })
16671 .collect::<Vec<_>>();
16672
16673 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16674}
16675
16676pub fn highlight_diagnostic_message(
16677 diagnostic: &Diagnostic,
16678 mut max_message_rows: Option<u8>,
16679) -> (SharedString, Vec<Range<usize>>) {
16680 let mut text_without_backticks = String::new();
16681 let mut code_ranges = Vec::new();
16682
16683 if let Some(source) = &diagnostic.source {
16684 text_without_backticks.push_str(source);
16685 code_ranges.push(0..source.len());
16686 text_without_backticks.push_str(": ");
16687 }
16688
16689 let mut prev_offset = 0;
16690 let mut in_code_block = false;
16691 let has_row_limit = max_message_rows.is_some();
16692 let mut newline_indices = diagnostic
16693 .message
16694 .match_indices('\n')
16695 .filter(|_| has_row_limit)
16696 .map(|(ix, _)| ix)
16697 .fuse()
16698 .peekable();
16699
16700 for (quote_ix, _) in diagnostic
16701 .message
16702 .match_indices('`')
16703 .chain([(diagnostic.message.len(), "")])
16704 {
16705 let mut first_newline_ix = None;
16706 let mut last_newline_ix = None;
16707 while let Some(newline_ix) = newline_indices.peek() {
16708 if *newline_ix < quote_ix {
16709 if first_newline_ix.is_none() {
16710 first_newline_ix = Some(*newline_ix);
16711 }
16712 last_newline_ix = Some(*newline_ix);
16713
16714 if let Some(rows_left) = &mut max_message_rows {
16715 if *rows_left == 0 {
16716 break;
16717 } else {
16718 *rows_left -= 1;
16719 }
16720 }
16721 let _ = newline_indices.next();
16722 } else {
16723 break;
16724 }
16725 }
16726 let prev_len = text_without_backticks.len();
16727 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16728 text_without_backticks.push_str(new_text);
16729 if in_code_block {
16730 code_ranges.push(prev_len..text_without_backticks.len());
16731 }
16732 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16733 in_code_block = !in_code_block;
16734 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16735 text_without_backticks.push_str("...");
16736 break;
16737 }
16738 }
16739
16740 (text_without_backticks.into(), code_ranges)
16741}
16742
16743fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16744 match severity {
16745 DiagnosticSeverity::ERROR => colors.error,
16746 DiagnosticSeverity::WARNING => colors.warning,
16747 DiagnosticSeverity::INFORMATION => colors.info,
16748 DiagnosticSeverity::HINT => colors.info,
16749 _ => colors.ignored,
16750 }
16751}
16752
16753pub fn styled_runs_for_code_label<'a>(
16754 label: &'a CodeLabel,
16755 syntax_theme: &'a theme::SyntaxTheme,
16756) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16757 let fade_out = HighlightStyle {
16758 fade_out: Some(0.35),
16759 ..Default::default()
16760 };
16761
16762 let mut prev_end = label.filter_range.end;
16763 label
16764 .runs
16765 .iter()
16766 .enumerate()
16767 .flat_map(move |(ix, (range, highlight_id))| {
16768 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16769 style
16770 } else {
16771 return Default::default();
16772 };
16773 let mut muted_style = style;
16774 muted_style.highlight(fade_out);
16775
16776 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16777 if range.start >= label.filter_range.end {
16778 if range.start > prev_end {
16779 runs.push((prev_end..range.start, fade_out));
16780 }
16781 runs.push((range.clone(), muted_style));
16782 } else if range.end <= label.filter_range.end {
16783 runs.push((range.clone(), style));
16784 } else {
16785 runs.push((range.start..label.filter_range.end, style));
16786 runs.push((label.filter_range.end..range.end, muted_style));
16787 }
16788 prev_end = cmp::max(prev_end, range.end);
16789
16790 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16791 runs.push((prev_end..label.text.len(), fade_out));
16792 }
16793
16794 runs
16795 })
16796}
16797
16798pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16799 let mut prev_index = 0;
16800 let mut prev_codepoint: Option<char> = None;
16801 text.char_indices()
16802 .chain([(text.len(), '\0')])
16803 .filter_map(move |(index, codepoint)| {
16804 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16805 let is_boundary = index == text.len()
16806 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16807 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16808 if is_boundary {
16809 let chunk = &text[prev_index..index];
16810 prev_index = index;
16811 Some(chunk)
16812 } else {
16813 None
16814 }
16815 })
16816}
16817
16818pub trait RangeToAnchorExt: Sized {
16819 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16820
16821 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16822 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16823 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16824 }
16825}
16826
16827impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16828 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16829 let start_offset = self.start.to_offset(snapshot);
16830 let end_offset = self.end.to_offset(snapshot);
16831 if start_offset == end_offset {
16832 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16833 } else {
16834 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16835 }
16836 }
16837}
16838
16839pub trait RowExt {
16840 fn as_f32(&self) -> f32;
16841
16842 fn next_row(&self) -> Self;
16843
16844 fn previous_row(&self) -> Self;
16845
16846 fn minus(&self, other: Self) -> u32;
16847}
16848
16849impl RowExt for DisplayRow {
16850 fn as_f32(&self) -> f32 {
16851 self.0 as f32
16852 }
16853
16854 fn next_row(&self) -> Self {
16855 Self(self.0 + 1)
16856 }
16857
16858 fn previous_row(&self) -> Self {
16859 Self(self.0.saturating_sub(1))
16860 }
16861
16862 fn minus(&self, other: Self) -> u32 {
16863 self.0 - other.0
16864 }
16865}
16866
16867impl RowExt for MultiBufferRow {
16868 fn as_f32(&self) -> f32 {
16869 self.0 as f32
16870 }
16871
16872 fn next_row(&self) -> Self {
16873 Self(self.0 + 1)
16874 }
16875
16876 fn previous_row(&self) -> Self {
16877 Self(self.0.saturating_sub(1))
16878 }
16879
16880 fn minus(&self, other: Self) -> u32 {
16881 self.0 - other.0
16882 }
16883}
16884
16885trait RowRangeExt {
16886 type Row;
16887
16888 fn len(&self) -> usize;
16889
16890 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16891}
16892
16893impl RowRangeExt for Range<MultiBufferRow> {
16894 type Row = MultiBufferRow;
16895
16896 fn len(&self) -> usize {
16897 (self.end.0 - self.start.0) as usize
16898 }
16899
16900 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16901 (self.start.0..self.end.0).map(MultiBufferRow)
16902 }
16903}
16904
16905impl RowRangeExt for Range<DisplayRow> {
16906 type Row = DisplayRow;
16907
16908 fn len(&self) -> usize {
16909 (self.end.0 - self.start.0) as usize
16910 }
16911
16912 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16913 (self.start.0..self.end.0).map(DisplayRow)
16914 }
16915}
16916
16917/// If select range has more than one line, we
16918/// just point the cursor to range.start.
16919fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16920 if range.start.row == range.end.row {
16921 range
16922 } else {
16923 range.start..range.start
16924 }
16925}
16926pub struct KillRing(ClipboardItem);
16927impl Global for KillRing {}
16928
16929const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16930
16931fn all_edits_insertions_or_deletions(
16932 edits: &Vec<(Range<Anchor>, String)>,
16933 snapshot: &MultiBufferSnapshot,
16934) -> bool {
16935 let mut all_insertions = true;
16936 let mut all_deletions = true;
16937
16938 for (range, new_text) in edits.iter() {
16939 let range_is_empty = range.to_offset(&snapshot).is_empty();
16940 let text_is_empty = new_text.is_empty();
16941
16942 if range_is_empty != text_is_empty {
16943 if range_is_empty {
16944 all_deletions = false;
16945 } else {
16946 all_insertions = false;
16947 }
16948 } else {
16949 return false;
16950 }
16951
16952 if !all_insertions && !all_deletions {
16953 return false;
16954 }
16955 }
16956 all_insertions || all_deletions
16957}