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 let showing_completions = self
1595 .context_menu
1596 .borrow()
1597 .as_ref()
1598 .map_or(false, |context| {
1599 matches!(context, CodeContextMenu::Completions(_))
1600 });
1601
1602 showing_completions
1603 || self.edit_prediction_requires_modifier()
1604 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1605 // bindings to insert tab characters.
1606 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1607 }
1608
1609 pub fn accept_edit_prediction_keybind(
1610 &self,
1611 window: &Window,
1612 cx: &App,
1613 ) -> AcceptEditPredictionBinding {
1614 let key_context = self.key_context_internal(true, window, cx);
1615 let in_conflict = self.edit_prediction_in_conflict();
1616 AcceptEditPredictionBinding(
1617 window
1618 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1619 .into_iter()
1620 .filter(|binding| {
1621 !in_conflict
1622 || binding
1623 .keystrokes()
1624 .first()
1625 .map_or(false, |keystroke| keystroke.modifiers.modified())
1626 })
1627 .rev()
1628 .next(),
1629 )
1630 }
1631
1632 pub fn new_file(
1633 workspace: &mut Workspace,
1634 _: &workspace::NewFile,
1635 window: &mut Window,
1636 cx: &mut Context<Workspace>,
1637 ) {
1638 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1639 "Failed to create buffer",
1640 window,
1641 cx,
1642 |e, _, _| match e.error_code() {
1643 ErrorCode::RemoteUpgradeRequired => Some(format!(
1644 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1645 e.error_tag("required").unwrap_or("the latest version")
1646 )),
1647 _ => None,
1648 },
1649 );
1650 }
1651
1652 pub fn new_in_workspace(
1653 workspace: &mut Workspace,
1654 window: &mut Window,
1655 cx: &mut Context<Workspace>,
1656 ) -> Task<Result<Entity<Editor>>> {
1657 let project = workspace.project().clone();
1658 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1659
1660 cx.spawn_in(window, |workspace, mut cx| async move {
1661 let buffer = create.await?;
1662 workspace.update_in(&mut cx, |workspace, window, cx| {
1663 let editor =
1664 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1665 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1666 editor
1667 })
1668 })
1669 }
1670
1671 fn new_file_vertical(
1672 workspace: &mut Workspace,
1673 _: &workspace::NewFileSplitVertical,
1674 window: &mut Window,
1675 cx: &mut Context<Workspace>,
1676 ) {
1677 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1678 }
1679
1680 fn new_file_horizontal(
1681 workspace: &mut Workspace,
1682 _: &workspace::NewFileSplitHorizontal,
1683 window: &mut Window,
1684 cx: &mut Context<Workspace>,
1685 ) {
1686 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1687 }
1688
1689 fn new_file_in_direction(
1690 workspace: &mut Workspace,
1691 direction: SplitDirection,
1692 window: &mut Window,
1693 cx: &mut Context<Workspace>,
1694 ) {
1695 let project = workspace.project().clone();
1696 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1697
1698 cx.spawn_in(window, |workspace, mut cx| async move {
1699 let buffer = create.await?;
1700 workspace.update_in(&mut cx, move |workspace, window, cx| {
1701 workspace.split_item(
1702 direction,
1703 Box::new(
1704 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1705 ),
1706 window,
1707 cx,
1708 )
1709 })?;
1710 anyhow::Ok(())
1711 })
1712 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1713 match e.error_code() {
1714 ErrorCode::RemoteUpgradeRequired => Some(format!(
1715 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1716 e.error_tag("required").unwrap_or("the latest version")
1717 )),
1718 _ => None,
1719 }
1720 });
1721 }
1722
1723 pub fn leader_peer_id(&self) -> Option<PeerId> {
1724 self.leader_peer_id
1725 }
1726
1727 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1728 &self.buffer
1729 }
1730
1731 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1732 self.workspace.as_ref()?.0.upgrade()
1733 }
1734
1735 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1736 self.buffer().read(cx).title(cx)
1737 }
1738
1739 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1740 let git_blame_gutter_max_author_length = self
1741 .render_git_blame_gutter(cx)
1742 .then(|| {
1743 if let Some(blame) = self.blame.as_ref() {
1744 let max_author_length =
1745 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1746 Some(max_author_length)
1747 } else {
1748 None
1749 }
1750 })
1751 .flatten();
1752
1753 EditorSnapshot {
1754 mode: self.mode,
1755 show_gutter: self.show_gutter,
1756 show_line_numbers: self.show_line_numbers,
1757 show_git_diff_gutter: self.show_git_diff_gutter,
1758 show_code_actions: self.show_code_actions,
1759 show_runnables: self.show_runnables,
1760 git_blame_gutter_max_author_length,
1761 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1762 scroll_anchor: self.scroll_manager.anchor(),
1763 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1764 placeholder_text: self.placeholder_text.clone(),
1765 is_focused: self.focus_handle.is_focused(window),
1766 current_line_highlight: self
1767 .current_line_highlight
1768 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1769 gutter_hovered: self.gutter_hovered,
1770 }
1771 }
1772
1773 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1774 self.buffer.read(cx).language_at(point, cx)
1775 }
1776
1777 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1778 self.buffer.read(cx).read(cx).file_at(point).cloned()
1779 }
1780
1781 pub fn active_excerpt(
1782 &self,
1783 cx: &App,
1784 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1785 self.buffer
1786 .read(cx)
1787 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1788 }
1789
1790 pub fn mode(&self) -> EditorMode {
1791 self.mode
1792 }
1793
1794 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1795 self.collaboration_hub.as_deref()
1796 }
1797
1798 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1799 self.collaboration_hub = Some(hub);
1800 }
1801
1802 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1803 self.in_project_search = in_project_search;
1804 }
1805
1806 pub fn set_custom_context_menu(
1807 &mut self,
1808 f: impl 'static
1809 + Fn(
1810 &mut Self,
1811 DisplayPoint,
1812 &mut Window,
1813 &mut Context<Self>,
1814 ) -> Option<Entity<ui::ContextMenu>>,
1815 ) {
1816 self.custom_context_menu = Some(Box::new(f))
1817 }
1818
1819 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1820 self.completion_provider = provider;
1821 }
1822
1823 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1824 self.semantics_provider.clone()
1825 }
1826
1827 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1828 self.semantics_provider = provider;
1829 }
1830
1831 pub fn set_edit_prediction_provider<T>(
1832 &mut self,
1833 provider: Option<Entity<T>>,
1834 window: &mut Window,
1835 cx: &mut Context<Self>,
1836 ) where
1837 T: EditPredictionProvider,
1838 {
1839 self.edit_prediction_provider =
1840 provider.map(|provider| RegisteredInlineCompletionProvider {
1841 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1842 if this.focus_handle.is_focused(window) {
1843 this.update_visible_inline_completion(window, cx);
1844 }
1845 }),
1846 provider: Arc::new(provider),
1847 });
1848 self.refresh_inline_completion(false, false, window, cx);
1849 }
1850
1851 pub fn placeholder_text(&self) -> Option<&str> {
1852 self.placeholder_text.as_deref()
1853 }
1854
1855 pub fn set_placeholder_text(
1856 &mut self,
1857 placeholder_text: impl Into<Arc<str>>,
1858 cx: &mut Context<Self>,
1859 ) {
1860 let placeholder_text = Some(placeholder_text.into());
1861 if self.placeholder_text != placeholder_text {
1862 self.placeholder_text = placeholder_text;
1863 cx.notify();
1864 }
1865 }
1866
1867 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1868 self.cursor_shape = cursor_shape;
1869
1870 // Disrupt blink for immediate user feedback that the cursor shape has changed
1871 self.blink_manager.update(cx, BlinkManager::show_cursor);
1872
1873 cx.notify();
1874 }
1875
1876 pub fn set_current_line_highlight(
1877 &mut self,
1878 current_line_highlight: Option<CurrentLineHighlight>,
1879 ) {
1880 self.current_line_highlight = current_line_highlight;
1881 }
1882
1883 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1884 self.collapse_matches = collapse_matches;
1885 }
1886
1887 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1888 let buffers = self.buffer.read(cx).all_buffers();
1889 let Some(lsp_store) = self.lsp_store(cx) else {
1890 return;
1891 };
1892 lsp_store.update(cx, |lsp_store, cx| {
1893 for buffer in buffers {
1894 self.registered_buffers
1895 .entry(buffer.read(cx).remote_id())
1896 .or_insert_with(|| {
1897 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1898 });
1899 }
1900 })
1901 }
1902
1903 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1904 if self.collapse_matches {
1905 return range.start..range.start;
1906 }
1907 range.clone()
1908 }
1909
1910 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1911 if self.display_map.read(cx).clip_at_line_ends != clip {
1912 self.display_map
1913 .update(cx, |map, _| map.clip_at_line_ends = clip);
1914 }
1915 }
1916
1917 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1918 self.input_enabled = input_enabled;
1919 }
1920
1921 pub fn set_inline_completions_hidden_for_vim_mode(
1922 &mut self,
1923 hidden: bool,
1924 window: &mut Window,
1925 cx: &mut Context<Self>,
1926 ) {
1927 if hidden != self.inline_completions_hidden_for_vim_mode {
1928 self.inline_completions_hidden_for_vim_mode = hidden;
1929 if hidden {
1930 self.update_visible_inline_completion(window, cx);
1931 } else {
1932 self.refresh_inline_completion(true, false, window, cx);
1933 }
1934 }
1935 }
1936
1937 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1938 self.menu_inline_completions_policy = value;
1939 }
1940
1941 pub fn set_autoindent(&mut self, autoindent: bool) {
1942 if autoindent {
1943 self.autoindent_mode = Some(AutoindentMode::EachLine);
1944 } else {
1945 self.autoindent_mode = None;
1946 }
1947 }
1948
1949 pub fn read_only(&self, cx: &App) -> bool {
1950 self.read_only || self.buffer.read(cx).read_only()
1951 }
1952
1953 pub fn set_read_only(&mut self, read_only: bool) {
1954 self.read_only = read_only;
1955 }
1956
1957 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1958 self.use_autoclose = autoclose;
1959 }
1960
1961 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1962 self.use_auto_surround = auto_surround;
1963 }
1964
1965 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1966 self.auto_replace_emoji_shortcode = auto_replace;
1967 }
1968
1969 pub fn toggle_inline_completions(
1970 &mut self,
1971 _: &ToggleEditPrediction,
1972 window: &mut Window,
1973 cx: &mut Context<Self>,
1974 ) {
1975 if self.show_inline_completions_override.is_some() {
1976 self.set_show_edit_predictions(None, window, cx);
1977 } else {
1978 let show_edit_predictions = !self.edit_predictions_enabled();
1979 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1980 }
1981 }
1982
1983 pub fn set_show_edit_predictions(
1984 &mut self,
1985 show_edit_predictions: Option<bool>,
1986 window: &mut Window,
1987 cx: &mut Context<Self>,
1988 ) {
1989 self.show_inline_completions_override = show_edit_predictions;
1990 self.refresh_inline_completion(false, true, window, cx);
1991 }
1992
1993 fn inline_completions_disabled_in_scope(
1994 &self,
1995 buffer: &Entity<Buffer>,
1996 buffer_position: language::Anchor,
1997 cx: &App,
1998 ) -> bool {
1999 let snapshot = buffer.read(cx).snapshot();
2000 let settings = snapshot.settings_at(buffer_position, cx);
2001
2002 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2003 return false;
2004 };
2005
2006 scope.override_name().map_or(false, |scope_name| {
2007 settings
2008 .edit_predictions_disabled_in
2009 .iter()
2010 .any(|s| s == scope_name)
2011 })
2012 }
2013
2014 pub fn set_use_modal_editing(&mut self, to: bool) {
2015 self.use_modal_editing = to;
2016 }
2017
2018 pub fn use_modal_editing(&self) -> bool {
2019 self.use_modal_editing
2020 }
2021
2022 fn selections_did_change(
2023 &mut self,
2024 local: bool,
2025 old_cursor_position: &Anchor,
2026 show_completions: bool,
2027 window: &mut Window,
2028 cx: &mut Context<Self>,
2029 ) {
2030 window.invalidate_character_coordinates();
2031
2032 // Copy selections to primary selection buffer
2033 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2034 if local {
2035 let selections = self.selections.all::<usize>(cx);
2036 let buffer_handle = self.buffer.read(cx).read(cx);
2037
2038 let mut text = String::new();
2039 for (index, selection) in selections.iter().enumerate() {
2040 let text_for_selection = buffer_handle
2041 .text_for_range(selection.start..selection.end)
2042 .collect::<String>();
2043
2044 text.push_str(&text_for_selection);
2045 if index != selections.len() - 1 {
2046 text.push('\n');
2047 }
2048 }
2049
2050 if !text.is_empty() {
2051 cx.write_to_primary(ClipboardItem::new_string(text));
2052 }
2053 }
2054
2055 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2056 self.buffer.update(cx, |buffer, cx| {
2057 buffer.set_active_selections(
2058 &self.selections.disjoint_anchors(),
2059 self.selections.line_mode,
2060 self.cursor_shape,
2061 cx,
2062 )
2063 });
2064 }
2065 let display_map = self
2066 .display_map
2067 .update(cx, |display_map, cx| display_map.snapshot(cx));
2068 let buffer = &display_map.buffer_snapshot;
2069 self.add_selections_state = None;
2070 self.select_next_state = None;
2071 self.select_prev_state = None;
2072 self.select_larger_syntax_node_stack.clear();
2073 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2074 self.snippet_stack
2075 .invalidate(&self.selections.disjoint_anchors(), buffer);
2076 self.take_rename(false, window, cx);
2077
2078 let new_cursor_position = self.selections.newest_anchor().head();
2079
2080 self.push_to_nav_history(
2081 *old_cursor_position,
2082 Some(new_cursor_position.to_point(buffer)),
2083 cx,
2084 );
2085
2086 if local {
2087 let new_cursor_position = self.selections.newest_anchor().head();
2088 let mut context_menu = self.context_menu.borrow_mut();
2089 let completion_menu = match context_menu.as_ref() {
2090 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2091 _ => {
2092 *context_menu = None;
2093 None
2094 }
2095 };
2096 if let Some(buffer_id) = new_cursor_position.buffer_id {
2097 if !self.registered_buffers.contains_key(&buffer_id) {
2098 if let Some(lsp_store) = self.lsp_store(cx) {
2099 lsp_store.update(cx, |lsp_store, cx| {
2100 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2101 return;
2102 };
2103 self.registered_buffers.insert(
2104 buffer_id,
2105 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2106 );
2107 })
2108 }
2109 }
2110 }
2111
2112 if let Some(completion_menu) = completion_menu {
2113 let cursor_position = new_cursor_position.to_offset(buffer);
2114 let (word_range, kind) =
2115 buffer.surrounding_word(completion_menu.initial_position, true);
2116 if kind == Some(CharKind::Word)
2117 && word_range.to_inclusive().contains(&cursor_position)
2118 {
2119 let mut completion_menu = completion_menu.clone();
2120 drop(context_menu);
2121
2122 let query = Self::completion_query(buffer, cursor_position);
2123 cx.spawn(move |this, mut cx| async move {
2124 completion_menu
2125 .filter(query.as_deref(), cx.background_executor().clone())
2126 .await;
2127
2128 this.update(&mut cx, |this, cx| {
2129 let mut context_menu = this.context_menu.borrow_mut();
2130 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2131 else {
2132 return;
2133 };
2134
2135 if menu.id > completion_menu.id {
2136 return;
2137 }
2138
2139 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2140 drop(context_menu);
2141 cx.notify();
2142 })
2143 })
2144 .detach();
2145
2146 if show_completions {
2147 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2148 }
2149 } else {
2150 drop(context_menu);
2151 self.hide_context_menu(window, cx);
2152 }
2153 } else {
2154 drop(context_menu);
2155 }
2156
2157 hide_hover(self, cx);
2158
2159 if old_cursor_position.to_display_point(&display_map).row()
2160 != new_cursor_position.to_display_point(&display_map).row()
2161 {
2162 self.available_code_actions.take();
2163 }
2164 self.refresh_code_actions(window, cx);
2165 self.refresh_document_highlights(cx);
2166 refresh_matching_bracket_highlights(self, window, cx);
2167 self.update_visible_inline_completion(window, cx);
2168 self.edit_prediction_requires_modifier_in_leading_space = true;
2169 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2170 if self.git_blame_inline_enabled {
2171 self.start_inline_blame_timer(window, cx);
2172 }
2173 }
2174
2175 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2176 cx.emit(EditorEvent::SelectionsChanged { local });
2177
2178 if self.selections.disjoint_anchors().len() == 1 {
2179 cx.emit(SearchEvent::ActiveMatchChanged)
2180 }
2181 cx.notify();
2182 }
2183
2184 pub fn change_selections<R>(
2185 &mut self,
2186 autoscroll: Option<Autoscroll>,
2187 window: &mut Window,
2188 cx: &mut Context<Self>,
2189 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2190 ) -> R {
2191 self.change_selections_inner(autoscroll, true, window, cx, change)
2192 }
2193
2194 pub fn change_selections_inner<R>(
2195 &mut self,
2196 autoscroll: Option<Autoscroll>,
2197 request_completions: bool,
2198 window: &mut Window,
2199 cx: &mut Context<Self>,
2200 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2201 ) -> R {
2202 let old_cursor_position = self.selections.newest_anchor().head();
2203 self.push_to_selection_history();
2204
2205 let (changed, result) = self.selections.change_with(cx, change);
2206
2207 if changed {
2208 if let Some(autoscroll) = autoscroll {
2209 self.request_autoscroll(autoscroll, cx);
2210 }
2211 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2212
2213 if self.should_open_signature_help_automatically(
2214 &old_cursor_position,
2215 self.signature_help_state.backspace_pressed(),
2216 cx,
2217 ) {
2218 self.show_signature_help(&ShowSignatureHelp, window, cx);
2219 }
2220 self.signature_help_state.set_backspace_pressed(false);
2221 }
2222
2223 result
2224 }
2225
2226 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2227 where
2228 I: IntoIterator<Item = (Range<S>, T)>,
2229 S: ToOffset,
2230 T: Into<Arc<str>>,
2231 {
2232 if self.read_only(cx) {
2233 return;
2234 }
2235
2236 self.buffer
2237 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2238 }
2239
2240 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2241 where
2242 I: IntoIterator<Item = (Range<S>, T)>,
2243 S: ToOffset,
2244 T: Into<Arc<str>>,
2245 {
2246 if self.read_only(cx) {
2247 return;
2248 }
2249
2250 self.buffer.update(cx, |buffer, cx| {
2251 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2252 });
2253 }
2254
2255 pub fn edit_with_block_indent<I, S, T>(
2256 &mut self,
2257 edits: I,
2258 original_indent_columns: Vec<u32>,
2259 cx: &mut Context<Self>,
2260 ) where
2261 I: IntoIterator<Item = (Range<S>, T)>,
2262 S: ToOffset,
2263 T: Into<Arc<str>>,
2264 {
2265 if self.read_only(cx) {
2266 return;
2267 }
2268
2269 self.buffer.update(cx, |buffer, cx| {
2270 buffer.edit(
2271 edits,
2272 Some(AutoindentMode::Block {
2273 original_indent_columns,
2274 }),
2275 cx,
2276 )
2277 });
2278 }
2279
2280 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2281 self.hide_context_menu(window, cx);
2282
2283 match phase {
2284 SelectPhase::Begin {
2285 position,
2286 add,
2287 click_count,
2288 } => self.begin_selection(position, add, click_count, window, cx),
2289 SelectPhase::BeginColumnar {
2290 position,
2291 goal_column,
2292 reset,
2293 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2294 SelectPhase::Extend {
2295 position,
2296 click_count,
2297 } => self.extend_selection(position, click_count, window, cx),
2298 SelectPhase::Update {
2299 position,
2300 goal_column,
2301 scroll_delta,
2302 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2303 SelectPhase::End => self.end_selection(window, cx),
2304 }
2305 }
2306
2307 fn extend_selection(
2308 &mut self,
2309 position: DisplayPoint,
2310 click_count: usize,
2311 window: &mut Window,
2312 cx: &mut Context<Self>,
2313 ) {
2314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2315 let tail = self.selections.newest::<usize>(cx).tail();
2316 self.begin_selection(position, false, click_count, window, cx);
2317
2318 let position = position.to_offset(&display_map, Bias::Left);
2319 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2320
2321 let mut pending_selection = self
2322 .selections
2323 .pending_anchor()
2324 .expect("extend_selection not called with pending selection");
2325 if position >= tail {
2326 pending_selection.start = tail_anchor;
2327 } else {
2328 pending_selection.end = tail_anchor;
2329 pending_selection.reversed = true;
2330 }
2331
2332 let mut pending_mode = self.selections.pending_mode().unwrap();
2333 match &mut pending_mode {
2334 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2335 _ => {}
2336 }
2337
2338 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2339 s.set_pending(pending_selection, pending_mode)
2340 });
2341 }
2342
2343 fn begin_selection(
2344 &mut self,
2345 position: DisplayPoint,
2346 add: bool,
2347 click_count: usize,
2348 window: &mut Window,
2349 cx: &mut Context<Self>,
2350 ) {
2351 if !self.focus_handle.is_focused(window) {
2352 self.last_focused_descendant = None;
2353 window.focus(&self.focus_handle);
2354 }
2355
2356 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2357 let buffer = &display_map.buffer_snapshot;
2358 let newest_selection = self.selections.newest_anchor().clone();
2359 let position = display_map.clip_point(position, Bias::Left);
2360
2361 let start;
2362 let end;
2363 let mode;
2364 let mut auto_scroll;
2365 match click_count {
2366 1 => {
2367 start = buffer.anchor_before(position.to_point(&display_map));
2368 end = start;
2369 mode = SelectMode::Character;
2370 auto_scroll = true;
2371 }
2372 2 => {
2373 let range = movement::surrounding_word(&display_map, position);
2374 start = buffer.anchor_before(range.start.to_point(&display_map));
2375 end = buffer.anchor_before(range.end.to_point(&display_map));
2376 mode = SelectMode::Word(start..end);
2377 auto_scroll = true;
2378 }
2379 3 => {
2380 let position = display_map
2381 .clip_point(position, Bias::Left)
2382 .to_point(&display_map);
2383 let line_start = display_map.prev_line_boundary(position).0;
2384 let next_line_start = buffer.clip_point(
2385 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2386 Bias::Left,
2387 );
2388 start = buffer.anchor_before(line_start);
2389 end = buffer.anchor_before(next_line_start);
2390 mode = SelectMode::Line(start..end);
2391 auto_scroll = true;
2392 }
2393 _ => {
2394 start = buffer.anchor_before(0);
2395 end = buffer.anchor_before(buffer.len());
2396 mode = SelectMode::All;
2397 auto_scroll = false;
2398 }
2399 }
2400 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2401
2402 let point_to_delete: Option<usize> = {
2403 let selected_points: Vec<Selection<Point>> =
2404 self.selections.disjoint_in_range(start..end, cx);
2405
2406 if !add || click_count > 1 {
2407 None
2408 } else if !selected_points.is_empty() {
2409 Some(selected_points[0].id)
2410 } else {
2411 let clicked_point_already_selected =
2412 self.selections.disjoint.iter().find(|selection| {
2413 selection.start.to_point(buffer) == start.to_point(buffer)
2414 || selection.end.to_point(buffer) == end.to_point(buffer)
2415 });
2416
2417 clicked_point_already_selected.map(|selection| selection.id)
2418 }
2419 };
2420
2421 let selections_count = self.selections.count();
2422
2423 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2424 if let Some(point_to_delete) = point_to_delete {
2425 s.delete(point_to_delete);
2426
2427 if selections_count == 1 {
2428 s.set_pending_anchor_range(start..end, mode);
2429 }
2430 } else {
2431 if !add {
2432 s.clear_disjoint();
2433 } else if click_count > 1 {
2434 s.delete(newest_selection.id)
2435 }
2436
2437 s.set_pending_anchor_range(start..end, mode);
2438 }
2439 });
2440 }
2441
2442 fn begin_columnar_selection(
2443 &mut self,
2444 position: DisplayPoint,
2445 goal_column: u32,
2446 reset: bool,
2447 window: &mut Window,
2448 cx: &mut Context<Self>,
2449 ) {
2450 if !self.focus_handle.is_focused(window) {
2451 self.last_focused_descendant = None;
2452 window.focus(&self.focus_handle);
2453 }
2454
2455 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2456
2457 if reset {
2458 let pointer_position = display_map
2459 .buffer_snapshot
2460 .anchor_before(position.to_point(&display_map));
2461
2462 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2463 s.clear_disjoint();
2464 s.set_pending_anchor_range(
2465 pointer_position..pointer_position,
2466 SelectMode::Character,
2467 );
2468 });
2469 }
2470
2471 let tail = self.selections.newest::<Point>(cx).tail();
2472 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2473
2474 if !reset {
2475 self.select_columns(
2476 tail.to_display_point(&display_map),
2477 position,
2478 goal_column,
2479 &display_map,
2480 window,
2481 cx,
2482 );
2483 }
2484 }
2485
2486 fn update_selection(
2487 &mut self,
2488 position: DisplayPoint,
2489 goal_column: u32,
2490 scroll_delta: gpui::Point<f32>,
2491 window: &mut Window,
2492 cx: &mut Context<Self>,
2493 ) {
2494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2495
2496 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2497 let tail = tail.to_display_point(&display_map);
2498 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2499 } else if let Some(mut pending) = self.selections.pending_anchor() {
2500 let buffer = self.buffer.read(cx).snapshot(cx);
2501 let head;
2502 let tail;
2503 let mode = self.selections.pending_mode().unwrap();
2504 match &mode {
2505 SelectMode::Character => {
2506 head = position.to_point(&display_map);
2507 tail = pending.tail().to_point(&buffer);
2508 }
2509 SelectMode::Word(original_range) => {
2510 let original_display_range = original_range.start.to_display_point(&display_map)
2511 ..original_range.end.to_display_point(&display_map);
2512 let original_buffer_range = original_display_range.start.to_point(&display_map)
2513 ..original_display_range.end.to_point(&display_map);
2514 if movement::is_inside_word(&display_map, position)
2515 || original_display_range.contains(&position)
2516 {
2517 let word_range = movement::surrounding_word(&display_map, position);
2518 if word_range.start < original_display_range.start {
2519 head = word_range.start.to_point(&display_map);
2520 } else {
2521 head = word_range.end.to_point(&display_map);
2522 }
2523 } else {
2524 head = position.to_point(&display_map);
2525 }
2526
2527 if head <= original_buffer_range.start {
2528 tail = original_buffer_range.end;
2529 } else {
2530 tail = original_buffer_range.start;
2531 }
2532 }
2533 SelectMode::Line(original_range) => {
2534 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2535
2536 let position = display_map
2537 .clip_point(position, Bias::Left)
2538 .to_point(&display_map);
2539 let line_start = display_map.prev_line_boundary(position).0;
2540 let next_line_start = buffer.clip_point(
2541 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2542 Bias::Left,
2543 );
2544
2545 if line_start < original_range.start {
2546 head = line_start
2547 } else {
2548 head = next_line_start
2549 }
2550
2551 if head <= original_range.start {
2552 tail = original_range.end;
2553 } else {
2554 tail = original_range.start;
2555 }
2556 }
2557 SelectMode::All => {
2558 return;
2559 }
2560 };
2561
2562 if head < tail {
2563 pending.start = buffer.anchor_before(head);
2564 pending.end = buffer.anchor_before(tail);
2565 pending.reversed = true;
2566 } else {
2567 pending.start = buffer.anchor_before(tail);
2568 pending.end = buffer.anchor_before(head);
2569 pending.reversed = false;
2570 }
2571
2572 self.change_selections(None, window, cx, |s| {
2573 s.set_pending(pending, mode);
2574 });
2575 } else {
2576 log::error!("update_selection dispatched with no pending selection");
2577 return;
2578 }
2579
2580 self.apply_scroll_delta(scroll_delta, window, cx);
2581 cx.notify();
2582 }
2583
2584 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2585 self.columnar_selection_tail.take();
2586 if self.selections.pending_anchor().is_some() {
2587 let selections = self.selections.all::<usize>(cx);
2588 self.change_selections(None, window, cx, |s| {
2589 s.select(selections);
2590 s.clear_pending();
2591 });
2592 }
2593 }
2594
2595 fn select_columns(
2596 &mut self,
2597 tail: DisplayPoint,
2598 head: DisplayPoint,
2599 goal_column: u32,
2600 display_map: &DisplaySnapshot,
2601 window: &mut Window,
2602 cx: &mut Context<Self>,
2603 ) {
2604 let start_row = cmp::min(tail.row(), head.row());
2605 let end_row = cmp::max(tail.row(), head.row());
2606 let start_column = cmp::min(tail.column(), goal_column);
2607 let end_column = cmp::max(tail.column(), goal_column);
2608 let reversed = start_column < tail.column();
2609
2610 let selection_ranges = (start_row.0..=end_row.0)
2611 .map(DisplayRow)
2612 .filter_map(|row| {
2613 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2614 let start = display_map
2615 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2616 .to_point(display_map);
2617 let end = display_map
2618 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2619 .to_point(display_map);
2620 if reversed {
2621 Some(end..start)
2622 } else {
2623 Some(start..end)
2624 }
2625 } else {
2626 None
2627 }
2628 })
2629 .collect::<Vec<_>>();
2630
2631 self.change_selections(None, window, cx, |s| {
2632 s.select_ranges(selection_ranges);
2633 });
2634 cx.notify();
2635 }
2636
2637 pub fn has_pending_nonempty_selection(&self) -> bool {
2638 let pending_nonempty_selection = match self.selections.pending_anchor() {
2639 Some(Selection { start, end, .. }) => start != end,
2640 None => false,
2641 };
2642
2643 pending_nonempty_selection
2644 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2645 }
2646
2647 pub fn has_pending_selection(&self) -> bool {
2648 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2649 }
2650
2651 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2652 self.selection_mark_mode = false;
2653
2654 if self.clear_expanded_diff_hunks(cx) {
2655 cx.notify();
2656 return;
2657 }
2658 if self.dismiss_menus_and_popups(true, window, cx) {
2659 return;
2660 }
2661
2662 if self.mode == EditorMode::Full
2663 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2664 {
2665 return;
2666 }
2667
2668 cx.propagate();
2669 }
2670
2671 pub fn dismiss_menus_and_popups(
2672 &mut self,
2673 is_user_requested: bool,
2674 window: &mut Window,
2675 cx: &mut Context<Self>,
2676 ) -> bool {
2677 if self.take_rename(false, window, cx).is_some() {
2678 return true;
2679 }
2680
2681 if hide_hover(self, cx) {
2682 return true;
2683 }
2684
2685 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2686 return true;
2687 }
2688
2689 if self.hide_context_menu(window, cx).is_some() {
2690 return true;
2691 }
2692
2693 if self.mouse_context_menu.take().is_some() {
2694 return true;
2695 }
2696
2697 if is_user_requested && self.discard_inline_completion(true, cx) {
2698 return true;
2699 }
2700
2701 if self.snippet_stack.pop().is_some() {
2702 return true;
2703 }
2704
2705 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2706 self.dismiss_diagnostics(cx);
2707 return true;
2708 }
2709
2710 false
2711 }
2712
2713 fn linked_editing_ranges_for(
2714 &self,
2715 selection: Range<text::Anchor>,
2716 cx: &App,
2717 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2718 if self.linked_edit_ranges.is_empty() {
2719 return None;
2720 }
2721 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2722 selection.end.buffer_id.and_then(|end_buffer_id| {
2723 if selection.start.buffer_id != Some(end_buffer_id) {
2724 return None;
2725 }
2726 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2727 let snapshot = buffer.read(cx).snapshot();
2728 self.linked_edit_ranges
2729 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2730 .map(|ranges| (ranges, snapshot, buffer))
2731 })?;
2732 use text::ToOffset as TO;
2733 // find offset from the start of current range to current cursor position
2734 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2735
2736 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2737 let start_difference = start_offset - start_byte_offset;
2738 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2739 let end_difference = end_offset - start_byte_offset;
2740 // Current range has associated linked ranges.
2741 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2742 for range in linked_ranges.iter() {
2743 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2744 let end_offset = start_offset + end_difference;
2745 let start_offset = start_offset + start_difference;
2746 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2747 continue;
2748 }
2749 if self.selections.disjoint_anchor_ranges().any(|s| {
2750 if s.start.buffer_id != selection.start.buffer_id
2751 || s.end.buffer_id != selection.end.buffer_id
2752 {
2753 return false;
2754 }
2755 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2756 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2757 }) {
2758 continue;
2759 }
2760 let start = buffer_snapshot.anchor_after(start_offset);
2761 let end = buffer_snapshot.anchor_after(end_offset);
2762 linked_edits
2763 .entry(buffer.clone())
2764 .or_default()
2765 .push(start..end);
2766 }
2767 Some(linked_edits)
2768 }
2769
2770 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2771 let text: Arc<str> = text.into();
2772
2773 if self.read_only(cx) {
2774 return;
2775 }
2776
2777 let selections = self.selections.all_adjusted(cx);
2778 let mut bracket_inserted = false;
2779 let mut edits = Vec::new();
2780 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2781 let mut new_selections = Vec::with_capacity(selections.len());
2782 let mut new_autoclose_regions = Vec::new();
2783 let snapshot = self.buffer.read(cx).read(cx);
2784
2785 for (selection, autoclose_region) in
2786 self.selections_with_autoclose_regions(selections, &snapshot)
2787 {
2788 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2789 // Determine if the inserted text matches the opening or closing
2790 // bracket of any of this language's bracket pairs.
2791 let mut bracket_pair = None;
2792 let mut is_bracket_pair_start = false;
2793 let mut is_bracket_pair_end = false;
2794 if !text.is_empty() {
2795 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2796 // and they are removing the character that triggered IME popup.
2797 for (pair, enabled) in scope.brackets() {
2798 if !pair.close && !pair.surround {
2799 continue;
2800 }
2801
2802 if enabled && pair.start.ends_with(text.as_ref()) {
2803 let prefix_len = pair.start.len() - text.len();
2804 let preceding_text_matches_prefix = prefix_len == 0
2805 || (selection.start.column >= (prefix_len as u32)
2806 && snapshot.contains_str_at(
2807 Point::new(
2808 selection.start.row,
2809 selection.start.column - (prefix_len as u32),
2810 ),
2811 &pair.start[..prefix_len],
2812 ));
2813 if preceding_text_matches_prefix {
2814 bracket_pair = Some(pair.clone());
2815 is_bracket_pair_start = true;
2816 break;
2817 }
2818 }
2819 if pair.end.as_str() == text.as_ref() {
2820 bracket_pair = Some(pair.clone());
2821 is_bracket_pair_end = true;
2822 break;
2823 }
2824 }
2825 }
2826
2827 if let Some(bracket_pair) = bracket_pair {
2828 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2829 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2830 let auto_surround =
2831 self.use_auto_surround && snapshot_settings.use_auto_surround;
2832 if selection.is_empty() {
2833 if is_bracket_pair_start {
2834 // If the inserted text is a suffix of an opening bracket and the
2835 // selection is preceded by the rest of the opening bracket, then
2836 // insert the closing bracket.
2837 let following_text_allows_autoclose = snapshot
2838 .chars_at(selection.start)
2839 .next()
2840 .map_or(true, |c| scope.should_autoclose_before(c));
2841
2842 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2843 && bracket_pair.start.len() == 1
2844 {
2845 let target = bracket_pair.start.chars().next().unwrap();
2846 let current_line_count = snapshot
2847 .reversed_chars_at(selection.start)
2848 .take_while(|&c| c != '\n')
2849 .filter(|&c| c == target)
2850 .count();
2851 current_line_count % 2 == 1
2852 } else {
2853 false
2854 };
2855
2856 if autoclose
2857 && bracket_pair.close
2858 && following_text_allows_autoclose
2859 && !is_closing_quote
2860 {
2861 let anchor = snapshot.anchor_before(selection.end);
2862 new_selections.push((selection.map(|_| anchor), text.len()));
2863 new_autoclose_regions.push((
2864 anchor,
2865 text.len(),
2866 selection.id,
2867 bracket_pair.clone(),
2868 ));
2869 edits.push((
2870 selection.range(),
2871 format!("{}{}", text, bracket_pair.end).into(),
2872 ));
2873 bracket_inserted = true;
2874 continue;
2875 }
2876 }
2877
2878 if let Some(region) = autoclose_region {
2879 // If the selection is followed by an auto-inserted closing bracket,
2880 // then don't insert that closing bracket again; just move the selection
2881 // past the closing bracket.
2882 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2883 && text.as_ref() == region.pair.end.as_str();
2884 if should_skip {
2885 let anchor = snapshot.anchor_after(selection.end);
2886 new_selections
2887 .push((selection.map(|_| anchor), region.pair.end.len()));
2888 continue;
2889 }
2890 }
2891
2892 let always_treat_brackets_as_autoclosed = snapshot
2893 .settings_at(selection.start, cx)
2894 .always_treat_brackets_as_autoclosed;
2895 if always_treat_brackets_as_autoclosed
2896 && is_bracket_pair_end
2897 && snapshot.contains_str_at(selection.end, text.as_ref())
2898 {
2899 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2900 // and the inserted text is a closing bracket and the selection is followed
2901 // by the closing bracket then move the selection past the closing bracket.
2902 let anchor = snapshot.anchor_after(selection.end);
2903 new_selections.push((selection.map(|_| anchor), text.len()));
2904 continue;
2905 }
2906 }
2907 // If an opening bracket is 1 character long and is typed while
2908 // text is selected, then surround that text with the bracket pair.
2909 else if auto_surround
2910 && bracket_pair.surround
2911 && is_bracket_pair_start
2912 && bracket_pair.start.chars().count() == 1
2913 {
2914 edits.push((selection.start..selection.start, text.clone()));
2915 edits.push((
2916 selection.end..selection.end,
2917 bracket_pair.end.as_str().into(),
2918 ));
2919 bracket_inserted = true;
2920 new_selections.push((
2921 Selection {
2922 id: selection.id,
2923 start: snapshot.anchor_after(selection.start),
2924 end: snapshot.anchor_before(selection.end),
2925 reversed: selection.reversed,
2926 goal: selection.goal,
2927 },
2928 0,
2929 ));
2930 continue;
2931 }
2932 }
2933 }
2934
2935 if self.auto_replace_emoji_shortcode
2936 && selection.is_empty()
2937 && text.as_ref().ends_with(':')
2938 {
2939 if let Some(possible_emoji_short_code) =
2940 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2941 {
2942 if !possible_emoji_short_code.is_empty() {
2943 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2944 let emoji_shortcode_start = Point::new(
2945 selection.start.row,
2946 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2947 );
2948
2949 // Remove shortcode from buffer
2950 edits.push((
2951 emoji_shortcode_start..selection.start,
2952 "".to_string().into(),
2953 ));
2954 new_selections.push((
2955 Selection {
2956 id: selection.id,
2957 start: snapshot.anchor_after(emoji_shortcode_start),
2958 end: snapshot.anchor_before(selection.start),
2959 reversed: selection.reversed,
2960 goal: selection.goal,
2961 },
2962 0,
2963 ));
2964
2965 // Insert emoji
2966 let selection_start_anchor = snapshot.anchor_after(selection.start);
2967 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2968 edits.push((selection.start..selection.end, emoji.to_string().into()));
2969
2970 continue;
2971 }
2972 }
2973 }
2974 }
2975
2976 // If not handling any auto-close operation, then just replace the selected
2977 // text with the given input and move the selection to the end of the
2978 // newly inserted text.
2979 let anchor = snapshot.anchor_after(selection.end);
2980 if !self.linked_edit_ranges.is_empty() {
2981 let start_anchor = snapshot.anchor_before(selection.start);
2982
2983 let is_word_char = text.chars().next().map_or(true, |char| {
2984 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2985 classifier.is_word(char)
2986 });
2987
2988 if is_word_char {
2989 if let Some(ranges) = self
2990 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2991 {
2992 for (buffer, edits) in ranges {
2993 linked_edits
2994 .entry(buffer.clone())
2995 .or_default()
2996 .extend(edits.into_iter().map(|range| (range, text.clone())));
2997 }
2998 }
2999 }
3000 }
3001
3002 new_selections.push((selection.map(|_| anchor), 0));
3003 edits.push((selection.start..selection.end, text.clone()));
3004 }
3005
3006 drop(snapshot);
3007
3008 self.transact(window, cx, |this, window, cx| {
3009 this.buffer.update(cx, |buffer, cx| {
3010 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3011 });
3012 for (buffer, edits) in linked_edits {
3013 buffer.update(cx, |buffer, cx| {
3014 let snapshot = buffer.snapshot();
3015 let edits = edits
3016 .into_iter()
3017 .map(|(range, text)| {
3018 use text::ToPoint as TP;
3019 let end_point = TP::to_point(&range.end, &snapshot);
3020 let start_point = TP::to_point(&range.start, &snapshot);
3021 (start_point..end_point, text)
3022 })
3023 .sorted_by_key(|(range, _)| range.start)
3024 .collect::<Vec<_>>();
3025 buffer.edit(edits, None, cx);
3026 })
3027 }
3028 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3029 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3030 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3031 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3032 .zip(new_selection_deltas)
3033 .map(|(selection, delta)| Selection {
3034 id: selection.id,
3035 start: selection.start + delta,
3036 end: selection.end + delta,
3037 reversed: selection.reversed,
3038 goal: SelectionGoal::None,
3039 })
3040 .collect::<Vec<_>>();
3041
3042 let mut i = 0;
3043 for (position, delta, selection_id, pair) in new_autoclose_regions {
3044 let position = position.to_offset(&map.buffer_snapshot) + delta;
3045 let start = map.buffer_snapshot.anchor_before(position);
3046 let end = map.buffer_snapshot.anchor_after(position);
3047 while let Some(existing_state) = this.autoclose_regions.get(i) {
3048 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3049 Ordering::Less => i += 1,
3050 Ordering::Greater => break,
3051 Ordering::Equal => {
3052 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3053 Ordering::Less => i += 1,
3054 Ordering::Equal => break,
3055 Ordering::Greater => break,
3056 }
3057 }
3058 }
3059 }
3060 this.autoclose_regions.insert(
3061 i,
3062 AutocloseRegion {
3063 selection_id,
3064 range: start..end,
3065 pair,
3066 },
3067 );
3068 }
3069
3070 let had_active_inline_completion = this.has_active_inline_completion();
3071 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3072 s.select(new_selections)
3073 });
3074
3075 if !bracket_inserted {
3076 if let Some(on_type_format_task) =
3077 this.trigger_on_type_formatting(text.to_string(), window, cx)
3078 {
3079 on_type_format_task.detach_and_log_err(cx);
3080 }
3081 }
3082
3083 let editor_settings = EditorSettings::get_global(cx);
3084 if bracket_inserted
3085 && (editor_settings.auto_signature_help
3086 || editor_settings.show_signature_help_after_edits)
3087 {
3088 this.show_signature_help(&ShowSignatureHelp, window, cx);
3089 }
3090
3091 let trigger_in_words =
3092 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3093 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3094 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3095 this.refresh_inline_completion(true, false, window, cx);
3096 });
3097 }
3098
3099 fn find_possible_emoji_shortcode_at_position(
3100 snapshot: &MultiBufferSnapshot,
3101 position: Point,
3102 ) -> Option<String> {
3103 let mut chars = Vec::new();
3104 let mut found_colon = false;
3105 for char in snapshot.reversed_chars_at(position).take(100) {
3106 // Found a possible emoji shortcode in the middle of the buffer
3107 if found_colon {
3108 if char.is_whitespace() {
3109 chars.reverse();
3110 return Some(chars.iter().collect());
3111 }
3112 // If the previous character is not a whitespace, we are in the middle of a word
3113 // and we only want to complete the shortcode if the word is made up of other emojis
3114 let mut containing_word = String::new();
3115 for ch in snapshot
3116 .reversed_chars_at(position)
3117 .skip(chars.len() + 1)
3118 .take(100)
3119 {
3120 if ch.is_whitespace() {
3121 break;
3122 }
3123 containing_word.push(ch);
3124 }
3125 let containing_word = containing_word.chars().rev().collect::<String>();
3126 if util::word_consists_of_emojis(containing_word.as_str()) {
3127 chars.reverse();
3128 return Some(chars.iter().collect());
3129 }
3130 }
3131
3132 if char.is_whitespace() || !char.is_ascii() {
3133 return None;
3134 }
3135 if char == ':' {
3136 found_colon = true;
3137 } else {
3138 chars.push(char);
3139 }
3140 }
3141 // Found a possible emoji shortcode at the beginning of the buffer
3142 chars.reverse();
3143 Some(chars.iter().collect())
3144 }
3145
3146 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3147 self.transact(window, cx, |this, window, cx| {
3148 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3149 let selections = this.selections.all::<usize>(cx);
3150 let multi_buffer = this.buffer.read(cx);
3151 let buffer = multi_buffer.snapshot(cx);
3152 selections
3153 .iter()
3154 .map(|selection| {
3155 let start_point = selection.start.to_point(&buffer);
3156 let mut indent =
3157 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3158 indent.len = cmp::min(indent.len, start_point.column);
3159 let start = selection.start;
3160 let end = selection.end;
3161 let selection_is_empty = start == end;
3162 let language_scope = buffer.language_scope_at(start);
3163 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3164 &language_scope
3165 {
3166 let leading_whitespace_len = buffer
3167 .reversed_chars_at(start)
3168 .take_while(|c| c.is_whitespace() && *c != '\n')
3169 .map(|c| c.len_utf8())
3170 .sum::<usize>();
3171
3172 let trailing_whitespace_len = buffer
3173 .chars_at(end)
3174 .take_while(|c| c.is_whitespace() && *c != '\n')
3175 .map(|c| c.len_utf8())
3176 .sum::<usize>();
3177
3178 let insert_extra_newline =
3179 language.brackets().any(|(pair, enabled)| {
3180 let pair_start = pair.start.trim_end();
3181 let pair_end = pair.end.trim_start();
3182
3183 enabled
3184 && pair.newline
3185 && buffer.contains_str_at(
3186 end + trailing_whitespace_len,
3187 pair_end,
3188 )
3189 && buffer.contains_str_at(
3190 (start - leading_whitespace_len)
3191 .saturating_sub(pair_start.len()),
3192 pair_start,
3193 )
3194 });
3195
3196 // Comment extension on newline is allowed only for cursor selections
3197 let comment_delimiter = maybe!({
3198 if !selection_is_empty {
3199 return None;
3200 }
3201
3202 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3203 return None;
3204 }
3205
3206 let delimiters = language.line_comment_prefixes();
3207 let max_len_of_delimiter =
3208 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3209 let (snapshot, range) =
3210 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3211
3212 let mut index_of_first_non_whitespace = 0;
3213 let comment_candidate = snapshot
3214 .chars_for_range(range)
3215 .skip_while(|c| {
3216 let should_skip = c.is_whitespace();
3217 if should_skip {
3218 index_of_first_non_whitespace += 1;
3219 }
3220 should_skip
3221 })
3222 .take(max_len_of_delimiter)
3223 .collect::<String>();
3224 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3225 comment_candidate.starts_with(comment_prefix.as_ref())
3226 })?;
3227 let cursor_is_placed_after_comment_marker =
3228 index_of_first_non_whitespace + comment_prefix.len()
3229 <= start_point.column as usize;
3230 if cursor_is_placed_after_comment_marker {
3231 Some(comment_prefix.clone())
3232 } else {
3233 None
3234 }
3235 });
3236 (comment_delimiter, insert_extra_newline)
3237 } else {
3238 (None, false)
3239 };
3240
3241 let capacity_for_delimiter = comment_delimiter
3242 .as_deref()
3243 .map(str::len)
3244 .unwrap_or_default();
3245 let mut new_text =
3246 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3247 new_text.push('\n');
3248 new_text.extend(indent.chars());
3249 if let Some(delimiter) = &comment_delimiter {
3250 new_text.push_str(delimiter);
3251 }
3252 if insert_extra_newline {
3253 new_text = new_text.repeat(2);
3254 }
3255
3256 let anchor = buffer.anchor_after(end);
3257 let new_selection = selection.map(|_| anchor);
3258 (
3259 (start..end, new_text),
3260 (insert_extra_newline, new_selection),
3261 )
3262 })
3263 .unzip()
3264 };
3265
3266 this.edit_with_autoindent(edits, cx);
3267 let buffer = this.buffer.read(cx).snapshot(cx);
3268 let new_selections = selection_fixup_info
3269 .into_iter()
3270 .map(|(extra_newline_inserted, new_selection)| {
3271 let mut cursor = new_selection.end.to_point(&buffer);
3272 if extra_newline_inserted {
3273 cursor.row -= 1;
3274 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3275 }
3276 new_selection.map(|_| cursor)
3277 })
3278 .collect();
3279
3280 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3281 s.select(new_selections)
3282 });
3283 this.refresh_inline_completion(true, false, window, cx);
3284 });
3285 }
3286
3287 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3288 let buffer = self.buffer.read(cx);
3289 let snapshot = buffer.snapshot(cx);
3290
3291 let mut edits = Vec::new();
3292 let mut rows = Vec::new();
3293
3294 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3295 let cursor = selection.head();
3296 let row = cursor.row;
3297
3298 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3299
3300 let newline = "\n".to_string();
3301 edits.push((start_of_line..start_of_line, newline));
3302
3303 rows.push(row + rows_inserted as u32);
3304 }
3305
3306 self.transact(window, cx, |editor, window, cx| {
3307 editor.edit(edits, cx);
3308
3309 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3310 let mut index = 0;
3311 s.move_cursors_with(|map, _, _| {
3312 let row = rows[index];
3313 index += 1;
3314
3315 let point = Point::new(row, 0);
3316 let boundary = map.next_line_boundary(point).1;
3317 let clipped = map.clip_point(boundary, Bias::Left);
3318
3319 (clipped, SelectionGoal::None)
3320 });
3321 });
3322
3323 let mut indent_edits = Vec::new();
3324 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3325 for row in rows {
3326 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3327 for (row, indent) in indents {
3328 if indent.len == 0 {
3329 continue;
3330 }
3331
3332 let text = match indent.kind {
3333 IndentKind::Space => " ".repeat(indent.len as usize),
3334 IndentKind::Tab => "\t".repeat(indent.len as usize),
3335 };
3336 let point = Point::new(row.0, 0);
3337 indent_edits.push((point..point, text));
3338 }
3339 }
3340 editor.edit(indent_edits, cx);
3341 });
3342 }
3343
3344 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3345 let buffer = self.buffer.read(cx);
3346 let snapshot = buffer.snapshot(cx);
3347
3348 let mut edits = Vec::new();
3349 let mut rows = Vec::new();
3350 let mut rows_inserted = 0;
3351
3352 for selection in self.selections.all_adjusted(cx) {
3353 let cursor = selection.head();
3354 let row = cursor.row;
3355
3356 let point = Point::new(row + 1, 0);
3357 let start_of_line = snapshot.clip_point(point, Bias::Left);
3358
3359 let newline = "\n".to_string();
3360 edits.push((start_of_line..start_of_line, newline));
3361
3362 rows_inserted += 1;
3363 rows.push(row + rows_inserted);
3364 }
3365
3366 self.transact(window, cx, |editor, window, cx| {
3367 editor.edit(edits, cx);
3368
3369 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3370 let mut index = 0;
3371 s.move_cursors_with(|map, _, _| {
3372 let row = rows[index];
3373 index += 1;
3374
3375 let point = Point::new(row, 0);
3376 let boundary = map.next_line_boundary(point).1;
3377 let clipped = map.clip_point(boundary, Bias::Left);
3378
3379 (clipped, SelectionGoal::None)
3380 });
3381 });
3382
3383 let mut indent_edits = Vec::new();
3384 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3385 for row in rows {
3386 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3387 for (row, indent) in indents {
3388 if indent.len == 0 {
3389 continue;
3390 }
3391
3392 let text = match indent.kind {
3393 IndentKind::Space => " ".repeat(indent.len as usize),
3394 IndentKind::Tab => "\t".repeat(indent.len as usize),
3395 };
3396 let point = Point::new(row.0, 0);
3397 indent_edits.push((point..point, text));
3398 }
3399 }
3400 editor.edit(indent_edits, cx);
3401 });
3402 }
3403
3404 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3405 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3406 original_indent_columns: Vec::new(),
3407 });
3408 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3409 }
3410
3411 fn insert_with_autoindent_mode(
3412 &mut self,
3413 text: &str,
3414 autoindent_mode: Option<AutoindentMode>,
3415 window: &mut Window,
3416 cx: &mut Context<Self>,
3417 ) {
3418 if self.read_only(cx) {
3419 return;
3420 }
3421
3422 let text: Arc<str> = text.into();
3423 self.transact(window, cx, |this, window, cx| {
3424 let old_selections = this.selections.all_adjusted(cx);
3425 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3426 let anchors = {
3427 let snapshot = buffer.read(cx);
3428 old_selections
3429 .iter()
3430 .map(|s| {
3431 let anchor = snapshot.anchor_after(s.head());
3432 s.map(|_| anchor)
3433 })
3434 .collect::<Vec<_>>()
3435 };
3436 buffer.edit(
3437 old_selections
3438 .iter()
3439 .map(|s| (s.start..s.end, text.clone())),
3440 autoindent_mode,
3441 cx,
3442 );
3443 anchors
3444 });
3445
3446 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3447 s.select_anchors(selection_anchors);
3448 });
3449
3450 cx.notify();
3451 });
3452 }
3453
3454 fn trigger_completion_on_input(
3455 &mut self,
3456 text: &str,
3457 trigger_in_words: bool,
3458 window: &mut Window,
3459 cx: &mut Context<Self>,
3460 ) {
3461 if self.is_completion_trigger(text, trigger_in_words, cx) {
3462 self.show_completions(
3463 &ShowCompletions {
3464 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3465 },
3466 window,
3467 cx,
3468 );
3469 } else {
3470 self.hide_context_menu(window, cx);
3471 }
3472 }
3473
3474 fn is_completion_trigger(
3475 &self,
3476 text: &str,
3477 trigger_in_words: bool,
3478 cx: &mut Context<Self>,
3479 ) -> bool {
3480 let position = self.selections.newest_anchor().head();
3481 let multibuffer = self.buffer.read(cx);
3482 let Some(buffer) = position
3483 .buffer_id
3484 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3485 else {
3486 return false;
3487 };
3488
3489 if let Some(completion_provider) = &self.completion_provider {
3490 completion_provider.is_completion_trigger(
3491 &buffer,
3492 position.text_anchor,
3493 text,
3494 trigger_in_words,
3495 cx,
3496 )
3497 } else {
3498 false
3499 }
3500 }
3501
3502 /// If any empty selections is touching the start of its innermost containing autoclose
3503 /// region, expand it to select the brackets.
3504 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3505 let selections = self.selections.all::<usize>(cx);
3506 let buffer = self.buffer.read(cx).read(cx);
3507 let new_selections = self
3508 .selections_with_autoclose_regions(selections, &buffer)
3509 .map(|(mut selection, region)| {
3510 if !selection.is_empty() {
3511 return selection;
3512 }
3513
3514 if let Some(region) = region {
3515 let mut range = region.range.to_offset(&buffer);
3516 if selection.start == range.start && range.start >= region.pair.start.len() {
3517 range.start -= region.pair.start.len();
3518 if buffer.contains_str_at(range.start, ®ion.pair.start)
3519 && buffer.contains_str_at(range.end, ®ion.pair.end)
3520 {
3521 range.end += region.pair.end.len();
3522 selection.start = range.start;
3523 selection.end = range.end;
3524
3525 return selection;
3526 }
3527 }
3528 }
3529
3530 let always_treat_brackets_as_autoclosed = buffer
3531 .settings_at(selection.start, cx)
3532 .always_treat_brackets_as_autoclosed;
3533
3534 if !always_treat_brackets_as_autoclosed {
3535 return selection;
3536 }
3537
3538 if let Some(scope) = buffer.language_scope_at(selection.start) {
3539 for (pair, enabled) in scope.brackets() {
3540 if !enabled || !pair.close {
3541 continue;
3542 }
3543
3544 if buffer.contains_str_at(selection.start, &pair.end) {
3545 let pair_start_len = pair.start.len();
3546 if buffer.contains_str_at(
3547 selection.start.saturating_sub(pair_start_len),
3548 &pair.start,
3549 ) {
3550 selection.start -= pair_start_len;
3551 selection.end += pair.end.len();
3552
3553 return selection;
3554 }
3555 }
3556 }
3557 }
3558
3559 selection
3560 })
3561 .collect();
3562
3563 drop(buffer);
3564 self.change_selections(None, window, cx, |selections| {
3565 selections.select(new_selections)
3566 });
3567 }
3568
3569 /// Iterate the given selections, and for each one, find the smallest surrounding
3570 /// autoclose region. This uses the ordering of the selections and the autoclose
3571 /// regions to avoid repeated comparisons.
3572 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3573 &'a self,
3574 selections: impl IntoIterator<Item = Selection<D>>,
3575 buffer: &'a MultiBufferSnapshot,
3576 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3577 let mut i = 0;
3578 let mut regions = self.autoclose_regions.as_slice();
3579 selections.into_iter().map(move |selection| {
3580 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3581
3582 let mut enclosing = None;
3583 while let Some(pair_state) = regions.get(i) {
3584 if pair_state.range.end.to_offset(buffer) < range.start {
3585 regions = ®ions[i + 1..];
3586 i = 0;
3587 } else if pair_state.range.start.to_offset(buffer) > range.end {
3588 break;
3589 } else {
3590 if pair_state.selection_id == selection.id {
3591 enclosing = Some(pair_state);
3592 }
3593 i += 1;
3594 }
3595 }
3596
3597 (selection, enclosing)
3598 })
3599 }
3600
3601 /// Remove any autoclose regions that no longer contain their selection.
3602 fn invalidate_autoclose_regions(
3603 &mut self,
3604 mut selections: &[Selection<Anchor>],
3605 buffer: &MultiBufferSnapshot,
3606 ) {
3607 self.autoclose_regions.retain(|state| {
3608 let mut i = 0;
3609 while let Some(selection) = selections.get(i) {
3610 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3611 selections = &selections[1..];
3612 continue;
3613 }
3614 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3615 break;
3616 }
3617 if selection.id == state.selection_id {
3618 return true;
3619 } else {
3620 i += 1;
3621 }
3622 }
3623 false
3624 });
3625 }
3626
3627 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3628 let offset = position.to_offset(buffer);
3629 let (word_range, kind) = buffer.surrounding_word(offset, true);
3630 if offset > word_range.start && kind == Some(CharKind::Word) {
3631 Some(
3632 buffer
3633 .text_for_range(word_range.start..offset)
3634 .collect::<String>(),
3635 )
3636 } else {
3637 None
3638 }
3639 }
3640
3641 pub fn toggle_inlay_hints(
3642 &mut self,
3643 _: &ToggleInlayHints,
3644 _: &mut Window,
3645 cx: &mut Context<Self>,
3646 ) {
3647 self.refresh_inlay_hints(
3648 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3649 cx,
3650 );
3651 }
3652
3653 pub fn inlay_hints_enabled(&self) -> bool {
3654 self.inlay_hint_cache.enabled
3655 }
3656
3657 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3658 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3659 return;
3660 }
3661
3662 let reason_description = reason.description();
3663 let ignore_debounce = matches!(
3664 reason,
3665 InlayHintRefreshReason::SettingsChange(_)
3666 | InlayHintRefreshReason::Toggle(_)
3667 | InlayHintRefreshReason::ExcerptsRemoved(_)
3668 );
3669 let (invalidate_cache, required_languages) = match reason {
3670 InlayHintRefreshReason::Toggle(enabled) => {
3671 self.inlay_hint_cache.enabled = enabled;
3672 if enabled {
3673 (InvalidationStrategy::RefreshRequested, None)
3674 } else {
3675 self.inlay_hint_cache.clear();
3676 self.splice_inlays(
3677 &self
3678 .visible_inlay_hints(cx)
3679 .iter()
3680 .map(|inlay| inlay.id)
3681 .collect::<Vec<InlayId>>(),
3682 Vec::new(),
3683 cx,
3684 );
3685 return;
3686 }
3687 }
3688 InlayHintRefreshReason::SettingsChange(new_settings) => {
3689 match self.inlay_hint_cache.update_settings(
3690 &self.buffer,
3691 new_settings,
3692 self.visible_inlay_hints(cx),
3693 cx,
3694 ) {
3695 ControlFlow::Break(Some(InlaySplice {
3696 to_remove,
3697 to_insert,
3698 })) => {
3699 self.splice_inlays(&to_remove, to_insert, cx);
3700 return;
3701 }
3702 ControlFlow::Break(None) => return,
3703 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3704 }
3705 }
3706 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3707 if let Some(InlaySplice {
3708 to_remove,
3709 to_insert,
3710 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3711 {
3712 self.splice_inlays(&to_remove, to_insert, cx);
3713 }
3714 return;
3715 }
3716 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3717 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3718 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3719 }
3720 InlayHintRefreshReason::RefreshRequested => {
3721 (InvalidationStrategy::RefreshRequested, None)
3722 }
3723 };
3724
3725 if let Some(InlaySplice {
3726 to_remove,
3727 to_insert,
3728 }) = self.inlay_hint_cache.spawn_hint_refresh(
3729 reason_description,
3730 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3731 invalidate_cache,
3732 ignore_debounce,
3733 cx,
3734 ) {
3735 self.splice_inlays(&to_remove, to_insert, cx);
3736 }
3737 }
3738
3739 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3740 self.display_map
3741 .read(cx)
3742 .current_inlays()
3743 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3744 .cloned()
3745 .collect()
3746 }
3747
3748 pub fn excerpts_for_inlay_hints_query(
3749 &self,
3750 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3751 cx: &mut Context<Editor>,
3752 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3753 let Some(project) = self.project.as_ref() else {
3754 return HashMap::default();
3755 };
3756 let project = project.read(cx);
3757 let multi_buffer = self.buffer().read(cx);
3758 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3759 let multi_buffer_visible_start = self
3760 .scroll_manager
3761 .anchor()
3762 .anchor
3763 .to_point(&multi_buffer_snapshot);
3764 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3765 multi_buffer_visible_start
3766 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3767 Bias::Left,
3768 );
3769 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3770 multi_buffer_snapshot
3771 .range_to_buffer_ranges(multi_buffer_visible_range)
3772 .into_iter()
3773 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3774 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3775 let buffer_file = project::File::from_dyn(buffer.file())?;
3776 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3777 let worktree_entry = buffer_worktree
3778 .read(cx)
3779 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3780 if worktree_entry.is_ignored {
3781 return None;
3782 }
3783
3784 let language = buffer.language()?;
3785 if let Some(restrict_to_languages) = restrict_to_languages {
3786 if !restrict_to_languages.contains(language) {
3787 return None;
3788 }
3789 }
3790 Some((
3791 excerpt_id,
3792 (
3793 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3794 buffer.version().clone(),
3795 excerpt_visible_range,
3796 ),
3797 ))
3798 })
3799 .collect()
3800 }
3801
3802 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3803 TextLayoutDetails {
3804 text_system: window.text_system().clone(),
3805 editor_style: self.style.clone().unwrap(),
3806 rem_size: window.rem_size(),
3807 scroll_anchor: self.scroll_manager.anchor(),
3808 visible_rows: self.visible_line_count(),
3809 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3810 }
3811 }
3812
3813 pub fn splice_inlays(
3814 &self,
3815 to_remove: &[InlayId],
3816 to_insert: Vec<Inlay>,
3817 cx: &mut Context<Self>,
3818 ) {
3819 self.display_map.update(cx, |display_map, cx| {
3820 display_map.splice_inlays(to_remove, to_insert, cx)
3821 });
3822 cx.notify();
3823 }
3824
3825 fn trigger_on_type_formatting(
3826 &self,
3827 input: String,
3828 window: &mut Window,
3829 cx: &mut Context<Self>,
3830 ) -> Option<Task<Result<()>>> {
3831 if input.len() != 1 {
3832 return None;
3833 }
3834
3835 let project = self.project.as_ref()?;
3836 let position = self.selections.newest_anchor().head();
3837 let (buffer, buffer_position) = self
3838 .buffer
3839 .read(cx)
3840 .text_anchor_for_position(position, cx)?;
3841
3842 let settings = language_settings::language_settings(
3843 buffer
3844 .read(cx)
3845 .language_at(buffer_position)
3846 .map(|l| l.name()),
3847 buffer.read(cx).file(),
3848 cx,
3849 );
3850 if !settings.use_on_type_format {
3851 return None;
3852 }
3853
3854 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3855 // hence we do LSP request & edit on host side only — add formats to host's history.
3856 let push_to_lsp_host_history = true;
3857 // If this is not the host, append its history with new edits.
3858 let push_to_client_history = project.read(cx).is_via_collab();
3859
3860 let on_type_formatting = project.update(cx, |project, cx| {
3861 project.on_type_format(
3862 buffer.clone(),
3863 buffer_position,
3864 input,
3865 push_to_lsp_host_history,
3866 cx,
3867 )
3868 });
3869 Some(cx.spawn_in(window, |editor, mut cx| async move {
3870 if let Some(transaction) = on_type_formatting.await? {
3871 if push_to_client_history {
3872 buffer
3873 .update(&mut cx, |buffer, _| {
3874 buffer.push_transaction(transaction, Instant::now());
3875 })
3876 .ok();
3877 }
3878 editor.update(&mut cx, |editor, cx| {
3879 editor.refresh_document_highlights(cx);
3880 })?;
3881 }
3882 Ok(())
3883 }))
3884 }
3885
3886 pub fn show_completions(
3887 &mut self,
3888 options: &ShowCompletions,
3889 window: &mut Window,
3890 cx: &mut Context<Self>,
3891 ) {
3892 if self.pending_rename.is_some() {
3893 return;
3894 }
3895
3896 let Some(provider) = self.completion_provider.as_ref() else {
3897 return;
3898 };
3899
3900 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3901 return;
3902 }
3903
3904 let position = self.selections.newest_anchor().head();
3905 if position.diff_base_anchor.is_some() {
3906 return;
3907 }
3908 let (buffer, buffer_position) =
3909 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3910 output
3911 } else {
3912 return;
3913 };
3914 let show_completion_documentation = buffer
3915 .read(cx)
3916 .snapshot()
3917 .settings_at(buffer_position, cx)
3918 .show_completion_documentation;
3919
3920 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3921
3922 let trigger_kind = match &options.trigger {
3923 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3924 CompletionTriggerKind::TRIGGER_CHARACTER
3925 }
3926 _ => CompletionTriggerKind::INVOKED,
3927 };
3928 let completion_context = CompletionContext {
3929 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3930 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3931 Some(String::from(trigger))
3932 } else {
3933 None
3934 }
3935 }),
3936 trigger_kind,
3937 };
3938 let completions =
3939 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3940 let sort_completions = provider.sort_completions();
3941
3942 let id = post_inc(&mut self.next_completion_id);
3943 let task = cx.spawn_in(window, |editor, mut cx| {
3944 async move {
3945 editor.update(&mut cx, |this, _| {
3946 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3947 })?;
3948 let completions = completions.await.log_err();
3949 let menu = if let Some(completions) = completions {
3950 let mut menu = CompletionsMenu::new(
3951 id,
3952 sort_completions,
3953 show_completion_documentation,
3954 position,
3955 buffer.clone(),
3956 completions.into(),
3957 );
3958
3959 menu.filter(query.as_deref(), cx.background_executor().clone())
3960 .await;
3961
3962 menu.visible().then_some(menu)
3963 } else {
3964 None
3965 };
3966
3967 editor.update_in(&mut cx, |editor, window, cx| {
3968 match editor.context_menu.borrow().as_ref() {
3969 None => {}
3970 Some(CodeContextMenu::Completions(prev_menu)) => {
3971 if prev_menu.id > id {
3972 return;
3973 }
3974 }
3975 _ => return,
3976 }
3977
3978 if editor.focus_handle.is_focused(window) && menu.is_some() {
3979 let mut menu = menu.unwrap();
3980 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3981
3982 *editor.context_menu.borrow_mut() =
3983 Some(CodeContextMenu::Completions(menu));
3984
3985 if editor.show_edit_predictions_in_menu() {
3986 editor.update_visible_inline_completion(window, cx);
3987 } else {
3988 editor.discard_inline_completion(false, cx);
3989 }
3990
3991 cx.notify();
3992 } else if editor.completion_tasks.len() <= 1 {
3993 // If there are no more completion tasks and the last menu was
3994 // empty, we should hide it.
3995 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3996 // If it was already hidden and we don't show inline
3997 // completions in the menu, we should also show the
3998 // inline-completion when available.
3999 if was_hidden && editor.show_edit_predictions_in_menu() {
4000 editor.update_visible_inline_completion(window, cx);
4001 }
4002 }
4003 })?;
4004
4005 Ok::<_, anyhow::Error>(())
4006 }
4007 .log_err()
4008 });
4009
4010 self.completion_tasks.push((id, task));
4011 }
4012
4013 pub fn confirm_completion(
4014 &mut self,
4015 action: &ConfirmCompletion,
4016 window: &mut Window,
4017 cx: &mut Context<Self>,
4018 ) -> Option<Task<Result<()>>> {
4019 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4020 }
4021
4022 pub fn compose_completion(
4023 &mut self,
4024 action: &ComposeCompletion,
4025 window: &mut Window,
4026 cx: &mut Context<Self>,
4027 ) -> Option<Task<Result<()>>> {
4028 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4029 }
4030
4031 fn do_completion(
4032 &mut self,
4033 item_ix: Option<usize>,
4034 intent: CompletionIntent,
4035 window: &mut Window,
4036 cx: &mut Context<Editor>,
4037 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4038 use language::ToOffset as _;
4039
4040 let completions_menu =
4041 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4042 menu
4043 } else {
4044 return None;
4045 };
4046
4047 let entries = completions_menu.entries.borrow();
4048 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4049 if self.show_edit_predictions_in_menu() {
4050 self.discard_inline_completion(true, cx);
4051 }
4052 let candidate_id = mat.candidate_id;
4053 drop(entries);
4054
4055 let buffer_handle = completions_menu.buffer;
4056 let completion = completions_menu
4057 .completions
4058 .borrow()
4059 .get(candidate_id)?
4060 .clone();
4061 cx.stop_propagation();
4062
4063 let snippet;
4064 let text;
4065
4066 if completion.is_snippet() {
4067 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4068 text = snippet.as_ref().unwrap().text.clone();
4069 } else {
4070 snippet = None;
4071 text = completion.new_text.clone();
4072 };
4073 let selections = self.selections.all::<usize>(cx);
4074 let buffer = buffer_handle.read(cx);
4075 let old_range = completion.old_range.to_offset(buffer);
4076 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4077
4078 let newest_selection = self.selections.newest_anchor();
4079 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4080 return None;
4081 }
4082
4083 let lookbehind = newest_selection
4084 .start
4085 .text_anchor
4086 .to_offset(buffer)
4087 .saturating_sub(old_range.start);
4088 let lookahead = old_range
4089 .end
4090 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4091 let mut common_prefix_len = old_text
4092 .bytes()
4093 .zip(text.bytes())
4094 .take_while(|(a, b)| a == b)
4095 .count();
4096
4097 let snapshot = self.buffer.read(cx).snapshot(cx);
4098 let mut range_to_replace: Option<Range<isize>> = None;
4099 let mut ranges = Vec::new();
4100 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4101 for selection in &selections {
4102 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4103 let start = selection.start.saturating_sub(lookbehind);
4104 let end = selection.end + lookahead;
4105 if selection.id == newest_selection.id {
4106 range_to_replace = Some(
4107 ((start + common_prefix_len) as isize - selection.start as isize)
4108 ..(end as isize - selection.start as isize),
4109 );
4110 }
4111 ranges.push(start + common_prefix_len..end);
4112 } else {
4113 common_prefix_len = 0;
4114 ranges.clear();
4115 ranges.extend(selections.iter().map(|s| {
4116 if s.id == newest_selection.id {
4117 range_to_replace = Some(
4118 old_range.start.to_offset_utf16(&snapshot).0 as isize
4119 - selection.start as isize
4120 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4121 - selection.start as isize,
4122 );
4123 old_range.clone()
4124 } else {
4125 s.start..s.end
4126 }
4127 }));
4128 break;
4129 }
4130 if !self.linked_edit_ranges.is_empty() {
4131 let start_anchor = snapshot.anchor_before(selection.head());
4132 let end_anchor = snapshot.anchor_after(selection.tail());
4133 if let Some(ranges) = self
4134 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4135 {
4136 for (buffer, edits) in ranges {
4137 linked_edits.entry(buffer.clone()).or_default().extend(
4138 edits
4139 .into_iter()
4140 .map(|range| (range, text[common_prefix_len..].to_owned())),
4141 );
4142 }
4143 }
4144 }
4145 }
4146 let text = &text[common_prefix_len..];
4147
4148 cx.emit(EditorEvent::InputHandled {
4149 utf16_range_to_replace: range_to_replace,
4150 text: text.into(),
4151 });
4152
4153 self.transact(window, cx, |this, window, cx| {
4154 if let Some(mut snippet) = snippet {
4155 snippet.text = text.to_string();
4156 for tabstop in snippet
4157 .tabstops
4158 .iter_mut()
4159 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4160 {
4161 tabstop.start -= common_prefix_len as isize;
4162 tabstop.end -= common_prefix_len as isize;
4163 }
4164
4165 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4166 } else {
4167 this.buffer.update(cx, |buffer, cx| {
4168 buffer.edit(
4169 ranges.iter().map(|range| (range.clone(), text)),
4170 this.autoindent_mode.clone(),
4171 cx,
4172 );
4173 });
4174 }
4175 for (buffer, edits) in linked_edits {
4176 buffer.update(cx, |buffer, cx| {
4177 let snapshot = buffer.snapshot();
4178 let edits = edits
4179 .into_iter()
4180 .map(|(range, text)| {
4181 use text::ToPoint as TP;
4182 let end_point = TP::to_point(&range.end, &snapshot);
4183 let start_point = TP::to_point(&range.start, &snapshot);
4184 (start_point..end_point, text)
4185 })
4186 .sorted_by_key(|(range, _)| range.start)
4187 .collect::<Vec<_>>();
4188 buffer.edit(edits, None, cx);
4189 })
4190 }
4191
4192 this.refresh_inline_completion(true, false, window, cx);
4193 });
4194
4195 let show_new_completions_on_confirm = completion
4196 .confirm
4197 .as_ref()
4198 .map_or(false, |confirm| confirm(intent, window, cx));
4199 if show_new_completions_on_confirm {
4200 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4201 }
4202
4203 let provider = self.completion_provider.as_ref()?;
4204 drop(completion);
4205 let apply_edits = provider.apply_additional_edits_for_completion(
4206 buffer_handle,
4207 completions_menu.completions.clone(),
4208 candidate_id,
4209 true,
4210 cx,
4211 );
4212
4213 let editor_settings = EditorSettings::get_global(cx);
4214 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4215 // After the code completion is finished, users often want to know what signatures are needed.
4216 // so we should automatically call signature_help
4217 self.show_signature_help(&ShowSignatureHelp, window, cx);
4218 }
4219
4220 Some(cx.foreground_executor().spawn(async move {
4221 apply_edits.await?;
4222 Ok(())
4223 }))
4224 }
4225
4226 pub fn toggle_code_actions(
4227 &mut self,
4228 action: &ToggleCodeActions,
4229 window: &mut Window,
4230 cx: &mut Context<Self>,
4231 ) {
4232 let mut context_menu = self.context_menu.borrow_mut();
4233 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4234 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4235 // Toggle if we're selecting the same one
4236 *context_menu = None;
4237 cx.notify();
4238 return;
4239 } else {
4240 // Otherwise, clear it and start a new one
4241 *context_menu = None;
4242 cx.notify();
4243 }
4244 }
4245 drop(context_menu);
4246 let snapshot = self.snapshot(window, cx);
4247 let deployed_from_indicator = action.deployed_from_indicator;
4248 let mut task = self.code_actions_task.take();
4249 let action = action.clone();
4250 cx.spawn_in(window, |editor, mut cx| async move {
4251 while let Some(prev_task) = task {
4252 prev_task.await.log_err();
4253 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4254 }
4255
4256 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4257 if editor.focus_handle.is_focused(window) {
4258 let multibuffer_point = action
4259 .deployed_from_indicator
4260 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4261 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4262 let (buffer, buffer_row) = snapshot
4263 .buffer_snapshot
4264 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4265 .and_then(|(buffer_snapshot, range)| {
4266 editor
4267 .buffer
4268 .read(cx)
4269 .buffer(buffer_snapshot.remote_id())
4270 .map(|buffer| (buffer, range.start.row))
4271 })?;
4272 let (_, code_actions) = editor
4273 .available_code_actions
4274 .clone()
4275 .and_then(|(location, code_actions)| {
4276 let snapshot = location.buffer.read(cx).snapshot();
4277 let point_range = location.range.to_point(&snapshot);
4278 let point_range = point_range.start.row..=point_range.end.row;
4279 if point_range.contains(&buffer_row) {
4280 Some((location, code_actions))
4281 } else {
4282 None
4283 }
4284 })
4285 .unzip();
4286 let buffer_id = buffer.read(cx).remote_id();
4287 let tasks = editor
4288 .tasks
4289 .get(&(buffer_id, buffer_row))
4290 .map(|t| Arc::new(t.to_owned()));
4291 if tasks.is_none() && code_actions.is_none() {
4292 return None;
4293 }
4294
4295 editor.completion_tasks.clear();
4296 editor.discard_inline_completion(false, cx);
4297 let task_context =
4298 tasks
4299 .as_ref()
4300 .zip(editor.project.clone())
4301 .map(|(tasks, project)| {
4302 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4303 });
4304
4305 Some(cx.spawn_in(window, |editor, mut cx| async move {
4306 let task_context = match task_context {
4307 Some(task_context) => task_context.await,
4308 None => None,
4309 };
4310 let resolved_tasks =
4311 tasks.zip(task_context).map(|(tasks, task_context)| {
4312 Rc::new(ResolvedTasks {
4313 templates: tasks.resolve(&task_context).collect(),
4314 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4315 multibuffer_point.row,
4316 tasks.column,
4317 )),
4318 })
4319 });
4320 let spawn_straight_away = resolved_tasks
4321 .as_ref()
4322 .map_or(false, |tasks| tasks.templates.len() == 1)
4323 && code_actions
4324 .as_ref()
4325 .map_or(true, |actions| actions.is_empty());
4326 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4327 *editor.context_menu.borrow_mut() =
4328 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4329 buffer,
4330 actions: CodeActionContents {
4331 tasks: resolved_tasks,
4332 actions: code_actions,
4333 },
4334 selected_item: Default::default(),
4335 scroll_handle: UniformListScrollHandle::default(),
4336 deployed_from_indicator,
4337 }));
4338 if spawn_straight_away {
4339 if let Some(task) = editor.confirm_code_action(
4340 &ConfirmCodeAction { item_ix: Some(0) },
4341 window,
4342 cx,
4343 ) {
4344 cx.notify();
4345 return task;
4346 }
4347 }
4348 cx.notify();
4349 Task::ready(Ok(()))
4350 }) {
4351 task.await
4352 } else {
4353 Ok(())
4354 }
4355 }))
4356 } else {
4357 Some(Task::ready(Ok(())))
4358 }
4359 })?;
4360 if let Some(task) = spawned_test_task {
4361 task.await?;
4362 }
4363
4364 Ok::<_, anyhow::Error>(())
4365 })
4366 .detach_and_log_err(cx);
4367 }
4368
4369 pub fn confirm_code_action(
4370 &mut self,
4371 action: &ConfirmCodeAction,
4372 window: &mut Window,
4373 cx: &mut Context<Self>,
4374 ) -> Option<Task<Result<()>>> {
4375 let actions_menu =
4376 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4377 menu
4378 } else {
4379 return None;
4380 };
4381 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4382 let action = actions_menu.actions.get(action_ix)?;
4383 let title = action.label();
4384 let buffer = actions_menu.buffer;
4385 let workspace = self.workspace()?;
4386
4387 match action {
4388 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4389 workspace.update(cx, |workspace, cx| {
4390 workspace::tasks::schedule_resolved_task(
4391 workspace,
4392 task_source_kind,
4393 resolved_task,
4394 false,
4395 cx,
4396 );
4397
4398 Some(Task::ready(Ok(())))
4399 })
4400 }
4401 CodeActionsItem::CodeAction {
4402 excerpt_id,
4403 action,
4404 provider,
4405 } => {
4406 let apply_code_action =
4407 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4408 let workspace = workspace.downgrade();
4409 Some(cx.spawn_in(window, |editor, cx| async move {
4410 let project_transaction = apply_code_action.await?;
4411 Self::open_project_transaction(
4412 &editor,
4413 workspace,
4414 project_transaction,
4415 title,
4416 cx,
4417 )
4418 .await
4419 }))
4420 }
4421 }
4422 }
4423
4424 pub async fn open_project_transaction(
4425 this: &WeakEntity<Editor>,
4426 workspace: WeakEntity<Workspace>,
4427 transaction: ProjectTransaction,
4428 title: String,
4429 mut cx: AsyncWindowContext,
4430 ) -> Result<()> {
4431 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4432 cx.update(|_, cx| {
4433 entries.sort_unstable_by_key(|(buffer, _)| {
4434 buffer.read(cx).file().map(|f| f.path().clone())
4435 });
4436 })?;
4437
4438 // If the project transaction's edits are all contained within this editor, then
4439 // avoid opening a new editor to display them.
4440
4441 if let Some((buffer, transaction)) = entries.first() {
4442 if entries.len() == 1 {
4443 let excerpt = this.update(&mut cx, |editor, cx| {
4444 editor
4445 .buffer()
4446 .read(cx)
4447 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4448 })?;
4449 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4450 if excerpted_buffer == *buffer {
4451 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4452 let excerpt_range = excerpt_range.to_offset(buffer);
4453 buffer
4454 .edited_ranges_for_transaction::<usize>(transaction)
4455 .all(|range| {
4456 excerpt_range.start <= range.start
4457 && excerpt_range.end >= range.end
4458 })
4459 })?;
4460
4461 if all_edits_within_excerpt {
4462 return Ok(());
4463 }
4464 }
4465 }
4466 }
4467 } else {
4468 return Ok(());
4469 }
4470
4471 let mut ranges_to_highlight = Vec::new();
4472 let excerpt_buffer = cx.new(|cx| {
4473 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4474 for (buffer_handle, transaction) in &entries {
4475 let buffer = buffer_handle.read(cx);
4476 ranges_to_highlight.extend(
4477 multibuffer.push_excerpts_with_context_lines(
4478 buffer_handle.clone(),
4479 buffer
4480 .edited_ranges_for_transaction::<usize>(transaction)
4481 .collect(),
4482 DEFAULT_MULTIBUFFER_CONTEXT,
4483 cx,
4484 ),
4485 );
4486 }
4487 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4488 multibuffer
4489 })?;
4490
4491 workspace.update_in(&mut cx, |workspace, window, cx| {
4492 let project = workspace.project().clone();
4493 let editor = cx
4494 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4495 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4496 editor.update(cx, |editor, cx| {
4497 editor.highlight_background::<Self>(
4498 &ranges_to_highlight,
4499 |theme| theme.editor_highlighted_line_background,
4500 cx,
4501 );
4502 });
4503 })?;
4504
4505 Ok(())
4506 }
4507
4508 pub fn clear_code_action_providers(&mut self) {
4509 self.code_action_providers.clear();
4510 self.available_code_actions.take();
4511 }
4512
4513 pub fn add_code_action_provider(
4514 &mut self,
4515 provider: Rc<dyn CodeActionProvider>,
4516 window: &mut Window,
4517 cx: &mut Context<Self>,
4518 ) {
4519 if self
4520 .code_action_providers
4521 .iter()
4522 .any(|existing_provider| existing_provider.id() == provider.id())
4523 {
4524 return;
4525 }
4526
4527 self.code_action_providers.push(provider);
4528 self.refresh_code_actions(window, cx);
4529 }
4530
4531 pub fn remove_code_action_provider(
4532 &mut self,
4533 id: Arc<str>,
4534 window: &mut Window,
4535 cx: &mut Context<Self>,
4536 ) {
4537 self.code_action_providers
4538 .retain(|provider| provider.id() != id);
4539 self.refresh_code_actions(window, cx);
4540 }
4541
4542 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4543 let buffer = self.buffer.read(cx);
4544 let newest_selection = self.selections.newest_anchor().clone();
4545 if newest_selection.head().diff_base_anchor.is_some() {
4546 return None;
4547 }
4548 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4549 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4550 if start_buffer != end_buffer {
4551 return None;
4552 }
4553
4554 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4555 cx.background_executor()
4556 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4557 .await;
4558
4559 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4560 let providers = this.code_action_providers.clone();
4561 let tasks = this
4562 .code_action_providers
4563 .iter()
4564 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4565 .collect::<Vec<_>>();
4566 (providers, tasks)
4567 })?;
4568
4569 let mut actions = Vec::new();
4570 for (provider, provider_actions) in
4571 providers.into_iter().zip(future::join_all(tasks).await)
4572 {
4573 if let Some(provider_actions) = provider_actions.log_err() {
4574 actions.extend(provider_actions.into_iter().map(|action| {
4575 AvailableCodeAction {
4576 excerpt_id: newest_selection.start.excerpt_id,
4577 action,
4578 provider: provider.clone(),
4579 }
4580 }));
4581 }
4582 }
4583
4584 this.update(&mut cx, |this, cx| {
4585 this.available_code_actions = if actions.is_empty() {
4586 None
4587 } else {
4588 Some((
4589 Location {
4590 buffer: start_buffer,
4591 range: start..end,
4592 },
4593 actions.into(),
4594 ))
4595 };
4596 cx.notify();
4597 })
4598 }));
4599 None
4600 }
4601
4602 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4603 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4604 self.show_git_blame_inline = false;
4605
4606 self.show_git_blame_inline_delay_task =
4607 Some(cx.spawn_in(window, |this, mut cx| async move {
4608 cx.background_executor().timer(delay).await;
4609
4610 this.update(&mut cx, |this, cx| {
4611 this.show_git_blame_inline = true;
4612 cx.notify();
4613 })
4614 .log_err();
4615 }));
4616 }
4617 }
4618
4619 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4620 if self.pending_rename.is_some() {
4621 return None;
4622 }
4623
4624 let provider = self.semantics_provider.clone()?;
4625 let buffer = self.buffer.read(cx);
4626 let newest_selection = self.selections.newest_anchor().clone();
4627 let cursor_position = newest_selection.head();
4628 let (cursor_buffer, cursor_buffer_position) =
4629 buffer.text_anchor_for_position(cursor_position, cx)?;
4630 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4631 if cursor_buffer != tail_buffer {
4632 return None;
4633 }
4634 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4635 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4636 cx.background_executor()
4637 .timer(Duration::from_millis(debounce))
4638 .await;
4639
4640 let highlights = if let Some(highlights) = cx
4641 .update(|cx| {
4642 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4643 })
4644 .ok()
4645 .flatten()
4646 {
4647 highlights.await.log_err()
4648 } else {
4649 None
4650 };
4651
4652 if let Some(highlights) = highlights {
4653 this.update(&mut cx, |this, cx| {
4654 if this.pending_rename.is_some() {
4655 return;
4656 }
4657
4658 let buffer_id = cursor_position.buffer_id;
4659 let buffer = this.buffer.read(cx);
4660 if !buffer
4661 .text_anchor_for_position(cursor_position, cx)
4662 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4663 {
4664 return;
4665 }
4666
4667 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4668 let mut write_ranges = Vec::new();
4669 let mut read_ranges = Vec::new();
4670 for highlight in highlights {
4671 for (excerpt_id, excerpt_range) in
4672 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4673 {
4674 let start = highlight
4675 .range
4676 .start
4677 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4678 let end = highlight
4679 .range
4680 .end
4681 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4682 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4683 continue;
4684 }
4685
4686 let range = Anchor {
4687 buffer_id,
4688 excerpt_id,
4689 text_anchor: start,
4690 diff_base_anchor: None,
4691 }..Anchor {
4692 buffer_id,
4693 excerpt_id,
4694 text_anchor: end,
4695 diff_base_anchor: None,
4696 };
4697 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4698 write_ranges.push(range);
4699 } else {
4700 read_ranges.push(range);
4701 }
4702 }
4703 }
4704
4705 this.highlight_background::<DocumentHighlightRead>(
4706 &read_ranges,
4707 |theme| theme.editor_document_highlight_read_background,
4708 cx,
4709 );
4710 this.highlight_background::<DocumentHighlightWrite>(
4711 &write_ranges,
4712 |theme| theme.editor_document_highlight_write_background,
4713 cx,
4714 );
4715 cx.notify();
4716 })
4717 .log_err();
4718 }
4719 }));
4720 None
4721 }
4722
4723 pub fn refresh_inline_completion(
4724 &mut self,
4725 debounce: bool,
4726 user_requested: bool,
4727 window: &mut Window,
4728 cx: &mut Context<Self>,
4729 ) -> Option<()> {
4730 let provider = self.edit_prediction_provider()?;
4731 let cursor = self.selections.newest_anchor().head();
4732 let (buffer, cursor_buffer_position) =
4733 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4734
4735 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4736 self.discard_inline_completion(false, cx);
4737 return None;
4738 }
4739
4740 if !user_requested
4741 && (!self.should_show_edit_predictions()
4742 || !self.is_focused(window)
4743 || buffer.read(cx).is_empty())
4744 {
4745 self.discard_inline_completion(false, cx);
4746 return None;
4747 }
4748
4749 self.update_visible_inline_completion(window, cx);
4750 provider.refresh(
4751 self.project.clone(),
4752 buffer,
4753 cursor_buffer_position,
4754 debounce,
4755 cx,
4756 );
4757 Some(())
4758 }
4759
4760 fn show_edit_predictions_in_menu(&self) -> bool {
4761 match self.edit_prediction_settings {
4762 EditPredictionSettings::Disabled => false,
4763 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4764 }
4765 }
4766
4767 pub fn edit_predictions_enabled(&self) -> bool {
4768 match self.edit_prediction_settings {
4769 EditPredictionSettings::Disabled => false,
4770 EditPredictionSettings::Enabled { .. } => true,
4771 }
4772 }
4773
4774 fn edit_prediction_requires_modifier(&self) -> bool {
4775 match self.edit_prediction_settings {
4776 EditPredictionSettings::Disabled => false,
4777 EditPredictionSettings::Enabled {
4778 preview_requires_modifier,
4779 ..
4780 } => preview_requires_modifier,
4781 }
4782 }
4783
4784 fn edit_prediction_settings_at_position(
4785 &self,
4786 buffer: &Entity<Buffer>,
4787 buffer_position: language::Anchor,
4788 cx: &App,
4789 ) -> EditPredictionSettings {
4790 if self.mode != EditorMode::Full
4791 || !self.show_inline_completions_override.unwrap_or(true)
4792 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4793 {
4794 return EditPredictionSettings::Disabled;
4795 }
4796
4797 let buffer = buffer.read(cx);
4798
4799 let file = buffer.file();
4800
4801 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4802 return EditPredictionSettings::Disabled;
4803 };
4804
4805 let by_provider = matches!(
4806 self.menu_inline_completions_policy,
4807 MenuInlineCompletionsPolicy::ByProvider
4808 );
4809
4810 let show_in_menu = by_provider
4811 && self
4812 .edit_prediction_provider
4813 .as_ref()
4814 .map_or(false, |provider| {
4815 provider.provider.show_completions_in_menu()
4816 });
4817
4818 let preview_requires_modifier =
4819 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4820
4821 EditPredictionSettings::Enabled {
4822 show_in_menu,
4823 preview_requires_modifier,
4824 }
4825 }
4826
4827 fn should_show_edit_predictions(&self) -> bool {
4828 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4829 }
4830
4831 pub fn edit_prediction_preview_is_active(&self) -> bool {
4832 matches!(
4833 self.edit_prediction_preview,
4834 EditPredictionPreview::Active { .. }
4835 )
4836 }
4837
4838 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4839 let cursor = self.selections.newest_anchor().head();
4840 if let Some((buffer, cursor_position)) =
4841 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4842 {
4843 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4844 } else {
4845 false
4846 }
4847 }
4848
4849 fn inline_completions_enabled_in_buffer(
4850 &self,
4851 buffer: &Entity<Buffer>,
4852 buffer_position: language::Anchor,
4853 cx: &App,
4854 ) -> bool {
4855 maybe!({
4856 let provider = self.edit_prediction_provider()?;
4857 if !provider.is_enabled(&buffer, buffer_position, cx) {
4858 return Some(false);
4859 }
4860 let buffer = buffer.read(cx);
4861 let Some(file) = buffer.file() else {
4862 return Some(true);
4863 };
4864 let settings = all_language_settings(Some(file), cx);
4865 Some(settings.inline_completions_enabled_for_path(file.path()))
4866 })
4867 .unwrap_or(false)
4868 }
4869
4870 fn cycle_inline_completion(
4871 &mut self,
4872 direction: Direction,
4873 window: &mut Window,
4874 cx: &mut Context<Self>,
4875 ) -> Option<()> {
4876 let provider = self.edit_prediction_provider()?;
4877 let cursor = self.selections.newest_anchor().head();
4878 let (buffer, cursor_buffer_position) =
4879 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4880 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4881 return None;
4882 }
4883
4884 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4885 self.update_visible_inline_completion(window, cx);
4886
4887 Some(())
4888 }
4889
4890 pub fn show_inline_completion(
4891 &mut self,
4892 _: &ShowEditPrediction,
4893 window: &mut Window,
4894 cx: &mut Context<Self>,
4895 ) {
4896 if !self.has_active_inline_completion() {
4897 self.refresh_inline_completion(false, true, window, cx);
4898 return;
4899 }
4900
4901 self.update_visible_inline_completion(window, cx);
4902 }
4903
4904 pub fn display_cursor_names(
4905 &mut self,
4906 _: &DisplayCursorNames,
4907 window: &mut Window,
4908 cx: &mut Context<Self>,
4909 ) {
4910 self.show_cursor_names(window, cx);
4911 }
4912
4913 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4914 self.show_cursor_names = true;
4915 cx.notify();
4916 cx.spawn_in(window, |this, mut cx| async move {
4917 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4918 this.update(&mut cx, |this, cx| {
4919 this.show_cursor_names = false;
4920 cx.notify()
4921 })
4922 .ok()
4923 })
4924 .detach();
4925 }
4926
4927 pub fn next_edit_prediction(
4928 &mut self,
4929 _: &NextEditPrediction,
4930 window: &mut Window,
4931 cx: &mut Context<Self>,
4932 ) {
4933 if self.has_active_inline_completion() {
4934 self.cycle_inline_completion(Direction::Next, window, cx);
4935 } else {
4936 let is_copilot_disabled = self
4937 .refresh_inline_completion(false, true, window, cx)
4938 .is_none();
4939 if is_copilot_disabled {
4940 cx.propagate();
4941 }
4942 }
4943 }
4944
4945 pub fn previous_edit_prediction(
4946 &mut self,
4947 _: &PreviousEditPrediction,
4948 window: &mut Window,
4949 cx: &mut Context<Self>,
4950 ) {
4951 if self.has_active_inline_completion() {
4952 self.cycle_inline_completion(Direction::Prev, window, cx);
4953 } else {
4954 let is_copilot_disabled = self
4955 .refresh_inline_completion(false, true, window, cx)
4956 .is_none();
4957 if is_copilot_disabled {
4958 cx.propagate();
4959 }
4960 }
4961 }
4962
4963 pub fn accept_edit_prediction(
4964 &mut self,
4965 _: &AcceptEditPrediction,
4966 window: &mut Window,
4967 cx: &mut Context<Self>,
4968 ) {
4969 if self.show_edit_predictions_in_menu() {
4970 self.hide_context_menu(window, cx);
4971 }
4972
4973 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4974 return;
4975 };
4976
4977 self.report_inline_completion_event(
4978 active_inline_completion.completion_id.clone(),
4979 true,
4980 cx,
4981 );
4982
4983 match &active_inline_completion.completion {
4984 InlineCompletion::Move { target, .. } => {
4985 let target = *target;
4986
4987 if let Some(position_map) = &self.last_position_map {
4988 if position_map
4989 .visible_row_range
4990 .contains(&target.to_display_point(&position_map.snapshot).row())
4991 || !self.edit_prediction_requires_modifier()
4992 {
4993 // Note that this is also done in vim's handler of the Tab action.
4994 self.change_selections(
4995 Some(Autoscroll::newest()),
4996 window,
4997 cx,
4998 |selections| {
4999 selections.select_anchor_ranges([target..target]);
5000 },
5001 );
5002 self.clear_row_highlights::<EditPredictionPreview>();
5003
5004 self.edit_prediction_preview = EditPredictionPreview::Active {
5005 previous_scroll_position: None,
5006 };
5007 } else {
5008 self.edit_prediction_preview = EditPredictionPreview::Active {
5009 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5010 };
5011 self.highlight_rows::<EditPredictionPreview>(
5012 target..target,
5013 cx.theme().colors().editor_highlighted_line_background,
5014 true,
5015 cx,
5016 );
5017 self.request_autoscroll(Autoscroll::fit(), cx);
5018 }
5019 }
5020 }
5021 InlineCompletion::Edit { edits, .. } => {
5022 if let Some(provider) = self.edit_prediction_provider() {
5023 provider.accept(cx);
5024 }
5025
5026 let snapshot = self.buffer.read(cx).snapshot(cx);
5027 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5028
5029 self.buffer.update(cx, |buffer, cx| {
5030 buffer.edit(edits.iter().cloned(), None, cx)
5031 });
5032
5033 self.change_selections(None, window, cx, |s| {
5034 s.select_anchor_ranges([last_edit_end..last_edit_end])
5035 });
5036
5037 self.update_visible_inline_completion(window, cx);
5038 if self.active_inline_completion.is_none() {
5039 self.refresh_inline_completion(true, true, window, cx);
5040 }
5041
5042 cx.notify();
5043 }
5044 }
5045
5046 self.edit_prediction_requires_modifier_in_leading_space = false;
5047 }
5048
5049 pub fn accept_partial_inline_completion(
5050 &mut self,
5051 _: &AcceptPartialEditPrediction,
5052 window: &mut Window,
5053 cx: &mut Context<Self>,
5054 ) {
5055 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5056 return;
5057 };
5058 if self.selections.count() != 1 {
5059 return;
5060 }
5061
5062 self.report_inline_completion_event(
5063 active_inline_completion.completion_id.clone(),
5064 true,
5065 cx,
5066 );
5067
5068 match &active_inline_completion.completion {
5069 InlineCompletion::Move { target, .. } => {
5070 let target = *target;
5071 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5072 selections.select_anchor_ranges([target..target]);
5073 });
5074 }
5075 InlineCompletion::Edit { edits, .. } => {
5076 // Find an insertion that starts at the cursor position.
5077 let snapshot = self.buffer.read(cx).snapshot(cx);
5078 let cursor_offset = self.selections.newest::<usize>(cx).head();
5079 let insertion = edits.iter().find_map(|(range, text)| {
5080 let range = range.to_offset(&snapshot);
5081 if range.is_empty() && range.start == cursor_offset {
5082 Some(text)
5083 } else {
5084 None
5085 }
5086 });
5087
5088 if let Some(text) = insertion {
5089 let mut partial_completion = text
5090 .chars()
5091 .by_ref()
5092 .take_while(|c| c.is_alphabetic())
5093 .collect::<String>();
5094 if partial_completion.is_empty() {
5095 partial_completion = text
5096 .chars()
5097 .by_ref()
5098 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5099 .collect::<String>();
5100 }
5101
5102 cx.emit(EditorEvent::InputHandled {
5103 utf16_range_to_replace: None,
5104 text: partial_completion.clone().into(),
5105 });
5106
5107 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5108
5109 self.refresh_inline_completion(true, true, window, cx);
5110 cx.notify();
5111 } else {
5112 self.accept_edit_prediction(&Default::default(), window, cx);
5113 }
5114 }
5115 }
5116 }
5117
5118 fn discard_inline_completion(
5119 &mut self,
5120 should_report_inline_completion_event: bool,
5121 cx: &mut Context<Self>,
5122 ) -> bool {
5123 if should_report_inline_completion_event {
5124 let completion_id = self
5125 .active_inline_completion
5126 .as_ref()
5127 .and_then(|active_completion| active_completion.completion_id.clone());
5128
5129 self.report_inline_completion_event(completion_id, false, cx);
5130 }
5131
5132 if let Some(provider) = self.edit_prediction_provider() {
5133 provider.discard(cx);
5134 }
5135
5136 self.take_active_inline_completion(cx)
5137 }
5138
5139 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5140 let Some(provider) = self.edit_prediction_provider() else {
5141 return;
5142 };
5143
5144 let Some((_, buffer, _)) = self
5145 .buffer
5146 .read(cx)
5147 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5148 else {
5149 return;
5150 };
5151
5152 let extension = buffer
5153 .read(cx)
5154 .file()
5155 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5156
5157 let event_type = match accepted {
5158 true => "Edit Prediction Accepted",
5159 false => "Edit Prediction Discarded",
5160 };
5161 telemetry::event!(
5162 event_type,
5163 provider = provider.name(),
5164 prediction_id = id,
5165 suggestion_accepted = accepted,
5166 file_extension = extension,
5167 );
5168 }
5169
5170 pub fn has_active_inline_completion(&self) -> bool {
5171 self.active_inline_completion.is_some()
5172 }
5173
5174 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5175 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5176 return false;
5177 };
5178
5179 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5180 self.clear_highlights::<InlineCompletionHighlight>(cx);
5181 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5182 true
5183 }
5184
5185 /// Returns true when we're displaying the edit prediction popover below the cursor
5186 /// like we are not previewing and the LSP autocomplete menu is visible
5187 /// or we are in `when_holding_modifier` mode.
5188 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5189 if self.edit_prediction_preview_is_active()
5190 || !self.show_edit_predictions_in_menu()
5191 || !self.edit_predictions_enabled()
5192 {
5193 return false;
5194 }
5195
5196 if self.has_visible_completions_menu() {
5197 return true;
5198 }
5199
5200 has_completion && self.edit_prediction_requires_modifier()
5201 }
5202
5203 fn handle_modifiers_changed(
5204 &mut self,
5205 modifiers: Modifiers,
5206 position_map: &PositionMap,
5207 window: &mut Window,
5208 cx: &mut Context<Self>,
5209 ) {
5210 if self.show_edit_predictions_in_menu() {
5211 self.update_edit_prediction_preview(&modifiers, window, cx);
5212 }
5213
5214 let mouse_position = window.mouse_position();
5215 if !position_map.text_hitbox.is_hovered(window) {
5216 return;
5217 }
5218
5219 self.update_hovered_link(
5220 position_map.point_for_position(mouse_position),
5221 &position_map.snapshot,
5222 modifiers,
5223 window,
5224 cx,
5225 )
5226 }
5227
5228 fn update_edit_prediction_preview(
5229 &mut self,
5230 modifiers: &Modifiers,
5231 window: &mut Window,
5232 cx: &mut Context<Self>,
5233 ) {
5234 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5235 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5236 return;
5237 };
5238
5239 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5240 if matches!(
5241 self.edit_prediction_preview,
5242 EditPredictionPreview::Inactive
5243 ) {
5244 self.edit_prediction_preview = EditPredictionPreview::Active {
5245 previous_scroll_position: None,
5246 };
5247
5248 self.update_visible_inline_completion(window, cx);
5249 cx.notify();
5250 }
5251 } else if let EditPredictionPreview::Active {
5252 previous_scroll_position,
5253 } = self.edit_prediction_preview
5254 {
5255 if let (Some(previous_scroll_position), Some(position_map)) =
5256 (previous_scroll_position, self.last_position_map.as_ref())
5257 {
5258 self.set_scroll_position(
5259 previous_scroll_position
5260 .scroll_position(&position_map.snapshot.display_snapshot),
5261 window,
5262 cx,
5263 );
5264 }
5265
5266 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5267 self.clear_row_highlights::<EditPredictionPreview>();
5268 self.update_visible_inline_completion(window, cx);
5269 cx.notify();
5270 }
5271 }
5272
5273 fn update_visible_inline_completion(
5274 &mut self,
5275 _window: &mut Window,
5276 cx: &mut Context<Self>,
5277 ) -> Option<()> {
5278 let selection = self.selections.newest_anchor();
5279 let cursor = selection.head();
5280 let multibuffer = self.buffer.read(cx).snapshot(cx);
5281 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5282 let excerpt_id = cursor.excerpt_id;
5283
5284 let show_in_menu = self.show_edit_predictions_in_menu();
5285 let completions_menu_has_precedence = !show_in_menu
5286 && (self.context_menu.borrow().is_some()
5287 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5288
5289 if completions_menu_has_precedence
5290 || !offset_selection.is_empty()
5291 || self
5292 .active_inline_completion
5293 .as_ref()
5294 .map_or(false, |completion| {
5295 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5296 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5297 !invalidation_range.contains(&offset_selection.head())
5298 })
5299 {
5300 self.discard_inline_completion(false, cx);
5301 return None;
5302 }
5303
5304 self.take_active_inline_completion(cx);
5305 let Some(provider) = self.edit_prediction_provider() else {
5306 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5307 return None;
5308 };
5309
5310 let (buffer, cursor_buffer_position) =
5311 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5312
5313 self.edit_prediction_settings =
5314 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5315
5316 if !self.edit_prediction_settings.is_enabled() {
5317 self.discard_inline_completion(false, cx);
5318 return None;
5319 }
5320
5321 self.edit_prediction_cursor_on_leading_whitespace =
5322 multibuffer.is_line_whitespace_upto(cursor);
5323
5324 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5325 let edits = inline_completion
5326 .edits
5327 .into_iter()
5328 .flat_map(|(range, new_text)| {
5329 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5330 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5331 Some((start..end, new_text))
5332 })
5333 .collect::<Vec<_>>();
5334 if edits.is_empty() {
5335 return None;
5336 }
5337
5338 let first_edit_start = edits.first().unwrap().0.start;
5339 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5340 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5341
5342 let last_edit_end = edits.last().unwrap().0.end;
5343 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5344 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5345
5346 let cursor_row = cursor.to_point(&multibuffer).row;
5347
5348 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5349
5350 let mut inlay_ids = Vec::new();
5351 let invalidation_row_range;
5352 let move_invalidation_row_range = if cursor_row < edit_start_row {
5353 Some(cursor_row..edit_end_row)
5354 } else if cursor_row > edit_end_row {
5355 Some(edit_start_row..cursor_row)
5356 } else {
5357 None
5358 };
5359 let is_move =
5360 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5361 let completion = if is_move {
5362 invalidation_row_range =
5363 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5364 let target = first_edit_start;
5365 InlineCompletion::Move { target, snapshot }
5366 } else {
5367 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5368 && !self.inline_completions_hidden_for_vim_mode;
5369
5370 if show_completions_in_buffer {
5371 if edits
5372 .iter()
5373 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5374 {
5375 let mut inlays = Vec::new();
5376 for (range, new_text) in &edits {
5377 let inlay = Inlay::inline_completion(
5378 post_inc(&mut self.next_inlay_id),
5379 range.start,
5380 new_text.as_str(),
5381 );
5382 inlay_ids.push(inlay.id);
5383 inlays.push(inlay);
5384 }
5385
5386 self.splice_inlays(&[], inlays, cx);
5387 } else {
5388 let background_color = cx.theme().status().deleted_background;
5389 self.highlight_text::<InlineCompletionHighlight>(
5390 edits.iter().map(|(range, _)| range.clone()).collect(),
5391 HighlightStyle {
5392 background_color: Some(background_color),
5393 ..Default::default()
5394 },
5395 cx,
5396 );
5397 }
5398 }
5399
5400 invalidation_row_range = edit_start_row..edit_end_row;
5401
5402 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5403 if provider.show_tab_accept_marker() {
5404 EditDisplayMode::TabAccept
5405 } else {
5406 EditDisplayMode::Inline
5407 }
5408 } else {
5409 EditDisplayMode::DiffPopover
5410 };
5411
5412 InlineCompletion::Edit {
5413 edits,
5414 edit_preview: inline_completion.edit_preview,
5415 display_mode,
5416 snapshot,
5417 }
5418 };
5419
5420 let invalidation_range = multibuffer
5421 .anchor_before(Point::new(invalidation_row_range.start, 0))
5422 ..multibuffer.anchor_after(Point::new(
5423 invalidation_row_range.end,
5424 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5425 ));
5426
5427 self.stale_inline_completion_in_menu = None;
5428 self.active_inline_completion = Some(InlineCompletionState {
5429 inlay_ids,
5430 completion,
5431 completion_id: inline_completion.id,
5432 invalidation_range,
5433 });
5434
5435 cx.notify();
5436
5437 Some(())
5438 }
5439
5440 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5441 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5442 }
5443
5444 fn render_code_actions_indicator(
5445 &self,
5446 _style: &EditorStyle,
5447 row: DisplayRow,
5448 is_active: bool,
5449 cx: &mut Context<Self>,
5450 ) -> Option<IconButton> {
5451 if self.available_code_actions.is_some() {
5452 Some(
5453 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5454 .shape(ui::IconButtonShape::Square)
5455 .icon_size(IconSize::XSmall)
5456 .icon_color(Color::Muted)
5457 .toggle_state(is_active)
5458 .tooltip({
5459 let focus_handle = self.focus_handle.clone();
5460 move |window, cx| {
5461 Tooltip::for_action_in(
5462 "Toggle Code Actions",
5463 &ToggleCodeActions {
5464 deployed_from_indicator: None,
5465 },
5466 &focus_handle,
5467 window,
5468 cx,
5469 )
5470 }
5471 })
5472 .on_click(cx.listener(move |editor, _e, window, cx| {
5473 window.focus(&editor.focus_handle(cx));
5474 editor.toggle_code_actions(
5475 &ToggleCodeActions {
5476 deployed_from_indicator: Some(row),
5477 },
5478 window,
5479 cx,
5480 );
5481 })),
5482 )
5483 } else {
5484 None
5485 }
5486 }
5487
5488 fn clear_tasks(&mut self) {
5489 self.tasks.clear()
5490 }
5491
5492 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5493 if self.tasks.insert(key, value).is_some() {
5494 // This case should hopefully be rare, but just in case...
5495 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5496 }
5497 }
5498
5499 fn build_tasks_context(
5500 project: &Entity<Project>,
5501 buffer: &Entity<Buffer>,
5502 buffer_row: u32,
5503 tasks: &Arc<RunnableTasks>,
5504 cx: &mut Context<Self>,
5505 ) -> Task<Option<task::TaskContext>> {
5506 let position = Point::new(buffer_row, tasks.column);
5507 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5508 let location = Location {
5509 buffer: buffer.clone(),
5510 range: range_start..range_start,
5511 };
5512 // Fill in the environmental variables from the tree-sitter captures
5513 let mut captured_task_variables = TaskVariables::default();
5514 for (capture_name, value) in tasks.extra_variables.clone() {
5515 captured_task_variables.insert(
5516 task::VariableName::Custom(capture_name.into()),
5517 value.clone(),
5518 );
5519 }
5520 project.update(cx, |project, cx| {
5521 project.task_store().update(cx, |task_store, cx| {
5522 task_store.task_context_for_location(captured_task_variables, location, cx)
5523 })
5524 })
5525 }
5526
5527 pub fn spawn_nearest_task(
5528 &mut self,
5529 action: &SpawnNearestTask,
5530 window: &mut Window,
5531 cx: &mut Context<Self>,
5532 ) {
5533 let Some((workspace, _)) = self.workspace.clone() else {
5534 return;
5535 };
5536 let Some(project) = self.project.clone() else {
5537 return;
5538 };
5539
5540 // Try to find a closest, enclosing node using tree-sitter that has a
5541 // task
5542 let Some((buffer, buffer_row, tasks)) = self
5543 .find_enclosing_node_task(cx)
5544 // Or find the task that's closest in row-distance.
5545 .or_else(|| self.find_closest_task(cx))
5546 else {
5547 return;
5548 };
5549
5550 let reveal_strategy = action.reveal;
5551 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5552 cx.spawn_in(window, |_, mut cx| async move {
5553 let context = task_context.await?;
5554 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5555
5556 let resolved = resolved_task.resolved.as_mut()?;
5557 resolved.reveal = reveal_strategy;
5558
5559 workspace
5560 .update(&mut cx, |workspace, cx| {
5561 workspace::tasks::schedule_resolved_task(
5562 workspace,
5563 task_source_kind,
5564 resolved_task,
5565 false,
5566 cx,
5567 );
5568 })
5569 .ok()
5570 })
5571 .detach();
5572 }
5573
5574 fn find_closest_task(
5575 &mut self,
5576 cx: &mut Context<Self>,
5577 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5578 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5579
5580 let ((buffer_id, row), tasks) = self
5581 .tasks
5582 .iter()
5583 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5584
5585 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5586 let tasks = Arc::new(tasks.to_owned());
5587 Some((buffer, *row, tasks))
5588 }
5589
5590 fn find_enclosing_node_task(
5591 &mut self,
5592 cx: &mut Context<Self>,
5593 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5594 let snapshot = self.buffer.read(cx).snapshot(cx);
5595 let offset = self.selections.newest::<usize>(cx).head();
5596 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5597 let buffer_id = excerpt.buffer().remote_id();
5598
5599 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5600 let mut cursor = layer.node().walk();
5601
5602 while cursor.goto_first_child_for_byte(offset).is_some() {
5603 if cursor.node().end_byte() == offset {
5604 cursor.goto_next_sibling();
5605 }
5606 }
5607
5608 // Ascend to the smallest ancestor that contains the range and has a task.
5609 loop {
5610 let node = cursor.node();
5611 let node_range = node.byte_range();
5612 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5613
5614 // Check if this node contains our offset
5615 if node_range.start <= offset && node_range.end >= offset {
5616 // If it contains offset, check for task
5617 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5618 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5619 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5620 }
5621 }
5622
5623 if !cursor.goto_parent() {
5624 break;
5625 }
5626 }
5627 None
5628 }
5629
5630 fn render_run_indicator(
5631 &self,
5632 _style: &EditorStyle,
5633 is_active: bool,
5634 row: DisplayRow,
5635 cx: &mut Context<Self>,
5636 ) -> IconButton {
5637 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5638 .shape(ui::IconButtonShape::Square)
5639 .icon_size(IconSize::XSmall)
5640 .icon_color(Color::Muted)
5641 .toggle_state(is_active)
5642 .on_click(cx.listener(move |editor, _e, window, cx| {
5643 window.focus(&editor.focus_handle(cx));
5644 editor.toggle_code_actions(
5645 &ToggleCodeActions {
5646 deployed_from_indicator: Some(row),
5647 },
5648 window,
5649 cx,
5650 );
5651 }))
5652 }
5653
5654 pub fn context_menu_visible(&self) -> bool {
5655 !self.edit_prediction_preview_is_active()
5656 && self
5657 .context_menu
5658 .borrow()
5659 .as_ref()
5660 .map_or(false, |menu| menu.visible())
5661 }
5662
5663 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5664 self.context_menu
5665 .borrow()
5666 .as_ref()
5667 .map(|menu| menu.origin())
5668 }
5669
5670 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5671 px(30.)
5672 }
5673
5674 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5675 if self.read_only(cx) {
5676 cx.theme().players().read_only()
5677 } else {
5678 self.style.as_ref().unwrap().local_player
5679 }
5680 }
5681
5682 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5683 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5684 let accept_keystroke = accept_binding.keystroke()?;
5685
5686 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5687
5688 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5689 Color::Accent
5690 } else {
5691 Color::Muted
5692 };
5693
5694 h_flex()
5695 .px_0p5()
5696 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5697 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5698 .text_size(TextSize::XSmall.rems(cx))
5699 .child(h_flex().children(ui::render_modifiers(
5700 &accept_keystroke.modifiers,
5701 PlatformStyle::platform(),
5702 Some(modifiers_color),
5703 Some(IconSize::XSmall.rems().into()),
5704 true,
5705 )))
5706 .when(is_platform_style_mac, |parent| {
5707 parent.child(accept_keystroke.key.clone())
5708 })
5709 .when(!is_platform_style_mac, |parent| {
5710 parent.child(
5711 Key::new(
5712 util::capitalize(&accept_keystroke.key),
5713 Some(Color::Default),
5714 )
5715 .size(Some(IconSize::XSmall.rems().into())),
5716 )
5717 })
5718 .into()
5719 }
5720
5721 fn render_edit_prediction_line_popover(
5722 &self,
5723 label: impl Into<SharedString>,
5724 icon: Option<IconName>,
5725 window: &mut Window,
5726 cx: &App,
5727 ) -> Option<Div> {
5728 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5729
5730 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5731
5732 let result = h_flex()
5733 .gap_1()
5734 .border_1()
5735 .rounded_lg()
5736 .shadow_sm()
5737 .bg(bg_color)
5738 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5739 .py_0p5()
5740 .pl_1()
5741 .pr(padding_right)
5742 .children(self.render_edit_prediction_accept_keybind(window, cx))
5743 .child(Label::new(label).size(LabelSize::Small))
5744 .when_some(icon, |element, icon| {
5745 element.child(
5746 div()
5747 .mt(px(1.5))
5748 .child(Icon::new(icon).size(IconSize::Small)),
5749 )
5750 });
5751
5752 Some(result)
5753 }
5754
5755 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5756 let accent_color = cx.theme().colors().text_accent;
5757 let editor_bg_color = cx.theme().colors().editor_background;
5758 editor_bg_color.blend(accent_color.opacity(0.1))
5759 }
5760
5761 #[allow(clippy::too_many_arguments)]
5762 fn render_edit_prediction_cursor_popover(
5763 &self,
5764 min_width: Pixels,
5765 max_width: Pixels,
5766 cursor_point: Point,
5767 style: &EditorStyle,
5768 accept_keystroke: &gpui::Keystroke,
5769 _window: &Window,
5770 cx: &mut Context<Editor>,
5771 ) -> Option<AnyElement> {
5772 let provider = self.edit_prediction_provider.as_ref()?;
5773
5774 if provider.provider.needs_terms_acceptance(cx) {
5775 return Some(
5776 h_flex()
5777 .min_w(min_width)
5778 .flex_1()
5779 .px_2()
5780 .py_1()
5781 .gap_3()
5782 .elevation_2(cx)
5783 .hover(|style| style.bg(cx.theme().colors().element_hover))
5784 .id("accept-terms")
5785 .cursor_pointer()
5786 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5787 .on_click(cx.listener(|this, _event, window, cx| {
5788 cx.stop_propagation();
5789 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5790 window.dispatch_action(
5791 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5792 cx,
5793 );
5794 }))
5795 .child(
5796 h_flex()
5797 .flex_1()
5798 .gap_2()
5799 .child(Icon::new(IconName::ZedPredict))
5800 .child(Label::new("Accept Terms of Service"))
5801 .child(div().w_full())
5802 .child(
5803 Icon::new(IconName::ArrowUpRight)
5804 .color(Color::Muted)
5805 .size(IconSize::Small),
5806 )
5807 .into_any_element(),
5808 )
5809 .into_any(),
5810 );
5811 }
5812
5813 let is_refreshing = provider.provider.is_refreshing(cx);
5814
5815 fn pending_completion_container() -> Div {
5816 h_flex()
5817 .h_full()
5818 .flex_1()
5819 .gap_2()
5820 .child(Icon::new(IconName::ZedPredict))
5821 }
5822
5823 let completion = match &self.active_inline_completion {
5824 Some(completion) => match &completion.completion {
5825 InlineCompletion::Move {
5826 target, snapshot, ..
5827 } if !self.has_visible_completions_menu() => {
5828 use text::ToPoint as _;
5829
5830 return Some(
5831 h_flex()
5832 .px_2()
5833 .py_1()
5834 .elevation_2(cx)
5835 .border_color(cx.theme().colors().border)
5836 .rounded_tl(px(0.))
5837 .gap_2()
5838 .child(
5839 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5840 Icon::new(IconName::ZedPredictDown)
5841 } else {
5842 Icon::new(IconName::ZedPredictUp)
5843 },
5844 )
5845 .child(Label::new("Hold").size(LabelSize::Small))
5846 .child(h_flex().children(ui::render_modifiers(
5847 &accept_keystroke.modifiers,
5848 PlatformStyle::platform(),
5849 Some(Color::Default),
5850 Some(IconSize::Small.rems().into()),
5851 false,
5852 )))
5853 .into_any(),
5854 );
5855 }
5856 _ => self.render_edit_prediction_cursor_popover_preview(
5857 completion,
5858 cursor_point,
5859 style,
5860 cx,
5861 )?,
5862 },
5863
5864 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5865 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5866 stale_completion,
5867 cursor_point,
5868 style,
5869 cx,
5870 )?,
5871
5872 None => {
5873 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5874 }
5875 },
5876
5877 None => pending_completion_container().child(Label::new("No Prediction")),
5878 };
5879
5880 let completion = if is_refreshing {
5881 completion
5882 .with_animation(
5883 "loading-completion",
5884 Animation::new(Duration::from_secs(2))
5885 .repeat()
5886 .with_easing(pulsating_between(0.4, 0.8)),
5887 |label, delta| label.opacity(delta),
5888 )
5889 .into_any_element()
5890 } else {
5891 completion.into_any_element()
5892 };
5893
5894 let has_completion = self.active_inline_completion.is_some();
5895
5896 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5897 Some(
5898 h_flex()
5899 .min_w(min_width)
5900 .max_w(max_width)
5901 .flex_1()
5902 .elevation_2(cx)
5903 .border_color(cx.theme().colors().border)
5904 .child(
5905 div()
5906 .flex_1()
5907 .py_1()
5908 .px_2()
5909 .overflow_hidden()
5910 .child(completion),
5911 )
5912 .child(
5913 h_flex()
5914 .h_full()
5915 .border_l_1()
5916 .rounded_r_lg()
5917 .border_color(cx.theme().colors().border)
5918 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5919 .gap_1()
5920 .py_1()
5921 .px_2()
5922 .child(
5923 h_flex()
5924 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5925 .when(is_platform_style_mac, |parent| parent.gap_1())
5926 .child(h_flex().children(ui::render_modifiers(
5927 &accept_keystroke.modifiers,
5928 PlatformStyle::platform(),
5929 Some(if !has_completion {
5930 Color::Muted
5931 } else {
5932 Color::Default
5933 }),
5934 None,
5935 false,
5936 ))),
5937 )
5938 .child(Label::new("Preview").into_any_element())
5939 .opacity(if has_completion { 1.0 } else { 0.4 }),
5940 )
5941 .into_any(),
5942 )
5943 }
5944
5945 fn render_edit_prediction_cursor_popover_preview(
5946 &self,
5947 completion: &InlineCompletionState,
5948 cursor_point: Point,
5949 style: &EditorStyle,
5950 cx: &mut Context<Editor>,
5951 ) -> Option<Div> {
5952 use text::ToPoint as _;
5953
5954 fn render_relative_row_jump(
5955 prefix: impl Into<String>,
5956 current_row: u32,
5957 target_row: u32,
5958 ) -> Div {
5959 let (row_diff, arrow) = if target_row < current_row {
5960 (current_row - target_row, IconName::ArrowUp)
5961 } else {
5962 (target_row - current_row, IconName::ArrowDown)
5963 };
5964
5965 h_flex()
5966 .child(
5967 Label::new(format!("{}{}", prefix.into(), row_diff))
5968 .color(Color::Muted)
5969 .size(LabelSize::Small),
5970 )
5971 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5972 }
5973
5974 match &completion.completion {
5975 InlineCompletion::Move {
5976 target, snapshot, ..
5977 } => Some(
5978 h_flex()
5979 .px_2()
5980 .gap_2()
5981 .flex_1()
5982 .child(
5983 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5984 Icon::new(IconName::ZedPredictDown)
5985 } else {
5986 Icon::new(IconName::ZedPredictUp)
5987 },
5988 )
5989 .child(Label::new("Jump to Edit")),
5990 ),
5991
5992 InlineCompletion::Edit {
5993 edits,
5994 edit_preview,
5995 snapshot,
5996 display_mode: _,
5997 } => {
5998 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5999
6000 let highlighted_edits = crate::inline_completion_edit_text(
6001 &snapshot,
6002 &edits,
6003 edit_preview.as_ref()?,
6004 true,
6005 cx,
6006 );
6007
6008 let len_total = highlighted_edits.text.len();
6009 let first_line = &highlighted_edits.text
6010 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
6011 let first_line_len = first_line.len();
6012
6013 let first_highlight_start = highlighted_edits
6014 .highlights
6015 .first()
6016 .map_or(0, |(range, _)| range.start);
6017 let drop_prefix_len = first_line
6018 .char_indices()
6019 .find(|(_, c)| !c.is_whitespace())
6020 .map_or(first_highlight_start, |(ix, _)| {
6021 ix.min(first_highlight_start)
6022 });
6023
6024 let preview_text = &first_line[drop_prefix_len..];
6025 let preview_len = preview_text.len();
6026 let highlights = highlighted_edits
6027 .highlights
6028 .into_iter()
6029 .take_until(|(range, _)| range.start > first_line_len)
6030 .map(|(range, style)| {
6031 (
6032 range.start - drop_prefix_len
6033 ..(range.end - drop_prefix_len).min(preview_len),
6034 style,
6035 )
6036 });
6037
6038 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
6039 .with_highlights(&style.text, highlights);
6040
6041 let preview = h_flex()
6042 .gap_1()
6043 .min_w_16()
6044 .child(styled_text)
6045 .when(len_total > first_line_len, |parent| parent.child("…"));
6046
6047 let left = if first_edit_row != cursor_point.row {
6048 render_relative_row_jump("", cursor_point.row, first_edit_row)
6049 .into_any_element()
6050 } else {
6051 Icon::new(IconName::ZedPredict).into_any_element()
6052 };
6053
6054 Some(
6055 h_flex()
6056 .h_full()
6057 .flex_1()
6058 .gap_2()
6059 .pr_1()
6060 .overflow_x_hidden()
6061 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6062 .child(left)
6063 .child(preview),
6064 )
6065 }
6066 }
6067 }
6068
6069 fn render_context_menu(
6070 &self,
6071 style: &EditorStyle,
6072 max_height_in_lines: u32,
6073 y_flipped: bool,
6074 window: &mut Window,
6075 cx: &mut Context<Editor>,
6076 ) -> Option<AnyElement> {
6077 let menu = self.context_menu.borrow();
6078 let menu = menu.as_ref()?;
6079 if !menu.visible() {
6080 return None;
6081 };
6082 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6083 }
6084
6085 fn render_context_menu_aside(
6086 &self,
6087 style: &EditorStyle,
6088 max_size: Size<Pixels>,
6089 cx: &mut Context<Editor>,
6090 ) -> Option<AnyElement> {
6091 self.context_menu.borrow().as_ref().and_then(|menu| {
6092 if menu.visible() {
6093 menu.render_aside(
6094 style,
6095 max_size,
6096 self.workspace.as_ref().map(|(w, _)| w.clone()),
6097 cx,
6098 )
6099 } else {
6100 None
6101 }
6102 })
6103 }
6104
6105 fn hide_context_menu(
6106 &mut self,
6107 window: &mut Window,
6108 cx: &mut Context<Self>,
6109 ) -> Option<CodeContextMenu> {
6110 cx.notify();
6111 self.completion_tasks.clear();
6112 let context_menu = self.context_menu.borrow_mut().take();
6113 self.stale_inline_completion_in_menu.take();
6114 self.update_visible_inline_completion(window, cx);
6115 context_menu
6116 }
6117
6118 fn show_snippet_choices(
6119 &mut self,
6120 choices: &Vec<String>,
6121 selection: Range<Anchor>,
6122 cx: &mut Context<Self>,
6123 ) {
6124 if selection.start.buffer_id.is_none() {
6125 return;
6126 }
6127 let buffer_id = selection.start.buffer_id.unwrap();
6128 let buffer = self.buffer().read(cx).buffer(buffer_id);
6129 let id = post_inc(&mut self.next_completion_id);
6130
6131 if let Some(buffer) = buffer {
6132 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6133 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6134 ));
6135 }
6136 }
6137
6138 pub fn insert_snippet(
6139 &mut self,
6140 insertion_ranges: &[Range<usize>],
6141 snippet: Snippet,
6142 window: &mut Window,
6143 cx: &mut Context<Self>,
6144 ) -> Result<()> {
6145 struct Tabstop<T> {
6146 is_end_tabstop: bool,
6147 ranges: Vec<Range<T>>,
6148 choices: Option<Vec<String>>,
6149 }
6150
6151 let tabstops = self.buffer.update(cx, |buffer, cx| {
6152 let snippet_text: Arc<str> = snippet.text.clone().into();
6153 buffer.edit(
6154 insertion_ranges
6155 .iter()
6156 .cloned()
6157 .map(|range| (range, snippet_text.clone())),
6158 Some(AutoindentMode::EachLine),
6159 cx,
6160 );
6161
6162 let snapshot = &*buffer.read(cx);
6163 let snippet = &snippet;
6164 snippet
6165 .tabstops
6166 .iter()
6167 .map(|tabstop| {
6168 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6169 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6170 });
6171 let mut tabstop_ranges = tabstop
6172 .ranges
6173 .iter()
6174 .flat_map(|tabstop_range| {
6175 let mut delta = 0_isize;
6176 insertion_ranges.iter().map(move |insertion_range| {
6177 let insertion_start = insertion_range.start as isize + delta;
6178 delta +=
6179 snippet.text.len() as isize - insertion_range.len() as isize;
6180
6181 let start = ((insertion_start + tabstop_range.start) as usize)
6182 .min(snapshot.len());
6183 let end = ((insertion_start + tabstop_range.end) as usize)
6184 .min(snapshot.len());
6185 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6186 })
6187 })
6188 .collect::<Vec<_>>();
6189 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6190
6191 Tabstop {
6192 is_end_tabstop,
6193 ranges: tabstop_ranges,
6194 choices: tabstop.choices.clone(),
6195 }
6196 })
6197 .collect::<Vec<_>>()
6198 });
6199 if let Some(tabstop) = tabstops.first() {
6200 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6201 s.select_ranges(tabstop.ranges.iter().cloned());
6202 });
6203
6204 if let Some(choices) = &tabstop.choices {
6205 if let Some(selection) = tabstop.ranges.first() {
6206 self.show_snippet_choices(choices, selection.clone(), cx)
6207 }
6208 }
6209
6210 // If we're already at the last tabstop and it's at the end of the snippet,
6211 // we're done, we don't need to keep the state around.
6212 if !tabstop.is_end_tabstop {
6213 let choices = tabstops
6214 .iter()
6215 .map(|tabstop| tabstop.choices.clone())
6216 .collect();
6217
6218 let ranges = tabstops
6219 .into_iter()
6220 .map(|tabstop| tabstop.ranges)
6221 .collect::<Vec<_>>();
6222
6223 self.snippet_stack.push(SnippetState {
6224 active_index: 0,
6225 ranges,
6226 choices,
6227 });
6228 }
6229
6230 // Check whether the just-entered snippet ends with an auto-closable bracket.
6231 if self.autoclose_regions.is_empty() {
6232 let snapshot = self.buffer.read(cx).snapshot(cx);
6233 for selection in &mut self.selections.all::<Point>(cx) {
6234 let selection_head = selection.head();
6235 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6236 continue;
6237 };
6238
6239 let mut bracket_pair = None;
6240 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6241 let prev_chars = snapshot
6242 .reversed_chars_at(selection_head)
6243 .collect::<String>();
6244 for (pair, enabled) in scope.brackets() {
6245 if enabled
6246 && pair.close
6247 && prev_chars.starts_with(pair.start.as_str())
6248 && next_chars.starts_with(pair.end.as_str())
6249 {
6250 bracket_pair = Some(pair.clone());
6251 break;
6252 }
6253 }
6254 if let Some(pair) = bracket_pair {
6255 let start = snapshot.anchor_after(selection_head);
6256 let end = snapshot.anchor_after(selection_head);
6257 self.autoclose_regions.push(AutocloseRegion {
6258 selection_id: selection.id,
6259 range: start..end,
6260 pair,
6261 });
6262 }
6263 }
6264 }
6265 }
6266 Ok(())
6267 }
6268
6269 pub fn move_to_next_snippet_tabstop(
6270 &mut self,
6271 window: &mut Window,
6272 cx: &mut Context<Self>,
6273 ) -> bool {
6274 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6275 }
6276
6277 pub fn move_to_prev_snippet_tabstop(
6278 &mut self,
6279 window: &mut Window,
6280 cx: &mut Context<Self>,
6281 ) -> bool {
6282 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6283 }
6284
6285 pub fn move_to_snippet_tabstop(
6286 &mut self,
6287 bias: Bias,
6288 window: &mut Window,
6289 cx: &mut Context<Self>,
6290 ) -> bool {
6291 if let Some(mut snippet) = self.snippet_stack.pop() {
6292 match bias {
6293 Bias::Left => {
6294 if snippet.active_index > 0 {
6295 snippet.active_index -= 1;
6296 } else {
6297 self.snippet_stack.push(snippet);
6298 return false;
6299 }
6300 }
6301 Bias::Right => {
6302 if snippet.active_index + 1 < snippet.ranges.len() {
6303 snippet.active_index += 1;
6304 } else {
6305 self.snippet_stack.push(snippet);
6306 return false;
6307 }
6308 }
6309 }
6310 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6311 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6312 s.select_anchor_ranges(current_ranges.iter().cloned())
6313 });
6314
6315 if let Some(choices) = &snippet.choices[snippet.active_index] {
6316 if let Some(selection) = current_ranges.first() {
6317 self.show_snippet_choices(&choices, selection.clone(), cx);
6318 }
6319 }
6320
6321 // If snippet state is not at the last tabstop, push it back on the stack
6322 if snippet.active_index + 1 < snippet.ranges.len() {
6323 self.snippet_stack.push(snippet);
6324 }
6325 return true;
6326 }
6327 }
6328
6329 false
6330 }
6331
6332 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6333 self.transact(window, cx, |this, window, cx| {
6334 this.select_all(&SelectAll, window, cx);
6335 this.insert("", window, cx);
6336 });
6337 }
6338
6339 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6340 self.transact(window, cx, |this, window, cx| {
6341 this.select_autoclose_pair(window, cx);
6342 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6343 if !this.linked_edit_ranges.is_empty() {
6344 let selections = this.selections.all::<MultiBufferPoint>(cx);
6345 let snapshot = this.buffer.read(cx).snapshot(cx);
6346
6347 for selection in selections.iter() {
6348 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6349 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6350 if selection_start.buffer_id != selection_end.buffer_id {
6351 continue;
6352 }
6353 if let Some(ranges) =
6354 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6355 {
6356 for (buffer, entries) in ranges {
6357 linked_ranges.entry(buffer).or_default().extend(entries);
6358 }
6359 }
6360 }
6361 }
6362
6363 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6364 if !this.selections.line_mode {
6365 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6366 for selection in &mut selections {
6367 if selection.is_empty() {
6368 let old_head = selection.head();
6369 let mut new_head =
6370 movement::left(&display_map, old_head.to_display_point(&display_map))
6371 .to_point(&display_map);
6372 if let Some((buffer, line_buffer_range)) = display_map
6373 .buffer_snapshot
6374 .buffer_line_for_row(MultiBufferRow(old_head.row))
6375 {
6376 let indent_size =
6377 buffer.indent_size_for_line(line_buffer_range.start.row);
6378 let indent_len = match indent_size.kind {
6379 IndentKind::Space => {
6380 buffer.settings_at(line_buffer_range.start, cx).tab_size
6381 }
6382 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6383 };
6384 if old_head.column <= indent_size.len && old_head.column > 0 {
6385 let indent_len = indent_len.get();
6386 new_head = cmp::min(
6387 new_head,
6388 MultiBufferPoint::new(
6389 old_head.row,
6390 ((old_head.column - 1) / indent_len) * indent_len,
6391 ),
6392 );
6393 }
6394 }
6395
6396 selection.set_head(new_head, SelectionGoal::None);
6397 }
6398 }
6399 }
6400
6401 this.signature_help_state.set_backspace_pressed(true);
6402 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6403 s.select(selections)
6404 });
6405 this.insert("", window, cx);
6406 let empty_str: Arc<str> = Arc::from("");
6407 for (buffer, edits) in linked_ranges {
6408 let snapshot = buffer.read(cx).snapshot();
6409 use text::ToPoint as TP;
6410
6411 let edits = edits
6412 .into_iter()
6413 .map(|range| {
6414 let end_point = TP::to_point(&range.end, &snapshot);
6415 let mut start_point = TP::to_point(&range.start, &snapshot);
6416
6417 if end_point == start_point {
6418 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6419 .saturating_sub(1);
6420 start_point =
6421 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6422 };
6423
6424 (start_point..end_point, empty_str.clone())
6425 })
6426 .sorted_by_key(|(range, _)| range.start)
6427 .collect::<Vec<_>>();
6428 buffer.update(cx, |this, cx| {
6429 this.edit(edits, None, cx);
6430 })
6431 }
6432 this.refresh_inline_completion(true, false, window, cx);
6433 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6434 });
6435 }
6436
6437 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6438 self.transact(window, cx, |this, window, cx| {
6439 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6440 let line_mode = s.line_mode;
6441 s.move_with(|map, selection| {
6442 if selection.is_empty() && !line_mode {
6443 let cursor = movement::right(map, selection.head());
6444 selection.end = cursor;
6445 selection.reversed = true;
6446 selection.goal = SelectionGoal::None;
6447 }
6448 })
6449 });
6450 this.insert("", window, cx);
6451 this.refresh_inline_completion(true, false, window, cx);
6452 });
6453 }
6454
6455 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6456 if self.move_to_prev_snippet_tabstop(window, cx) {
6457 return;
6458 }
6459
6460 self.outdent(&Outdent, window, cx);
6461 }
6462
6463 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6464 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6465 return;
6466 }
6467
6468 let mut selections = self.selections.all_adjusted(cx);
6469 let buffer = self.buffer.read(cx);
6470 let snapshot = buffer.snapshot(cx);
6471 let rows_iter = selections.iter().map(|s| s.head().row);
6472 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6473
6474 let mut edits = Vec::new();
6475 let mut prev_edited_row = 0;
6476 let mut row_delta = 0;
6477 for selection in &mut selections {
6478 if selection.start.row != prev_edited_row {
6479 row_delta = 0;
6480 }
6481 prev_edited_row = selection.end.row;
6482
6483 // If the selection is non-empty, then increase the indentation of the selected lines.
6484 if !selection.is_empty() {
6485 row_delta =
6486 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6487 continue;
6488 }
6489
6490 // If the selection is empty and the cursor is in the leading whitespace before the
6491 // suggested indentation, then auto-indent the line.
6492 let cursor = selection.head();
6493 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6494 if let Some(suggested_indent) =
6495 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6496 {
6497 if cursor.column < suggested_indent.len
6498 && cursor.column <= current_indent.len
6499 && current_indent.len <= suggested_indent.len
6500 {
6501 selection.start = Point::new(cursor.row, suggested_indent.len);
6502 selection.end = selection.start;
6503 if row_delta == 0 {
6504 edits.extend(Buffer::edit_for_indent_size_adjustment(
6505 cursor.row,
6506 current_indent,
6507 suggested_indent,
6508 ));
6509 row_delta = suggested_indent.len - current_indent.len;
6510 }
6511 continue;
6512 }
6513 }
6514
6515 // Otherwise, insert a hard or soft tab.
6516 let settings = buffer.settings_at(cursor, cx);
6517 let tab_size = if settings.hard_tabs {
6518 IndentSize::tab()
6519 } else {
6520 let tab_size = settings.tab_size.get();
6521 let char_column = snapshot
6522 .text_for_range(Point::new(cursor.row, 0)..cursor)
6523 .flat_map(str::chars)
6524 .count()
6525 + row_delta as usize;
6526 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6527 IndentSize::spaces(chars_to_next_tab_stop)
6528 };
6529 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6530 selection.end = selection.start;
6531 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6532 row_delta += tab_size.len;
6533 }
6534
6535 self.transact(window, cx, |this, window, cx| {
6536 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6537 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6538 s.select(selections)
6539 });
6540 this.refresh_inline_completion(true, false, window, cx);
6541 });
6542 }
6543
6544 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6545 if self.read_only(cx) {
6546 return;
6547 }
6548 let mut selections = self.selections.all::<Point>(cx);
6549 let mut prev_edited_row = 0;
6550 let mut row_delta = 0;
6551 let mut edits = Vec::new();
6552 let buffer = self.buffer.read(cx);
6553 let snapshot = buffer.snapshot(cx);
6554 for selection in &mut selections {
6555 if selection.start.row != prev_edited_row {
6556 row_delta = 0;
6557 }
6558 prev_edited_row = selection.end.row;
6559
6560 row_delta =
6561 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6562 }
6563
6564 self.transact(window, cx, |this, window, cx| {
6565 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6566 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6567 s.select(selections)
6568 });
6569 });
6570 }
6571
6572 fn indent_selection(
6573 buffer: &MultiBuffer,
6574 snapshot: &MultiBufferSnapshot,
6575 selection: &mut Selection<Point>,
6576 edits: &mut Vec<(Range<Point>, String)>,
6577 delta_for_start_row: u32,
6578 cx: &App,
6579 ) -> u32 {
6580 let settings = buffer.settings_at(selection.start, cx);
6581 let tab_size = settings.tab_size.get();
6582 let indent_kind = if settings.hard_tabs {
6583 IndentKind::Tab
6584 } else {
6585 IndentKind::Space
6586 };
6587 let mut start_row = selection.start.row;
6588 let mut end_row = selection.end.row + 1;
6589
6590 // If a selection ends at the beginning of a line, don't indent
6591 // that last line.
6592 if selection.end.column == 0 && selection.end.row > selection.start.row {
6593 end_row -= 1;
6594 }
6595
6596 // Avoid re-indenting a row that has already been indented by a
6597 // previous selection, but still update this selection's column
6598 // to reflect that indentation.
6599 if delta_for_start_row > 0 {
6600 start_row += 1;
6601 selection.start.column += delta_for_start_row;
6602 if selection.end.row == selection.start.row {
6603 selection.end.column += delta_for_start_row;
6604 }
6605 }
6606
6607 let mut delta_for_end_row = 0;
6608 let has_multiple_rows = start_row + 1 != end_row;
6609 for row in start_row..end_row {
6610 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6611 let indent_delta = match (current_indent.kind, indent_kind) {
6612 (IndentKind::Space, IndentKind::Space) => {
6613 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6614 IndentSize::spaces(columns_to_next_tab_stop)
6615 }
6616 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6617 (_, IndentKind::Tab) => IndentSize::tab(),
6618 };
6619
6620 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6621 0
6622 } else {
6623 selection.start.column
6624 };
6625 let row_start = Point::new(row, start);
6626 edits.push((
6627 row_start..row_start,
6628 indent_delta.chars().collect::<String>(),
6629 ));
6630
6631 // Update this selection's endpoints to reflect the indentation.
6632 if row == selection.start.row {
6633 selection.start.column += indent_delta.len;
6634 }
6635 if row == selection.end.row {
6636 selection.end.column += indent_delta.len;
6637 delta_for_end_row = indent_delta.len;
6638 }
6639 }
6640
6641 if selection.start.row == selection.end.row {
6642 delta_for_start_row + delta_for_end_row
6643 } else {
6644 delta_for_end_row
6645 }
6646 }
6647
6648 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6649 if self.read_only(cx) {
6650 return;
6651 }
6652 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6653 let selections = self.selections.all::<Point>(cx);
6654 let mut deletion_ranges = Vec::new();
6655 let mut last_outdent = None;
6656 {
6657 let buffer = self.buffer.read(cx);
6658 let snapshot = buffer.snapshot(cx);
6659 for selection in &selections {
6660 let settings = buffer.settings_at(selection.start, cx);
6661 let tab_size = settings.tab_size.get();
6662 let mut rows = selection.spanned_rows(false, &display_map);
6663
6664 // Avoid re-outdenting a row that has already been outdented by a
6665 // previous selection.
6666 if let Some(last_row) = last_outdent {
6667 if last_row == rows.start {
6668 rows.start = rows.start.next_row();
6669 }
6670 }
6671 let has_multiple_rows = rows.len() > 1;
6672 for row in rows.iter_rows() {
6673 let indent_size = snapshot.indent_size_for_line(row);
6674 if indent_size.len > 0 {
6675 let deletion_len = match indent_size.kind {
6676 IndentKind::Space => {
6677 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6678 if columns_to_prev_tab_stop == 0 {
6679 tab_size
6680 } else {
6681 columns_to_prev_tab_stop
6682 }
6683 }
6684 IndentKind::Tab => 1,
6685 };
6686 let start = if has_multiple_rows
6687 || deletion_len > selection.start.column
6688 || indent_size.len < selection.start.column
6689 {
6690 0
6691 } else {
6692 selection.start.column - deletion_len
6693 };
6694 deletion_ranges.push(
6695 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6696 );
6697 last_outdent = Some(row);
6698 }
6699 }
6700 }
6701 }
6702
6703 self.transact(window, cx, |this, window, cx| {
6704 this.buffer.update(cx, |buffer, cx| {
6705 let empty_str: Arc<str> = Arc::default();
6706 buffer.edit(
6707 deletion_ranges
6708 .into_iter()
6709 .map(|range| (range, empty_str.clone())),
6710 None,
6711 cx,
6712 );
6713 });
6714 let selections = this.selections.all::<usize>(cx);
6715 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6716 s.select(selections)
6717 });
6718 });
6719 }
6720
6721 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6722 if self.read_only(cx) {
6723 return;
6724 }
6725 let selections = self
6726 .selections
6727 .all::<usize>(cx)
6728 .into_iter()
6729 .map(|s| s.range());
6730
6731 self.transact(window, cx, |this, window, cx| {
6732 this.buffer.update(cx, |buffer, cx| {
6733 buffer.autoindent_ranges(selections, cx);
6734 });
6735 let selections = this.selections.all::<usize>(cx);
6736 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6737 s.select(selections)
6738 });
6739 });
6740 }
6741
6742 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6743 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6744 let selections = self.selections.all::<Point>(cx);
6745
6746 let mut new_cursors = Vec::new();
6747 let mut edit_ranges = Vec::new();
6748 let mut selections = selections.iter().peekable();
6749 while let Some(selection) = selections.next() {
6750 let mut rows = selection.spanned_rows(false, &display_map);
6751 let goal_display_column = selection.head().to_display_point(&display_map).column();
6752
6753 // Accumulate contiguous regions of rows that we want to delete.
6754 while let Some(next_selection) = selections.peek() {
6755 let next_rows = next_selection.spanned_rows(false, &display_map);
6756 if next_rows.start <= rows.end {
6757 rows.end = next_rows.end;
6758 selections.next().unwrap();
6759 } else {
6760 break;
6761 }
6762 }
6763
6764 let buffer = &display_map.buffer_snapshot;
6765 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6766 let edit_end;
6767 let cursor_buffer_row;
6768 if buffer.max_point().row >= rows.end.0 {
6769 // If there's a line after the range, delete the \n from the end of the row range
6770 // and position the cursor on the next line.
6771 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6772 cursor_buffer_row = rows.end;
6773 } else {
6774 // If there isn't a line after the range, delete the \n from the line before the
6775 // start of the row range and position the cursor there.
6776 edit_start = edit_start.saturating_sub(1);
6777 edit_end = buffer.len();
6778 cursor_buffer_row = rows.start.previous_row();
6779 }
6780
6781 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6782 *cursor.column_mut() =
6783 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6784
6785 new_cursors.push((
6786 selection.id,
6787 buffer.anchor_after(cursor.to_point(&display_map)),
6788 ));
6789 edit_ranges.push(edit_start..edit_end);
6790 }
6791
6792 self.transact(window, cx, |this, window, cx| {
6793 let buffer = this.buffer.update(cx, |buffer, cx| {
6794 let empty_str: Arc<str> = Arc::default();
6795 buffer.edit(
6796 edit_ranges
6797 .into_iter()
6798 .map(|range| (range, empty_str.clone())),
6799 None,
6800 cx,
6801 );
6802 buffer.snapshot(cx)
6803 });
6804 let new_selections = new_cursors
6805 .into_iter()
6806 .map(|(id, cursor)| {
6807 let cursor = cursor.to_point(&buffer);
6808 Selection {
6809 id,
6810 start: cursor,
6811 end: cursor,
6812 reversed: false,
6813 goal: SelectionGoal::None,
6814 }
6815 })
6816 .collect();
6817
6818 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6819 s.select(new_selections);
6820 });
6821 });
6822 }
6823
6824 pub fn join_lines_impl(
6825 &mut self,
6826 insert_whitespace: bool,
6827 window: &mut Window,
6828 cx: &mut Context<Self>,
6829 ) {
6830 if self.read_only(cx) {
6831 return;
6832 }
6833 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6834 for selection in self.selections.all::<Point>(cx) {
6835 let start = MultiBufferRow(selection.start.row);
6836 // Treat single line selections as if they include the next line. Otherwise this action
6837 // would do nothing for single line selections individual cursors.
6838 let end = if selection.start.row == selection.end.row {
6839 MultiBufferRow(selection.start.row + 1)
6840 } else {
6841 MultiBufferRow(selection.end.row)
6842 };
6843
6844 if let Some(last_row_range) = row_ranges.last_mut() {
6845 if start <= last_row_range.end {
6846 last_row_range.end = end;
6847 continue;
6848 }
6849 }
6850 row_ranges.push(start..end);
6851 }
6852
6853 let snapshot = self.buffer.read(cx).snapshot(cx);
6854 let mut cursor_positions = Vec::new();
6855 for row_range in &row_ranges {
6856 let anchor = snapshot.anchor_before(Point::new(
6857 row_range.end.previous_row().0,
6858 snapshot.line_len(row_range.end.previous_row()),
6859 ));
6860 cursor_positions.push(anchor..anchor);
6861 }
6862
6863 self.transact(window, cx, |this, window, cx| {
6864 for row_range in row_ranges.into_iter().rev() {
6865 for row in row_range.iter_rows().rev() {
6866 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6867 let next_line_row = row.next_row();
6868 let indent = snapshot.indent_size_for_line(next_line_row);
6869 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6870
6871 let replace =
6872 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6873 " "
6874 } else {
6875 ""
6876 };
6877
6878 this.buffer.update(cx, |buffer, cx| {
6879 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6880 });
6881 }
6882 }
6883
6884 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6885 s.select_anchor_ranges(cursor_positions)
6886 });
6887 });
6888 }
6889
6890 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6891 self.join_lines_impl(true, window, cx);
6892 }
6893
6894 pub fn sort_lines_case_sensitive(
6895 &mut self,
6896 _: &SortLinesCaseSensitive,
6897 window: &mut Window,
6898 cx: &mut Context<Self>,
6899 ) {
6900 self.manipulate_lines(window, cx, |lines| lines.sort())
6901 }
6902
6903 pub fn sort_lines_case_insensitive(
6904 &mut self,
6905 _: &SortLinesCaseInsensitive,
6906 window: &mut Window,
6907 cx: &mut Context<Self>,
6908 ) {
6909 self.manipulate_lines(window, cx, |lines| {
6910 lines.sort_by_key(|line| line.to_lowercase())
6911 })
6912 }
6913
6914 pub fn unique_lines_case_insensitive(
6915 &mut self,
6916 _: &UniqueLinesCaseInsensitive,
6917 window: &mut Window,
6918 cx: &mut Context<Self>,
6919 ) {
6920 self.manipulate_lines(window, cx, |lines| {
6921 let mut seen = HashSet::default();
6922 lines.retain(|line| seen.insert(line.to_lowercase()));
6923 })
6924 }
6925
6926 pub fn unique_lines_case_sensitive(
6927 &mut self,
6928 _: &UniqueLinesCaseSensitive,
6929 window: &mut Window,
6930 cx: &mut Context<Self>,
6931 ) {
6932 self.manipulate_lines(window, cx, |lines| {
6933 let mut seen = HashSet::default();
6934 lines.retain(|line| seen.insert(*line));
6935 })
6936 }
6937
6938 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6939 let mut revert_changes = HashMap::default();
6940 let snapshot = self.snapshot(window, cx);
6941 for hunk in snapshot
6942 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6943 {
6944 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6945 }
6946 if !revert_changes.is_empty() {
6947 self.transact(window, cx, |editor, window, cx| {
6948 editor.revert(revert_changes, window, cx);
6949 });
6950 }
6951 }
6952
6953 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6954 let Some(project) = self.project.clone() else {
6955 return;
6956 };
6957 self.reload(project, window, cx)
6958 .detach_and_notify_err(window, cx);
6959 }
6960
6961 pub fn revert_selected_hunks(
6962 &mut self,
6963 _: &RevertSelectedHunks,
6964 window: &mut Window,
6965 cx: &mut Context<Self>,
6966 ) {
6967 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6968 self.revert_hunks_in_ranges(selections, window, cx);
6969 }
6970
6971 fn revert_hunks_in_ranges(
6972 &mut self,
6973 ranges: impl Iterator<Item = Range<Point>>,
6974 window: &mut Window,
6975 cx: &mut Context<Editor>,
6976 ) {
6977 let mut revert_changes = HashMap::default();
6978 let snapshot = self.snapshot(window, cx);
6979 for hunk in &snapshot.hunks_for_ranges(ranges) {
6980 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6981 }
6982 if !revert_changes.is_empty() {
6983 self.transact(window, cx, |editor, window, cx| {
6984 editor.revert(revert_changes, window, cx);
6985 });
6986 }
6987 }
6988
6989 pub fn open_active_item_in_terminal(
6990 &mut self,
6991 _: &OpenInTerminal,
6992 window: &mut Window,
6993 cx: &mut Context<Self>,
6994 ) {
6995 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6996 let project_path = buffer.read(cx).project_path(cx)?;
6997 let project = self.project.as_ref()?.read(cx);
6998 let entry = project.entry_for_path(&project_path, cx)?;
6999 let parent = match &entry.canonical_path {
7000 Some(canonical_path) => canonical_path.to_path_buf(),
7001 None => project.absolute_path(&project_path, cx)?,
7002 }
7003 .parent()?
7004 .to_path_buf();
7005 Some(parent)
7006 }) {
7007 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7008 }
7009 }
7010
7011 pub fn prepare_revert_change(
7012 &self,
7013 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7014 hunk: &MultiBufferDiffHunk,
7015 cx: &mut App,
7016 ) -> Option<()> {
7017 let buffer = self.buffer.read(cx);
7018 let diff = buffer.diff_for(hunk.buffer_id)?;
7019 let buffer = buffer.buffer(hunk.buffer_id)?;
7020 let buffer = buffer.read(cx);
7021 let original_text = diff
7022 .read(cx)
7023 .base_text()
7024 .as_ref()?
7025 .as_rope()
7026 .slice(hunk.diff_base_byte_range.clone());
7027 let buffer_snapshot = buffer.snapshot();
7028 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7029 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7030 probe
7031 .0
7032 .start
7033 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7034 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7035 }) {
7036 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7037 Some(())
7038 } else {
7039 None
7040 }
7041 }
7042
7043 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7044 self.manipulate_lines(window, cx, |lines| lines.reverse())
7045 }
7046
7047 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7048 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7049 }
7050
7051 fn manipulate_lines<Fn>(
7052 &mut self,
7053 window: &mut Window,
7054 cx: &mut Context<Self>,
7055 mut callback: Fn,
7056 ) where
7057 Fn: FnMut(&mut Vec<&str>),
7058 {
7059 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7060 let buffer = self.buffer.read(cx).snapshot(cx);
7061
7062 let mut edits = Vec::new();
7063
7064 let selections = self.selections.all::<Point>(cx);
7065 let mut selections = selections.iter().peekable();
7066 let mut contiguous_row_selections = Vec::new();
7067 let mut new_selections = Vec::new();
7068 let mut added_lines = 0;
7069 let mut removed_lines = 0;
7070
7071 while let Some(selection) = selections.next() {
7072 let (start_row, end_row) = consume_contiguous_rows(
7073 &mut contiguous_row_selections,
7074 selection,
7075 &display_map,
7076 &mut selections,
7077 );
7078
7079 let start_point = Point::new(start_row.0, 0);
7080 let end_point = Point::new(
7081 end_row.previous_row().0,
7082 buffer.line_len(end_row.previous_row()),
7083 );
7084 let text = buffer
7085 .text_for_range(start_point..end_point)
7086 .collect::<String>();
7087
7088 let mut lines = text.split('\n').collect_vec();
7089
7090 let lines_before = lines.len();
7091 callback(&mut lines);
7092 let lines_after = lines.len();
7093
7094 edits.push((start_point..end_point, lines.join("\n")));
7095
7096 // Selections must change based on added and removed line count
7097 let start_row =
7098 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7099 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7100 new_selections.push(Selection {
7101 id: selection.id,
7102 start: start_row,
7103 end: end_row,
7104 goal: SelectionGoal::None,
7105 reversed: selection.reversed,
7106 });
7107
7108 if lines_after > lines_before {
7109 added_lines += lines_after - lines_before;
7110 } else if lines_before > lines_after {
7111 removed_lines += lines_before - lines_after;
7112 }
7113 }
7114
7115 self.transact(window, cx, |this, window, cx| {
7116 let buffer = this.buffer.update(cx, |buffer, cx| {
7117 buffer.edit(edits, None, cx);
7118 buffer.snapshot(cx)
7119 });
7120
7121 // Recalculate offsets on newly edited buffer
7122 let new_selections = new_selections
7123 .iter()
7124 .map(|s| {
7125 let start_point = Point::new(s.start.0, 0);
7126 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7127 Selection {
7128 id: s.id,
7129 start: buffer.point_to_offset(start_point),
7130 end: buffer.point_to_offset(end_point),
7131 goal: s.goal,
7132 reversed: s.reversed,
7133 }
7134 })
7135 .collect();
7136
7137 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7138 s.select(new_selections);
7139 });
7140
7141 this.request_autoscroll(Autoscroll::fit(), cx);
7142 });
7143 }
7144
7145 pub fn convert_to_upper_case(
7146 &mut self,
7147 _: &ConvertToUpperCase,
7148 window: &mut Window,
7149 cx: &mut Context<Self>,
7150 ) {
7151 self.manipulate_text(window, cx, |text| text.to_uppercase())
7152 }
7153
7154 pub fn convert_to_lower_case(
7155 &mut self,
7156 _: &ConvertToLowerCase,
7157 window: &mut Window,
7158 cx: &mut Context<Self>,
7159 ) {
7160 self.manipulate_text(window, cx, |text| text.to_lowercase())
7161 }
7162
7163 pub fn convert_to_title_case(
7164 &mut self,
7165 _: &ConvertToTitleCase,
7166 window: &mut Window,
7167 cx: &mut Context<Self>,
7168 ) {
7169 self.manipulate_text(window, cx, |text| {
7170 text.split('\n')
7171 .map(|line| line.to_case(Case::Title))
7172 .join("\n")
7173 })
7174 }
7175
7176 pub fn convert_to_snake_case(
7177 &mut self,
7178 _: &ConvertToSnakeCase,
7179 window: &mut Window,
7180 cx: &mut Context<Self>,
7181 ) {
7182 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7183 }
7184
7185 pub fn convert_to_kebab_case(
7186 &mut self,
7187 _: &ConvertToKebabCase,
7188 window: &mut Window,
7189 cx: &mut Context<Self>,
7190 ) {
7191 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7192 }
7193
7194 pub fn convert_to_upper_camel_case(
7195 &mut self,
7196 _: &ConvertToUpperCamelCase,
7197 window: &mut Window,
7198 cx: &mut Context<Self>,
7199 ) {
7200 self.manipulate_text(window, cx, |text| {
7201 text.split('\n')
7202 .map(|line| line.to_case(Case::UpperCamel))
7203 .join("\n")
7204 })
7205 }
7206
7207 pub fn convert_to_lower_camel_case(
7208 &mut self,
7209 _: &ConvertToLowerCamelCase,
7210 window: &mut Window,
7211 cx: &mut Context<Self>,
7212 ) {
7213 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7214 }
7215
7216 pub fn convert_to_opposite_case(
7217 &mut self,
7218 _: &ConvertToOppositeCase,
7219 window: &mut Window,
7220 cx: &mut Context<Self>,
7221 ) {
7222 self.manipulate_text(window, cx, |text| {
7223 text.chars()
7224 .fold(String::with_capacity(text.len()), |mut t, c| {
7225 if c.is_uppercase() {
7226 t.extend(c.to_lowercase());
7227 } else {
7228 t.extend(c.to_uppercase());
7229 }
7230 t
7231 })
7232 })
7233 }
7234
7235 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7236 where
7237 Fn: FnMut(&str) -> String,
7238 {
7239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7240 let buffer = self.buffer.read(cx).snapshot(cx);
7241
7242 let mut new_selections = Vec::new();
7243 let mut edits = Vec::new();
7244 let mut selection_adjustment = 0i32;
7245
7246 for selection in self.selections.all::<usize>(cx) {
7247 let selection_is_empty = selection.is_empty();
7248
7249 let (start, end) = if selection_is_empty {
7250 let word_range = movement::surrounding_word(
7251 &display_map,
7252 selection.start.to_display_point(&display_map),
7253 );
7254 let start = word_range.start.to_offset(&display_map, Bias::Left);
7255 let end = word_range.end.to_offset(&display_map, Bias::Left);
7256 (start, end)
7257 } else {
7258 (selection.start, selection.end)
7259 };
7260
7261 let text = buffer.text_for_range(start..end).collect::<String>();
7262 let old_length = text.len() as i32;
7263 let text = callback(&text);
7264
7265 new_selections.push(Selection {
7266 start: (start as i32 - selection_adjustment) as usize,
7267 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7268 goal: SelectionGoal::None,
7269 ..selection
7270 });
7271
7272 selection_adjustment += old_length - text.len() as i32;
7273
7274 edits.push((start..end, text));
7275 }
7276
7277 self.transact(window, cx, |this, window, cx| {
7278 this.buffer.update(cx, |buffer, cx| {
7279 buffer.edit(edits, None, cx);
7280 });
7281
7282 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7283 s.select(new_selections);
7284 });
7285
7286 this.request_autoscroll(Autoscroll::fit(), cx);
7287 });
7288 }
7289
7290 pub fn duplicate(
7291 &mut self,
7292 upwards: bool,
7293 whole_lines: bool,
7294 window: &mut Window,
7295 cx: &mut Context<Self>,
7296 ) {
7297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7298 let buffer = &display_map.buffer_snapshot;
7299 let selections = self.selections.all::<Point>(cx);
7300
7301 let mut edits = Vec::new();
7302 let mut selections_iter = selections.iter().peekable();
7303 while let Some(selection) = selections_iter.next() {
7304 let mut rows = selection.spanned_rows(false, &display_map);
7305 // duplicate line-wise
7306 if whole_lines || selection.start == selection.end {
7307 // Avoid duplicating the same lines twice.
7308 while let Some(next_selection) = selections_iter.peek() {
7309 let next_rows = next_selection.spanned_rows(false, &display_map);
7310 if next_rows.start < rows.end {
7311 rows.end = next_rows.end;
7312 selections_iter.next().unwrap();
7313 } else {
7314 break;
7315 }
7316 }
7317
7318 // Copy the text from the selected row region and splice it either at the start
7319 // or end of the region.
7320 let start = Point::new(rows.start.0, 0);
7321 let end = Point::new(
7322 rows.end.previous_row().0,
7323 buffer.line_len(rows.end.previous_row()),
7324 );
7325 let text = buffer
7326 .text_for_range(start..end)
7327 .chain(Some("\n"))
7328 .collect::<String>();
7329 let insert_location = if upwards {
7330 Point::new(rows.end.0, 0)
7331 } else {
7332 start
7333 };
7334 edits.push((insert_location..insert_location, text));
7335 } else {
7336 // duplicate character-wise
7337 let start = selection.start;
7338 let end = selection.end;
7339 let text = buffer.text_for_range(start..end).collect::<String>();
7340 edits.push((selection.end..selection.end, text));
7341 }
7342 }
7343
7344 self.transact(window, cx, |this, _, cx| {
7345 this.buffer.update(cx, |buffer, cx| {
7346 buffer.edit(edits, None, cx);
7347 });
7348
7349 this.request_autoscroll(Autoscroll::fit(), cx);
7350 });
7351 }
7352
7353 pub fn duplicate_line_up(
7354 &mut self,
7355 _: &DuplicateLineUp,
7356 window: &mut Window,
7357 cx: &mut Context<Self>,
7358 ) {
7359 self.duplicate(true, true, window, cx);
7360 }
7361
7362 pub fn duplicate_line_down(
7363 &mut self,
7364 _: &DuplicateLineDown,
7365 window: &mut Window,
7366 cx: &mut Context<Self>,
7367 ) {
7368 self.duplicate(false, true, window, cx);
7369 }
7370
7371 pub fn duplicate_selection(
7372 &mut self,
7373 _: &DuplicateSelection,
7374 window: &mut Window,
7375 cx: &mut Context<Self>,
7376 ) {
7377 self.duplicate(false, false, window, cx);
7378 }
7379
7380 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7382 let buffer = self.buffer.read(cx).snapshot(cx);
7383
7384 let mut edits = Vec::new();
7385 let mut unfold_ranges = Vec::new();
7386 let mut refold_creases = Vec::new();
7387
7388 let selections = self.selections.all::<Point>(cx);
7389 let mut selections = selections.iter().peekable();
7390 let mut contiguous_row_selections = Vec::new();
7391 let mut new_selections = Vec::new();
7392
7393 while let Some(selection) = selections.next() {
7394 // Find all the selections that span a contiguous row range
7395 let (start_row, end_row) = consume_contiguous_rows(
7396 &mut contiguous_row_selections,
7397 selection,
7398 &display_map,
7399 &mut selections,
7400 );
7401
7402 // Move the text spanned by the row range to be before the line preceding the row range
7403 if start_row.0 > 0 {
7404 let range_to_move = Point::new(
7405 start_row.previous_row().0,
7406 buffer.line_len(start_row.previous_row()),
7407 )
7408 ..Point::new(
7409 end_row.previous_row().0,
7410 buffer.line_len(end_row.previous_row()),
7411 );
7412 let insertion_point = display_map
7413 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7414 .0;
7415
7416 // Don't move lines across excerpts
7417 if buffer
7418 .excerpt_containing(insertion_point..range_to_move.end)
7419 .is_some()
7420 {
7421 let text = buffer
7422 .text_for_range(range_to_move.clone())
7423 .flat_map(|s| s.chars())
7424 .skip(1)
7425 .chain(['\n'])
7426 .collect::<String>();
7427
7428 edits.push((
7429 buffer.anchor_after(range_to_move.start)
7430 ..buffer.anchor_before(range_to_move.end),
7431 String::new(),
7432 ));
7433 let insertion_anchor = buffer.anchor_after(insertion_point);
7434 edits.push((insertion_anchor..insertion_anchor, text));
7435
7436 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7437
7438 // Move selections up
7439 new_selections.extend(contiguous_row_selections.drain(..).map(
7440 |mut selection| {
7441 selection.start.row -= row_delta;
7442 selection.end.row -= row_delta;
7443 selection
7444 },
7445 ));
7446
7447 // Move folds up
7448 unfold_ranges.push(range_to_move.clone());
7449 for fold in display_map.folds_in_range(
7450 buffer.anchor_before(range_to_move.start)
7451 ..buffer.anchor_after(range_to_move.end),
7452 ) {
7453 let mut start = fold.range.start.to_point(&buffer);
7454 let mut end = fold.range.end.to_point(&buffer);
7455 start.row -= row_delta;
7456 end.row -= row_delta;
7457 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7458 }
7459 }
7460 }
7461
7462 // If we didn't move line(s), preserve the existing selections
7463 new_selections.append(&mut contiguous_row_selections);
7464 }
7465
7466 self.transact(window, cx, |this, window, cx| {
7467 this.unfold_ranges(&unfold_ranges, true, true, cx);
7468 this.buffer.update(cx, |buffer, cx| {
7469 for (range, text) in edits {
7470 buffer.edit([(range, text)], None, cx);
7471 }
7472 });
7473 this.fold_creases(refold_creases, true, window, cx);
7474 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7475 s.select(new_selections);
7476 })
7477 });
7478 }
7479
7480 pub fn move_line_down(
7481 &mut self,
7482 _: &MoveLineDown,
7483 window: &mut Window,
7484 cx: &mut Context<Self>,
7485 ) {
7486 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7487 let buffer = self.buffer.read(cx).snapshot(cx);
7488
7489 let mut edits = Vec::new();
7490 let mut unfold_ranges = Vec::new();
7491 let mut refold_creases = Vec::new();
7492
7493 let selections = self.selections.all::<Point>(cx);
7494 let mut selections = selections.iter().peekable();
7495 let mut contiguous_row_selections = Vec::new();
7496 let mut new_selections = Vec::new();
7497
7498 while let Some(selection) = selections.next() {
7499 // Find all the selections that span a contiguous row range
7500 let (start_row, end_row) = consume_contiguous_rows(
7501 &mut contiguous_row_selections,
7502 selection,
7503 &display_map,
7504 &mut selections,
7505 );
7506
7507 // Move the text spanned by the row range to be after the last line of the row range
7508 if end_row.0 <= buffer.max_point().row {
7509 let range_to_move =
7510 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7511 let insertion_point = display_map
7512 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7513 .0;
7514
7515 // Don't move lines across excerpt boundaries
7516 if buffer
7517 .excerpt_containing(range_to_move.start..insertion_point)
7518 .is_some()
7519 {
7520 let mut text = String::from("\n");
7521 text.extend(buffer.text_for_range(range_to_move.clone()));
7522 text.pop(); // Drop trailing newline
7523 edits.push((
7524 buffer.anchor_after(range_to_move.start)
7525 ..buffer.anchor_before(range_to_move.end),
7526 String::new(),
7527 ));
7528 let insertion_anchor = buffer.anchor_after(insertion_point);
7529 edits.push((insertion_anchor..insertion_anchor, text));
7530
7531 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7532
7533 // Move selections down
7534 new_selections.extend(contiguous_row_selections.drain(..).map(
7535 |mut selection| {
7536 selection.start.row += row_delta;
7537 selection.end.row += row_delta;
7538 selection
7539 },
7540 ));
7541
7542 // Move folds down
7543 unfold_ranges.push(range_to_move.clone());
7544 for fold in display_map.folds_in_range(
7545 buffer.anchor_before(range_to_move.start)
7546 ..buffer.anchor_after(range_to_move.end),
7547 ) {
7548 let mut start = fold.range.start.to_point(&buffer);
7549 let mut end = fold.range.end.to_point(&buffer);
7550 start.row += row_delta;
7551 end.row += row_delta;
7552 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7553 }
7554 }
7555 }
7556
7557 // If we didn't move line(s), preserve the existing selections
7558 new_selections.append(&mut contiguous_row_selections);
7559 }
7560
7561 self.transact(window, cx, |this, window, cx| {
7562 this.unfold_ranges(&unfold_ranges, true, true, cx);
7563 this.buffer.update(cx, |buffer, cx| {
7564 for (range, text) in edits {
7565 buffer.edit([(range, text)], None, cx);
7566 }
7567 });
7568 this.fold_creases(refold_creases, true, window, cx);
7569 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7570 s.select(new_selections)
7571 });
7572 });
7573 }
7574
7575 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7576 let text_layout_details = &self.text_layout_details(window);
7577 self.transact(window, cx, |this, window, cx| {
7578 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7579 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7580 let line_mode = s.line_mode;
7581 s.move_with(|display_map, selection| {
7582 if !selection.is_empty() || line_mode {
7583 return;
7584 }
7585
7586 let mut head = selection.head();
7587 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7588 if head.column() == display_map.line_len(head.row()) {
7589 transpose_offset = display_map
7590 .buffer_snapshot
7591 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7592 }
7593
7594 if transpose_offset == 0 {
7595 return;
7596 }
7597
7598 *head.column_mut() += 1;
7599 head = display_map.clip_point(head, Bias::Right);
7600 let goal = SelectionGoal::HorizontalPosition(
7601 display_map
7602 .x_for_display_point(head, text_layout_details)
7603 .into(),
7604 );
7605 selection.collapse_to(head, goal);
7606
7607 let transpose_start = display_map
7608 .buffer_snapshot
7609 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7610 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7611 let transpose_end = display_map
7612 .buffer_snapshot
7613 .clip_offset(transpose_offset + 1, Bias::Right);
7614 if let Some(ch) =
7615 display_map.buffer_snapshot.chars_at(transpose_start).next()
7616 {
7617 edits.push((transpose_start..transpose_offset, String::new()));
7618 edits.push((transpose_end..transpose_end, ch.to_string()));
7619 }
7620 }
7621 });
7622 edits
7623 });
7624 this.buffer
7625 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7626 let selections = this.selections.all::<usize>(cx);
7627 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7628 s.select(selections);
7629 });
7630 });
7631 }
7632
7633 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7634 self.rewrap_impl(IsVimMode::No, cx)
7635 }
7636
7637 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7638 let buffer = self.buffer.read(cx).snapshot(cx);
7639 let selections = self.selections.all::<Point>(cx);
7640 let mut selections = selections.iter().peekable();
7641
7642 let mut edits = Vec::new();
7643 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7644
7645 while let Some(selection) = selections.next() {
7646 let mut start_row = selection.start.row;
7647 let mut end_row = selection.end.row;
7648
7649 // Skip selections that overlap with a range that has already been rewrapped.
7650 let selection_range = start_row..end_row;
7651 if rewrapped_row_ranges
7652 .iter()
7653 .any(|range| range.overlaps(&selection_range))
7654 {
7655 continue;
7656 }
7657
7658 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7659
7660 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7661 match language_scope.language_name().as_ref() {
7662 "Markdown" | "Plain Text" => {
7663 should_rewrap = true;
7664 }
7665 _ => {}
7666 }
7667 }
7668
7669 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7670
7671 // Since not all lines in the selection may be at the same indent
7672 // level, choose the indent size that is the most common between all
7673 // of the lines.
7674 //
7675 // If there is a tie, we use the deepest indent.
7676 let (indent_size, indent_end) = {
7677 let mut indent_size_occurrences = HashMap::default();
7678 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7679
7680 for row in start_row..=end_row {
7681 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7682 rows_by_indent_size.entry(indent).or_default().push(row);
7683 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7684 }
7685
7686 let indent_size = indent_size_occurrences
7687 .into_iter()
7688 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7689 .map(|(indent, _)| indent)
7690 .unwrap_or_default();
7691 let row = rows_by_indent_size[&indent_size][0];
7692 let indent_end = Point::new(row, indent_size.len);
7693
7694 (indent_size, indent_end)
7695 };
7696
7697 let mut line_prefix = indent_size.chars().collect::<String>();
7698
7699 if let Some(comment_prefix) =
7700 buffer
7701 .language_scope_at(selection.head())
7702 .and_then(|language| {
7703 language
7704 .line_comment_prefixes()
7705 .iter()
7706 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7707 .cloned()
7708 })
7709 {
7710 line_prefix.push_str(&comment_prefix);
7711 should_rewrap = true;
7712 }
7713
7714 if !should_rewrap {
7715 continue;
7716 }
7717
7718 if selection.is_empty() {
7719 'expand_upwards: while start_row > 0 {
7720 let prev_row = start_row - 1;
7721 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7722 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7723 {
7724 start_row = prev_row;
7725 } else {
7726 break 'expand_upwards;
7727 }
7728 }
7729
7730 'expand_downwards: while end_row < buffer.max_point().row {
7731 let next_row = end_row + 1;
7732 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7733 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7734 {
7735 end_row = next_row;
7736 } else {
7737 break 'expand_downwards;
7738 }
7739 }
7740 }
7741
7742 let start = Point::new(start_row, 0);
7743 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7744 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7745 let Some(lines_without_prefixes) = selection_text
7746 .lines()
7747 .map(|line| {
7748 line.strip_prefix(&line_prefix)
7749 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7750 .ok_or_else(|| {
7751 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7752 })
7753 })
7754 .collect::<Result<Vec<_>, _>>()
7755 .log_err()
7756 else {
7757 continue;
7758 };
7759
7760 let wrap_column = buffer
7761 .settings_at(Point::new(start_row, 0), cx)
7762 .preferred_line_length as usize;
7763 let wrapped_text = wrap_with_prefix(
7764 line_prefix,
7765 lines_without_prefixes.join(" "),
7766 wrap_column,
7767 tab_size,
7768 );
7769
7770 // TODO: should always use char-based diff while still supporting cursor behavior that
7771 // matches vim.
7772 let diff = match is_vim_mode {
7773 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7774 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7775 };
7776 let mut offset = start.to_offset(&buffer);
7777 let mut moved_since_edit = true;
7778
7779 for change in diff.iter_all_changes() {
7780 let value = change.value();
7781 match change.tag() {
7782 ChangeTag::Equal => {
7783 offset += value.len();
7784 moved_since_edit = true;
7785 }
7786 ChangeTag::Delete => {
7787 let start = buffer.anchor_after(offset);
7788 let end = buffer.anchor_before(offset + value.len());
7789
7790 if moved_since_edit {
7791 edits.push((start..end, String::new()));
7792 } else {
7793 edits.last_mut().unwrap().0.end = end;
7794 }
7795
7796 offset += value.len();
7797 moved_since_edit = false;
7798 }
7799 ChangeTag::Insert => {
7800 if moved_since_edit {
7801 let anchor = buffer.anchor_after(offset);
7802 edits.push((anchor..anchor, value.to_string()));
7803 } else {
7804 edits.last_mut().unwrap().1.push_str(value);
7805 }
7806
7807 moved_since_edit = false;
7808 }
7809 }
7810 }
7811
7812 rewrapped_row_ranges.push(start_row..=end_row);
7813 }
7814
7815 self.buffer
7816 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7817 }
7818
7819 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7820 let mut text = String::new();
7821 let buffer = self.buffer.read(cx).snapshot(cx);
7822 let mut selections = self.selections.all::<Point>(cx);
7823 let mut clipboard_selections = Vec::with_capacity(selections.len());
7824 {
7825 let max_point = buffer.max_point();
7826 let mut is_first = true;
7827 for selection in &mut selections {
7828 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7829 if is_entire_line {
7830 selection.start = Point::new(selection.start.row, 0);
7831 if !selection.is_empty() && selection.end.column == 0 {
7832 selection.end = cmp::min(max_point, selection.end);
7833 } else {
7834 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7835 }
7836 selection.goal = SelectionGoal::None;
7837 }
7838 if is_first {
7839 is_first = false;
7840 } else {
7841 text += "\n";
7842 }
7843 let mut len = 0;
7844 for chunk in buffer.text_for_range(selection.start..selection.end) {
7845 text.push_str(chunk);
7846 len += chunk.len();
7847 }
7848 clipboard_selections.push(ClipboardSelection {
7849 len,
7850 is_entire_line,
7851 first_line_indent: buffer
7852 .indent_size_for_line(MultiBufferRow(selection.start.row))
7853 .len,
7854 });
7855 }
7856 }
7857
7858 self.transact(window, cx, |this, window, cx| {
7859 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7860 s.select(selections);
7861 });
7862 this.insert("", window, cx);
7863 });
7864 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7865 }
7866
7867 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7868 let item = self.cut_common(window, cx);
7869 cx.write_to_clipboard(item);
7870 }
7871
7872 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7873 self.change_selections(None, window, cx, |s| {
7874 s.move_with(|snapshot, sel| {
7875 if sel.is_empty() {
7876 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7877 }
7878 });
7879 });
7880 let item = self.cut_common(window, cx);
7881 cx.set_global(KillRing(item))
7882 }
7883
7884 pub fn kill_ring_yank(
7885 &mut self,
7886 _: &KillRingYank,
7887 window: &mut Window,
7888 cx: &mut Context<Self>,
7889 ) {
7890 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7891 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7892 (kill_ring.text().to_string(), kill_ring.metadata_json())
7893 } else {
7894 return;
7895 }
7896 } else {
7897 return;
7898 };
7899 self.do_paste(&text, metadata, false, window, cx);
7900 }
7901
7902 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7903 let selections = self.selections.all::<Point>(cx);
7904 let buffer = self.buffer.read(cx).read(cx);
7905 let mut text = String::new();
7906
7907 let mut clipboard_selections = Vec::with_capacity(selections.len());
7908 {
7909 let max_point = buffer.max_point();
7910 let mut is_first = true;
7911 for selection in selections.iter() {
7912 let mut start = selection.start;
7913 let mut end = selection.end;
7914 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7915 if is_entire_line {
7916 start = Point::new(start.row, 0);
7917 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7918 }
7919 if is_first {
7920 is_first = false;
7921 } else {
7922 text += "\n";
7923 }
7924 let mut len = 0;
7925 for chunk in buffer.text_for_range(start..end) {
7926 text.push_str(chunk);
7927 len += chunk.len();
7928 }
7929 clipboard_selections.push(ClipboardSelection {
7930 len,
7931 is_entire_line,
7932 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7933 });
7934 }
7935 }
7936
7937 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7938 text,
7939 clipboard_selections,
7940 ));
7941 }
7942
7943 pub fn do_paste(
7944 &mut self,
7945 text: &String,
7946 clipboard_selections: Option<Vec<ClipboardSelection>>,
7947 handle_entire_lines: bool,
7948 window: &mut Window,
7949 cx: &mut Context<Self>,
7950 ) {
7951 if self.read_only(cx) {
7952 return;
7953 }
7954
7955 let clipboard_text = Cow::Borrowed(text);
7956
7957 self.transact(window, cx, |this, window, cx| {
7958 if let Some(mut clipboard_selections) = clipboard_selections {
7959 let old_selections = this.selections.all::<usize>(cx);
7960 let all_selections_were_entire_line =
7961 clipboard_selections.iter().all(|s| s.is_entire_line);
7962 let first_selection_indent_column =
7963 clipboard_selections.first().map(|s| s.first_line_indent);
7964 if clipboard_selections.len() != old_selections.len() {
7965 clipboard_selections.drain(..);
7966 }
7967 let cursor_offset = this.selections.last::<usize>(cx).head();
7968 let mut auto_indent_on_paste = true;
7969
7970 this.buffer.update(cx, |buffer, cx| {
7971 let snapshot = buffer.read(cx);
7972 auto_indent_on_paste =
7973 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7974
7975 let mut start_offset = 0;
7976 let mut edits = Vec::new();
7977 let mut original_indent_columns = Vec::new();
7978 for (ix, selection) in old_selections.iter().enumerate() {
7979 let to_insert;
7980 let entire_line;
7981 let original_indent_column;
7982 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7983 let end_offset = start_offset + clipboard_selection.len;
7984 to_insert = &clipboard_text[start_offset..end_offset];
7985 entire_line = clipboard_selection.is_entire_line;
7986 start_offset = end_offset + 1;
7987 original_indent_column = Some(clipboard_selection.first_line_indent);
7988 } else {
7989 to_insert = clipboard_text.as_str();
7990 entire_line = all_selections_were_entire_line;
7991 original_indent_column = first_selection_indent_column
7992 }
7993
7994 // If the corresponding selection was empty when this slice of the
7995 // clipboard text was written, then the entire line containing the
7996 // selection was copied. If this selection is also currently empty,
7997 // then paste the line before the current line of the buffer.
7998 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7999 let column = selection.start.to_point(&snapshot).column as usize;
8000 let line_start = selection.start - column;
8001 line_start..line_start
8002 } else {
8003 selection.range()
8004 };
8005
8006 edits.push((range, to_insert));
8007 original_indent_columns.extend(original_indent_column);
8008 }
8009 drop(snapshot);
8010
8011 buffer.edit(
8012 edits,
8013 if auto_indent_on_paste {
8014 Some(AutoindentMode::Block {
8015 original_indent_columns,
8016 })
8017 } else {
8018 None
8019 },
8020 cx,
8021 );
8022 });
8023
8024 let selections = this.selections.all::<usize>(cx);
8025 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8026 s.select(selections)
8027 });
8028 } else {
8029 this.insert(&clipboard_text, window, cx);
8030 }
8031 });
8032 }
8033
8034 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8035 if let Some(item) = cx.read_from_clipboard() {
8036 let entries = item.entries();
8037
8038 match entries.first() {
8039 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8040 // of all the pasted entries.
8041 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8042 .do_paste(
8043 clipboard_string.text(),
8044 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8045 true,
8046 window,
8047 cx,
8048 ),
8049 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8050 }
8051 }
8052 }
8053
8054 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8055 if self.read_only(cx) {
8056 return;
8057 }
8058
8059 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8060 if let Some((selections, _)) =
8061 self.selection_history.transaction(transaction_id).cloned()
8062 {
8063 self.change_selections(None, window, cx, |s| {
8064 s.select_anchors(selections.to_vec());
8065 });
8066 }
8067 self.request_autoscroll(Autoscroll::fit(), cx);
8068 self.unmark_text(window, cx);
8069 self.refresh_inline_completion(true, false, window, cx);
8070 cx.emit(EditorEvent::Edited { transaction_id });
8071 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8072 }
8073 }
8074
8075 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8076 if self.read_only(cx) {
8077 return;
8078 }
8079
8080 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8081 if let Some((_, Some(selections))) =
8082 self.selection_history.transaction(transaction_id).cloned()
8083 {
8084 self.change_selections(None, window, cx, |s| {
8085 s.select_anchors(selections.to_vec());
8086 });
8087 }
8088 self.request_autoscroll(Autoscroll::fit(), cx);
8089 self.unmark_text(window, cx);
8090 self.refresh_inline_completion(true, false, window, cx);
8091 cx.emit(EditorEvent::Edited { transaction_id });
8092 }
8093 }
8094
8095 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8096 self.buffer
8097 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8098 }
8099
8100 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8101 self.buffer
8102 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8103 }
8104
8105 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8106 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8107 let line_mode = s.line_mode;
8108 s.move_with(|map, selection| {
8109 let cursor = if selection.is_empty() && !line_mode {
8110 movement::left(map, selection.start)
8111 } else {
8112 selection.start
8113 };
8114 selection.collapse_to(cursor, SelectionGoal::None);
8115 });
8116 })
8117 }
8118
8119 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8120 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8121 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8122 })
8123 }
8124
8125 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8126 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8127 let line_mode = s.line_mode;
8128 s.move_with(|map, selection| {
8129 let cursor = if selection.is_empty() && !line_mode {
8130 movement::right(map, selection.end)
8131 } else {
8132 selection.end
8133 };
8134 selection.collapse_to(cursor, SelectionGoal::None)
8135 });
8136 })
8137 }
8138
8139 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8141 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8142 })
8143 }
8144
8145 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8146 if self.take_rename(true, window, cx).is_some() {
8147 return;
8148 }
8149
8150 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8151 cx.propagate();
8152 return;
8153 }
8154
8155 let text_layout_details = &self.text_layout_details(window);
8156 let selection_count = self.selections.count();
8157 let first_selection = self.selections.first_anchor();
8158
8159 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8160 let line_mode = s.line_mode;
8161 s.move_with(|map, selection| {
8162 if !selection.is_empty() && !line_mode {
8163 selection.goal = SelectionGoal::None;
8164 }
8165 let (cursor, goal) = movement::up(
8166 map,
8167 selection.start,
8168 selection.goal,
8169 false,
8170 text_layout_details,
8171 );
8172 selection.collapse_to(cursor, goal);
8173 });
8174 });
8175
8176 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8177 {
8178 cx.propagate();
8179 }
8180 }
8181
8182 pub fn move_up_by_lines(
8183 &mut self,
8184 action: &MoveUpByLines,
8185 window: &mut Window,
8186 cx: &mut Context<Self>,
8187 ) {
8188 if self.take_rename(true, window, cx).is_some() {
8189 return;
8190 }
8191
8192 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8193 cx.propagate();
8194 return;
8195 }
8196
8197 let text_layout_details = &self.text_layout_details(window);
8198
8199 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8200 let line_mode = s.line_mode;
8201 s.move_with(|map, selection| {
8202 if !selection.is_empty() && !line_mode {
8203 selection.goal = SelectionGoal::None;
8204 }
8205 let (cursor, goal) = movement::up_by_rows(
8206 map,
8207 selection.start,
8208 action.lines,
8209 selection.goal,
8210 false,
8211 text_layout_details,
8212 );
8213 selection.collapse_to(cursor, goal);
8214 });
8215 })
8216 }
8217
8218 pub fn move_down_by_lines(
8219 &mut self,
8220 action: &MoveDownByLines,
8221 window: &mut Window,
8222 cx: &mut Context<Self>,
8223 ) {
8224 if self.take_rename(true, window, cx).is_some() {
8225 return;
8226 }
8227
8228 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8229 cx.propagate();
8230 return;
8231 }
8232
8233 let text_layout_details = &self.text_layout_details(window);
8234
8235 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8236 let line_mode = s.line_mode;
8237 s.move_with(|map, selection| {
8238 if !selection.is_empty() && !line_mode {
8239 selection.goal = SelectionGoal::None;
8240 }
8241 let (cursor, goal) = movement::down_by_rows(
8242 map,
8243 selection.start,
8244 action.lines,
8245 selection.goal,
8246 false,
8247 text_layout_details,
8248 );
8249 selection.collapse_to(cursor, goal);
8250 });
8251 })
8252 }
8253
8254 pub fn select_down_by_lines(
8255 &mut self,
8256 action: &SelectDownByLines,
8257 window: &mut Window,
8258 cx: &mut Context<Self>,
8259 ) {
8260 let text_layout_details = &self.text_layout_details(window);
8261 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8262 s.move_heads_with(|map, head, goal| {
8263 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8264 })
8265 })
8266 }
8267
8268 pub fn select_up_by_lines(
8269 &mut self,
8270 action: &SelectUpByLines,
8271 window: &mut Window,
8272 cx: &mut Context<Self>,
8273 ) {
8274 let text_layout_details = &self.text_layout_details(window);
8275 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8276 s.move_heads_with(|map, head, goal| {
8277 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8278 })
8279 })
8280 }
8281
8282 pub fn select_page_up(
8283 &mut self,
8284 _: &SelectPageUp,
8285 window: &mut Window,
8286 cx: &mut Context<Self>,
8287 ) {
8288 let Some(row_count) = self.visible_row_count() else {
8289 return;
8290 };
8291
8292 let text_layout_details = &self.text_layout_details(window);
8293
8294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8295 s.move_heads_with(|map, head, goal| {
8296 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8297 })
8298 })
8299 }
8300
8301 pub fn move_page_up(
8302 &mut self,
8303 action: &MovePageUp,
8304 window: &mut Window,
8305 cx: &mut Context<Self>,
8306 ) {
8307 if self.take_rename(true, window, cx).is_some() {
8308 return;
8309 }
8310
8311 if self
8312 .context_menu
8313 .borrow_mut()
8314 .as_mut()
8315 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8316 .unwrap_or(false)
8317 {
8318 return;
8319 }
8320
8321 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8322 cx.propagate();
8323 return;
8324 }
8325
8326 let Some(row_count) = self.visible_row_count() else {
8327 return;
8328 };
8329
8330 let autoscroll = if action.center_cursor {
8331 Autoscroll::center()
8332 } else {
8333 Autoscroll::fit()
8334 };
8335
8336 let text_layout_details = &self.text_layout_details(window);
8337
8338 self.change_selections(Some(autoscroll), window, cx, |s| {
8339 let line_mode = s.line_mode;
8340 s.move_with(|map, selection| {
8341 if !selection.is_empty() && !line_mode {
8342 selection.goal = SelectionGoal::None;
8343 }
8344 let (cursor, goal) = movement::up_by_rows(
8345 map,
8346 selection.end,
8347 row_count,
8348 selection.goal,
8349 false,
8350 text_layout_details,
8351 );
8352 selection.collapse_to(cursor, goal);
8353 });
8354 });
8355 }
8356
8357 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8358 let text_layout_details = &self.text_layout_details(window);
8359 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8360 s.move_heads_with(|map, head, goal| {
8361 movement::up(map, head, goal, false, text_layout_details)
8362 })
8363 })
8364 }
8365
8366 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8367 self.take_rename(true, window, cx);
8368
8369 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8370 cx.propagate();
8371 return;
8372 }
8373
8374 let text_layout_details = &self.text_layout_details(window);
8375 let selection_count = self.selections.count();
8376 let first_selection = self.selections.first_anchor();
8377
8378 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8379 let line_mode = s.line_mode;
8380 s.move_with(|map, selection| {
8381 if !selection.is_empty() && !line_mode {
8382 selection.goal = SelectionGoal::None;
8383 }
8384 let (cursor, goal) = movement::down(
8385 map,
8386 selection.end,
8387 selection.goal,
8388 false,
8389 text_layout_details,
8390 );
8391 selection.collapse_to(cursor, goal);
8392 });
8393 });
8394
8395 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8396 {
8397 cx.propagate();
8398 }
8399 }
8400
8401 pub fn select_page_down(
8402 &mut self,
8403 _: &SelectPageDown,
8404 window: &mut Window,
8405 cx: &mut Context<Self>,
8406 ) {
8407 let Some(row_count) = self.visible_row_count() else {
8408 return;
8409 };
8410
8411 let text_layout_details = &self.text_layout_details(window);
8412
8413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8414 s.move_heads_with(|map, head, goal| {
8415 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8416 })
8417 })
8418 }
8419
8420 pub fn move_page_down(
8421 &mut self,
8422 action: &MovePageDown,
8423 window: &mut Window,
8424 cx: &mut Context<Self>,
8425 ) {
8426 if self.take_rename(true, window, cx).is_some() {
8427 return;
8428 }
8429
8430 if self
8431 .context_menu
8432 .borrow_mut()
8433 .as_mut()
8434 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8435 .unwrap_or(false)
8436 {
8437 return;
8438 }
8439
8440 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8441 cx.propagate();
8442 return;
8443 }
8444
8445 let Some(row_count) = self.visible_row_count() else {
8446 return;
8447 };
8448
8449 let autoscroll = if action.center_cursor {
8450 Autoscroll::center()
8451 } else {
8452 Autoscroll::fit()
8453 };
8454
8455 let text_layout_details = &self.text_layout_details(window);
8456 self.change_selections(Some(autoscroll), window, cx, |s| {
8457 let line_mode = s.line_mode;
8458 s.move_with(|map, selection| {
8459 if !selection.is_empty() && !line_mode {
8460 selection.goal = SelectionGoal::None;
8461 }
8462 let (cursor, goal) = movement::down_by_rows(
8463 map,
8464 selection.end,
8465 row_count,
8466 selection.goal,
8467 false,
8468 text_layout_details,
8469 );
8470 selection.collapse_to(cursor, goal);
8471 });
8472 });
8473 }
8474
8475 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8476 let text_layout_details = &self.text_layout_details(window);
8477 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8478 s.move_heads_with(|map, head, goal| {
8479 movement::down(map, head, goal, false, text_layout_details)
8480 })
8481 });
8482 }
8483
8484 pub fn context_menu_first(
8485 &mut self,
8486 _: &ContextMenuFirst,
8487 _window: &mut Window,
8488 cx: &mut Context<Self>,
8489 ) {
8490 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8491 context_menu.select_first(self.completion_provider.as_deref(), cx);
8492 }
8493 }
8494
8495 pub fn context_menu_prev(
8496 &mut self,
8497 _: &ContextMenuPrev,
8498 _window: &mut Window,
8499 cx: &mut Context<Self>,
8500 ) {
8501 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8502 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8503 }
8504 }
8505
8506 pub fn context_menu_next(
8507 &mut self,
8508 _: &ContextMenuNext,
8509 _window: &mut Window,
8510 cx: &mut Context<Self>,
8511 ) {
8512 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8513 context_menu.select_next(self.completion_provider.as_deref(), cx);
8514 }
8515 }
8516
8517 pub fn context_menu_last(
8518 &mut self,
8519 _: &ContextMenuLast,
8520 _window: &mut Window,
8521 cx: &mut Context<Self>,
8522 ) {
8523 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8524 context_menu.select_last(self.completion_provider.as_deref(), cx);
8525 }
8526 }
8527
8528 pub fn move_to_previous_word_start(
8529 &mut self,
8530 _: &MoveToPreviousWordStart,
8531 window: &mut Window,
8532 cx: &mut Context<Self>,
8533 ) {
8534 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8535 s.move_cursors_with(|map, head, _| {
8536 (
8537 movement::previous_word_start(map, head),
8538 SelectionGoal::None,
8539 )
8540 });
8541 })
8542 }
8543
8544 pub fn move_to_previous_subword_start(
8545 &mut self,
8546 _: &MoveToPreviousSubwordStart,
8547 window: &mut Window,
8548 cx: &mut Context<Self>,
8549 ) {
8550 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8551 s.move_cursors_with(|map, head, _| {
8552 (
8553 movement::previous_subword_start(map, head),
8554 SelectionGoal::None,
8555 )
8556 });
8557 })
8558 }
8559
8560 pub fn select_to_previous_word_start(
8561 &mut self,
8562 _: &SelectToPreviousWordStart,
8563 window: &mut Window,
8564 cx: &mut Context<Self>,
8565 ) {
8566 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8567 s.move_heads_with(|map, head, _| {
8568 (
8569 movement::previous_word_start(map, head),
8570 SelectionGoal::None,
8571 )
8572 });
8573 })
8574 }
8575
8576 pub fn select_to_previous_subword_start(
8577 &mut self,
8578 _: &SelectToPreviousSubwordStart,
8579 window: &mut Window,
8580 cx: &mut Context<Self>,
8581 ) {
8582 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8583 s.move_heads_with(|map, head, _| {
8584 (
8585 movement::previous_subword_start(map, head),
8586 SelectionGoal::None,
8587 )
8588 });
8589 })
8590 }
8591
8592 pub fn delete_to_previous_word_start(
8593 &mut self,
8594 action: &DeleteToPreviousWordStart,
8595 window: &mut Window,
8596 cx: &mut Context<Self>,
8597 ) {
8598 self.transact(window, cx, |this, window, cx| {
8599 this.select_autoclose_pair(window, cx);
8600 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8601 let line_mode = s.line_mode;
8602 s.move_with(|map, selection| {
8603 if selection.is_empty() && !line_mode {
8604 let cursor = if action.ignore_newlines {
8605 movement::previous_word_start(map, selection.head())
8606 } else {
8607 movement::previous_word_start_or_newline(map, selection.head())
8608 };
8609 selection.set_head(cursor, SelectionGoal::None);
8610 }
8611 });
8612 });
8613 this.insert("", window, cx);
8614 });
8615 }
8616
8617 pub fn delete_to_previous_subword_start(
8618 &mut self,
8619 _: &DeleteToPreviousSubwordStart,
8620 window: &mut Window,
8621 cx: &mut Context<Self>,
8622 ) {
8623 self.transact(window, cx, |this, window, cx| {
8624 this.select_autoclose_pair(window, cx);
8625 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8626 let line_mode = s.line_mode;
8627 s.move_with(|map, selection| {
8628 if selection.is_empty() && !line_mode {
8629 let cursor = movement::previous_subword_start(map, selection.head());
8630 selection.set_head(cursor, SelectionGoal::None);
8631 }
8632 });
8633 });
8634 this.insert("", window, cx);
8635 });
8636 }
8637
8638 pub fn move_to_next_word_end(
8639 &mut self,
8640 _: &MoveToNextWordEnd,
8641 window: &mut Window,
8642 cx: &mut Context<Self>,
8643 ) {
8644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8645 s.move_cursors_with(|map, head, _| {
8646 (movement::next_word_end(map, head), SelectionGoal::None)
8647 });
8648 })
8649 }
8650
8651 pub fn move_to_next_subword_end(
8652 &mut self,
8653 _: &MoveToNextSubwordEnd,
8654 window: &mut Window,
8655 cx: &mut Context<Self>,
8656 ) {
8657 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8658 s.move_cursors_with(|map, head, _| {
8659 (movement::next_subword_end(map, head), SelectionGoal::None)
8660 });
8661 })
8662 }
8663
8664 pub fn select_to_next_word_end(
8665 &mut self,
8666 _: &SelectToNextWordEnd,
8667 window: &mut Window,
8668 cx: &mut Context<Self>,
8669 ) {
8670 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8671 s.move_heads_with(|map, head, _| {
8672 (movement::next_word_end(map, head), SelectionGoal::None)
8673 });
8674 })
8675 }
8676
8677 pub fn select_to_next_subword_end(
8678 &mut self,
8679 _: &SelectToNextSubwordEnd,
8680 window: &mut Window,
8681 cx: &mut Context<Self>,
8682 ) {
8683 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8684 s.move_heads_with(|map, head, _| {
8685 (movement::next_subword_end(map, head), SelectionGoal::None)
8686 });
8687 })
8688 }
8689
8690 pub fn delete_to_next_word_end(
8691 &mut self,
8692 action: &DeleteToNextWordEnd,
8693 window: &mut Window,
8694 cx: &mut Context<Self>,
8695 ) {
8696 self.transact(window, cx, |this, window, cx| {
8697 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8698 let line_mode = s.line_mode;
8699 s.move_with(|map, selection| {
8700 if selection.is_empty() && !line_mode {
8701 let cursor = if action.ignore_newlines {
8702 movement::next_word_end(map, selection.head())
8703 } else {
8704 movement::next_word_end_or_newline(map, selection.head())
8705 };
8706 selection.set_head(cursor, SelectionGoal::None);
8707 }
8708 });
8709 });
8710 this.insert("", window, cx);
8711 });
8712 }
8713
8714 pub fn delete_to_next_subword_end(
8715 &mut self,
8716 _: &DeleteToNextSubwordEnd,
8717 window: &mut Window,
8718 cx: &mut Context<Self>,
8719 ) {
8720 self.transact(window, cx, |this, window, cx| {
8721 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8722 s.move_with(|map, selection| {
8723 if selection.is_empty() {
8724 let cursor = movement::next_subword_end(map, selection.head());
8725 selection.set_head(cursor, SelectionGoal::None);
8726 }
8727 });
8728 });
8729 this.insert("", window, cx);
8730 });
8731 }
8732
8733 pub fn move_to_beginning_of_line(
8734 &mut self,
8735 action: &MoveToBeginningOfLine,
8736 window: &mut Window,
8737 cx: &mut Context<Self>,
8738 ) {
8739 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8740 s.move_cursors_with(|map, head, _| {
8741 (
8742 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8743 SelectionGoal::None,
8744 )
8745 });
8746 })
8747 }
8748
8749 pub fn select_to_beginning_of_line(
8750 &mut self,
8751 action: &SelectToBeginningOfLine,
8752 window: &mut Window,
8753 cx: &mut Context<Self>,
8754 ) {
8755 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8756 s.move_heads_with(|map, head, _| {
8757 (
8758 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8759 SelectionGoal::None,
8760 )
8761 });
8762 });
8763 }
8764
8765 pub fn delete_to_beginning_of_line(
8766 &mut self,
8767 _: &DeleteToBeginningOfLine,
8768 window: &mut Window,
8769 cx: &mut Context<Self>,
8770 ) {
8771 self.transact(window, cx, |this, window, cx| {
8772 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.move_with(|_, selection| {
8774 selection.reversed = true;
8775 });
8776 });
8777
8778 this.select_to_beginning_of_line(
8779 &SelectToBeginningOfLine {
8780 stop_at_soft_wraps: false,
8781 },
8782 window,
8783 cx,
8784 );
8785 this.backspace(&Backspace, window, cx);
8786 });
8787 }
8788
8789 pub fn move_to_end_of_line(
8790 &mut self,
8791 action: &MoveToEndOfLine,
8792 window: &mut Window,
8793 cx: &mut Context<Self>,
8794 ) {
8795 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8796 s.move_cursors_with(|map, head, _| {
8797 (
8798 movement::line_end(map, head, action.stop_at_soft_wraps),
8799 SelectionGoal::None,
8800 )
8801 });
8802 })
8803 }
8804
8805 pub fn select_to_end_of_line(
8806 &mut self,
8807 action: &SelectToEndOfLine,
8808 window: &mut Window,
8809 cx: &mut Context<Self>,
8810 ) {
8811 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8812 s.move_heads_with(|map, head, _| {
8813 (
8814 movement::line_end(map, head, action.stop_at_soft_wraps),
8815 SelectionGoal::None,
8816 )
8817 });
8818 })
8819 }
8820
8821 pub fn delete_to_end_of_line(
8822 &mut self,
8823 _: &DeleteToEndOfLine,
8824 window: &mut Window,
8825 cx: &mut Context<Self>,
8826 ) {
8827 self.transact(window, cx, |this, window, cx| {
8828 this.select_to_end_of_line(
8829 &SelectToEndOfLine {
8830 stop_at_soft_wraps: false,
8831 },
8832 window,
8833 cx,
8834 );
8835 this.delete(&Delete, window, cx);
8836 });
8837 }
8838
8839 pub fn cut_to_end_of_line(
8840 &mut self,
8841 _: &CutToEndOfLine,
8842 window: &mut Window,
8843 cx: &mut Context<Self>,
8844 ) {
8845 self.transact(window, cx, |this, window, cx| {
8846 this.select_to_end_of_line(
8847 &SelectToEndOfLine {
8848 stop_at_soft_wraps: false,
8849 },
8850 window,
8851 cx,
8852 );
8853 this.cut(&Cut, window, cx);
8854 });
8855 }
8856
8857 pub fn move_to_start_of_paragraph(
8858 &mut self,
8859 _: &MoveToStartOfParagraph,
8860 window: &mut Window,
8861 cx: &mut Context<Self>,
8862 ) {
8863 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8864 cx.propagate();
8865 return;
8866 }
8867
8868 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8869 s.move_with(|map, selection| {
8870 selection.collapse_to(
8871 movement::start_of_paragraph(map, selection.head(), 1),
8872 SelectionGoal::None,
8873 )
8874 });
8875 })
8876 }
8877
8878 pub fn move_to_end_of_paragraph(
8879 &mut self,
8880 _: &MoveToEndOfParagraph,
8881 window: &mut Window,
8882 cx: &mut Context<Self>,
8883 ) {
8884 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8885 cx.propagate();
8886 return;
8887 }
8888
8889 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8890 s.move_with(|map, selection| {
8891 selection.collapse_to(
8892 movement::end_of_paragraph(map, selection.head(), 1),
8893 SelectionGoal::None,
8894 )
8895 });
8896 })
8897 }
8898
8899 pub fn select_to_start_of_paragraph(
8900 &mut self,
8901 _: &SelectToStartOfParagraph,
8902 window: &mut Window,
8903 cx: &mut Context<Self>,
8904 ) {
8905 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8906 cx.propagate();
8907 return;
8908 }
8909
8910 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8911 s.move_heads_with(|map, head, _| {
8912 (
8913 movement::start_of_paragraph(map, head, 1),
8914 SelectionGoal::None,
8915 )
8916 });
8917 })
8918 }
8919
8920 pub fn select_to_end_of_paragraph(
8921 &mut self,
8922 _: &SelectToEndOfParagraph,
8923 window: &mut Window,
8924 cx: &mut Context<Self>,
8925 ) {
8926 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8927 cx.propagate();
8928 return;
8929 }
8930
8931 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8932 s.move_heads_with(|map, head, _| {
8933 (
8934 movement::end_of_paragraph(map, head, 1),
8935 SelectionGoal::None,
8936 )
8937 });
8938 })
8939 }
8940
8941 pub fn move_to_beginning(
8942 &mut self,
8943 _: &MoveToBeginning,
8944 window: &mut Window,
8945 cx: &mut Context<Self>,
8946 ) {
8947 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8948 cx.propagate();
8949 return;
8950 }
8951
8952 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8953 s.select_ranges(vec![0..0]);
8954 });
8955 }
8956
8957 pub fn select_to_beginning(
8958 &mut self,
8959 _: &SelectToBeginning,
8960 window: &mut Window,
8961 cx: &mut Context<Self>,
8962 ) {
8963 let mut selection = self.selections.last::<Point>(cx);
8964 selection.set_head(Point::zero(), SelectionGoal::None);
8965
8966 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8967 s.select(vec![selection]);
8968 });
8969 }
8970
8971 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8972 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8973 cx.propagate();
8974 return;
8975 }
8976
8977 let cursor = self.buffer.read(cx).read(cx).len();
8978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8979 s.select_ranges(vec![cursor..cursor])
8980 });
8981 }
8982
8983 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8984 self.nav_history = nav_history;
8985 }
8986
8987 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8988 self.nav_history.as_ref()
8989 }
8990
8991 fn push_to_nav_history(
8992 &mut self,
8993 cursor_anchor: Anchor,
8994 new_position: Option<Point>,
8995 cx: &mut Context<Self>,
8996 ) {
8997 if let Some(nav_history) = self.nav_history.as_mut() {
8998 let buffer = self.buffer.read(cx).read(cx);
8999 let cursor_position = cursor_anchor.to_point(&buffer);
9000 let scroll_state = self.scroll_manager.anchor();
9001 let scroll_top_row = scroll_state.top_row(&buffer);
9002 drop(buffer);
9003
9004 if let Some(new_position) = new_position {
9005 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9006 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9007 return;
9008 }
9009 }
9010
9011 nav_history.push(
9012 Some(NavigationData {
9013 cursor_anchor,
9014 cursor_position,
9015 scroll_anchor: scroll_state,
9016 scroll_top_row,
9017 }),
9018 cx,
9019 );
9020 }
9021 }
9022
9023 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9024 let buffer = self.buffer.read(cx).snapshot(cx);
9025 let mut selection = self.selections.first::<usize>(cx);
9026 selection.set_head(buffer.len(), SelectionGoal::None);
9027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9028 s.select(vec![selection]);
9029 });
9030 }
9031
9032 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9033 let end = self.buffer.read(cx).read(cx).len();
9034 self.change_selections(None, window, cx, |s| {
9035 s.select_ranges(vec![0..end]);
9036 });
9037 }
9038
9039 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9040 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9041 let mut selections = self.selections.all::<Point>(cx);
9042 let max_point = display_map.buffer_snapshot.max_point();
9043 for selection in &mut selections {
9044 let rows = selection.spanned_rows(true, &display_map);
9045 selection.start = Point::new(rows.start.0, 0);
9046 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9047 selection.reversed = false;
9048 }
9049 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9050 s.select(selections);
9051 });
9052 }
9053
9054 pub fn split_selection_into_lines(
9055 &mut self,
9056 _: &SplitSelectionIntoLines,
9057 window: &mut Window,
9058 cx: &mut Context<Self>,
9059 ) {
9060 let mut to_unfold = Vec::new();
9061 let mut new_selection_ranges = Vec::new();
9062 {
9063 let selections = self.selections.all::<Point>(cx);
9064 let buffer = self.buffer.read(cx).read(cx);
9065 for selection in selections {
9066 for row in selection.start.row..selection.end.row {
9067 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9068 new_selection_ranges.push(cursor..cursor);
9069 }
9070 new_selection_ranges.push(selection.end..selection.end);
9071 to_unfold.push(selection.start..selection.end);
9072 }
9073 }
9074 self.unfold_ranges(&to_unfold, true, true, cx);
9075 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9076 s.select_ranges(new_selection_ranges);
9077 });
9078 }
9079
9080 pub fn add_selection_above(
9081 &mut self,
9082 _: &AddSelectionAbove,
9083 window: &mut Window,
9084 cx: &mut Context<Self>,
9085 ) {
9086 self.add_selection(true, window, cx);
9087 }
9088
9089 pub fn add_selection_below(
9090 &mut self,
9091 _: &AddSelectionBelow,
9092 window: &mut Window,
9093 cx: &mut Context<Self>,
9094 ) {
9095 self.add_selection(false, window, cx);
9096 }
9097
9098 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9099 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9100 let mut selections = self.selections.all::<Point>(cx);
9101 let text_layout_details = self.text_layout_details(window);
9102 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9103 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9104 let range = oldest_selection.display_range(&display_map).sorted();
9105
9106 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9107 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9108 let positions = start_x.min(end_x)..start_x.max(end_x);
9109
9110 selections.clear();
9111 let mut stack = Vec::new();
9112 for row in range.start.row().0..=range.end.row().0 {
9113 if let Some(selection) = self.selections.build_columnar_selection(
9114 &display_map,
9115 DisplayRow(row),
9116 &positions,
9117 oldest_selection.reversed,
9118 &text_layout_details,
9119 ) {
9120 stack.push(selection.id);
9121 selections.push(selection);
9122 }
9123 }
9124
9125 if above {
9126 stack.reverse();
9127 }
9128
9129 AddSelectionsState { above, stack }
9130 });
9131
9132 let last_added_selection = *state.stack.last().unwrap();
9133 let mut new_selections = Vec::new();
9134 if above == state.above {
9135 let end_row = if above {
9136 DisplayRow(0)
9137 } else {
9138 display_map.max_point().row()
9139 };
9140
9141 'outer: for selection in selections {
9142 if selection.id == last_added_selection {
9143 let range = selection.display_range(&display_map).sorted();
9144 debug_assert_eq!(range.start.row(), range.end.row());
9145 let mut row = range.start.row();
9146 let positions =
9147 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9148 px(start)..px(end)
9149 } else {
9150 let start_x =
9151 display_map.x_for_display_point(range.start, &text_layout_details);
9152 let end_x =
9153 display_map.x_for_display_point(range.end, &text_layout_details);
9154 start_x.min(end_x)..start_x.max(end_x)
9155 };
9156
9157 while row != end_row {
9158 if above {
9159 row.0 -= 1;
9160 } else {
9161 row.0 += 1;
9162 }
9163
9164 if let Some(new_selection) = self.selections.build_columnar_selection(
9165 &display_map,
9166 row,
9167 &positions,
9168 selection.reversed,
9169 &text_layout_details,
9170 ) {
9171 state.stack.push(new_selection.id);
9172 if above {
9173 new_selections.push(new_selection);
9174 new_selections.push(selection);
9175 } else {
9176 new_selections.push(selection);
9177 new_selections.push(new_selection);
9178 }
9179
9180 continue 'outer;
9181 }
9182 }
9183 }
9184
9185 new_selections.push(selection);
9186 }
9187 } else {
9188 new_selections = selections;
9189 new_selections.retain(|s| s.id != last_added_selection);
9190 state.stack.pop();
9191 }
9192
9193 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9194 s.select(new_selections);
9195 });
9196 if state.stack.len() > 1 {
9197 self.add_selections_state = Some(state);
9198 }
9199 }
9200
9201 pub fn select_next_match_internal(
9202 &mut self,
9203 display_map: &DisplaySnapshot,
9204 replace_newest: bool,
9205 autoscroll: Option<Autoscroll>,
9206 window: &mut Window,
9207 cx: &mut Context<Self>,
9208 ) -> Result<()> {
9209 fn select_next_match_ranges(
9210 this: &mut Editor,
9211 range: Range<usize>,
9212 replace_newest: bool,
9213 auto_scroll: Option<Autoscroll>,
9214 window: &mut Window,
9215 cx: &mut Context<Editor>,
9216 ) {
9217 this.unfold_ranges(&[range.clone()], false, true, cx);
9218 this.change_selections(auto_scroll, window, cx, |s| {
9219 if replace_newest {
9220 s.delete(s.newest_anchor().id);
9221 }
9222 s.insert_range(range.clone());
9223 });
9224 }
9225
9226 let buffer = &display_map.buffer_snapshot;
9227 let mut selections = self.selections.all::<usize>(cx);
9228 if let Some(mut select_next_state) = self.select_next_state.take() {
9229 let query = &select_next_state.query;
9230 if !select_next_state.done {
9231 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9232 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9233 let mut next_selected_range = None;
9234
9235 let bytes_after_last_selection =
9236 buffer.bytes_in_range(last_selection.end..buffer.len());
9237 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9238 let query_matches = query
9239 .stream_find_iter(bytes_after_last_selection)
9240 .map(|result| (last_selection.end, result))
9241 .chain(
9242 query
9243 .stream_find_iter(bytes_before_first_selection)
9244 .map(|result| (0, result)),
9245 );
9246
9247 for (start_offset, query_match) in query_matches {
9248 let query_match = query_match.unwrap(); // can only fail due to I/O
9249 let offset_range =
9250 start_offset + query_match.start()..start_offset + query_match.end();
9251 let display_range = offset_range.start.to_display_point(display_map)
9252 ..offset_range.end.to_display_point(display_map);
9253
9254 if !select_next_state.wordwise
9255 || (!movement::is_inside_word(display_map, display_range.start)
9256 && !movement::is_inside_word(display_map, display_range.end))
9257 {
9258 // TODO: This is n^2, because we might check all the selections
9259 if !selections
9260 .iter()
9261 .any(|selection| selection.range().overlaps(&offset_range))
9262 {
9263 next_selected_range = Some(offset_range);
9264 break;
9265 }
9266 }
9267 }
9268
9269 if let Some(next_selected_range) = next_selected_range {
9270 select_next_match_ranges(
9271 self,
9272 next_selected_range,
9273 replace_newest,
9274 autoscroll,
9275 window,
9276 cx,
9277 );
9278 } else {
9279 select_next_state.done = true;
9280 }
9281 }
9282
9283 self.select_next_state = Some(select_next_state);
9284 } else {
9285 let mut only_carets = true;
9286 let mut same_text_selected = true;
9287 let mut selected_text = None;
9288
9289 let mut selections_iter = selections.iter().peekable();
9290 while let Some(selection) = selections_iter.next() {
9291 if selection.start != selection.end {
9292 only_carets = false;
9293 }
9294
9295 if same_text_selected {
9296 if selected_text.is_none() {
9297 selected_text =
9298 Some(buffer.text_for_range(selection.range()).collect::<String>());
9299 }
9300
9301 if let Some(next_selection) = selections_iter.peek() {
9302 if next_selection.range().len() == selection.range().len() {
9303 let next_selected_text = buffer
9304 .text_for_range(next_selection.range())
9305 .collect::<String>();
9306 if Some(next_selected_text) != selected_text {
9307 same_text_selected = false;
9308 selected_text = None;
9309 }
9310 } else {
9311 same_text_selected = false;
9312 selected_text = None;
9313 }
9314 }
9315 }
9316 }
9317
9318 if only_carets {
9319 for selection in &mut selections {
9320 let word_range = movement::surrounding_word(
9321 display_map,
9322 selection.start.to_display_point(display_map),
9323 );
9324 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9325 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9326 selection.goal = SelectionGoal::None;
9327 selection.reversed = false;
9328 select_next_match_ranges(
9329 self,
9330 selection.start..selection.end,
9331 replace_newest,
9332 autoscroll,
9333 window,
9334 cx,
9335 );
9336 }
9337
9338 if selections.len() == 1 {
9339 let selection = selections
9340 .last()
9341 .expect("ensured that there's only one selection");
9342 let query = buffer
9343 .text_for_range(selection.start..selection.end)
9344 .collect::<String>();
9345 let is_empty = query.is_empty();
9346 let select_state = SelectNextState {
9347 query: AhoCorasick::new(&[query])?,
9348 wordwise: true,
9349 done: is_empty,
9350 };
9351 self.select_next_state = Some(select_state);
9352 } else {
9353 self.select_next_state = None;
9354 }
9355 } else if let Some(selected_text) = selected_text {
9356 self.select_next_state = Some(SelectNextState {
9357 query: AhoCorasick::new(&[selected_text])?,
9358 wordwise: false,
9359 done: false,
9360 });
9361 self.select_next_match_internal(
9362 display_map,
9363 replace_newest,
9364 autoscroll,
9365 window,
9366 cx,
9367 )?;
9368 }
9369 }
9370 Ok(())
9371 }
9372
9373 pub fn select_all_matches(
9374 &mut self,
9375 _action: &SelectAllMatches,
9376 window: &mut Window,
9377 cx: &mut Context<Self>,
9378 ) -> Result<()> {
9379 self.push_to_selection_history();
9380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9381
9382 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9383 let Some(select_next_state) = self.select_next_state.as_mut() else {
9384 return Ok(());
9385 };
9386 if select_next_state.done {
9387 return Ok(());
9388 }
9389
9390 let mut new_selections = self.selections.all::<usize>(cx);
9391
9392 let buffer = &display_map.buffer_snapshot;
9393 let query_matches = select_next_state
9394 .query
9395 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9396
9397 for query_match in query_matches {
9398 let query_match = query_match.unwrap(); // can only fail due to I/O
9399 let offset_range = query_match.start()..query_match.end();
9400 let display_range = offset_range.start.to_display_point(&display_map)
9401 ..offset_range.end.to_display_point(&display_map);
9402
9403 if !select_next_state.wordwise
9404 || (!movement::is_inside_word(&display_map, display_range.start)
9405 && !movement::is_inside_word(&display_map, display_range.end))
9406 {
9407 self.selections.change_with(cx, |selections| {
9408 new_selections.push(Selection {
9409 id: selections.new_selection_id(),
9410 start: offset_range.start,
9411 end: offset_range.end,
9412 reversed: false,
9413 goal: SelectionGoal::None,
9414 });
9415 });
9416 }
9417 }
9418
9419 new_selections.sort_by_key(|selection| selection.start);
9420 let mut ix = 0;
9421 while ix + 1 < new_selections.len() {
9422 let current_selection = &new_selections[ix];
9423 let next_selection = &new_selections[ix + 1];
9424 if current_selection.range().overlaps(&next_selection.range()) {
9425 if current_selection.id < next_selection.id {
9426 new_selections.remove(ix + 1);
9427 } else {
9428 new_selections.remove(ix);
9429 }
9430 } else {
9431 ix += 1;
9432 }
9433 }
9434
9435 let reversed = self.selections.oldest::<usize>(cx).reversed;
9436
9437 for selection in new_selections.iter_mut() {
9438 selection.reversed = reversed;
9439 }
9440
9441 select_next_state.done = true;
9442 self.unfold_ranges(
9443 &new_selections
9444 .iter()
9445 .map(|selection| selection.range())
9446 .collect::<Vec<_>>(),
9447 false,
9448 false,
9449 cx,
9450 );
9451 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9452 selections.select(new_selections)
9453 });
9454
9455 Ok(())
9456 }
9457
9458 pub fn select_next(
9459 &mut self,
9460 action: &SelectNext,
9461 window: &mut Window,
9462 cx: &mut Context<Self>,
9463 ) -> Result<()> {
9464 self.push_to_selection_history();
9465 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9466 self.select_next_match_internal(
9467 &display_map,
9468 action.replace_newest,
9469 Some(Autoscroll::newest()),
9470 window,
9471 cx,
9472 )?;
9473 Ok(())
9474 }
9475
9476 pub fn select_previous(
9477 &mut self,
9478 action: &SelectPrevious,
9479 window: &mut Window,
9480 cx: &mut Context<Self>,
9481 ) -> Result<()> {
9482 self.push_to_selection_history();
9483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9484 let buffer = &display_map.buffer_snapshot;
9485 let mut selections = self.selections.all::<usize>(cx);
9486 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9487 let query = &select_prev_state.query;
9488 if !select_prev_state.done {
9489 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9490 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9491 let mut next_selected_range = None;
9492 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9493 let bytes_before_last_selection =
9494 buffer.reversed_bytes_in_range(0..last_selection.start);
9495 let bytes_after_first_selection =
9496 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9497 let query_matches = query
9498 .stream_find_iter(bytes_before_last_selection)
9499 .map(|result| (last_selection.start, result))
9500 .chain(
9501 query
9502 .stream_find_iter(bytes_after_first_selection)
9503 .map(|result| (buffer.len(), result)),
9504 );
9505 for (end_offset, query_match) in query_matches {
9506 let query_match = query_match.unwrap(); // can only fail due to I/O
9507 let offset_range =
9508 end_offset - query_match.end()..end_offset - query_match.start();
9509 let display_range = offset_range.start.to_display_point(&display_map)
9510 ..offset_range.end.to_display_point(&display_map);
9511
9512 if !select_prev_state.wordwise
9513 || (!movement::is_inside_word(&display_map, display_range.start)
9514 && !movement::is_inside_word(&display_map, display_range.end))
9515 {
9516 next_selected_range = Some(offset_range);
9517 break;
9518 }
9519 }
9520
9521 if let Some(next_selected_range) = next_selected_range {
9522 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9523 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9524 if action.replace_newest {
9525 s.delete(s.newest_anchor().id);
9526 }
9527 s.insert_range(next_selected_range);
9528 });
9529 } else {
9530 select_prev_state.done = true;
9531 }
9532 }
9533
9534 self.select_prev_state = Some(select_prev_state);
9535 } else {
9536 let mut only_carets = true;
9537 let mut same_text_selected = true;
9538 let mut selected_text = None;
9539
9540 let mut selections_iter = selections.iter().peekable();
9541 while let Some(selection) = selections_iter.next() {
9542 if selection.start != selection.end {
9543 only_carets = false;
9544 }
9545
9546 if same_text_selected {
9547 if selected_text.is_none() {
9548 selected_text =
9549 Some(buffer.text_for_range(selection.range()).collect::<String>());
9550 }
9551
9552 if let Some(next_selection) = selections_iter.peek() {
9553 if next_selection.range().len() == selection.range().len() {
9554 let next_selected_text = buffer
9555 .text_for_range(next_selection.range())
9556 .collect::<String>();
9557 if Some(next_selected_text) != selected_text {
9558 same_text_selected = false;
9559 selected_text = None;
9560 }
9561 } else {
9562 same_text_selected = false;
9563 selected_text = None;
9564 }
9565 }
9566 }
9567 }
9568
9569 if only_carets {
9570 for selection in &mut selections {
9571 let word_range = movement::surrounding_word(
9572 &display_map,
9573 selection.start.to_display_point(&display_map),
9574 );
9575 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9576 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9577 selection.goal = SelectionGoal::None;
9578 selection.reversed = false;
9579 }
9580 if selections.len() == 1 {
9581 let selection = selections
9582 .last()
9583 .expect("ensured that there's only one selection");
9584 let query = buffer
9585 .text_for_range(selection.start..selection.end)
9586 .collect::<String>();
9587 let is_empty = query.is_empty();
9588 let select_state = SelectNextState {
9589 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9590 wordwise: true,
9591 done: is_empty,
9592 };
9593 self.select_prev_state = Some(select_state);
9594 } else {
9595 self.select_prev_state = None;
9596 }
9597
9598 self.unfold_ranges(
9599 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9600 false,
9601 true,
9602 cx,
9603 );
9604 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9605 s.select(selections);
9606 });
9607 } else if let Some(selected_text) = selected_text {
9608 self.select_prev_state = Some(SelectNextState {
9609 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9610 wordwise: false,
9611 done: false,
9612 });
9613 self.select_previous(action, window, cx)?;
9614 }
9615 }
9616 Ok(())
9617 }
9618
9619 pub fn toggle_comments(
9620 &mut self,
9621 action: &ToggleComments,
9622 window: &mut Window,
9623 cx: &mut Context<Self>,
9624 ) {
9625 if self.read_only(cx) {
9626 return;
9627 }
9628 let text_layout_details = &self.text_layout_details(window);
9629 self.transact(window, cx, |this, window, cx| {
9630 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9631 let mut edits = Vec::new();
9632 let mut selection_edit_ranges = Vec::new();
9633 let mut last_toggled_row = None;
9634 let snapshot = this.buffer.read(cx).read(cx);
9635 let empty_str: Arc<str> = Arc::default();
9636 let mut suffixes_inserted = Vec::new();
9637 let ignore_indent = action.ignore_indent;
9638
9639 fn comment_prefix_range(
9640 snapshot: &MultiBufferSnapshot,
9641 row: MultiBufferRow,
9642 comment_prefix: &str,
9643 comment_prefix_whitespace: &str,
9644 ignore_indent: bool,
9645 ) -> Range<Point> {
9646 let indent_size = if ignore_indent {
9647 0
9648 } else {
9649 snapshot.indent_size_for_line(row).len
9650 };
9651
9652 let start = Point::new(row.0, indent_size);
9653
9654 let mut line_bytes = snapshot
9655 .bytes_in_range(start..snapshot.max_point())
9656 .flatten()
9657 .copied();
9658
9659 // If this line currently begins with the line comment prefix, then record
9660 // the range containing the prefix.
9661 if line_bytes
9662 .by_ref()
9663 .take(comment_prefix.len())
9664 .eq(comment_prefix.bytes())
9665 {
9666 // Include any whitespace that matches the comment prefix.
9667 let matching_whitespace_len = line_bytes
9668 .zip(comment_prefix_whitespace.bytes())
9669 .take_while(|(a, b)| a == b)
9670 .count() as u32;
9671 let end = Point::new(
9672 start.row,
9673 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9674 );
9675 start..end
9676 } else {
9677 start..start
9678 }
9679 }
9680
9681 fn comment_suffix_range(
9682 snapshot: &MultiBufferSnapshot,
9683 row: MultiBufferRow,
9684 comment_suffix: &str,
9685 comment_suffix_has_leading_space: bool,
9686 ) -> Range<Point> {
9687 let end = Point::new(row.0, snapshot.line_len(row));
9688 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9689
9690 let mut line_end_bytes = snapshot
9691 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9692 .flatten()
9693 .copied();
9694
9695 let leading_space_len = if suffix_start_column > 0
9696 && line_end_bytes.next() == Some(b' ')
9697 && comment_suffix_has_leading_space
9698 {
9699 1
9700 } else {
9701 0
9702 };
9703
9704 // If this line currently begins with the line comment prefix, then record
9705 // the range containing the prefix.
9706 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9707 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9708 start..end
9709 } else {
9710 end..end
9711 }
9712 }
9713
9714 // TODO: Handle selections that cross excerpts
9715 for selection in &mut selections {
9716 let start_column = snapshot
9717 .indent_size_for_line(MultiBufferRow(selection.start.row))
9718 .len;
9719 let language = if let Some(language) =
9720 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9721 {
9722 language
9723 } else {
9724 continue;
9725 };
9726
9727 selection_edit_ranges.clear();
9728
9729 // If multiple selections contain a given row, avoid processing that
9730 // row more than once.
9731 let mut start_row = MultiBufferRow(selection.start.row);
9732 if last_toggled_row == Some(start_row) {
9733 start_row = start_row.next_row();
9734 }
9735 let end_row =
9736 if selection.end.row > selection.start.row && selection.end.column == 0 {
9737 MultiBufferRow(selection.end.row - 1)
9738 } else {
9739 MultiBufferRow(selection.end.row)
9740 };
9741 last_toggled_row = Some(end_row);
9742
9743 if start_row > end_row {
9744 continue;
9745 }
9746
9747 // If the language has line comments, toggle those.
9748 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9749
9750 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9751 if ignore_indent {
9752 full_comment_prefixes = full_comment_prefixes
9753 .into_iter()
9754 .map(|s| Arc::from(s.trim_end()))
9755 .collect();
9756 }
9757
9758 if !full_comment_prefixes.is_empty() {
9759 let first_prefix = full_comment_prefixes
9760 .first()
9761 .expect("prefixes is non-empty");
9762 let prefix_trimmed_lengths = full_comment_prefixes
9763 .iter()
9764 .map(|p| p.trim_end_matches(' ').len())
9765 .collect::<SmallVec<[usize; 4]>>();
9766
9767 let mut all_selection_lines_are_comments = true;
9768
9769 for row in start_row.0..=end_row.0 {
9770 let row = MultiBufferRow(row);
9771 if start_row < end_row && snapshot.is_line_blank(row) {
9772 continue;
9773 }
9774
9775 let prefix_range = full_comment_prefixes
9776 .iter()
9777 .zip(prefix_trimmed_lengths.iter().copied())
9778 .map(|(prefix, trimmed_prefix_len)| {
9779 comment_prefix_range(
9780 snapshot.deref(),
9781 row,
9782 &prefix[..trimmed_prefix_len],
9783 &prefix[trimmed_prefix_len..],
9784 ignore_indent,
9785 )
9786 })
9787 .max_by_key(|range| range.end.column - range.start.column)
9788 .expect("prefixes is non-empty");
9789
9790 if prefix_range.is_empty() {
9791 all_selection_lines_are_comments = false;
9792 }
9793
9794 selection_edit_ranges.push(prefix_range);
9795 }
9796
9797 if all_selection_lines_are_comments {
9798 edits.extend(
9799 selection_edit_ranges
9800 .iter()
9801 .cloned()
9802 .map(|range| (range, empty_str.clone())),
9803 );
9804 } else {
9805 let min_column = selection_edit_ranges
9806 .iter()
9807 .map(|range| range.start.column)
9808 .min()
9809 .unwrap_or(0);
9810 edits.extend(selection_edit_ranges.iter().map(|range| {
9811 let position = Point::new(range.start.row, min_column);
9812 (position..position, first_prefix.clone())
9813 }));
9814 }
9815 } else if let Some((full_comment_prefix, comment_suffix)) =
9816 language.block_comment_delimiters()
9817 {
9818 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9819 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9820 let prefix_range = comment_prefix_range(
9821 snapshot.deref(),
9822 start_row,
9823 comment_prefix,
9824 comment_prefix_whitespace,
9825 ignore_indent,
9826 );
9827 let suffix_range = comment_suffix_range(
9828 snapshot.deref(),
9829 end_row,
9830 comment_suffix.trim_start_matches(' '),
9831 comment_suffix.starts_with(' '),
9832 );
9833
9834 if prefix_range.is_empty() || suffix_range.is_empty() {
9835 edits.push((
9836 prefix_range.start..prefix_range.start,
9837 full_comment_prefix.clone(),
9838 ));
9839 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9840 suffixes_inserted.push((end_row, comment_suffix.len()));
9841 } else {
9842 edits.push((prefix_range, empty_str.clone()));
9843 edits.push((suffix_range, empty_str.clone()));
9844 }
9845 } else {
9846 continue;
9847 }
9848 }
9849
9850 drop(snapshot);
9851 this.buffer.update(cx, |buffer, cx| {
9852 buffer.edit(edits, None, cx);
9853 });
9854
9855 // Adjust selections so that they end before any comment suffixes that
9856 // were inserted.
9857 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9858 let mut selections = this.selections.all::<Point>(cx);
9859 let snapshot = this.buffer.read(cx).read(cx);
9860 for selection in &mut selections {
9861 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9862 match row.cmp(&MultiBufferRow(selection.end.row)) {
9863 Ordering::Less => {
9864 suffixes_inserted.next();
9865 continue;
9866 }
9867 Ordering::Greater => break,
9868 Ordering::Equal => {
9869 if selection.end.column == snapshot.line_len(row) {
9870 if selection.is_empty() {
9871 selection.start.column -= suffix_len as u32;
9872 }
9873 selection.end.column -= suffix_len as u32;
9874 }
9875 break;
9876 }
9877 }
9878 }
9879 }
9880
9881 drop(snapshot);
9882 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9883 s.select(selections)
9884 });
9885
9886 let selections = this.selections.all::<Point>(cx);
9887 let selections_on_single_row = selections.windows(2).all(|selections| {
9888 selections[0].start.row == selections[1].start.row
9889 && selections[0].end.row == selections[1].end.row
9890 && selections[0].start.row == selections[0].end.row
9891 });
9892 let selections_selecting = selections
9893 .iter()
9894 .any(|selection| selection.start != selection.end);
9895 let advance_downwards = action.advance_downwards
9896 && selections_on_single_row
9897 && !selections_selecting
9898 && !matches!(this.mode, EditorMode::SingleLine { .. });
9899
9900 if advance_downwards {
9901 let snapshot = this.buffer.read(cx).snapshot(cx);
9902
9903 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9904 s.move_cursors_with(|display_snapshot, display_point, _| {
9905 let mut point = display_point.to_point(display_snapshot);
9906 point.row += 1;
9907 point = snapshot.clip_point(point, Bias::Left);
9908 let display_point = point.to_display_point(display_snapshot);
9909 let goal = SelectionGoal::HorizontalPosition(
9910 display_snapshot
9911 .x_for_display_point(display_point, text_layout_details)
9912 .into(),
9913 );
9914 (display_point, goal)
9915 })
9916 });
9917 }
9918 });
9919 }
9920
9921 pub fn select_enclosing_symbol(
9922 &mut self,
9923 _: &SelectEnclosingSymbol,
9924 window: &mut Window,
9925 cx: &mut Context<Self>,
9926 ) {
9927 let buffer = self.buffer.read(cx).snapshot(cx);
9928 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9929
9930 fn update_selection(
9931 selection: &Selection<usize>,
9932 buffer_snap: &MultiBufferSnapshot,
9933 ) -> Option<Selection<usize>> {
9934 let cursor = selection.head();
9935 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9936 for symbol in symbols.iter().rev() {
9937 let start = symbol.range.start.to_offset(buffer_snap);
9938 let end = symbol.range.end.to_offset(buffer_snap);
9939 let new_range = start..end;
9940 if start < selection.start || end > selection.end {
9941 return Some(Selection {
9942 id: selection.id,
9943 start: new_range.start,
9944 end: new_range.end,
9945 goal: SelectionGoal::None,
9946 reversed: selection.reversed,
9947 });
9948 }
9949 }
9950 None
9951 }
9952
9953 let mut selected_larger_symbol = false;
9954 let new_selections = old_selections
9955 .iter()
9956 .map(|selection| match update_selection(selection, &buffer) {
9957 Some(new_selection) => {
9958 if new_selection.range() != selection.range() {
9959 selected_larger_symbol = true;
9960 }
9961 new_selection
9962 }
9963 None => selection.clone(),
9964 })
9965 .collect::<Vec<_>>();
9966
9967 if selected_larger_symbol {
9968 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9969 s.select(new_selections);
9970 });
9971 }
9972 }
9973
9974 pub fn select_larger_syntax_node(
9975 &mut self,
9976 _: &SelectLargerSyntaxNode,
9977 window: &mut Window,
9978 cx: &mut Context<Self>,
9979 ) {
9980 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9981 let buffer = self.buffer.read(cx).snapshot(cx);
9982 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9983
9984 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9985 let mut selected_larger_node = false;
9986 let new_selections = old_selections
9987 .iter()
9988 .map(|selection| {
9989 let old_range = selection.start..selection.end;
9990 let mut new_range = old_range.clone();
9991 let mut new_node = None;
9992 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9993 {
9994 new_node = Some(node);
9995 new_range = containing_range;
9996 if !display_map.intersects_fold(new_range.start)
9997 && !display_map.intersects_fold(new_range.end)
9998 {
9999 break;
10000 }
10001 }
10002
10003 if let Some(node) = new_node {
10004 // Log the ancestor, to support using this action as a way to explore TreeSitter
10005 // nodes. Parent and grandparent are also logged because this operation will not
10006 // visit nodes that have the same range as their parent.
10007 log::info!("Node: {node:?}");
10008 let parent = node.parent();
10009 log::info!("Parent: {parent:?}");
10010 let grandparent = parent.and_then(|x| x.parent());
10011 log::info!("Grandparent: {grandparent:?}");
10012 }
10013
10014 selected_larger_node |= new_range != old_range;
10015 Selection {
10016 id: selection.id,
10017 start: new_range.start,
10018 end: new_range.end,
10019 goal: SelectionGoal::None,
10020 reversed: selection.reversed,
10021 }
10022 })
10023 .collect::<Vec<_>>();
10024
10025 if selected_larger_node {
10026 stack.push(old_selections);
10027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10028 s.select(new_selections);
10029 });
10030 }
10031 self.select_larger_syntax_node_stack = stack;
10032 }
10033
10034 pub fn select_smaller_syntax_node(
10035 &mut self,
10036 _: &SelectSmallerSyntaxNode,
10037 window: &mut Window,
10038 cx: &mut Context<Self>,
10039 ) {
10040 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10041 if let Some(selections) = stack.pop() {
10042 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10043 s.select(selections.to_vec());
10044 });
10045 }
10046 self.select_larger_syntax_node_stack = stack;
10047 }
10048
10049 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10050 if !EditorSettings::get_global(cx).gutter.runnables {
10051 self.clear_tasks();
10052 return Task::ready(());
10053 }
10054 let project = self.project.as_ref().map(Entity::downgrade);
10055 cx.spawn_in(window, |this, mut cx| async move {
10056 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10057 let Some(project) = project.and_then(|p| p.upgrade()) else {
10058 return;
10059 };
10060 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10061 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10062 }) else {
10063 return;
10064 };
10065
10066 let hide_runnables = project
10067 .update(&mut cx, |project, cx| {
10068 // Do not display any test indicators in non-dev server remote projects.
10069 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10070 })
10071 .unwrap_or(true);
10072 if hide_runnables {
10073 return;
10074 }
10075 let new_rows =
10076 cx.background_executor()
10077 .spawn({
10078 let snapshot = display_snapshot.clone();
10079 async move {
10080 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10081 }
10082 })
10083 .await;
10084
10085 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10086 this.update(&mut cx, |this, _| {
10087 this.clear_tasks();
10088 for (key, value) in rows {
10089 this.insert_tasks(key, value);
10090 }
10091 })
10092 .ok();
10093 })
10094 }
10095 fn fetch_runnable_ranges(
10096 snapshot: &DisplaySnapshot,
10097 range: Range<Anchor>,
10098 ) -> Vec<language::RunnableRange> {
10099 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10100 }
10101
10102 fn runnable_rows(
10103 project: Entity<Project>,
10104 snapshot: DisplaySnapshot,
10105 runnable_ranges: Vec<RunnableRange>,
10106 mut cx: AsyncWindowContext,
10107 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10108 runnable_ranges
10109 .into_iter()
10110 .filter_map(|mut runnable| {
10111 let tasks = cx
10112 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10113 .ok()?;
10114 if tasks.is_empty() {
10115 return None;
10116 }
10117
10118 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10119
10120 let row = snapshot
10121 .buffer_snapshot
10122 .buffer_line_for_row(MultiBufferRow(point.row))?
10123 .1
10124 .start
10125 .row;
10126
10127 let context_range =
10128 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10129 Some((
10130 (runnable.buffer_id, row),
10131 RunnableTasks {
10132 templates: tasks,
10133 offset: MultiBufferOffset(runnable.run_range.start),
10134 context_range,
10135 column: point.column,
10136 extra_variables: runnable.extra_captures,
10137 },
10138 ))
10139 })
10140 .collect()
10141 }
10142
10143 fn templates_with_tags(
10144 project: &Entity<Project>,
10145 runnable: &mut Runnable,
10146 cx: &mut App,
10147 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10148 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10149 let (worktree_id, file) = project
10150 .buffer_for_id(runnable.buffer, cx)
10151 .and_then(|buffer| buffer.read(cx).file())
10152 .map(|file| (file.worktree_id(cx), file.clone()))
10153 .unzip();
10154
10155 (
10156 project.task_store().read(cx).task_inventory().cloned(),
10157 worktree_id,
10158 file,
10159 )
10160 });
10161
10162 let tags = mem::take(&mut runnable.tags);
10163 let mut tags: Vec<_> = tags
10164 .into_iter()
10165 .flat_map(|tag| {
10166 let tag = tag.0.clone();
10167 inventory
10168 .as_ref()
10169 .into_iter()
10170 .flat_map(|inventory| {
10171 inventory.read(cx).list_tasks(
10172 file.clone(),
10173 Some(runnable.language.clone()),
10174 worktree_id,
10175 cx,
10176 )
10177 })
10178 .filter(move |(_, template)| {
10179 template.tags.iter().any(|source_tag| source_tag == &tag)
10180 })
10181 })
10182 .sorted_by_key(|(kind, _)| kind.to_owned())
10183 .collect();
10184 if let Some((leading_tag_source, _)) = tags.first() {
10185 // Strongest source wins; if we have worktree tag binding, prefer that to
10186 // global and language bindings;
10187 // if we have a global binding, prefer that to language binding.
10188 let first_mismatch = tags
10189 .iter()
10190 .position(|(tag_source, _)| tag_source != leading_tag_source);
10191 if let Some(index) = first_mismatch {
10192 tags.truncate(index);
10193 }
10194 }
10195
10196 tags
10197 }
10198
10199 pub fn move_to_enclosing_bracket(
10200 &mut self,
10201 _: &MoveToEnclosingBracket,
10202 window: &mut Window,
10203 cx: &mut Context<Self>,
10204 ) {
10205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10206 s.move_offsets_with(|snapshot, selection| {
10207 let Some(enclosing_bracket_ranges) =
10208 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10209 else {
10210 return;
10211 };
10212
10213 let mut best_length = usize::MAX;
10214 let mut best_inside = false;
10215 let mut best_in_bracket_range = false;
10216 let mut best_destination = None;
10217 for (open, close) in enclosing_bracket_ranges {
10218 let close = close.to_inclusive();
10219 let length = close.end() - open.start;
10220 let inside = selection.start >= open.end && selection.end <= *close.start();
10221 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10222 || close.contains(&selection.head());
10223
10224 // If best is next to a bracket and current isn't, skip
10225 if !in_bracket_range && best_in_bracket_range {
10226 continue;
10227 }
10228
10229 // Prefer smaller lengths unless best is inside and current isn't
10230 if length > best_length && (best_inside || !inside) {
10231 continue;
10232 }
10233
10234 best_length = length;
10235 best_inside = inside;
10236 best_in_bracket_range = in_bracket_range;
10237 best_destination = Some(
10238 if close.contains(&selection.start) && close.contains(&selection.end) {
10239 if inside {
10240 open.end
10241 } else {
10242 open.start
10243 }
10244 } else if inside {
10245 *close.start()
10246 } else {
10247 *close.end()
10248 },
10249 );
10250 }
10251
10252 if let Some(destination) = best_destination {
10253 selection.collapse_to(destination, SelectionGoal::None);
10254 }
10255 })
10256 });
10257 }
10258
10259 pub fn undo_selection(
10260 &mut self,
10261 _: &UndoSelection,
10262 window: &mut Window,
10263 cx: &mut Context<Self>,
10264 ) {
10265 self.end_selection(window, cx);
10266 self.selection_history.mode = SelectionHistoryMode::Undoing;
10267 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10268 self.change_selections(None, window, cx, |s| {
10269 s.select_anchors(entry.selections.to_vec())
10270 });
10271 self.select_next_state = entry.select_next_state;
10272 self.select_prev_state = entry.select_prev_state;
10273 self.add_selections_state = entry.add_selections_state;
10274 self.request_autoscroll(Autoscroll::newest(), cx);
10275 }
10276 self.selection_history.mode = SelectionHistoryMode::Normal;
10277 }
10278
10279 pub fn redo_selection(
10280 &mut self,
10281 _: &RedoSelection,
10282 window: &mut Window,
10283 cx: &mut Context<Self>,
10284 ) {
10285 self.end_selection(window, cx);
10286 self.selection_history.mode = SelectionHistoryMode::Redoing;
10287 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10288 self.change_selections(None, window, cx, |s| {
10289 s.select_anchors(entry.selections.to_vec())
10290 });
10291 self.select_next_state = entry.select_next_state;
10292 self.select_prev_state = entry.select_prev_state;
10293 self.add_selections_state = entry.add_selections_state;
10294 self.request_autoscroll(Autoscroll::newest(), cx);
10295 }
10296 self.selection_history.mode = SelectionHistoryMode::Normal;
10297 }
10298
10299 pub fn expand_excerpts(
10300 &mut self,
10301 action: &ExpandExcerpts,
10302 _: &mut Window,
10303 cx: &mut Context<Self>,
10304 ) {
10305 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10306 }
10307
10308 pub fn expand_excerpts_down(
10309 &mut self,
10310 action: &ExpandExcerptsDown,
10311 _: &mut Window,
10312 cx: &mut Context<Self>,
10313 ) {
10314 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10315 }
10316
10317 pub fn expand_excerpts_up(
10318 &mut self,
10319 action: &ExpandExcerptsUp,
10320 _: &mut Window,
10321 cx: &mut Context<Self>,
10322 ) {
10323 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10324 }
10325
10326 pub fn expand_excerpts_for_direction(
10327 &mut self,
10328 lines: u32,
10329 direction: ExpandExcerptDirection,
10330
10331 cx: &mut Context<Self>,
10332 ) {
10333 let selections = self.selections.disjoint_anchors();
10334
10335 let lines = if lines == 0 {
10336 EditorSettings::get_global(cx).expand_excerpt_lines
10337 } else {
10338 lines
10339 };
10340
10341 self.buffer.update(cx, |buffer, cx| {
10342 let snapshot = buffer.snapshot(cx);
10343 let mut excerpt_ids = selections
10344 .iter()
10345 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10346 .collect::<Vec<_>>();
10347 excerpt_ids.sort();
10348 excerpt_ids.dedup();
10349 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10350 })
10351 }
10352
10353 pub fn expand_excerpt(
10354 &mut self,
10355 excerpt: ExcerptId,
10356 direction: ExpandExcerptDirection,
10357 cx: &mut Context<Self>,
10358 ) {
10359 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10360 self.buffer.update(cx, |buffer, cx| {
10361 buffer.expand_excerpts([excerpt], lines, direction, cx)
10362 })
10363 }
10364
10365 pub fn go_to_singleton_buffer_point(
10366 &mut self,
10367 point: Point,
10368 window: &mut Window,
10369 cx: &mut Context<Self>,
10370 ) {
10371 self.go_to_singleton_buffer_range(point..point, window, cx);
10372 }
10373
10374 pub fn go_to_singleton_buffer_range(
10375 &mut self,
10376 range: Range<Point>,
10377 window: &mut Window,
10378 cx: &mut Context<Self>,
10379 ) {
10380 let multibuffer = self.buffer().read(cx);
10381 let Some(buffer) = multibuffer.as_singleton() else {
10382 return;
10383 };
10384 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10385 return;
10386 };
10387 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10388 return;
10389 };
10390 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10391 s.select_anchor_ranges([start..end])
10392 });
10393 }
10394
10395 fn go_to_diagnostic(
10396 &mut self,
10397 _: &GoToDiagnostic,
10398 window: &mut Window,
10399 cx: &mut Context<Self>,
10400 ) {
10401 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10402 }
10403
10404 fn go_to_prev_diagnostic(
10405 &mut self,
10406 _: &GoToPrevDiagnostic,
10407 window: &mut Window,
10408 cx: &mut Context<Self>,
10409 ) {
10410 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10411 }
10412
10413 pub fn go_to_diagnostic_impl(
10414 &mut self,
10415 direction: Direction,
10416 window: &mut Window,
10417 cx: &mut Context<Self>,
10418 ) {
10419 let buffer = self.buffer.read(cx).snapshot(cx);
10420 let selection = self.selections.newest::<usize>(cx);
10421
10422 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10423 if direction == Direction::Next {
10424 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10425 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10426 return;
10427 };
10428 self.activate_diagnostics(
10429 buffer_id,
10430 popover.local_diagnostic.diagnostic.group_id,
10431 window,
10432 cx,
10433 );
10434 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10435 let primary_range_start = active_diagnostics.primary_range.start;
10436 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10437 let mut new_selection = s.newest_anchor().clone();
10438 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10439 s.select_anchors(vec![new_selection.clone()]);
10440 });
10441 self.refresh_inline_completion(false, true, window, cx);
10442 }
10443 return;
10444 }
10445 }
10446
10447 let active_group_id = self
10448 .active_diagnostics
10449 .as_ref()
10450 .map(|active_group| active_group.group_id);
10451 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10452 active_diagnostics
10453 .primary_range
10454 .to_offset(&buffer)
10455 .to_inclusive()
10456 });
10457 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10458 if active_primary_range.contains(&selection.head()) {
10459 *active_primary_range.start()
10460 } else {
10461 selection.head()
10462 }
10463 } else {
10464 selection.head()
10465 };
10466
10467 let snapshot = self.snapshot(window, cx);
10468 let primary_diagnostics_before = buffer
10469 .diagnostics_in_range::<usize>(0..search_start)
10470 .filter(|entry| entry.diagnostic.is_primary)
10471 .filter(|entry| entry.range.start != entry.range.end)
10472 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10473 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10474 .collect::<Vec<_>>();
10475 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10476 primary_diagnostics_before
10477 .iter()
10478 .position(|entry| entry.diagnostic.group_id == active_group_id)
10479 });
10480
10481 let primary_diagnostics_after = buffer
10482 .diagnostics_in_range::<usize>(search_start..buffer.len())
10483 .filter(|entry| entry.diagnostic.is_primary)
10484 .filter(|entry| entry.range.start != entry.range.end)
10485 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10486 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10487 .collect::<Vec<_>>();
10488 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10489 primary_diagnostics_after
10490 .iter()
10491 .enumerate()
10492 .rev()
10493 .find_map(|(i, entry)| {
10494 if entry.diagnostic.group_id == active_group_id {
10495 Some(i)
10496 } else {
10497 None
10498 }
10499 })
10500 });
10501
10502 let next_primary_diagnostic = match direction {
10503 Direction::Prev => primary_diagnostics_before
10504 .iter()
10505 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10506 .rev()
10507 .next(),
10508 Direction::Next => primary_diagnostics_after
10509 .iter()
10510 .skip(
10511 last_same_group_diagnostic_after
10512 .map(|index| index + 1)
10513 .unwrap_or(0),
10514 )
10515 .next(),
10516 };
10517
10518 // Cycle around to the start of the buffer, potentially moving back to the start of
10519 // the currently active diagnostic.
10520 let cycle_around = || match direction {
10521 Direction::Prev => primary_diagnostics_after
10522 .iter()
10523 .rev()
10524 .chain(primary_diagnostics_before.iter().rev())
10525 .next(),
10526 Direction::Next => primary_diagnostics_before
10527 .iter()
10528 .chain(primary_diagnostics_after.iter())
10529 .next(),
10530 };
10531
10532 if let Some((primary_range, group_id)) = next_primary_diagnostic
10533 .or_else(cycle_around)
10534 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10535 {
10536 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10537 return;
10538 };
10539 self.activate_diagnostics(buffer_id, group_id, window, cx);
10540 if self.active_diagnostics.is_some() {
10541 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10542 s.select(vec![Selection {
10543 id: selection.id,
10544 start: primary_range.start,
10545 end: primary_range.start,
10546 reversed: false,
10547 goal: SelectionGoal::None,
10548 }]);
10549 });
10550 self.refresh_inline_completion(false, true, window, cx);
10551 }
10552 }
10553 }
10554
10555 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10556 let snapshot = self.snapshot(window, cx);
10557 let selection = self.selections.newest::<Point>(cx);
10558 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10559 }
10560
10561 fn go_to_hunk_after_position(
10562 &mut self,
10563 snapshot: &EditorSnapshot,
10564 position: Point,
10565 window: &mut Window,
10566 cx: &mut Context<Editor>,
10567 ) -> Option<MultiBufferDiffHunk> {
10568 let mut hunk = snapshot
10569 .buffer_snapshot
10570 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10571 .find(|hunk| hunk.row_range.start.0 > position.row);
10572 if hunk.is_none() {
10573 hunk = snapshot
10574 .buffer_snapshot
10575 .diff_hunks_in_range(Point::zero()..position)
10576 .find(|hunk| hunk.row_range.end.0 < position.row)
10577 }
10578 if let Some(hunk) = &hunk {
10579 let destination = Point::new(hunk.row_range.start.0, 0);
10580 self.unfold_ranges(&[destination..destination], false, false, cx);
10581 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10582 s.select_ranges(vec![destination..destination]);
10583 });
10584 }
10585
10586 hunk
10587 }
10588
10589 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10590 let snapshot = self.snapshot(window, cx);
10591 let selection = self.selections.newest::<Point>(cx);
10592 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10593 }
10594
10595 fn go_to_hunk_before_position(
10596 &mut self,
10597 snapshot: &EditorSnapshot,
10598 position: Point,
10599 window: &mut Window,
10600 cx: &mut Context<Editor>,
10601 ) -> Option<MultiBufferDiffHunk> {
10602 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10603 if hunk.is_none() {
10604 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10605 }
10606 if let Some(hunk) = &hunk {
10607 let destination = Point::new(hunk.row_range.start.0, 0);
10608 self.unfold_ranges(&[destination..destination], false, false, cx);
10609 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10610 s.select_ranges(vec![destination..destination]);
10611 });
10612 }
10613
10614 hunk
10615 }
10616
10617 pub fn go_to_definition(
10618 &mut self,
10619 _: &GoToDefinition,
10620 window: &mut Window,
10621 cx: &mut Context<Self>,
10622 ) -> Task<Result<Navigated>> {
10623 let definition =
10624 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10625 cx.spawn_in(window, |editor, mut cx| async move {
10626 if definition.await? == Navigated::Yes {
10627 return Ok(Navigated::Yes);
10628 }
10629 match editor.update_in(&mut cx, |editor, window, cx| {
10630 editor.find_all_references(&FindAllReferences, window, cx)
10631 })? {
10632 Some(references) => references.await,
10633 None => Ok(Navigated::No),
10634 }
10635 })
10636 }
10637
10638 pub fn go_to_declaration(
10639 &mut self,
10640 _: &GoToDeclaration,
10641 window: &mut Window,
10642 cx: &mut Context<Self>,
10643 ) -> Task<Result<Navigated>> {
10644 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10645 }
10646
10647 pub fn go_to_declaration_split(
10648 &mut self,
10649 _: &GoToDeclaration,
10650 window: &mut Window,
10651 cx: &mut Context<Self>,
10652 ) -> Task<Result<Navigated>> {
10653 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10654 }
10655
10656 pub fn go_to_implementation(
10657 &mut self,
10658 _: &GoToImplementation,
10659 window: &mut Window,
10660 cx: &mut Context<Self>,
10661 ) -> Task<Result<Navigated>> {
10662 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10663 }
10664
10665 pub fn go_to_implementation_split(
10666 &mut self,
10667 _: &GoToImplementationSplit,
10668 window: &mut Window,
10669 cx: &mut Context<Self>,
10670 ) -> Task<Result<Navigated>> {
10671 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10672 }
10673
10674 pub fn go_to_type_definition(
10675 &mut self,
10676 _: &GoToTypeDefinition,
10677 window: &mut Window,
10678 cx: &mut Context<Self>,
10679 ) -> Task<Result<Navigated>> {
10680 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10681 }
10682
10683 pub fn go_to_definition_split(
10684 &mut self,
10685 _: &GoToDefinitionSplit,
10686 window: &mut Window,
10687 cx: &mut Context<Self>,
10688 ) -> Task<Result<Navigated>> {
10689 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10690 }
10691
10692 pub fn go_to_type_definition_split(
10693 &mut self,
10694 _: &GoToTypeDefinitionSplit,
10695 window: &mut Window,
10696 cx: &mut Context<Self>,
10697 ) -> Task<Result<Navigated>> {
10698 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10699 }
10700
10701 fn go_to_definition_of_kind(
10702 &mut self,
10703 kind: GotoDefinitionKind,
10704 split: bool,
10705 window: &mut Window,
10706 cx: &mut Context<Self>,
10707 ) -> Task<Result<Navigated>> {
10708 let Some(provider) = self.semantics_provider.clone() else {
10709 return Task::ready(Ok(Navigated::No));
10710 };
10711 let head = self.selections.newest::<usize>(cx).head();
10712 let buffer = self.buffer.read(cx);
10713 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10714 text_anchor
10715 } else {
10716 return Task::ready(Ok(Navigated::No));
10717 };
10718
10719 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10720 return Task::ready(Ok(Navigated::No));
10721 };
10722
10723 cx.spawn_in(window, |editor, mut cx| async move {
10724 let definitions = definitions.await?;
10725 let navigated = editor
10726 .update_in(&mut cx, |editor, window, cx| {
10727 editor.navigate_to_hover_links(
10728 Some(kind),
10729 definitions
10730 .into_iter()
10731 .filter(|location| {
10732 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10733 })
10734 .map(HoverLink::Text)
10735 .collect::<Vec<_>>(),
10736 split,
10737 window,
10738 cx,
10739 )
10740 })?
10741 .await?;
10742 anyhow::Ok(navigated)
10743 })
10744 }
10745
10746 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10747 let selection = self.selections.newest_anchor();
10748 let head = selection.head();
10749 let tail = selection.tail();
10750
10751 let Some((buffer, start_position)) =
10752 self.buffer.read(cx).text_anchor_for_position(head, cx)
10753 else {
10754 return;
10755 };
10756
10757 let end_position = if head != tail {
10758 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10759 return;
10760 };
10761 Some(pos)
10762 } else {
10763 None
10764 };
10765
10766 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10767 let url = if let Some(end_pos) = end_position {
10768 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10769 } else {
10770 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10771 };
10772
10773 if let Some(url) = url {
10774 editor.update(&mut cx, |_, cx| {
10775 cx.open_url(&url);
10776 })
10777 } else {
10778 Ok(())
10779 }
10780 });
10781
10782 url_finder.detach();
10783 }
10784
10785 pub fn open_selected_filename(
10786 &mut self,
10787 _: &OpenSelectedFilename,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) {
10791 let Some(workspace) = self.workspace() else {
10792 return;
10793 };
10794
10795 let position = self.selections.newest_anchor().head();
10796
10797 let Some((buffer, buffer_position)) =
10798 self.buffer.read(cx).text_anchor_for_position(position, cx)
10799 else {
10800 return;
10801 };
10802
10803 let project = self.project.clone();
10804
10805 cx.spawn_in(window, |_, mut cx| async move {
10806 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10807
10808 if let Some((_, path)) = result {
10809 workspace
10810 .update_in(&mut cx, |workspace, window, cx| {
10811 workspace.open_resolved_path(path, window, cx)
10812 })?
10813 .await?;
10814 }
10815 anyhow::Ok(())
10816 })
10817 .detach();
10818 }
10819
10820 pub(crate) fn navigate_to_hover_links(
10821 &mut self,
10822 kind: Option<GotoDefinitionKind>,
10823 mut definitions: Vec<HoverLink>,
10824 split: bool,
10825 window: &mut Window,
10826 cx: &mut Context<Editor>,
10827 ) -> Task<Result<Navigated>> {
10828 // If there is one definition, just open it directly
10829 if definitions.len() == 1 {
10830 let definition = definitions.pop().unwrap();
10831
10832 enum TargetTaskResult {
10833 Location(Option<Location>),
10834 AlreadyNavigated,
10835 }
10836
10837 let target_task = match definition {
10838 HoverLink::Text(link) => {
10839 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10840 }
10841 HoverLink::InlayHint(lsp_location, server_id) => {
10842 let computation =
10843 self.compute_target_location(lsp_location, server_id, window, cx);
10844 cx.background_executor().spawn(async move {
10845 let location = computation.await?;
10846 Ok(TargetTaskResult::Location(location))
10847 })
10848 }
10849 HoverLink::Url(url) => {
10850 cx.open_url(&url);
10851 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10852 }
10853 HoverLink::File(path) => {
10854 if let Some(workspace) = self.workspace() {
10855 cx.spawn_in(window, |_, mut cx| async move {
10856 workspace
10857 .update_in(&mut cx, |workspace, window, cx| {
10858 workspace.open_resolved_path(path, window, cx)
10859 })?
10860 .await
10861 .map(|_| TargetTaskResult::AlreadyNavigated)
10862 })
10863 } else {
10864 Task::ready(Ok(TargetTaskResult::Location(None)))
10865 }
10866 }
10867 };
10868 cx.spawn_in(window, |editor, mut cx| async move {
10869 let target = match target_task.await.context("target resolution task")? {
10870 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10871 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10872 TargetTaskResult::Location(Some(target)) => target,
10873 };
10874
10875 editor.update_in(&mut cx, |editor, window, cx| {
10876 let Some(workspace) = editor.workspace() else {
10877 return Navigated::No;
10878 };
10879 let pane = workspace.read(cx).active_pane().clone();
10880
10881 let range = target.range.to_point(target.buffer.read(cx));
10882 let range = editor.range_for_match(&range);
10883 let range = collapse_multiline_range(range);
10884
10885 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10886 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10887 } else {
10888 window.defer(cx, move |window, cx| {
10889 let target_editor: Entity<Self> =
10890 workspace.update(cx, |workspace, cx| {
10891 let pane = if split {
10892 workspace.adjacent_pane(window, cx)
10893 } else {
10894 workspace.active_pane().clone()
10895 };
10896
10897 workspace.open_project_item(
10898 pane,
10899 target.buffer.clone(),
10900 true,
10901 true,
10902 window,
10903 cx,
10904 )
10905 });
10906 target_editor.update(cx, |target_editor, cx| {
10907 // When selecting a definition in a different buffer, disable the nav history
10908 // to avoid creating a history entry at the previous cursor location.
10909 pane.update(cx, |pane, _| pane.disable_history());
10910 target_editor.go_to_singleton_buffer_range(range, window, cx);
10911 pane.update(cx, |pane, _| pane.enable_history());
10912 });
10913 });
10914 }
10915 Navigated::Yes
10916 })
10917 })
10918 } else if !definitions.is_empty() {
10919 cx.spawn_in(window, |editor, mut cx| async move {
10920 let (title, location_tasks, workspace) = editor
10921 .update_in(&mut cx, |editor, window, cx| {
10922 let tab_kind = match kind {
10923 Some(GotoDefinitionKind::Implementation) => "Implementations",
10924 _ => "Definitions",
10925 };
10926 let title = definitions
10927 .iter()
10928 .find_map(|definition| match definition {
10929 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10930 let buffer = origin.buffer.read(cx);
10931 format!(
10932 "{} for {}",
10933 tab_kind,
10934 buffer
10935 .text_for_range(origin.range.clone())
10936 .collect::<String>()
10937 )
10938 }),
10939 HoverLink::InlayHint(_, _) => None,
10940 HoverLink::Url(_) => None,
10941 HoverLink::File(_) => None,
10942 })
10943 .unwrap_or(tab_kind.to_string());
10944 let location_tasks = definitions
10945 .into_iter()
10946 .map(|definition| match definition {
10947 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10948 HoverLink::InlayHint(lsp_location, server_id) => editor
10949 .compute_target_location(lsp_location, server_id, window, cx),
10950 HoverLink::Url(_) => Task::ready(Ok(None)),
10951 HoverLink::File(_) => Task::ready(Ok(None)),
10952 })
10953 .collect::<Vec<_>>();
10954 (title, location_tasks, editor.workspace().clone())
10955 })
10956 .context("location tasks preparation")?;
10957
10958 let locations = future::join_all(location_tasks)
10959 .await
10960 .into_iter()
10961 .filter_map(|location| location.transpose())
10962 .collect::<Result<_>>()
10963 .context("location tasks")?;
10964
10965 let Some(workspace) = workspace else {
10966 return Ok(Navigated::No);
10967 };
10968 let opened = workspace
10969 .update_in(&mut cx, |workspace, window, cx| {
10970 Self::open_locations_in_multibuffer(
10971 workspace,
10972 locations,
10973 title,
10974 split,
10975 MultibufferSelectionMode::First,
10976 window,
10977 cx,
10978 )
10979 })
10980 .ok();
10981
10982 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10983 })
10984 } else {
10985 Task::ready(Ok(Navigated::No))
10986 }
10987 }
10988
10989 fn compute_target_location(
10990 &self,
10991 lsp_location: lsp::Location,
10992 server_id: LanguageServerId,
10993 window: &mut Window,
10994 cx: &mut Context<Self>,
10995 ) -> Task<anyhow::Result<Option<Location>>> {
10996 let Some(project) = self.project.clone() else {
10997 return Task::ready(Ok(None));
10998 };
10999
11000 cx.spawn_in(window, move |editor, mut cx| async move {
11001 let location_task = editor.update(&mut cx, |_, cx| {
11002 project.update(cx, |project, cx| {
11003 let language_server_name = project
11004 .language_server_statuses(cx)
11005 .find(|(id, _)| server_id == *id)
11006 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11007 language_server_name.map(|language_server_name| {
11008 project.open_local_buffer_via_lsp(
11009 lsp_location.uri.clone(),
11010 server_id,
11011 language_server_name,
11012 cx,
11013 )
11014 })
11015 })
11016 })?;
11017 let location = match location_task {
11018 Some(task) => Some({
11019 let target_buffer_handle = task.await.context("open local buffer")?;
11020 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11021 let target_start = target_buffer
11022 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11023 let target_end = target_buffer
11024 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11025 target_buffer.anchor_after(target_start)
11026 ..target_buffer.anchor_before(target_end)
11027 })?;
11028 Location {
11029 buffer: target_buffer_handle,
11030 range,
11031 }
11032 }),
11033 None => None,
11034 };
11035 Ok(location)
11036 })
11037 }
11038
11039 pub fn find_all_references(
11040 &mut self,
11041 _: &FindAllReferences,
11042 window: &mut Window,
11043 cx: &mut Context<Self>,
11044 ) -> Option<Task<Result<Navigated>>> {
11045 let selection = self.selections.newest::<usize>(cx);
11046 let multi_buffer = self.buffer.read(cx);
11047 let head = selection.head();
11048
11049 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11050 let head_anchor = multi_buffer_snapshot.anchor_at(
11051 head,
11052 if head < selection.tail() {
11053 Bias::Right
11054 } else {
11055 Bias::Left
11056 },
11057 );
11058
11059 match self
11060 .find_all_references_task_sources
11061 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11062 {
11063 Ok(_) => {
11064 log::info!(
11065 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11066 );
11067 return None;
11068 }
11069 Err(i) => {
11070 self.find_all_references_task_sources.insert(i, head_anchor);
11071 }
11072 }
11073
11074 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11075 let workspace = self.workspace()?;
11076 let project = workspace.read(cx).project().clone();
11077 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11078 Some(cx.spawn_in(window, |editor, mut cx| async move {
11079 let _cleanup = defer({
11080 let mut cx = cx.clone();
11081 move || {
11082 let _ = editor.update(&mut cx, |editor, _| {
11083 if let Ok(i) =
11084 editor
11085 .find_all_references_task_sources
11086 .binary_search_by(|anchor| {
11087 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11088 })
11089 {
11090 editor.find_all_references_task_sources.remove(i);
11091 }
11092 });
11093 }
11094 });
11095
11096 let locations = references.await?;
11097 if locations.is_empty() {
11098 return anyhow::Ok(Navigated::No);
11099 }
11100
11101 workspace.update_in(&mut cx, |workspace, window, cx| {
11102 let title = locations
11103 .first()
11104 .as_ref()
11105 .map(|location| {
11106 let buffer = location.buffer.read(cx);
11107 format!(
11108 "References to `{}`",
11109 buffer
11110 .text_for_range(location.range.clone())
11111 .collect::<String>()
11112 )
11113 })
11114 .unwrap();
11115 Self::open_locations_in_multibuffer(
11116 workspace,
11117 locations,
11118 title,
11119 false,
11120 MultibufferSelectionMode::First,
11121 window,
11122 cx,
11123 );
11124 Navigated::Yes
11125 })
11126 }))
11127 }
11128
11129 /// Opens a multibuffer with the given project locations in it
11130 pub fn open_locations_in_multibuffer(
11131 workspace: &mut Workspace,
11132 mut locations: Vec<Location>,
11133 title: String,
11134 split: bool,
11135 multibuffer_selection_mode: MultibufferSelectionMode,
11136 window: &mut Window,
11137 cx: &mut Context<Workspace>,
11138 ) {
11139 // If there are multiple definitions, open them in a multibuffer
11140 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11141 let mut locations = locations.into_iter().peekable();
11142 let mut ranges = Vec::new();
11143 let capability = workspace.project().read(cx).capability();
11144
11145 let excerpt_buffer = cx.new(|cx| {
11146 let mut multibuffer = MultiBuffer::new(capability);
11147 while let Some(location) = locations.next() {
11148 let buffer = location.buffer.read(cx);
11149 let mut ranges_for_buffer = Vec::new();
11150 let range = location.range.to_offset(buffer);
11151 ranges_for_buffer.push(range.clone());
11152
11153 while let Some(next_location) = locations.peek() {
11154 if next_location.buffer == location.buffer {
11155 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11156 locations.next();
11157 } else {
11158 break;
11159 }
11160 }
11161
11162 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11163 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11164 location.buffer.clone(),
11165 ranges_for_buffer,
11166 DEFAULT_MULTIBUFFER_CONTEXT,
11167 cx,
11168 ))
11169 }
11170
11171 multibuffer.with_title(title)
11172 });
11173
11174 let editor = cx.new(|cx| {
11175 Editor::for_multibuffer(
11176 excerpt_buffer,
11177 Some(workspace.project().clone()),
11178 true,
11179 window,
11180 cx,
11181 )
11182 });
11183 editor.update(cx, |editor, cx| {
11184 match multibuffer_selection_mode {
11185 MultibufferSelectionMode::First => {
11186 if let Some(first_range) = ranges.first() {
11187 editor.change_selections(None, window, cx, |selections| {
11188 selections.clear_disjoint();
11189 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11190 });
11191 }
11192 editor.highlight_background::<Self>(
11193 &ranges,
11194 |theme| theme.editor_highlighted_line_background,
11195 cx,
11196 );
11197 }
11198 MultibufferSelectionMode::All => {
11199 editor.change_selections(None, window, cx, |selections| {
11200 selections.clear_disjoint();
11201 selections.select_anchor_ranges(ranges);
11202 });
11203 }
11204 }
11205 editor.register_buffers_with_language_servers(cx);
11206 });
11207
11208 let item = Box::new(editor);
11209 let item_id = item.item_id();
11210
11211 if split {
11212 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11213 } else {
11214 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11215 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11216 pane.close_current_preview_item(window, cx)
11217 } else {
11218 None
11219 }
11220 });
11221 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11222 }
11223 workspace.active_pane().update(cx, |pane, cx| {
11224 pane.set_preview_item_id(Some(item_id), cx);
11225 });
11226 }
11227
11228 pub fn rename(
11229 &mut self,
11230 _: &Rename,
11231 window: &mut Window,
11232 cx: &mut Context<Self>,
11233 ) -> Option<Task<Result<()>>> {
11234 use language::ToOffset as _;
11235
11236 let provider = self.semantics_provider.clone()?;
11237 let selection = self.selections.newest_anchor().clone();
11238 let (cursor_buffer, cursor_buffer_position) = self
11239 .buffer
11240 .read(cx)
11241 .text_anchor_for_position(selection.head(), cx)?;
11242 let (tail_buffer, cursor_buffer_position_end) = self
11243 .buffer
11244 .read(cx)
11245 .text_anchor_for_position(selection.tail(), cx)?;
11246 if tail_buffer != cursor_buffer {
11247 return None;
11248 }
11249
11250 let snapshot = cursor_buffer.read(cx).snapshot();
11251 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11252 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11253 let prepare_rename = provider
11254 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11255 .unwrap_or_else(|| Task::ready(Ok(None)));
11256 drop(snapshot);
11257
11258 Some(cx.spawn_in(window, |this, mut cx| async move {
11259 let rename_range = if let Some(range) = prepare_rename.await? {
11260 Some(range)
11261 } else {
11262 this.update(&mut cx, |this, cx| {
11263 let buffer = this.buffer.read(cx).snapshot(cx);
11264 let mut buffer_highlights = this
11265 .document_highlights_for_position(selection.head(), &buffer)
11266 .filter(|highlight| {
11267 highlight.start.excerpt_id == selection.head().excerpt_id
11268 && highlight.end.excerpt_id == selection.head().excerpt_id
11269 });
11270 buffer_highlights
11271 .next()
11272 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11273 })?
11274 };
11275 if let Some(rename_range) = rename_range {
11276 this.update_in(&mut cx, |this, window, cx| {
11277 let snapshot = cursor_buffer.read(cx).snapshot();
11278 let rename_buffer_range = rename_range.to_offset(&snapshot);
11279 let cursor_offset_in_rename_range =
11280 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11281 let cursor_offset_in_rename_range_end =
11282 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11283
11284 this.take_rename(false, window, cx);
11285 let buffer = this.buffer.read(cx).read(cx);
11286 let cursor_offset = selection.head().to_offset(&buffer);
11287 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11288 let rename_end = rename_start + rename_buffer_range.len();
11289 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11290 let mut old_highlight_id = None;
11291 let old_name: Arc<str> = buffer
11292 .chunks(rename_start..rename_end, true)
11293 .map(|chunk| {
11294 if old_highlight_id.is_none() {
11295 old_highlight_id = chunk.syntax_highlight_id;
11296 }
11297 chunk.text
11298 })
11299 .collect::<String>()
11300 .into();
11301
11302 drop(buffer);
11303
11304 // Position the selection in the rename editor so that it matches the current selection.
11305 this.show_local_selections = false;
11306 let rename_editor = cx.new(|cx| {
11307 let mut editor = Editor::single_line(window, cx);
11308 editor.buffer.update(cx, |buffer, cx| {
11309 buffer.edit([(0..0, old_name.clone())], None, cx)
11310 });
11311 let rename_selection_range = match cursor_offset_in_rename_range
11312 .cmp(&cursor_offset_in_rename_range_end)
11313 {
11314 Ordering::Equal => {
11315 editor.select_all(&SelectAll, window, cx);
11316 return editor;
11317 }
11318 Ordering::Less => {
11319 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11320 }
11321 Ordering::Greater => {
11322 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11323 }
11324 };
11325 if rename_selection_range.end > old_name.len() {
11326 editor.select_all(&SelectAll, window, cx);
11327 } else {
11328 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11329 s.select_ranges([rename_selection_range]);
11330 });
11331 }
11332 editor
11333 });
11334 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11335 if e == &EditorEvent::Focused {
11336 cx.emit(EditorEvent::FocusedIn)
11337 }
11338 })
11339 .detach();
11340
11341 let write_highlights =
11342 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11343 let read_highlights =
11344 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11345 let ranges = write_highlights
11346 .iter()
11347 .flat_map(|(_, ranges)| ranges.iter())
11348 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11349 .cloned()
11350 .collect();
11351
11352 this.highlight_text::<Rename>(
11353 ranges,
11354 HighlightStyle {
11355 fade_out: Some(0.6),
11356 ..Default::default()
11357 },
11358 cx,
11359 );
11360 let rename_focus_handle = rename_editor.focus_handle(cx);
11361 window.focus(&rename_focus_handle);
11362 let block_id = this.insert_blocks(
11363 [BlockProperties {
11364 style: BlockStyle::Flex,
11365 placement: BlockPlacement::Below(range.start),
11366 height: 1,
11367 render: Arc::new({
11368 let rename_editor = rename_editor.clone();
11369 move |cx: &mut BlockContext| {
11370 let mut text_style = cx.editor_style.text.clone();
11371 if let Some(highlight_style) = old_highlight_id
11372 .and_then(|h| h.style(&cx.editor_style.syntax))
11373 {
11374 text_style = text_style.highlight(highlight_style);
11375 }
11376 div()
11377 .block_mouse_down()
11378 .pl(cx.anchor_x)
11379 .child(EditorElement::new(
11380 &rename_editor,
11381 EditorStyle {
11382 background: cx.theme().system().transparent,
11383 local_player: cx.editor_style.local_player,
11384 text: text_style,
11385 scrollbar_width: cx.editor_style.scrollbar_width,
11386 syntax: cx.editor_style.syntax.clone(),
11387 status: cx.editor_style.status.clone(),
11388 inlay_hints_style: HighlightStyle {
11389 font_weight: Some(FontWeight::BOLD),
11390 ..make_inlay_hints_style(cx.app)
11391 },
11392 inline_completion_styles: make_suggestion_styles(
11393 cx.app,
11394 ),
11395 ..EditorStyle::default()
11396 },
11397 ))
11398 .into_any_element()
11399 }
11400 }),
11401 priority: 0,
11402 }],
11403 Some(Autoscroll::fit()),
11404 cx,
11405 )[0];
11406 this.pending_rename = Some(RenameState {
11407 range,
11408 old_name,
11409 editor: rename_editor,
11410 block_id,
11411 });
11412 })?;
11413 }
11414
11415 Ok(())
11416 }))
11417 }
11418
11419 pub fn confirm_rename(
11420 &mut self,
11421 _: &ConfirmRename,
11422 window: &mut Window,
11423 cx: &mut Context<Self>,
11424 ) -> Option<Task<Result<()>>> {
11425 let rename = self.take_rename(false, window, cx)?;
11426 let workspace = self.workspace()?.downgrade();
11427 let (buffer, start) = self
11428 .buffer
11429 .read(cx)
11430 .text_anchor_for_position(rename.range.start, cx)?;
11431 let (end_buffer, _) = self
11432 .buffer
11433 .read(cx)
11434 .text_anchor_for_position(rename.range.end, cx)?;
11435 if buffer != end_buffer {
11436 return None;
11437 }
11438
11439 let old_name = rename.old_name;
11440 let new_name = rename.editor.read(cx).text(cx);
11441
11442 let rename = self.semantics_provider.as_ref()?.perform_rename(
11443 &buffer,
11444 start,
11445 new_name.clone(),
11446 cx,
11447 )?;
11448
11449 Some(cx.spawn_in(window, |editor, mut cx| async move {
11450 let project_transaction = rename.await?;
11451 Self::open_project_transaction(
11452 &editor,
11453 workspace,
11454 project_transaction,
11455 format!("Rename: {} → {}", old_name, new_name),
11456 cx.clone(),
11457 )
11458 .await?;
11459
11460 editor.update(&mut cx, |editor, cx| {
11461 editor.refresh_document_highlights(cx);
11462 })?;
11463 Ok(())
11464 }))
11465 }
11466
11467 fn take_rename(
11468 &mut self,
11469 moving_cursor: bool,
11470 window: &mut Window,
11471 cx: &mut Context<Self>,
11472 ) -> Option<RenameState> {
11473 let rename = self.pending_rename.take()?;
11474 if rename.editor.focus_handle(cx).is_focused(window) {
11475 window.focus(&self.focus_handle);
11476 }
11477
11478 self.remove_blocks(
11479 [rename.block_id].into_iter().collect(),
11480 Some(Autoscroll::fit()),
11481 cx,
11482 );
11483 self.clear_highlights::<Rename>(cx);
11484 self.show_local_selections = true;
11485
11486 if moving_cursor {
11487 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11488 editor.selections.newest::<usize>(cx).head()
11489 });
11490
11491 // Update the selection to match the position of the selection inside
11492 // the rename editor.
11493 let snapshot = self.buffer.read(cx).read(cx);
11494 let rename_range = rename.range.to_offset(&snapshot);
11495 let cursor_in_editor = snapshot
11496 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11497 .min(rename_range.end);
11498 drop(snapshot);
11499
11500 self.change_selections(None, window, cx, |s| {
11501 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11502 });
11503 } else {
11504 self.refresh_document_highlights(cx);
11505 }
11506
11507 Some(rename)
11508 }
11509
11510 pub fn pending_rename(&self) -> Option<&RenameState> {
11511 self.pending_rename.as_ref()
11512 }
11513
11514 fn format(
11515 &mut self,
11516 _: &Format,
11517 window: &mut Window,
11518 cx: &mut Context<Self>,
11519 ) -> Option<Task<Result<()>>> {
11520 let project = match &self.project {
11521 Some(project) => project.clone(),
11522 None => return None,
11523 };
11524
11525 Some(self.perform_format(
11526 project,
11527 FormatTrigger::Manual,
11528 FormatTarget::Buffers,
11529 window,
11530 cx,
11531 ))
11532 }
11533
11534 fn format_selections(
11535 &mut self,
11536 _: &FormatSelections,
11537 window: &mut Window,
11538 cx: &mut Context<Self>,
11539 ) -> Option<Task<Result<()>>> {
11540 let project = match &self.project {
11541 Some(project) => project.clone(),
11542 None => return None,
11543 };
11544
11545 let ranges = self
11546 .selections
11547 .all_adjusted(cx)
11548 .into_iter()
11549 .map(|selection| selection.range())
11550 .collect_vec();
11551
11552 Some(self.perform_format(
11553 project,
11554 FormatTrigger::Manual,
11555 FormatTarget::Ranges(ranges),
11556 window,
11557 cx,
11558 ))
11559 }
11560
11561 fn perform_format(
11562 &mut self,
11563 project: Entity<Project>,
11564 trigger: FormatTrigger,
11565 target: FormatTarget,
11566 window: &mut Window,
11567 cx: &mut Context<Self>,
11568 ) -> Task<Result<()>> {
11569 let buffer = self.buffer.clone();
11570 let (buffers, target) = match target {
11571 FormatTarget::Buffers => {
11572 let mut buffers = buffer.read(cx).all_buffers();
11573 if trigger == FormatTrigger::Save {
11574 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11575 }
11576 (buffers, LspFormatTarget::Buffers)
11577 }
11578 FormatTarget::Ranges(selection_ranges) => {
11579 let multi_buffer = buffer.read(cx);
11580 let snapshot = multi_buffer.read(cx);
11581 let mut buffers = HashSet::default();
11582 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11583 BTreeMap::new();
11584 for selection_range in selection_ranges {
11585 for (buffer, buffer_range, _) in
11586 snapshot.range_to_buffer_ranges(selection_range)
11587 {
11588 let buffer_id = buffer.remote_id();
11589 let start = buffer.anchor_before(buffer_range.start);
11590 let end = buffer.anchor_after(buffer_range.end);
11591 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11592 buffer_id_to_ranges
11593 .entry(buffer_id)
11594 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11595 .or_insert_with(|| vec![start..end]);
11596 }
11597 }
11598 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11599 }
11600 };
11601
11602 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11603 let format = project.update(cx, |project, cx| {
11604 project.format(buffers, target, true, trigger, cx)
11605 });
11606
11607 cx.spawn_in(window, |_, mut cx| async move {
11608 let transaction = futures::select_biased! {
11609 () = timeout => {
11610 log::warn!("timed out waiting for formatting");
11611 None
11612 }
11613 transaction = format.log_err().fuse() => transaction,
11614 };
11615
11616 buffer
11617 .update(&mut cx, |buffer, cx| {
11618 if let Some(transaction) = transaction {
11619 if !buffer.is_singleton() {
11620 buffer.push_transaction(&transaction.0, cx);
11621 }
11622 }
11623
11624 cx.notify();
11625 })
11626 .ok();
11627
11628 Ok(())
11629 })
11630 }
11631
11632 fn restart_language_server(
11633 &mut self,
11634 _: &RestartLanguageServer,
11635 _: &mut Window,
11636 cx: &mut Context<Self>,
11637 ) {
11638 if let Some(project) = self.project.clone() {
11639 self.buffer.update(cx, |multi_buffer, cx| {
11640 project.update(cx, |project, cx| {
11641 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11642 });
11643 })
11644 }
11645 }
11646
11647 fn cancel_language_server_work(
11648 workspace: &mut Workspace,
11649 _: &actions::CancelLanguageServerWork,
11650 _: &mut Window,
11651 cx: &mut Context<Workspace>,
11652 ) {
11653 let project = workspace.project();
11654 let buffers = workspace
11655 .active_item(cx)
11656 .and_then(|item| item.act_as::<Editor>(cx))
11657 .map_or(HashSet::default(), |editor| {
11658 editor.read(cx).buffer.read(cx).all_buffers()
11659 });
11660 project.update(cx, |project, cx| {
11661 project.cancel_language_server_work_for_buffers(buffers, cx);
11662 });
11663 }
11664
11665 fn show_character_palette(
11666 &mut self,
11667 _: &ShowCharacterPalette,
11668 window: &mut Window,
11669 _: &mut Context<Self>,
11670 ) {
11671 window.show_character_palette();
11672 }
11673
11674 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11675 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11676 let buffer = self.buffer.read(cx).snapshot(cx);
11677 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11678 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11679 let is_valid = buffer
11680 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11681 .any(|entry| {
11682 entry.diagnostic.is_primary
11683 && !entry.range.is_empty()
11684 && entry.range.start == primary_range_start
11685 && entry.diagnostic.message == active_diagnostics.primary_message
11686 });
11687
11688 if is_valid != active_diagnostics.is_valid {
11689 active_diagnostics.is_valid = is_valid;
11690 let mut new_styles = HashMap::default();
11691 for (block_id, diagnostic) in &active_diagnostics.blocks {
11692 new_styles.insert(
11693 *block_id,
11694 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11695 );
11696 }
11697 self.display_map.update(cx, |display_map, _cx| {
11698 display_map.replace_blocks(new_styles)
11699 });
11700 }
11701 }
11702 }
11703
11704 fn activate_diagnostics(
11705 &mut self,
11706 buffer_id: BufferId,
11707 group_id: usize,
11708 window: &mut Window,
11709 cx: &mut Context<Self>,
11710 ) {
11711 self.dismiss_diagnostics(cx);
11712 let snapshot = self.snapshot(window, cx);
11713 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11714 let buffer = self.buffer.read(cx).snapshot(cx);
11715
11716 let mut primary_range = None;
11717 let mut primary_message = None;
11718 let diagnostic_group = buffer
11719 .diagnostic_group(buffer_id, group_id)
11720 .filter_map(|entry| {
11721 let start = entry.range.start;
11722 let end = entry.range.end;
11723 if snapshot.is_line_folded(MultiBufferRow(start.row))
11724 && (start.row == end.row
11725 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11726 {
11727 return None;
11728 }
11729 if entry.diagnostic.is_primary {
11730 primary_range = Some(entry.range.clone());
11731 primary_message = Some(entry.diagnostic.message.clone());
11732 }
11733 Some(entry)
11734 })
11735 .collect::<Vec<_>>();
11736 let primary_range = primary_range?;
11737 let primary_message = primary_message?;
11738
11739 let blocks = display_map
11740 .insert_blocks(
11741 diagnostic_group.iter().map(|entry| {
11742 let diagnostic = entry.diagnostic.clone();
11743 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11744 BlockProperties {
11745 style: BlockStyle::Fixed,
11746 placement: BlockPlacement::Below(
11747 buffer.anchor_after(entry.range.start),
11748 ),
11749 height: message_height,
11750 render: diagnostic_block_renderer(diagnostic, None, true, true),
11751 priority: 0,
11752 }
11753 }),
11754 cx,
11755 )
11756 .into_iter()
11757 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11758 .collect();
11759
11760 Some(ActiveDiagnosticGroup {
11761 primary_range: buffer.anchor_before(primary_range.start)
11762 ..buffer.anchor_after(primary_range.end),
11763 primary_message,
11764 group_id,
11765 blocks,
11766 is_valid: true,
11767 })
11768 });
11769 }
11770
11771 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11772 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11773 self.display_map.update(cx, |display_map, cx| {
11774 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11775 });
11776 cx.notify();
11777 }
11778 }
11779
11780 pub fn set_selections_from_remote(
11781 &mut self,
11782 selections: Vec<Selection<Anchor>>,
11783 pending_selection: Option<Selection<Anchor>>,
11784 window: &mut Window,
11785 cx: &mut Context<Self>,
11786 ) {
11787 let old_cursor_position = self.selections.newest_anchor().head();
11788 self.selections.change_with(cx, |s| {
11789 s.select_anchors(selections);
11790 if let Some(pending_selection) = pending_selection {
11791 s.set_pending(pending_selection, SelectMode::Character);
11792 } else {
11793 s.clear_pending();
11794 }
11795 });
11796 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11797 }
11798
11799 fn push_to_selection_history(&mut self) {
11800 self.selection_history.push(SelectionHistoryEntry {
11801 selections: self.selections.disjoint_anchors(),
11802 select_next_state: self.select_next_state.clone(),
11803 select_prev_state: self.select_prev_state.clone(),
11804 add_selections_state: self.add_selections_state.clone(),
11805 });
11806 }
11807
11808 pub fn transact(
11809 &mut self,
11810 window: &mut Window,
11811 cx: &mut Context<Self>,
11812 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11813 ) -> Option<TransactionId> {
11814 self.start_transaction_at(Instant::now(), window, cx);
11815 update(self, window, cx);
11816 self.end_transaction_at(Instant::now(), cx)
11817 }
11818
11819 pub fn start_transaction_at(
11820 &mut self,
11821 now: Instant,
11822 window: &mut Window,
11823 cx: &mut Context<Self>,
11824 ) {
11825 self.end_selection(window, cx);
11826 if let Some(tx_id) = self
11827 .buffer
11828 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11829 {
11830 self.selection_history
11831 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11832 cx.emit(EditorEvent::TransactionBegun {
11833 transaction_id: tx_id,
11834 })
11835 }
11836 }
11837
11838 pub fn end_transaction_at(
11839 &mut self,
11840 now: Instant,
11841 cx: &mut Context<Self>,
11842 ) -> Option<TransactionId> {
11843 if let Some(transaction_id) = self
11844 .buffer
11845 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11846 {
11847 if let Some((_, end_selections)) =
11848 self.selection_history.transaction_mut(transaction_id)
11849 {
11850 *end_selections = Some(self.selections.disjoint_anchors());
11851 } else {
11852 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11853 }
11854
11855 cx.emit(EditorEvent::Edited { transaction_id });
11856 Some(transaction_id)
11857 } else {
11858 None
11859 }
11860 }
11861
11862 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11863 if self.selection_mark_mode {
11864 self.change_selections(None, window, cx, |s| {
11865 s.move_with(|_, sel| {
11866 sel.collapse_to(sel.head(), SelectionGoal::None);
11867 });
11868 })
11869 }
11870 self.selection_mark_mode = true;
11871 cx.notify();
11872 }
11873
11874 pub fn swap_selection_ends(
11875 &mut self,
11876 _: &actions::SwapSelectionEnds,
11877 window: &mut Window,
11878 cx: &mut Context<Self>,
11879 ) {
11880 self.change_selections(None, window, cx, |s| {
11881 s.move_with(|_, sel| {
11882 if sel.start != sel.end {
11883 sel.reversed = !sel.reversed
11884 }
11885 });
11886 });
11887 self.request_autoscroll(Autoscroll::newest(), cx);
11888 cx.notify();
11889 }
11890
11891 pub fn toggle_fold(
11892 &mut self,
11893 _: &actions::ToggleFold,
11894 window: &mut Window,
11895 cx: &mut Context<Self>,
11896 ) {
11897 if self.is_singleton(cx) {
11898 let selection = self.selections.newest::<Point>(cx);
11899
11900 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11901 let range = if selection.is_empty() {
11902 let point = selection.head().to_display_point(&display_map);
11903 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11904 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11905 .to_point(&display_map);
11906 start..end
11907 } else {
11908 selection.range()
11909 };
11910 if display_map.folds_in_range(range).next().is_some() {
11911 self.unfold_lines(&Default::default(), window, cx)
11912 } else {
11913 self.fold(&Default::default(), window, cx)
11914 }
11915 } else {
11916 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11917 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11918 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11919 .map(|(snapshot, _, _)| snapshot.remote_id())
11920 .collect();
11921
11922 for buffer_id in buffer_ids {
11923 if self.is_buffer_folded(buffer_id, cx) {
11924 self.unfold_buffer(buffer_id, cx);
11925 } else {
11926 self.fold_buffer(buffer_id, cx);
11927 }
11928 }
11929 }
11930 }
11931
11932 pub fn toggle_fold_recursive(
11933 &mut self,
11934 _: &actions::ToggleFoldRecursive,
11935 window: &mut Window,
11936 cx: &mut Context<Self>,
11937 ) {
11938 let selection = self.selections.newest::<Point>(cx);
11939
11940 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11941 let range = if selection.is_empty() {
11942 let point = selection.head().to_display_point(&display_map);
11943 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11944 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11945 .to_point(&display_map);
11946 start..end
11947 } else {
11948 selection.range()
11949 };
11950 if display_map.folds_in_range(range).next().is_some() {
11951 self.unfold_recursive(&Default::default(), window, cx)
11952 } else {
11953 self.fold_recursive(&Default::default(), window, cx)
11954 }
11955 }
11956
11957 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11958 if self.is_singleton(cx) {
11959 let mut to_fold = Vec::new();
11960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11961 let selections = self.selections.all_adjusted(cx);
11962
11963 for selection in selections {
11964 let range = selection.range().sorted();
11965 let buffer_start_row = range.start.row;
11966
11967 if range.start.row != range.end.row {
11968 let mut found = false;
11969 let mut row = range.start.row;
11970 while row <= range.end.row {
11971 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11972 {
11973 found = true;
11974 row = crease.range().end.row + 1;
11975 to_fold.push(crease);
11976 } else {
11977 row += 1
11978 }
11979 }
11980 if found {
11981 continue;
11982 }
11983 }
11984
11985 for row in (0..=range.start.row).rev() {
11986 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11987 if crease.range().end.row >= buffer_start_row {
11988 to_fold.push(crease);
11989 if row <= range.start.row {
11990 break;
11991 }
11992 }
11993 }
11994 }
11995 }
11996
11997 self.fold_creases(to_fold, true, window, cx);
11998 } else {
11999 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12000
12001 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12002 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12003 .map(|(snapshot, _, _)| snapshot.remote_id())
12004 .collect();
12005 for buffer_id in buffer_ids {
12006 self.fold_buffer(buffer_id, cx);
12007 }
12008 }
12009 }
12010
12011 fn fold_at_level(
12012 &mut self,
12013 fold_at: &FoldAtLevel,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) {
12017 if !self.buffer.read(cx).is_singleton() {
12018 return;
12019 }
12020
12021 let fold_at_level = fold_at.0;
12022 let snapshot = self.buffer.read(cx).snapshot(cx);
12023 let mut to_fold = Vec::new();
12024 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12025
12026 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12027 while start_row < end_row {
12028 match self
12029 .snapshot(window, cx)
12030 .crease_for_buffer_row(MultiBufferRow(start_row))
12031 {
12032 Some(crease) => {
12033 let nested_start_row = crease.range().start.row + 1;
12034 let nested_end_row = crease.range().end.row;
12035
12036 if current_level < fold_at_level {
12037 stack.push((nested_start_row, nested_end_row, current_level + 1));
12038 } else if current_level == fold_at_level {
12039 to_fold.push(crease);
12040 }
12041
12042 start_row = nested_end_row + 1;
12043 }
12044 None => start_row += 1,
12045 }
12046 }
12047 }
12048
12049 self.fold_creases(to_fold, true, window, cx);
12050 }
12051
12052 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12053 if self.buffer.read(cx).is_singleton() {
12054 let mut fold_ranges = Vec::new();
12055 let snapshot = self.buffer.read(cx).snapshot(cx);
12056
12057 for row in 0..snapshot.max_row().0 {
12058 if let Some(foldable_range) = self
12059 .snapshot(window, cx)
12060 .crease_for_buffer_row(MultiBufferRow(row))
12061 {
12062 fold_ranges.push(foldable_range);
12063 }
12064 }
12065
12066 self.fold_creases(fold_ranges, true, window, cx);
12067 } else {
12068 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12069 editor
12070 .update_in(&mut cx, |editor, _, cx| {
12071 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12072 editor.fold_buffer(buffer_id, cx);
12073 }
12074 })
12075 .ok();
12076 });
12077 }
12078 }
12079
12080 pub fn fold_function_bodies(
12081 &mut self,
12082 _: &actions::FoldFunctionBodies,
12083 window: &mut Window,
12084 cx: &mut Context<Self>,
12085 ) {
12086 let snapshot = self.buffer.read(cx).snapshot(cx);
12087
12088 let ranges = snapshot
12089 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12090 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12091 .collect::<Vec<_>>();
12092
12093 let creases = ranges
12094 .into_iter()
12095 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12096 .collect();
12097
12098 self.fold_creases(creases, true, window, cx);
12099 }
12100
12101 pub fn fold_recursive(
12102 &mut self,
12103 _: &actions::FoldRecursive,
12104 window: &mut Window,
12105 cx: &mut Context<Self>,
12106 ) {
12107 let mut to_fold = Vec::new();
12108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12109 let selections = self.selections.all_adjusted(cx);
12110
12111 for selection in selections {
12112 let range = selection.range().sorted();
12113 let buffer_start_row = range.start.row;
12114
12115 if range.start.row != range.end.row {
12116 let mut found = false;
12117 for row in range.start.row..=range.end.row {
12118 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12119 found = true;
12120 to_fold.push(crease);
12121 }
12122 }
12123 if found {
12124 continue;
12125 }
12126 }
12127
12128 for row in (0..=range.start.row).rev() {
12129 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12130 if crease.range().end.row >= buffer_start_row {
12131 to_fold.push(crease);
12132 } else {
12133 break;
12134 }
12135 }
12136 }
12137 }
12138
12139 self.fold_creases(to_fold, true, window, cx);
12140 }
12141
12142 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12143 let buffer_row = fold_at.buffer_row;
12144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12145
12146 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12147 let autoscroll = self
12148 .selections
12149 .all::<Point>(cx)
12150 .iter()
12151 .any(|selection| crease.range().overlaps(&selection.range()));
12152
12153 self.fold_creases(vec![crease], autoscroll, window, cx);
12154 }
12155 }
12156
12157 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12158 if self.is_singleton(cx) {
12159 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12160 let buffer = &display_map.buffer_snapshot;
12161 let selections = self.selections.all::<Point>(cx);
12162 let ranges = selections
12163 .iter()
12164 .map(|s| {
12165 let range = s.display_range(&display_map).sorted();
12166 let mut start = range.start.to_point(&display_map);
12167 let mut end = range.end.to_point(&display_map);
12168 start.column = 0;
12169 end.column = buffer.line_len(MultiBufferRow(end.row));
12170 start..end
12171 })
12172 .collect::<Vec<_>>();
12173
12174 self.unfold_ranges(&ranges, true, true, cx);
12175 } else {
12176 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12177 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12178 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12179 .map(|(snapshot, _, _)| snapshot.remote_id())
12180 .collect();
12181 for buffer_id in buffer_ids {
12182 self.unfold_buffer(buffer_id, cx);
12183 }
12184 }
12185 }
12186
12187 pub fn unfold_recursive(
12188 &mut self,
12189 _: &UnfoldRecursive,
12190 _window: &mut Window,
12191 cx: &mut Context<Self>,
12192 ) {
12193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12194 let selections = self.selections.all::<Point>(cx);
12195 let ranges = selections
12196 .iter()
12197 .map(|s| {
12198 let mut range = s.display_range(&display_map).sorted();
12199 *range.start.column_mut() = 0;
12200 *range.end.column_mut() = display_map.line_len(range.end.row());
12201 let start = range.start.to_point(&display_map);
12202 let end = range.end.to_point(&display_map);
12203 start..end
12204 })
12205 .collect::<Vec<_>>();
12206
12207 self.unfold_ranges(&ranges, true, true, cx);
12208 }
12209
12210 pub fn unfold_at(
12211 &mut self,
12212 unfold_at: &UnfoldAt,
12213 _window: &mut Window,
12214 cx: &mut Context<Self>,
12215 ) {
12216 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12217
12218 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12219 ..Point::new(
12220 unfold_at.buffer_row.0,
12221 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12222 );
12223
12224 let autoscroll = self
12225 .selections
12226 .all::<Point>(cx)
12227 .iter()
12228 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12229
12230 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12231 }
12232
12233 pub fn unfold_all(
12234 &mut self,
12235 _: &actions::UnfoldAll,
12236 _window: &mut Window,
12237 cx: &mut Context<Self>,
12238 ) {
12239 if self.buffer.read(cx).is_singleton() {
12240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12241 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12242 } else {
12243 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12244 editor
12245 .update(&mut cx, |editor, cx| {
12246 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12247 editor.unfold_buffer(buffer_id, cx);
12248 }
12249 })
12250 .ok();
12251 });
12252 }
12253 }
12254
12255 pub fn fold_selected_ranges(
12256 &mut self,
12257 _: &FoldSelectedRanges,
12258 window: &mut Window,
12259 cx: &mut Context<Self>,
12260 ) {
12261 let selections = self.selections.all::<Point>(cx);
12262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12263 let line_mode = self.selections.line_mode;
12264 let ranges = selections
12265 .into_iter()
12266 .map(|s| {
12267 if line_mode {
12268 let start = Point::new(s.start.row, 0);
12269 let end = Point::new(
12270 s.end.row,
12271 display_map
12272 .buffer_snapshot
12273 .line_len(MultiBufferRow(s.end.row)),
12274 );
12275 Crease::simple(start..end, display_map.fold_placeholder.clone())
12276 } else {
12277 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12278 }
12279 })
12280 .collect::<Vec<_>>();
12281 self.fold_creases(ranges, true, window, cx);
12282 }
12283
12284 pub fn fold_ranges<T: ToOffset + Clone>(
12285 &mut self,
12286 ranges: Vec<Range<T>>,
12287 auto_scroll: bool,
12288 window: &mut Window,
12289 cx: &mut Context<Self>,
12290 ) {
12291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12292 let ranges = ranges
12293 .into_iter()
12294 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12295 .collect::<Vec<_>>();
12296 self.fold_creases(ranges, auto_scroll, window, cx);
12297 }
12298
12299 pub fn fold_creases<T: ToOffset + Clone>(
12300 &mut self,
12301 creases: Vec<Crease<T>>,
12302 auto_scroll: bool,
12303 window: &mut Window,
12304 cx: &mut Context<Self>,
12305 ) {
12306 if creases.is_empty() {
12307 return;
12308 }
12309
12310 let mut buffers_affected = HashSet::default();
12311 let multi_buffer = self.buffer().read(cx);
12312 for crease in &creases {
12313 if let Some((_, buffer, _)) =
12314 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12315 {
12316 buffers_affected.insert(buffer.read(cx).remote_id());
12317 };
12318 }
12319
12320 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12321
12322 if auto_scroll {
12323 self.request_autoscroll(Autoscroll::fit(), cx);
12324 }
12325
12326 cx.notify();
12327
12328 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12329 // Clear diagnostics block when folding a range that contains it.
12330 let snapshot = self.snapshot(window, cx);
12331 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12332 drop(snapshot);
12333 self.active_diagnostics = Some(active_diagnostics);
12334 self.dismiss_diagnostics(cx);
12335 } else {
12336 self.active_diagnostics = Some(active_diagnostics);
12337 }
12338 }
12339
12340 self.scrollbar_marker_state.dirty = true;
12341 }
12342
12343 /// Removes any folds whose ranges intersect any of the given ranges.
12344 pub fn unfold_ranges<T: ToOffset + Clone>(
12345 &mut self,
12346 ranges: &[Range<T>],
12347 inclusive: bool,
12348 auto_scroll: bool,
12349 cx: &mut Context<Self>,
12350 ) {
12351 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12352 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12353 });
12354 }
12355
12356 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12357 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12358 return;
12359 }
12360 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12361 self.display_map
12362 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12363 cx.emit(EditorEvent::BufferFoldToggled {
12364 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12365 folded: true,
12366 });
12367 cx.notify();
12368 }
12369
12370 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12371 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12372 return;
12373 }
12374 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12375 self.display_map.update(cx, |display_map, cx| {
12376 display_map.unfold_buffer(buffer_id, cx);
12377 });
12378 cx.emit(EditorEvent::BufferFoldToggled {
12379 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12380 folded: false,
12381 });
12382 cx.notify();
12383 }
12384
12385 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12386 self.display_map.read(cx).is_buffer_folded(buffer)
12387 }
12388
12389 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12390 self.display_map.read(cx).folded_buffers()
12391 }
12392
12393 /// Removes any folds with the given ranges.
12394 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12395 &mut self,
12396 ranges: &[Range<T>],
12397 type_id: TypeId,
12398 auto_scroll: bool,
12399 cx: &mut Context<Self>,
12400 ) {
12401 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12402 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12403 });
12404 }
12405
12406 fn remove_folds_with<T: ToOffset + Clone>(
12407 &mut self,
12408 ranges: &[Range<T>],
12409 auto_scroll: bool,
12410 cx: &mut Context<Self>,
12411 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12412 ) {
12413 if ranges.is_empty() {
12414 return;
12415 }
12416
12417 let mut buffers_affected = HashSet::default();
12418 let multi_buffer = self.buffer().read(cx);
12419 for range in ranges {
12420 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12421 buffers_affected.insert(buffer.read(cx).remote_id());
12422 };
12423 }
12424
12425 self.display_map.update(cx, update);
12426
12427 if auto_scroll {
12428 self.request_autoscroll(Autoscroll::fit(), cx);
12429 }
12430
12431 cx.notify();
12432 self.scrollbar_marker_state.dirty = true;
12433 self.active_indent_guides_state.dirty = true;
12434 }
12435
12436 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12437 self.display_map.read(cx).fold_placeholder.clone()
12438 }
12439
12440 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12441 self.buffer.update(cx, |buffer, cx| {
12442 buffer.set_all_diff_hunks_expanded(cx);
12443 });
12444 }
12445
12446 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12447 self.distinguish_unstaged_diff_hunks = true;
12448 }
12449
12450 pub fn expand_all_diff_hunks(
12451 &mut self,
12452 _: &ExpandAllHunkDiffs,
12453 _window: &mut Window,
12454 cx: &mut Context<Self>,
12455 ) {
12456 self.buffer.update(cx, |buffer, cx| {
12457 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12458 });
12459 }
12460
12461 pub fn toggle_selected_diff_hunks(
12462 &mut self,
12463 _: &ToggleSelectedDiffHunks,
12464 _window: &mut Window,
12465 cx: &mut Context<Self>,
12466 ) {
12467 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12468 self.toggle_diff_hunks_in_ranges(ranges, cx);
12469 }
12470
12471 fn diff_hunks_in_ranges<'a>(
12472 &'a self,
12473 ranges: &'a [Range<Anchor>],
12474 buffer: &'a MultiBufferSnapshot,
12475 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12476 ranges.iter().flat_map(move |range| {
12477 let end_excerpt_id = range.end.excerpt_id;
12478 let range = range.to_point(buffer);
12479 let mut peek_end = range.end;
12480 if range.end.row < buffer.max_row().0 {
12481 peek_end = Point::new(range.end.row + 1, 0);
12482 }
12483 buffer
12484 .diff_hunks_in_range(range.start..peek_end)
12485 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12486 })
12487 }
12488
12489 pub fn has_stageable_diff_hunks_in_ranges(
12490 &self,
12491 ranges: &[Range<Anchor>],
12492 snapshot: &MultiBufferSnapshot,
12493 ) -> bool {
12494 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12495 hunks.any(|hunk| {
12496 log::debug!("considering {hunk:?}");
12497 hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12498 })
12499 }
12500
12501 pub fn toggle_staged_selected_diff_hunks(
12502 &mut self,
12503 _: &ToggleStagedSelectedDiffHunks,
12504 _window: &mut Window,
12505 cx: &mut Context<Self>,
12506 ) {
12507 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12508 self.stage_or_unstage_diff_hunks(&ranges, cx);
12509 }
12510
12511 pub fn stage_or_unstage_diff_hunks(
12512 &mut self,
12513 ranges: &[Range<Anchor>],
12514 cx: &mut Context<Self>,
12515 ) {
12516 let Some(project) = &self.project else {
12517 return;
12518 };
12519 let snapshot = self.buffer.read(cx).snapshot(cx);
12520 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12521
12522 let chunk_by = self
12523 .diff_hunks_in_ranges(&ranges, &snapshot)
12524 .chunk_by(|hunk| hunk.buffer_id);
12525 for (buffer_id, hunks) in &chunk_by {
12526 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12527 log::debug!("no buffer for id");
12528 continue;
12529 };
12530 let buffer = buffer.read(cx).snapshot();
12531 let Some((repo, path)) = project
12532 .read(cx)
12533 .repository_and_path_for_buffer_id(buffer_id, cx)
12534 else {
12535 log::debug!("no git repo for buffer id");
12536 continue;
12537 };
12538 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12539 log::debug!("no diff for buffer id");
12540 continue;
12541 };
12542 let Some(secondary_diff) = diff.secondary_diff() else {
12543 log::debug!("no secondary diff for buffer id");
12544 continue;
12545 };
12546
12547 let edits = diff.secondary_edits_for_stage_or_unstage(
12548 stage,
12549 hunks.map(|hunk| {
12550 (
12551 hunk.diff_base_byte_range.clone(),
12552 hunk.secondary_diff_base_byte_range.clone(),
12553 hunk.buffer_range.clone(),
12554 )
12555 }),
12556 &buffer,
12557 );
12558
12559 let index_base = secondary_diff.base_text().map_or_else(
12560 || Rope::from(""),
12561 |snapshot| snapshot.text.as_rope().clone(),
12562 );
12563 let index_buffer = cx.new(|cx| {
12564 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12565 });
12566 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12567 index_buffer.edit(edits, None, cx);
12568 index_buffer.snapshot().as_rope().to_string()
12569 });
12570 let new_index_text = if new_index_text.is_empty()
12571 && (diff.is_single_insertion
12572 || buffer
12573 .file()
12574 .map_or(false, |file| file.disk_state() == DiskState::New))
12575 {
12576 log::debug!("removing from index");
12577 None
12578 } else {
12579 Some(new_index_text)
12580 };
12581
12582 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12583 }
12584 }
12585
12586 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12587 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12588 self.buffer
12589 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12590 }
12591
12592 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12593 self.buffer.update(cx, |buffer, cx| {
12594 let ranges = vec![Anchor::min()..Anchor::max()];
12595 if !buffer.all_diff_hunks_expanded()
12596 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12597 {
12598 buffer.collapse_diff_hunks(ranges, cx);
12599 true
12600 } else {
12601 false
12602 }
12603 })
12604 }
12605
12606 fn toggle_diff_hunks_in_ranges(
12607 &mut self,
12608 ranges: Vec<Range<Anchor>>,
12609 cx: &mut Context<'_, Editor>,
12610 ) {
12611 self.buffer.update(cx, |buffer, cx| {
12612 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12613 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12614 })
12615 }
12616
12617 fn toggle_diff_hunks_in_ranges_narrow(
12618 &mut self,
12619 ranges: Vec<Range<Anchor>>,
12620 cx: &mut Context<'_, Editor>,
12621 ) {
12622 self.buffer.update(cx, |buffer, cx| {
12623 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12624 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12625 })
12626 }
12627
12628 pub(crate) fn apply_all_diff_hunks(
12629 &mut self,
12630 _: &ApplyAllDiffHunks,
12631 window: &mut Window,
12632 cx: &mut Context<Self>,
12633 ) {
12634 let buffers = self.buffer.read(cx).all_buffers();
12635 for branch_buffer in buffers {
12636 branch_buffer.update(cx, |branch_buffer, cx| {
12637 branch_buffer.merge_into_base(Vec::new(), cx);
12638 });
12639 }
12640
12641 if let Some(project) = self.project.clone() {
12642 self.save(true, project, window, cx).detach_and_log_err(cx);
12643 }
12644 }
12645
12646 pub(crate) fn apply_selected_diff_hunks(
12647 &mut self,
12648 _: &ApplyDiffHunk,
12649 window: &mut Window,
12650 cx: &mut Context<Self>,
12651 ) {
12652 let snapshot = self.snapshot(window, cx);
12653 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12654 let mut ranges_by_buffer = HashMap::default();
12655 self.transact(window, cx, |editor, _window, cx| {
12656 for hunk in hunks {
12657 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12658 ranges_by_buffer
12659 .entry(buffer.clone())
12660 .or_insert_with(Vec::new)
12661 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12662 }
12663 }
12664
12665 for (buffer, ranges) in ranges_by_buffer {
12666 buffer.update(cx, |buffer, cx| {
12667 buffer.merge_into_base(ranges, cx);
12668 });
12669 }
12670 });
12671
12672 if let Some(project) = self.project.clone() {
12673 self.save(true, project, window, cx).detach_and_log_err(cx);
12674 }
12675 }
12676
12677 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12678 if hovered != self.gutter_hovered {
12679 self.gutter_hovered = hovered;
12680 cx.notify();
12681 }
12682 }
12683
12684 pub fn insert_blocks(
12685 &mut self,
12686 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12687 autoscroll: Option<Autoscroll>,
12688 cx: &mut Context<Self>,
12689 ) -> Vec<CustomBlockId> {
12690 let blocks = self
12691 .display_map
12692 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12693 if let Some(autoscroll) = autoscroll {
12694 self.request_autoscroll(autoscroll, cx);
12695 }
12696 cx.notify();
12697 blocks
12698 }
12699
12700 pub fn resize_blocks(
12701 &mut self,
12702 heights: HashMap<CustomBlockId, u32>,
12703 autoscroll: Option<Autoscroll>,
12704 cx: &mut Context<Self>,
12705 ) {
12706 self.display_map
12707 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12708 if let Some(autoscroll) = autoscroll {
12709 self.request_autoscroll(autoscroll, cx);
12710 }
12711 cx.notify();
12712 }
12713
12714 pub fn replace_blocks(
12715 &mut self,
12716 renderers: HashMap<CustomBlockId, RenderBlock>,
12717 autoscroll: Option<Autoscroll>,
12718 cx: &mut Context<Self>,
12719 ) {
12720 self.display_map
12721 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12722 if let Some(autoscroll) = autoscroll {
12723 self.request_autoscroll(autoscroll, cx);
12724 }
12725 cx.notify();
12726 }
12727
12728 pub fn remove_blocks(
12729 &mut self,
12730 block_ids: HashSet<CustomBlockId>,
12731 autoscroll: Option<Autoscroll>,
12732 cx: &mut Context<Self>,
12733 ) {
12734 self.display_map.update(cx, |display_map, cx| {
12735 display_map.remove_blocks(block_ids, cx)
12736 });
12737 if let Some(autoscroll) = autoscroll {
12738 self.request_autoscroll(autoscroll, cx);
12739 }
12740 cx.notify();
12741 }
12742
12743 pub fn row_for_block(
12744 &self,
12745 block_id: CustomBlockId,
12746 cx: &mut Context<Self>,
12747 ) -> Option<DisplayRow> {
12748 self.display_map
12749 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12750 }
12751
12752 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12753 self.focused_block = Some(focused_block);
12754 }
12755
12756 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12757 self.focused_block.take()
12758 }
12759
12760 pub fn insert_creases(
12761 &mut self,
12762 creases: impl IntoIterator<Item = Crease<Anchor>>,
12763 cx: &mut Context<Self>,
12764 ) -> Vec<CreaseId> {
12765 self.display_map
12766 .update(cx, |map, cx| map.insert_creases(creases, cx))
12767 }
12768
12769 pub fn remove_creases(
12770 &mut self,
12771 ids: impl IntoIterator<Item = CreaseId>,
12772 cx: &mut Context<Self>,
12773 ) {
12774 self.display_map
12775 .update(cx, |map, cx| map.remove_creases(ids, cx));
12776 }
12777
12778 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12779 self.display_map
12780 .update(cx, |map, cx| map.snapshot(cx))
12781 .longest_row()
12782 }
12783
12784 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12785 self.display_map
12786 .update(cx, |map, cx| map.snapshot(cx))
12787 .max_point()
12788 }
12789
12790 pub fn text(&self, cx: &App) -> String {
12791 self.buffer.read(cx).read(cx).text()
12792 }
12793
12794 pub fn is_empty(&self, cx: &App) -> bool {
12795 self.buffer.read(cx).read(cx).is_empty()
12796 }
12797
12798 pub fn text_option(&self, cx: &App) -> Option<String> {
12799 let text = self.text(cx);
12800 let text = text.trim();
12801
12802 if text.is_empty() {
12803 return None;
12804 }
12805
12806 Some(text.to_string())
12807 }
12808
12809 pub fn set_text(
12810 &mut self,
12811 text: impl Into<Arc<str>>,
12812 window: &mut Window,
12813 cx: &mut Context<Self>,
12814 ) {
12815 self.transact(window, cx, |this, _, cx| {
12816 this.buffer
12817 .read(cx)
12818 .as_singleton()
12819 .expect("you can only call set_text on editors for singleton buffers")
12820 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12821 });
12822 }
12823
12824 pub fn display_text(&self, cx: &mut App) -> String {
12825 self.display_map
12826 .update(cx, |map, cx| map.snapshot(cx))
12827 .text()
12828 }
12829
12830 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12831 let mut wrap_guides = smallvec::smallvec![];
12832
12833 if self.show_wrap_guides == Some(false) {
12834 return wrap_guides;
12835 }
12836
12837 let settings = self.buffer.read(cx).settings_at(0, cx);
12838 if settings.show_wrap_guides {
12839 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12840 wrap_guides.push((soft_wrap as usize, true));
12841 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12842 wrap_guides.push((soft_wrap as usize, true));
12843 }
12844 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12845 }
12846
12847 wrap_guides
12848 }
12849
12850 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12851 let settings = self.buffer.read(cx).settings_at(0, cx);
12852 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12853 match mode {
12854 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12855 SoftWrap::None
12856 }
12857 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12858 language_settings::SoftWrap::PreferredLineLength => {
12859 SoftWrap::Column(settings.preferred_line_length)
12860 }
12861 language_settings::SoftWrap::Bounded => {
12862 SoftWrap::Bounded(settings.preferred_line_length)
12863 }
12864 }
12865 }
12866
12867 pub fn set_soft_wrap_mode(
12868 &mut self,
12869 mode: language_settings::SoftWrap,
12870
12871 cx: &mut Context<Self>,
12872 ) {
12873 self.soft_wrap_mode_override = Some(mode);
12874 cx.notify();
12875 }
12876
12877 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12878 self.text_style_refinement = Some(style);
12879 }
12880
12881 /// called by the Element so we know what style we were most recently rendered with.
12882 pub(crate) fn set_style(
12883 &mut self,
12884 style: EditorStyle,
12885 window: &mut Window,
12886 cx: &mut Context<Self>,
12887 ) {
12888 let rem_size = window.rem_size();
12889 self.display_map.update(cx, |map, cx| {
12890 map.set_font(
12891 style.text.font(),
12892 style.text.font_size.to_pixels(rem_size),
12893 cx,
12894 )
12895 });
12896 self.style = Some(style);
12897 }
12898
12899 pub fn style(&self) -> Option<&EditorStyle> {
12900 self.style.as_ref()
12901 }
12902
12903 // Called by the element. This method is not designed to be called outside of the editor
12904 // element's layout code because it does not notify when rewrapping is computed synchronously.
12905 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12906 self.display_map
12907 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12908 }
12909
12910 pub fn set_soft_wrap(&mut self) {
12911 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12912 }
12913
12914 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12915 if self.soft_wrap_mode_override.is_some() {
12916 self.soft_wrap_mode_override.take();
12917 } else {
12918 let soft_wrap = match self.soft_wrap_mode(cx) {
12919 SoftWrap::GitDiff => return,
12920 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12921 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12922 language_settings::SoftWrap::None
12923 }
12924 };
12925 self.soft_wrap_mode_override = Some(soft_wrap);
12926 }
12927 cx.notify();
12928 }
12929
12930 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12931 let Some(workspace) = self.workspace() else {
12932 return;
12933 };
12934 let fs = workspace.read(cx).app_state().fs.clone();
12935 let current_show = TabBarSettings::get_global(cx).show;
12936 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12937 setting.show = Some(!current_show);
12938 });
12939 }
12940
12941 pub fn toggle_indent_guides(
12942 &mut self,
12943 _: &ToggleIndentGuides,
12944 _: &mut Window,
12945 cx: &mut Context<Self>,
12946 ) {
12947 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12948 self.buffer
12949 .read(cx)
12950 .settings_at(0, cx)
12951 .indent_guides
12952 .enabled
12953 });
12954 self.show_indent_guides = Some(!currently_enabled);
12955 cx.notify();
12956 }
12957
12958 fn should_show_indent_guides(&self) -> Option<bool> {
12959 self.show_indent_guides
12960 }
12961
12962 pub fn toggle_line_numbers(
12963 &mut self,
12964 _: &ToggleLineNumbers,
12965 _: &mut Window,
12966 cx: &mut Context<Self>,
12967 ) {
12968 let mut editor_settings = EditorSettings::get_global(cx).clone();
12969 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12970 EditorSettings::override_global(editor_settings, cx);
12971 }
12972
12973 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12974 self.use_relative_line_numbers
12975 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12976 }
12977
12978 pub fn toggle_relative_line_numbers(
12979 &mut self,
12980 _: &ToggleRelativeLineNumbers,
12981 _: &mut Window,
12982 cx: &mut Context<Self>,
12983 ) {
12984 let is_relative = self.should_use_relative_line_numbers(cx);
12985 self.set_relative_line_number(Some(!is_relative), cx)
12986 }
12987
12988 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12989 self.use_relative_line_numbers = is_relative;
12990 cx.notify();
12991 }
12992
12993 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12994 self.show_gutter = show_gutter;
12995 cx.notify();
12996 }
12997
12998 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12999 self.show_scrollbars = show_scrollbars;
13000 cx.notify();
13001 }
13002
13003 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13004 self.show_line_numbers = Some(show_line_numbers);
13005 cx.notify();
13006 }
13007
13008 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13009 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13010 cx.notify();
13011 }
13012
13013 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13014 self.show_code_actions = Some(show_code_actions);
13015 cx.notify();
13016 }
13017
13018 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13019 self.show_runnables = Some(show_runnables);
13020 cx.notify();
13021 }
13022
13023 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13024 if self.display_map.read(cx).masked != masked {
13025 self.display_map.update(cx, |map, _| map.masked = masked);
13026 }
13027 cx.notify()
13028 }
13029
13030 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13031 self.show_wrap_guides = Some(show_wrap_guides);
13032 cx.notify();
13033 }
13034
13035 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13036 self.show_indent_guides = Some(show_indent_guides);
13037 cx.notify();
13038 }
13039
13040 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13041 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13042 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13043 if let Some(dir) = file.abs_path(cx).parent() {
13044 return Some(dir.to_owned());
13045 }
13046 }
13047
13048 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13049 return Some(project_path.path.to_path_buf());
13050 }
13051 }
13052
13053 None
13054 }
13055
13056 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13057 self.active_excerpt(cx)?
13058 .1
13059 .read(cx)
13060 .file()
13061 .and_then(|f| f.as_local())
13062 }
13063
13064 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13065 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13066 let buffer = buffer.read(cx);
13067 if let Some(project_path) = buffer.project_path(cx) {
13068 let project = self.project.as_ref()?.read(cx);
13069 project.absolute_path(&project_path, cx)
13070 } else {
13071 buffer
13072 .file()
13073 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13074 }
13075 })
13076 }
13077
13078 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13079 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13080 let project_path = buffer.read(cx).project_path(cx)?;
13081 let project = self.project.as_ref()?.read(cx);
13082 let entry = project.entry_for_path(&project_path, cx)?;
13083 let path = entry.path.to_path_buf();
13084 Some(path)
13085 })
13086 }
13087
13088 pub fn reveal_in_finder(
13089 &mut self,
13090 _: &RevealInFileManager,
13091 _window: &mut Window,
13092 cx: &mut Context<Self>,
13093 ) {
13094 if let Some(target) = self.target_file(cx) {
13095 cx.reveal_path(&target.abs_path(cx));
13096 }
13097 }
13098
13099 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13100 if let Some(path) = self.target_file_abs_path(cx) {
13101 if let Some(path) = path.to_str() {
13102 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13103 }
13104 }
13105 }
13106
13107 pub fn copy_relative_path(
13108 &mut self,
13109 _: &CopyRelativePath,
13110 _window: &mut Window,
13111 cx: &mut Context<Self>,
13112 ) {
13113 if let Some(path) = self.target_file_path(cx) {
13114 if let Some(path) = path.to_str() {
13115 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13116 }
13117 }
13118 }
13119
13120 pub fn copy_file_name_without_extension(
13121 &mut self,
13122 _: &CopyFileNameWithoutExtension,
13123 _: &mut Window,
13124 cx: &mut Context<Self>,
13125 ) {
13126 if let Some(file) = self.target_file(cx) {
13127 if let Some(file_stem) = file.path().file_stem() {
13128 if let Some(name) = file_stem.to_str() {
13129 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13130 }
13131 }
13132 }
13133 }
13134
13135 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13136 if let Some(file) = self.target_file(cx) {
13137 if let Some(file_name) = file.path().file_name() {
13138 if let Some(name) = file_name.to_str() {
13139 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13140 }
13141 }
13142 }
13143 }
13144
13145 pub fn toggle_git_blame(
13146 &mut self,
13147 _: &ToggleGitBlame,
13148 window: &mut Window,
13149 cx: &mut Context<Self>,
13150 ) {
13151 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13152
13153 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13154 self.start_git_blame(true, window, cx);
13155 }
13156
13157 cx.notify();
13158 }
13159
13160 pub fn toggle_git_blame_inline(
13161 &mut self,
13162 _: &ToggleGitBlameInline,
13163 window: &mut Window,
13164 cx: &mut Context<Self>,
13165 ) {
13166 self.toggle_git_blame_inline_internal(true, window, cx);
13167 cx.notify();
13168 }
13169
13170 pub fn git_blame_inline_enabled(&self) -> bool {
13171 self.git_blame_inline_enabled
13172 }
13173
13174 pub fn toggle_selection_menu(
13175 &mut self,
13176 _: &ToggleSelectionMenu,
13177 _: &mut Window,
13178 cx: &mut Context<Self>,
13179 ) {
13180 self.show_selection_menu = self
13181 .show_selection_menu
13182 .map(|show_selections_menu| !show_selections_menu)
13183 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13184
13185 cx.notify();
13186 }
13187
13188 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13189 self.show_selection_menu
13190 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13191 }
13192
13193 fn start_git_blame(
13194 &mut self,
13195 user_triggered: bool,
13196 window: &mut Window,
13197 cx: &mut Context<Self>,
13198 ) {
13199 if let Some(project) = self.project.as_ref() {
13200 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13201 return;
13202 };
13203
13204 if buffer.read(cx).file().is_none() {
13205 return;
13206 }
13207
13208 let focused = self.focus_handle(cx).contains_focused(window, cx);
13209
13210 let project = project.clone();
13211 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13212 self.blame_subscription =
13213 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13214 self.blame = Some(blame);
13215 }
13216 }
13217
13218 fn toggle_git_blame_inline_internal(
13219 &mut self,
13220 user_triggered: bool,
13221 window: &mut Window,
13222 cx: &mut Context<Self>,
13223 ) {
13224 if self.git_blame_inline_enabled {
13225 self.git_blame_inline_enabled = false;
13226 self.show_git_blame_inline = false;
13227 self.show_git_blame_inline_delay_task.take();
13228 } else {
13229 self.git_blame_inline_enabled = true;
13230 self.start_git_blame_inline(user_triggered, window, cx);
13231 }
13232
13233 cx.notify();
13234 }
13235
13236 fn start_git_blame_inline(
13237 &mut self,
13238 user_triggered: bool,
13239 window: &mut Window,
13240 cx: &mut Context<Self>,
13241 ) {
13242 self.start_git_blame(user_triggered, window, cx);
13243
13244 if ProjectSettings::get_global(cx)
13245 .git
13246 .inline_blame_delay()
13247 .is_some()
13248 {
13249 self.start_inline_blame_timer(window, cx);
13250 } else {
13251 self.show_git_blame_inline = true
13252 }
13253 }
13254
13255 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13256 self.blame.as_ref()
13257 }
13258
13259 pub fn show_git_blame_gutter(&self) -> bool {
13260 self.show_git_blame_gutter
13261 }
13262
13263 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13264 self.show_git_blame_gutter && self.has_blame_entries(cx)
13265 }
13266
13267 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13268 self.show_git_blame_inline
13269 && self.focus_handle.is_focused(window)
13270 && !self.newest_selection_head_on_empty_line(cx)
13271 && self.has_blame_entries(cx)
13272 }
13273
13274 fn has_blame_entries(&self, cx: &App) -> bool {
13275 self.blame()
13276 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13277 }
13278
13279 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13280 let cursor_anchor = self.selections.newest_anchor().head();
13281
13282 let snapshot = self.buffer.read(cx).snapshot(cx);
13283 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13284
13285 snapshot.line_len(buffer_row) == 0
13286 }
13287
13288 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13289 let buffer_and_selection = maybe!({
13290 let selection = self.selections.newest::<Point>(cx);
13291 let selection_range = selection.range();
13292
13293 let multi_buffer = self.buffer().read(cx);
13294 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13295 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13296
13297 let (buffer, range, _) = if selection.reversed {
13298 buffer_ranges.first()
13299 } else {
13300 buffer_ranges.last()
13301 }?;
13302
13303 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13304 ..text::ToPoint::to_point(&range.end, &buffer).row;
13305 Some((
13306 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13307 selection,
13308 ))
13309 });
13310
13311 let Some((buffer, selection)) = buffer_and_selection else {
13312 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13313 };
13314
13315 let Some(project) = self.project.as_ref() else {
13316 return Task::ready(Err(anyhow!("editor does not have project")));
13317 };
13318
13319 project.update(cx, |project, cx| {
13320 project.get_permalink_to_line(&buffer, selection, cx)
13321 })
13322 }
13323
13324 pub fn copy_permalink_to_line(
13325 &mut self,
13326 _: &CopyPermalinkToLine,
13327 window: &mut Window,
13328 cx: &mut Context<Self>,
13329 ) {
13330 let permalink_task = self.get_permalink_to_line(cx);
13331 let workspace = self.workspace();
13332
13333 cx.spawn_in(window, |_, mut cx| async move {
13334 match permalink_task.await {
13335 Ok(permalink) => {
13336 cx.update(|_, cx| {
13337 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13338 })
13339 .ok();
13340 }
13341 Err(err) => {
13342 let message = format!("Failed to copy permalink: {err}");
13343
13344 Err::<(), anyhow::Error>(err).log_err();
13345
13346 if let Some(workspace) = workspace {
13347 workspace
13348 .update_in(&mut cx, |workspace, _, cx| {
13349 struct CopyPermalinkToLine;
13350
13351 workspace.show_toast(
13352 Toast::new(
13353 NotificationId::unique::<CopyPermalinkToLine>(),
13354 message,
13355 ),
13356 cx,
13357 )
13358 })
13359 .ok();
13360 }
13361 }
13362 }
13363 })
13364 .detach();
13365 }
13366
13367 pub fn copy_file_location(
13368 &mut self,
13369 _: &CopyFileLocation,
13370 _: &mut Window,
13371 cx: &mut Context<Self>,
13372 ) {
13373 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13374 if let Some(file) = self.target_file(cx) {
13375 if let Some(path) = file.path().to_str() {
13376 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13377 }
13378 }
13379 }
13380
13381 pub fn open_permalink_to_line(
13382 &mut self,
13383 _: &OpenPermalinkToLine,
13384 window: &mut Window,
13385 cx: &mut Context<Self>,
13386 ) {
13387 let permalink_task = self.get_permalink_to_line(cx);
13388 let workspace = self.workspace();
13389
13390 cx.spawn_in(window, |_, mut cx| async move {
13391 match permalink_task.await {
13392 Ok(permalink) => {
13393 cx.update(|_, cx| {
13394 cx.open_url(permalink.as_ref());
13395 })
13396 .ok();
13397 }
13398 Err(err) => {
13399 let message = format!("Failed to open permalink: {err}");
13400
13401 Err::<(), anyhow::Error>(err).log_err();
13402
13403 if let Some(workspace) = workspace {
13404 workspace
13405 .update(&mut cx, |workspace, cx| {
13406 struct OpenPermalinkToLine;
13407
13408 workspace.show_toast(
13409 Toast::new(
13410 NotificationId::unique::<OpenPermalinkToLine>(),
13411 message,
13412 ),
13413 cx,
13414 )
13415 })
13416 .ok();
13417 }
13418 }
13419 }
13420 })
13421 .detach();
13422 }
13423
13424 pub fn insert_uuid_v4(
13425 &mut self,
13426 _: &InsertUuidV4,
13427 window: &mut Window,
13428 cx: &mut Context<Self>,
13429 ) {
13430 self.insert_uuid(UuidVersion::V4, window, cx);
13431 }
13432
13433 pub fn insert_uuid_v7(
13434 &mut self,
13435 _: &InsertUuidV7,
13436 window: &mut Window,
13437 cx: &mut Context<Self>,
13438 ) {
13439 self.insert_uuid(UuidVersion::V7, window, cx);
13440 }
13441
13442 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13443 self.transact(window, cx, |this, window, cx| {
13444 let edits = this
13445 .selections
13446 .all::<Point>(cx)
13447 .into_iter()
13448 .map(|selection| {
13449 let uuid = match version {
13450 UuidVersion::V4 => uuid::Uuid::new_v4(),
13451 UuidVersion::V7 => uuid::Uuid::now_v7(),
13452 };
13453
13454 (selection.range(), uuid.to_string())
13455 });
13456 this.edit(edits, cx);
13457 this.refresh_inline_completion(true, false, window, cx);
13458 });
13459 }
13460
13461 pub fn open_selections_in_multibuffer(
13462 &mut self,
13463 _: &OpenSelectionsInMultibuffer,
13464 window: &mut Window,
13465 cx: &mut Context<Self>,
13466 ) {
13467 let multibuffer = self.buffer.read(cx);
13468
13469 let Some(buffer) = multibuffer.as_singleton() else {
13470 return;
13471 };
13472
13473 let Some(workspace) = self.workspace() else {
13474 return;
13475 };
13476
13477 let locations = self
13478 .selections
13479 .disjoint_anchors()
13480 .iter()
13481 .map(|range| Location {
13482 buffer: buffer.clone(),
13483 range: range.start.text_anchor..range.end.text_anchor,
13484 })
13485 .collect::<Vec<_>>();
13486
13487 let title = multibuffer.title(cx).to_string();
13488
13489 cx.spawn_in(window, |_, mut cx| async move {
13490 workspace.update_in(&mut cx, |workspace, window, cx| {
13491 Self::open_locations_in_multibuffer(
13492 workspace,
13493 locations,
13494 format!("Selections for '{title}'"),
13495 false,
13496 MultibufferSelectionMode::All,
13497 window,
13498 cx,
13499 );
13500 })
13501 })
13502 .detach();
13503 }
13504
13505 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13506 /// last highlight added will be used.
13507 ///
13508 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13509 pub fn highlight_rows<T: 'static>(
13510 &mut self,
13511 range: Range<Anchor>,
13512 color: Hsla,
13513 should_autoscroll: bool,
13514 cx: &mut Context<Self>,
13515 ) {
13516 let snapshot = self.buffer().read(cx).snapshot(cx);
13517 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13518 let ix = row_highlights.binary_search_by(|highlight| {
13519 Ordering::Equal
13520 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13521 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13522 });
13523
13524 if let Err(mut ix) = ix {
13525 let index = post_inc(&mut self.highlight_order);
13526
13527 // If this range intersects with the preceding highlight, then merge it with
13528 // the preceding highlight. Otherwise insert a new highlight.
13529 let mut merged = false;
13530 if ix > 0 {
13531 let prev_highlight = &mut row_highlights[ix - 1];
13532 if prev_highlight
13533 .range
13534 .end
13535 .cmp(&range.start, &snapshot)
13536 .is_ge()
13537 {
13538 ix -= 1;
13539 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13540 prev_highlight.range.end = range.end;
13541 }
13542 merged = true;
13543 prev_highlight.index = index;
13544 prev_highlight.color = color;
13545 prev_highlight.should_autoscroll = should_autoscroll;
13546 }
13547 }
13548
13549 if !merged {
13550 row_highlights.insert(
13551 ix,
13552 RowHighlight {
13553 range: range.clone(),
13554 index,
13555 color,
13556 should_autoscroll,
13557 },
13558 );
13559 }
13560
13561 // If any of the following highlights intersect with this one, merge them.
13562 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13563 let highlight = &row_highlights[ix];
13564 if next_highlight
13565 .range
13566 .start
13567 .cmp(&highlight.range.end, &snapshot)
13568 .is_le()
13569 {
13570 if next_highlight
13571 .range
13572 .end
13573 .cmp(&highlight.range.end, &snapshot)
13574 .is_gt()
13575 {
13576 row_highlights[ix].range.end = next_highlight.range.end;
13577 }
13578 row_highlights.remove(ix + 1);
13579 } else {
13580 break;
13581 }
13582 }
13583 }
13584 }
13585
13586 /// Remove any highlighted row ranges of the given type that intersect the
13587 /// given ranges.
13588 pub fn remove_highlighted_rows<T: 'static>(
13589 &mut self,
13590 ranges_to_remove: Vec<Range<Anchor>>,
13591 cx: &mut Context<Self>,
13592 ) {
13593 let snapshot = self.buffer().read(cx).snapshot(cx);
13594 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13595 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13596 row_highlights.retain(|highlight| {
13597 while let Some(range_to_remove) = ranges_to_remove.peek() {
13598 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13599 Ordering::Less | Ordering::Equal => {
13600 ranges_to_remove.next();
13601 }
13602 Ordering::Greater => {
13603 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13604 Ordering::Less | Ordering::Equal => {
13605 return false;
13606 }
13607 Ordering::Greater => break,
13608 }
13609 }
13610 }
13611 }
13612
13613 true
13614 })
13615 }
13616
13617 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13618 pub fn clear_row_highlights<T: 'static>(&mut self) {
13619 self.highlighted_rows.remove(&TypeId::of::<T>());
13620 }
13621
13622 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13623 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13624 self.highlighted_rows
13625 .get(&TypeId::of::<T>())
13626 .map_or(&[] as &[_], |vec| vec.as_slice())
13627 .iter()
13628 .map(|highlight| (highlight.range.clone(), highlight.color))
13629 }
13630
13631 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13632 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13633 /// Allows to ignore certain kinds of highlights.
13634 pub fn highlighted_display_rows(
13635 &self,
13636 window: &mut Window,
13637 cx: &mut App,
13638 ) -> BTreeMap<DisplayRow, Background> {
13639 let snapshot = self.snapshot(window, cx);
13640 let mut used_highlight_orders = HashMap::default();
13641 self.highlighted_rows
13642 .iter()
13643 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13644 .fold(
13645 BTreeMap::<DisplayRow, Background>::new(),
13646 |mut unique_rows, highlight| {
13647 let start = highlight.range.start.to_display_point(&snapshot);
13648 let end = highlight.range.end.to_display_point(&snapshot);
13649 let start_row = start.row().0;
13650 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13651 && end.column() == 0
13652 {
13653 end.row().0.saturating_sub(1)
13654 } else {
13655 end.row().0
13656 };
13657 for row in start_row..=end_row {
13658 let used_index =
13659 used_highlight_orders.entry(row).or_insert(highlight.index);
13660 if highlight.index >= *used_index {
13661 *used_index = highlight.index;
13662 unique_rows.insert(DisplayRow(row), highlight.color.into());
13663 }
13664 }
13665 unique_rows
13666 },
13667 )
13668 }
13669
13670 pub fn highlighted_display_row_for_autoscroll(
13671 &self,
13672 snapshot: &DisplaySnapshot,
13673 ) -> Option<DisplayRow> {
13674 self.highlighted_rows
13675 .values()
13676 .flat_map(|highlighted_rows| highlighted_rows.iter())
13677 .filter_map(|highlight| {
13678 if highlight.should_autoscroll {
13679 Some(highlight.range.start.to_display_point(snapshot).row())
13680 } else {
13681 None
13682 }
13683 })
13684 .min()
13685 }
13686
13687 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13688 self.highlight_background::<SearchWithinRange>(
13689 ranges,
13690 |colors| colors.editor_document_highlight_read_background,
13691 cx,
13692 )
13693 }
13694
13695 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13696 self.breadcrumb_header = Some(new_header);
13697 }
13698
13699 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13700 self.clear_background_highlights::<SearchWithinRange>(cx);
13701 }
13702
13703 pub fn highlight_background<T: 'static>(
13704 &mut self,
13705 ranges: &[Range<Anchor>],
13706 color_fetcher: fn(&ThemeColors) -> Hsla,
13707 cx: &mut Context<Self>,
13708 ) {
13709 self.background_highlights
13710 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13711 self.scrollbar_marker_state.dirty = true;
13712 cx.notify();
13713 }
13714
13715 pub fn clear_background_highlights<T: 'static>(
13716 &mut self,
13717 cx: &mut Context<Self>,
13718 ) -> Option<BackgroundHighlight> {
13719 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13720 if !text_highlights.1.is_empty() {
13721 self.scrollbar_marker_state.dirty = true;
13722 cx.notify();
13723 }
13724 Some(text_highlights)
13725 }
13726
13727 pub fn highlight_gutter<T: 'static>(
13728 &mut self,
13729 ranges: &[Range<Anchor>],
13730 color_fetcher: fn(&App) -> Hsla,
13731 cx: &mut Context<Self>,
13732 ) {
13733 self.gutter_highlights
13734 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13735 cx.notify();
13736 }
13737
13738 pub fn clear_gutter_highlights<T: 'static>(
13739 &mut self,
13740 cx: &mut Context<Self>,
13741 ) -> Option<GutterHighlight> {
13742 cx.notify();
13743 self.gutter_highlights.remove(&TypeId::of::<T>())
13744 }
13745
13746 #[cfg(feature = "test-support")]
13747 pub fn all_text_background_highlights(
13748 &self,
13749 window: &mut Window,
13750 cx: &mut Context<Self>,
13751 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13752 let snapshot = self.snapshot(window, cx);
13753 let buffer = &snapshot.buffer_snapshot;
13754 let start = buffer.anchor_before(0);
13755 let end = buffer.anchor_after(buffer.len());
13756 let theme = cx.theme().colors();
13757 self.background_highlights_in_range(start..end, &snapshot, theme)
13758 }
13759
13760 #[cfg(feature = "test-support")]
13761 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13762 let snapshot = self.buffer().read(cx).snapshot(cx);
13763
13764 let highlights = self
13765 .background_highlights
13766 .get(&TypeId::of::<items::BufferSearchHighlights>());
13767
13768 if let Some((_color, ranges)) = highlights {
13769 ranges
13770 .iter()
13771 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13772 .collect_vec()
13773 } else {
13774 vec![]
13775 }
13776 }
13777
13778 fn document_highlights_for_position<'a>(
13779 &'a self,
13780 position: Anchor,
13781 buffer: &'a MultiBufferSnapshot,
13782 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13783 let read_highlights = self
13784 .background_highlights
13785 .get(&TypeId::of::<DocumentHighlightRead>())
13786 .map(|h| &h.1);
13787 let write_highlights = self
13788 .background_highlights
13789 .get(&TypeId::of::<DocumentHighlightWrite>())
13790 .map(|h| &h.1);
13791 let left_position = position.bias_left(buffer);
13792 let right_position = position.bias_right(buffer);
13793 read_highlights
13794 .into_iter()
13795 .chain(write_highlights)
13796 .flat_map(move |ranges| {
13797 let start_ix = match ranges.binary_search_by(|probe| {
13798 let cmp = probe.end.cmp(&left_position, buffer);
13799 if cmp.is_ge() {
13800 Ordering::Greater
13801 } else {
13802 Ordering::Less
13803 }
13804 }) {
13805 Ok(i) | Err(i) => i,
13806 };
13807
13808 ranges[start_ix..]
13809 .iter()
13810 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13811 })
13812 }
13813
13814 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13815 self.background_highlights
13816 .get(&TypeId::of::<T>())
13817 .map_or(false, |(_, highlights)| !highlights.is_empty())
13818 }
13819
13820 pub fn background_highlights_in_range(
13821 &self,
13822 search_range: Range<Anchor>,
13823 display_snapshot: &DisplaySnapshot,
13824 theme: &ThemeColors,
13825 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13826 let mut results = Vec::new();
13827 for (color_fetcher, ranges) in self.background_highlights.values() {
13828 let color = color_fetcher(theme);
13829 let start_ix = match ranges.binary_search_by(|probe| {
13830 let cmp = probe
13831 .end
13832 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13833 if cmp.is_gt() {
13834 Ordering::Greater
13835 } else {
13836 Ordering::Less
13837 }
13838 }) {
13839 Ok(i) | Err(i) => i,
13840 };
13841 for range in &ranges[start_ix..] {
13842 if range
13843 .start
13844 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13845 .is_ge()
13846 {
13847 break;
13848 }
13849
13850 let start = range.start.to_display_point(display_snapshot);
13851 let end = range.end.to_display_point(display_snapshot);
13852 results.push((start..end, color))
13853 }
13854 }
13855 results
13856 }
13857
13858 pub fn background_highlight_row_ranges<T: 'static>(
13859 &self,
13860 search_range: Range<Anchor>,
13861 display_snapshot: &DisplaySnapshot,
13862 count: usize,
13863 ) -> Vec<RangeInclusive<DisplayPoint>> {
13864 let mut results = Vec::new();
13865 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13866 return vec![];
13867 };
13868
13869 let start_ix = match ranges.binary_search_by(|probe| {
13870 let cmp = probe
13871 .end
13872 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13873 if cmp.is_gt() {
13874 Ordering::Greater
13875 } else {
13876 Ordering::Less
13877 }
13878 }) {
13879 Ok(i) | Err(i) => i,
13880 };
13881 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13882 if let (Some(start_display), Some(end_display)) = (start, end) {
13883 results.push(
13884 start_display.to_display_point(display_snapshot)
13885 ..=end_display.to_display_point(display_snapshot),
13886 );
13887 }
13888 };
13889 let mut start_row: Option<Point> = None;
13890 let mut end_row: Option<Point> = None;
13891 if ranges.len() > count {
13892 return Vec::new();
13893 }
13894 for range in &ranges[start_ix..] {
13895 if range
13896 .start
13897 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13898 .is_ge()
13899 {
13900 break;
13901 }
13902 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13903 if let Some(current_row) = &end_row {
13904 if end.row == current_row.row {
13905 continue;
13906 }
13907 }
13908 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13909 if start_row.is_none() {
13910 assert_eq!(end_row, None);
13911 start_row = Some(start);
13912 end_row = Some(end);
13913 continue;
13914 }
13915 if let Some(current_end) = end_row.as_mut() {
13916 if start.row > current_end.row + 1 {
13917 push_region(start_row, end_row);
13918 start_row = Some(start);
13919 end_row = Some(end);
13920 } else {
13921 // Merge two hunks.
13922 *current_end = end;
13923 }
13924 } else {
13925 unreachable!();
13926 }
13927 }
13928 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13929 push_region(start_row, end_row);
13930 results
13931 }
13932
13933 pub fn gutter_highlights_in_range(
13934 &self,
13935 search_range: Range<Anchor>,
13936 display_snapshot: &DisplaySnapshot,
13937 cx: &App,
13938 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13939 let mut results = Vec::new();
13940 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13941 let color = color_fetcher(cx);
13942 let start_ix = match ranges.binary_search_by(|probe| {
13943 let cmp = probe
13944 .end
13945 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13946 if cmp.is_gt() {
13947 Ordering::Greater
13948 } else {
13949 Ordering::Less
13950 }
13951 }) {
13952 Ok(i) | Err(i) => i,
13953 };
13954 for range in &ranges[start_ix..] {
13955 if range
13956 .start
13957 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13958 .is_ge()
13959 {
13960 break;
13961 }
13962
13963 let start = range.start.to_display_point(display_snapshot);
13964 let end = range.end.to_display_point(display_snapshot);
13965 results.push((start..end, color))
13966 }
13967 }
13968 results
13969 }
13970
13971 /// Get the text ranges corresponding to the redaction query
13972 pub fn redacted_ranges(
13973 &self,
13974 search_range: Range<Anchor>,
13975 display_snapshot: &DisplaySnapshot,
13976 cx: &App,
13977 ) -> Vec<Range<DisplayPoint>> {
13978 display_snapshot
13979 .buffer_snapshot
13980 .redacted_ranges(search_range, |file| {
13981 if let Some(file) = file {
13982 file.is_private()
13983 && EditorSettings::get(
13984 Some(SettingsLocation {
13985 worktree_id: file.worktree_id(cx),
13986 path: file.path().as_ref(),
13987 }),
13988 cx,
13989 )
13990 .redact_private_values
13991 } else {
13992 false
13993 }
13994 })
13995 .map(|range| {
13996 range.start.to_display_point(display_snapshot)
13997 ..range.end.to_display_point(display_snapshot)
13998 })
13999 .collect()
14000 }
14001
14002 pub fn highlight_text<T: 'static>(
14003 &mut self,
14004 ranges: Vec<Range<Anchor>>,
14005 style: HighlightStyle,
14006 cx: &mut Context<Self>,
14007 ) {
14008 self.display_map.update(cx, |map, _| {
14009 map.highlight_text(TypeId::of::<T>(), ranges, style)
14010 });
14011 cx.notify();
14012 }
14013
14014 pub(crate) fn highlight_inlays<T: 'static>(
14015 &mut self,
14016 highlights: Vec<InlayHighlight>,
14017 style: HighlightStyle,
14018 cx: &mut Context<Self>,
14019 ) {
14020 self.display_map.update(cx, |map, _| {
14021 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14022 });
14023 cx.notify();
14024 }
14025
14026 pub fn text_highlights<'a, T: 'static>(
14027 &'a self,
14028 cx: &'a App,
14029 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14030 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14031 }
14032
14033 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14034 let cleared = self
14035 .display_map
14036 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14037 if cleared {
14038 cx.notify();
14039 }
14040 }
14041
14042 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14043 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14044 && self.focus_handle.is_focused(window)
14045 }
14046
14047 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14048 self.show_cursor_when_unfocused = is_enabled;
14049 cx.notify();
14050 }
14051
14052 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14053 self.project
14054 .as_ref()
14055 .map(|project| project.read(cx).lsp_store())
14056 }
14057
14058 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14059 cx.notify();
14060 }
14061
14062 fn on_buffer_event(
14063 &mut self,
14064 multibuffer: &Entity<MultiBuffer>,
14065 event: &multi_buffer::Event,
14066 window: &mut Window,
14067 cx: &mut Context<Self>,
14068 ) {
14069 match event {
14070 multi_buffer::Event::Edited {
14071 singleton_buffer_edited,
14072 edited_buffer: buffer_edited,
14073 } => {
14074 self.scrollbar_marker_state.dirty = true;
14075 self.active_indent_guides_state.dirty = true;
14076 self.refresh_active_diagnostics(cx);
14077 self.refresh_code_actions(window, cx);
14078 if self.has_active_inline_completion() {
14079 self.update_visible_inline_completion(window, cx);
14080 }
14081 if let Some(buffer) = buffer_edited {
14082 let buffer_id = buffer.read(cx).remote_id();
14083 if !self.registered_buffers.contains_key(&buffer_id) {
14084 if let Some(lsp_store) = self.lsp_store(cx) {
14085 lsp_store.update(cx, |lsp_store, cx| {
14086 self.registered_buffers.insert(
14087 buffer_id,
14088 lsp_store.register_buffer_with_language_servers(&buffer, cx),
14089 );
14090 })
14091 }
14092 }
14093 }
14094 cx.emit(EditorEvent::BufferEdited);
14095 cx.emit(SearchEvent::MatchesInvalidated);
14096 if *singleton_buffer_edited {
14097 if let Some(project) = &self.project {
14098 let project = project.read(cx);
14099 #[allow(clippy::mutable_key_type)]
14100 let languages_affected = multibuffer
14101 .read(cx)
14102 .all_buffers()
14103 .into_iter()
14104 .filter_map(|buffer| {
14105 let buffer = buffer.read(cx);
14106 let language = buffer.language()?;
14107 if project.is_local()
14108 && project
14109 .language_servers_for_local_buffer(buffer, cx)
14110 .count()
14111 == 0
14112 {
14113 None
14114 } else {
14115 Some(language)
14116 }
14117 })
14118 .cloned()
14119 .collect::<HashSet<_>>();
14120 if !languages_affected.is_empty() {
14121 self.refresh_inlay_hints(
14122 InlayHintRefreshReason::BufferEdited(languages_affected),
14123 cx,
14124 );
14125 }
14126 }
14127 }
14128
14129 let Some(project) = &self.project else { return };
14130 let (telemetry, is_via_ssh) = {
14131 let project = project.read(cx);
14132 let telemetry = project.client().telemetry().clone();
14133 let is_via_ssh = project.is_via_ssh();
14134 (telemetry, is_via_ssh)
14135 };
14136 refresh_linked_ranges(self, window, cx);
14137 telemetry.log_edit_event("editor", is_via_ssh);
14138 }
14139 multi_buffer::Event::ExcerptsAdded {
14140 buffer,
14141 predecessor,
14142 excerpts,
14143 } => {
14144 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14145 let buffer_id = buffer.read(cx).remote_id();
14146 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14147 if let Some(project) = &self.project {
14148 self.load_diff_task = Some(
14149 get_uncommitted_diff_for_buffer(
14150 project,
14151 [buffer.clone()],
14152 self.buffer.clone(),
14153 cx,
14154 )
14155 .shared(),
14156 );
14157 }
14158 }
14159 cx.emit(EditorEvent::ExcerptsAdded {
14160 buffer: buffer.clone(),
14161 predecessor: *predecessor,
14162 excerpts: excerpts.clone(),
14163 });
14164 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14165 }
14166 multi_buffer::Event::ExcerptsRemoved { ids } => {
14167 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14168 let buffer = self.buffer.read(cx);
14169 self.registered_buffers
14170 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14171 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14172 }
14173 multi_buffer::Event::ExcerptsEdited { ids } => {
14174 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14175 }
14176 multi_buffer::Event::ExcerptsExpanded { ids } => {
14177 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14178 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14179 }
14180 multi_buffer::Event::Reparsed(buffer_id) => {
14181 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14182
14183 cx.emit(EditorEvent::Reparsed(*buffer_id));
14184 }
14185 multi_buffer::Event::DiffHunksToggled => {
14186 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14187 }
14188 multi_buffer::Event::LanguageChanged(buffer_id) => {
14189 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14190 cx.emit(EditorEvent::Reparsed(*buffer_id));
14191 cx.notify();
14192 }
14193 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14194 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14195 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14196 cx.emit(EditorEvent::TitleChanged)
14197 }
14198 // multi_buffer::Event::DiffBaseChanged => {
14199 // self.scrollbar_marker_state.dirty = true;
14200 // cx.emit(EditorEvent::DiffBaseChanged);
14201 // cx.notify();
14202 // }
14203 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14204 multi_buffer::Event::DiagnosticsUpdated => {
14205 self.refresh_active_diagnostics(cx);
14206 self.scrollbar_marker_state.dirty = true;
14207 cx.notify();
14208 }
14209 _ => {}
14210 };
14211 }
14212
14213 fn on_display_map_changed(
14214 &mut self,
14215 _: Entity<DisplayMap>,
14216 _: &mut Window,
14217 cx: &mut Context<Self>,
14218 ) {
14219 cx.notify();
14220 }
14221
14222 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14223 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14224 self.refresh_inline_completion(true, false, window, cx);
14225 self.refresh_inlay_hints(
14226 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14227 self.selections.newest_anchor().head(),
14228 &self.buffer.read(cx).snapshot(cx),
14229 cx,
14230 )),
14231 cx,
14232 );
14233
14234 let old_cursor_shape = self.cursor_shape;
14235
14236 {
14237 let editor_settings = EditorSettings::get_global(cx);
14238 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14239 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14240 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14241 }
14242
14243 if old_cursor_shape != self.cursor_shape {
14244 cx.emit(EditorEvent::CursorShapeChanged);
14245 }
14246
14247 let project_settings = ProjectSettings::get_global(cx);
14248 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14249
14250 if self.mode == EditorMode::Full {
14251 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14252 if self.git_blame_inline_enabled != inline_blame_enabled {
14253 self.toggle_git_blame_inline_internal(false, window, cx);
14254 }
14255 }
14256
14257 cx.notify();
14258 }
14259
14260 pub fn set_searchable(&mut self, searchable: bool) {
14261 self.searchable = searchable;
14262 }
14263
14264 pub fn searchable(&self) -> bool {
14265 self.searchable
14266 }
14267
14268 fn open_proposed_changes_editor(
14269 &mut self,
14270 _: &OpenProposedChangesEditor,
14271 window: &mut Window,
14272 cx: &mut Context<Self>,
14273 ) {
14274 let Some(workspace) = self.workspace() else {
14275 cx.propagate();
14276 return;
14277 };
14278
14279 let selections = self.selections.all::<usize>(cx);
14280 let multi_buffer = self.buffer.read(cx);
14281 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14282 let mut new_selections_by_buffer = HashMap::default();
14283 for selection in selections {
14284 for (buffer, range, _) in
14285 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14286 {
14287 let mut range = range.to_point(buffer);
14288 range.start.column = 0;
14289 range.end.column = buffer.line_len(range.end.row);
14290 new_selections_by_buffer
14291 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14292 .or_insert(Vec::new())
14293 .push(range)
14294 }
14295 }
14296
14297 let proposed_changes_buffers = new_selections_by_buffer
14298 .into_iter()
14299 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14300 .collect::<Vec<_>>();
14301 let proposed_changes_editor = cx.new(|cx| {
14302 ProposedChangesEditor::new(
14303 "Proposed changes",
14304 proposed_changes_buffers,
14305 self.project.clone(),
14306 window,
14307 cx,
14308 )
14309 });
14310
14311 window.defer(cx, move |window, cx| {
14312 workspace.update(cx, |workspace, cx| {
14313 workspace.active_pane().update(cx, |pane, cx| {
14314 pane.add_item(
14315 Box::new(proposed_changes_editor),
14316 true,
14317 true,
14318 None,
14319 window,
14320 cx,
14321 );
14322 });
14323 });
14324 });
14325 }
14326
14327 pub fn open_excerpts_in_split(
14328 &mut self,
14329 _: &OpenExcerptsSplit,
14330 window: &mut Window,
14331 cx: &mut Context<Self>,
14332 ) {
14333 self.open_excerpts_common(None, true, window, cx)
14334 }
14335
14336 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14337 self.open_excerpts_common(None, false, window, cx)
14338 }
14339
14340 fn open_excerpts_common(
14341 &mut self,
14342 jump_data: Option<JumpData>,
14343 split: bool,
14344 window: &mut Window,
14345 cx: &mut Context<Self>,
14346 ) {
14347 let Some(workspace) = self.workspace() else {
14348 cx.propagate();
14349 return;
14350 };
14351
14352 if self.buffer.read(cx).is_singleton() {
14353 cx.propagate();
14354 return;
14355 }
14356
14357 let mut new_selections_by_buffer = HashMap::default();
14358 match &jump_data {
14359 Some(JumpData::MultiBufferPoint {
14360 excerpt_id,
14361 position,
14362 anchor,
14363 line_offset_from_top,
14364 }) => {
14365 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14366 if let Some(buffer) = multi_buffer_snapshot
14367 .buffer_id_for_excerpt(*excerpt_id)
14368 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14369 {
14370 let buffer_snapshot = buffer.read(cx).snapshot();
14371 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14372 language::ToPoint::to_point(anchor, &buffer_snapshot)
14373 } else {
14374 buffer_snapshot.clip_point(*position, Bias::Left)
14375 };
14376 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14377 new_selections_by_buffer.insert(
14378 buffer,
14379 (
14380 vec![jump_to_offset..jump_to_offset],
14381 Some(*line_offset_from_top),
14382 ),
14383 );
14384 }
14385 }
14386 Some(JumpData::MultiBufferRow {
14387 row,
14388 line_offset_from_top,
14389 }) => {
14390 let point = MultiBufferPoint::new(row.0, 0);
14391 if let Some((buffer, buffer_point, _)) =
14392 self.buffer.read(cx).point_to_buffer_point(point, cx)
14393 {
14394 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14395 new_selections_by_buffer
14396 .entry(buffer)
14397 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14398 .0
14399 .push(buffer_offset..buffer_offset)
14400 }
14401 }
14402 None => {
14403 let selections = self.selections.all::<usize>(cx);
14404 let multi_buffer = self.buffer.read(cx);
14405 for selection in selections {
14406 for (buffer, mut range, _) in multi_buffer
14407 .snapshot(cx)
14408 .range_to_buffer_ranges(selection.range())
14409 {
14410 // When editing branch buffers, jump to the corresponding location
14411 // in their base buffer.
14412 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14413 let buffer = buffer_handle.read(cx);
14414 if let Some(base_buffer) = buffer.base_buffer() {
14415 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14416 buffer_handle = base_buffer;
14417 }
14418
14419 if selection.reversed {
14420 mem::swap(&mut range.start, &mut range.end);
14421 }
14422 new_selections_by_buffer
14423 .entry(buffer_handle)
14424 .or_insert((Vec::new(), None))
14425 .0
14426 .push(range)
14427 }
14428 }
14429 }
14430 }
14431
14432 if new_selections_by_buffer.is_empty() {
14433 return;
14434 }
14435
14436 // We defer the pane interaction because we ourselves are a workspace item
14437 // and activating a new item causes the pane to call a method on us reentrantly,
14438 // which panics if we're on the stack.
14439 window.defer(cx, move |window, cx| {
14440 workspace.update(cx, |workspace, cx| {
14441 let pane = if split {
14442 workspace.adjacent_pane(window, cx)
14443 } else {
14444 workspace.active_pane().clone()
14445 };
14446
14447 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14448 let editor = buffer
14449 .read(cx)
14450 .file()
14451 .is_none()
14452 .then(|| {
14453 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14454 // so `workspace.open_project_item` will never find them, always opening a new editor.
14455 // Instead, we try to activate the existing editor in the pane first.
14456 let (editor, pane_item_index) =
14457 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14458 let editor = item.downcast::<Editor>()?;
14459 let singleton_buffer =
14460 editor.read(cx).buffer().read(cx).as_singleton()?;
14461 if singleton_buffer == buffer {
14462 Some((editor, i))
14463 } else {
14464 None
14465 }
14466 })?;
14467 pane.update(cx, |pane, cx| {
14468 pane.activate_item(pane_item_index, true, true, window, cx)
14469 });
14470 Some(editor)
14471 })
14472 .flatten()
14473 .unwrap_or_else(|| {
14474 workspace.open_project_item::<Self>(
14475 pane.clone(),
14476 buffer,
14477 true,
14478 true,
14479 window,
14480 cx,
14481 )
14482 });
14483
14484 editor.update(cx, |editor, cx| {
14485 let autoscroll = match scroll_offset {
14486 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14487 None => Autoscroll::newest(),
14488 };
14489 let nav_history = editor.nav_history.take();
14490 editor.change_selections(Some(autoscroll), window, cx, |s| {
14491 s.select_ranges(ranges);
14492 });
14493 editor.nav_history = nav_history;
14494 });
14495 }
14496 })
14497 });
14498 }
14499
14500 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14501 let snapshot = self.buffer.read(cx).read(cx);
14502 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14503 Some(
14504 ranges
14505 .iter()
14506 .map(move |range| {
14507 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14508 })
14509 .collect(),
14510 )
14511 }
14512
14513 fn selection_replacement_ranges(
14514 &self,
14515 range: Range<OffsetUtf16>,
14516 cx: &mut App,
14517 ) -> Vec<Range<OffsetUtf16>> {
14518 let selections = self.selections.all::<OffsetUtf16>(cx);
14519 let newest_selection = selections
14520 .iter()
14521 .max_by_key(|selection| selection.id)
14522 .unwrap();
14523 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14524 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14525 let snapshot = self.buffer.read(cx).read(cx);
14526 selections
14527 .into_iter()
14528 .map(|mut selection| {
14529 selection.start.0 =
14530 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14531 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14532 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14533 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14534 })
14535 .collect()
14536 }
14537
14538 fn report_editor_event(
14539 &self,
14540 event_type: &'static str,
14541 file_extension: Option<String>,
14542 cx: &App,
14543 ) {
14544 if cfg!(any(test, feature = "test-support")) {
14545 return;
14546 }
14547
14548 let Some(project) = &self.project else { return };
14549
14550 // If None, we are in a file without an extension
14551 let file = self
14552 .buffer
14553 .read(cx)
14554 .as_singleton()
14555 .and_then(|b| b.read(cx).file());
14556 let file_extension = file_extension.or(file
14557 .as_ref()
14558 .and_then(|file| Path::new(file.file_name(cx)).extension())
14559 .and_then(|e| e.to_str())
14560 .map(|a| a.to_string()));
14561
14562 let vim_mode = cx
14563 .global::<SettingsStore>()
14564 .raw_user_settings()
14565 .get("vim_mode")
14566 == Some(&serde_json::Value::Bool(true));
14567
14568 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14569 let copilot_enabled = edit_predictions_provider
14570 == language::language_settings::EditPredictionProvider::Copilot;
14571 let copilot_enabled_for_language = self
14572 .buffer
14573 .read(cx)
14574 .settings_at(0, cx)
14575 .show_edit_predictions;
14576
14577 let project = project.read(cx);
14578 telemetry::event!(
14579 event_type,
14580 file_extension,
14581 vim_mode,
14582 copilot_enabled,
14583 copilot_enabled_for_language,
14584 edit_predictions_provider,
14585 is_via_ssh = project.is_via_ssh(),
14586 );
14587 }
14588
14589 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14590 /// with each line being an array of {text, highlight} objects.
14591 fn copy_highlight_json(
14592 &mut self,
14593 _: &CopyHighlightJson,
14594 window: &mut Window,
14595 cx: &mut Context<Self>,
14596 ) {
14597 #[derive(Serialize)]
14598 struct Chunk<'a> {
14599 text: String,
14600 highlight: Option<&'a str>,
14601 }
14602
14603 let snapshot = self.buffer.read(cx).snapshot(cx);
14604 let range = self
14605 .selected_text_range(false, window, cx)
14606 .and_then(|selection| {
14607 if selection.range.is_empty() {
14608 None
14609 } else {
14610 Some(selection.range)
14611 }
14612 })
14613 .unwrap_or_else(|| 0..snapshot.len());
14614
14615 let chunks = snapshot.chunks(range, true);
14616 let mut lines = Vec::new();
14617 let mut line: VecDeque<Chunk> = VecDeque::new();
14618
14619 let Some(style) = self.style.as_ref() else {
14620 return;
14621 };
14622
14623 for chunk in chunks {
14624 let highlight = chunk
14625 .syntax_highlight_id
14626 .and_then(|id| id.name(&style.syntax));
14627 let mut chunk_lines = chunk.text.split('\n').peekable();
14628 while let Some(text) = chunk_lines.next() {
14629 let mut merged_with_last_token = false;
14630 if let Some(last_token) = line.back_mut() {
14631 if last_token.highlight == highlight {
14632 last_token.text.push_str(text);
14633 merged_with_last_token = true;
14634 }
14635 }
14636
14637 if !merged_with_last_token {
14638 line.push_back(Chunk {
14639 text: text.into(),
14640 highlight,
14641 });
14642 }
14643
14644 if chunk_lines.peek().is_some() {
14645 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14646 line.pop_front();
14647 }
14648 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14649 line.pop_back();
14650 }
14651
14652 lines.push(mem::take(&mut line));
14653 }
14654 }
14655 }
14656
14657 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14658 return;
14659 };
14660 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14661 }
14662
14663 pub fn open_context_menu(
14664 &mut self,
14665 _: &OpenContextMenu,
14666 window: &mut Window,
14667 cx: &mut Context<Self>,
14668 ) {
14669 self.request_autoscroll(Autoscroll::newest(), cx);
14670 let position = self.selections.newest_display(cx).start;
14671 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14672 }
14673
14674 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14675 &self.inlay_hint_cache
14676 }
14677
14678 pub fn replay_insert_event(
14679 &mut self,
14680 text: &str,
14681 relative_utf16_range: Option<Range<isize>>,
14682 window: &mut Window,
14683 cx: &mut Context<Self>,
14684 ) {
14685 if !self.input_enabled {
14686 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14687 return;
14688 }
14689 if let Some(relative_utf16_range) = relative_utf16_range {
14690 let selections = self.selections.all::<OffsetUtf16>(cx);
14691 self.change_selections(None, window, cx, |s| {
14692 let new_ranges = selections.into_iter().map(|range| {
14693 let start = OffsetUtf16(
14694 range
14695 .head()
14696 .0
14697 .saturating_add_signed(relative_utf16_range.start),
14698 );
14699 let end = OffsetUtf16(
14700 range
14701 .head()
14702 .0
14703 .saturating_add_signed(relative_utf16_range.end),
14704 );
14705 start..end
14706 });
14707 s.select_ranges(new_ranges);
14708 });
14709 }
14710
14711 self.handle_input(text, window, cx);
14712 }
14713
14714 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14715 let Some(provider) = self.semantics_provider.as_ref() else {
14716 return false;
14717 };
14718
14719 let mut supports = false;
14720 self.buffer().read(cx).for_each_buffer(|buffer| {
14721 supports |= provider.supports_inlay_hints(buffer, cx);
14722 });
14723 supports
14724 }
14725
14726 pub fn is_focused(&self, window: &Window) -> bool {
14727 self.focus_handle.is_focused(window)
14728 }
14729
14730 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14731 cx.emit(EditorEvent::Focused);
14732
14733 if let Some(descendant) = self
14734 .last_focused_descendant
14735 .take()
14736 .and_then(|descendant| descendant.upgrade())
14737 {
14738 window.focus(&descendant);
14739 } else {
14740 if let Some(blame) = self.blame.as_ref() {
14741 blame.update(cx, GitBlame::focus)
14742 }
14743
14744 self.blink_manager.update(cx, BlinkManager::enable);
14745 self.show_cursor_names(window, cx);
14746 self.buffer.update(cx, |buffer, cx| {
14747 buffer.finalize_last_transaction(cx);
14748 if self.leader_peer_id.is_none() {
14749 buffer.set_active_selections(
14750 &self.selections.disjoint_anchors(),
14751 self.selections.line_mode,
14752 self.cursor_shape,
14753 cx,
14754 );
14755 }
14756 });
14757 }
14758 }
14759
14760 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14761 cx.emit(EditorEvent::FocusedIn)
14762 }
14763
14764 fn handle_focus_out(
14765 &mut self,
14766 event: FocusOutEvent,
14767 _window: &mut Window,
14768 _cx: &mut Context<Self>,
14769 ) {
14770 if event.blurred != self.focus_handle {
14771 self.last_focused_descendant = Some(event.blurred);
14772 }
14773 }
14774
14775 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14776 self.blink_manager.update(cx, BlinkManager::disable);
14777 self.buffer
14778 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14779
14780 if let Some(blame) = self.blame.as_ref() {
14781 blame.update(cx, GitBlame::blur)
14782 }
14783 if !self.hover_state.focused(window, cx) {
14784 hide_hover(self, cx);
14785 }
14786
14787 self.hide_context_menu(window, cx);
14788 self.discard_inline_completion(false, cx);
14789 cx.emit(EditorEvent::Blurred);
14790 cx.notify();
14791 }
14792
14793 pub fn register_action<A: Action>(
14794 &mut self,
14795 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14796 ) -> Subscription {
14797 let id = self.next_editor_action_id.post_inc();
14798 let listener = Arc::new(listener);
14799 self.editor_actions.borrow_mut().insert(
14800 id,
14801 Box::new(move |window, _| {
14802 let listener = listener.clone();
14803 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14804 let action = action.downcast_ref().unwrap();
14805 if phase == DispatchPhase::Bubble {
14806 listener(action, window, cx)
14807 }
14808 })
14809 }),
14810 );
14811
14812 let editor_actions = self.editor_actions.clone();
14813 Subscription::new(move || {
14814 editor_actions.borrow_mut().remove(&id);
14815 })
14816 }
14817
14818 pub fn file_header_size(&self) -> u32 {
14819 FILE_HEADER_HEIGHT
14820 }
14821
14822 pub fn revert(
14823 &mut self,
14824 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14825 window: &mut Window,
14826 cx: &mut Context<Self>,
14827 ) {
14828 self.buffer().update(cx, |multi_buffer, cx| {
14829 for (buffer_id, changes) in revert_changes {
14830 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14831 buffer.update(cx, |buffer, cx| {
14832 buffer.edit(
14833 changes.into_iter().map(|(range, text)| {
14834 (range, text.to_string().map(Arc::<str>::from))
14835 }),
14836 None,
14837 cx,
14838 );
14839 });
14840 }
14841 }
14842 });
14843 self.change_selections(None, window, cx, |selections| selections.refresh());
14844 }
14845
14846 pub fn to_pixel_point(
14847 &self,
14848 source: multi_buffer::Anchor,
14849 editor_snapshot: &EditorSnapshot,
14850 window: &mut Window,
14851 ) -> Option<gpui::Point<Pixels>> {
14852 let source_point = source.to_display_point(editor_snapshot);
14853 self.display_to_pixel_point(source_point, editor_snapshot, window)
14854 }
14855
14856 pub fn display_to_pixel_point(
14857 &self,
14858 source: DisplayPoint,
14859 editor_snapshot: &EditorSnapshot,
14860 window: &mut Window,
14861 ) -> Option<gpui::Point<Pixels>> {
14862 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14863 let text_layout_details = self.text_layout_details(window);
14864 let scroll_top = text_layout_details
14865 .scroll_anchor
14866 .scroll_position(editor_snapshot)
14867 .y;
14868
14869 if source.row().as_f32() < scroll_top.floor() {
14870 return None;
14871 }
14872 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14873 let source_y = line_height * (source.row().as_f32() - scroll_top);
14874 Some(gpui::Point::new(source_x, source_y))
14875 }
14876
14877 pub fn has_visible_completions_menu(&self) -> bool {
14878 !self.edit_prediction_preview_is_active()
14879 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14880 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14881 })
14882 }
14883
14884 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14885 self.addons
14886 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14887 }
14888
14889 pub fn unregister_addon<T: Addon>(&mut self) {
14890 self.addons.remove(&std::any::TypeId::of::<T>());
14891 }
14892
14893 pub fn addon<T: Addon>(&self) -> Option<&T> {
14894 let type_id = std::any::TypeId::of::<T>();
14895 self.addons
14896 .get(&type_id)
14897 .and_then(|item| item.to_any().downcast_ref::<T>())
14898 }
14899
14900 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14901 let text_layout_details = self.text_layout_details(window);
14902 let style = &text_layout_details.editor_style;
14903 let font_id = window.text_system().resolve_font(&style.text.font());
14904 let font_size = style.text.font_size.to_pixels(window.rem_size());
14905 let line_height = style.text.line_height_in_pixels(window.rem_size());
14906 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14907
14908 gpui::Size::new(em_width, line_height)
14909 }
14910
14911 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14912 self.load_diff_task.clone()
14913 }
14914}
14915
14916fn get_uncommitted_diff_for_buffer(
14917 project: &Entity<Project>,
14918 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14919 buffer: Entity<MultiBuffer>,
14920 cx: &mut App,
14921) -> Task<()> {
14922 let mut tasks = Vec::new();
14923 project.update(cx, |project, cx| {
14924 for buffer in buffers {
14925 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14926 }
14927 });
14928 cx.spawn(|mut cx| async move {
14929 let diffs = futures::future::join_all(tasks).await;
14930 buffer
14931 .update(&mut cx, |buffer, cx| {
14932 for diff in diffs.into_iter().flatten() {
14933 buffer.add_diff(diff, cx);
14934 }
14935 })
14936 .ok();
14937 })
14938}
14939
14940fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14941 let tab_size = tab_size.get() as usize;
14942 let mut width = offset;
14943
14944 for ch in text.chars() {
14945 width += if ch == '\t' {
14946 tab_size - (width % tab_size)
14947 } else {
14948 1
14949 };
14950 }
14951
14952 width - offset
14953}
14954
14955#[cfg(test)]
14956mod tests {
14957 use super::*;
14958
14959 #[test]
14960 fn test_string_size_with_expanded_tabs() {
14961 let nz = |val| NonZeroU32::new(val).unwrap();
14962 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14963 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14964 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14965 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14966 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14967 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14968 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14969 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14970 }
14971}
14972
14973/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14974struct WordBreakingTokenizer<'a> {
14975 input: &'a str,
14976}
14977
14978impl<'a> WordBreakingTokenizer<'a> {
14979 fn new(input: &'a str) -> Self {
14980 Self { input }
14981 }
14982}
14983
14984fn is_char_ideographic(ch: char) -> bool {
14985 use unicode_script::Script::*;
14986 use unicode_script::UnicodeScript;
14987 matches!(ch.script(), Han | Tangut | Yi)
14988}
14989
14990fn is_grapheme_ideographic(text: &str) -> bool {
14991 text.chars().any(is_char_ideographic)
14992}
14993
14994fn is_grapheme_whitespace(text: &str) -> bool {
14995 text.chars().any(|x| x.is_whitespace())
14996}
14997
14998fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14999 text.chars().next().map_or(false, |ch| {
15000 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15001 })
15002}
15003
15004#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15005struct WordBreakToken<'a> {
15006 token: &'a str,
15007 grapheme_len: usize,
15008 is_whitespace: bool,
15009}
15010
15011impl<'a> Iterator for WordBreakingTokenizer<'a> {
15012 /// Yields a span, the count of graphemes in the token, and whether it was
15013 /// whitespace. Note that it also breaks at word boundaries.
15014 type Item = WordBreakToken<'a>;
15015
15016 fn next(&mut self) -> Option<Self::Item> {
15017 use unicode_segmentation::UnicodeSegmentation;
15018 if self.input.is_empty() {
15019 return None;
15020 }
15021
15022 let mut iter = self.input.graphemes(true).peekable();
15023 let mut offset = 0;
15024 let mut graphemes = 0;
15025 if let Some(first_grapheme) = iter.next() {
15026 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15027 offset += first_grapheme.len();
15028 graphemes += 1;
15029 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15030 if let Some(grapheme) = iter.peek().copied() {
15031 if should_stay_with_preceding_ideograph(grapheme) {
15032 offset += grapheme.len();
15033 graphemes += 1;
15034 }
15035 }
15036 } else {
15037 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15038 let mut next_word_bound = words.peek().copied();
15039 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15040 next_word_bound = words.next();
15041 }
15042 while let Some(grapheme) = iter.peek().copied() {
15043 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15044 break;
15045 };
15046 if is_grapheme_whitespace(grapheme) != is_whitespace {
15047 break;
15048 };
15049 offset += grapheme.len();
15050 graphemes += 1;
15051 iter.next();
15052 }
15053 }
15054 let token = &self.input[..offset];
15055 self.input = &self.input[offset..];
15056 if is_whitespace {
15057 Some(WordBreakToken {
15058 token: " ",
15059 grapheme_len: 1,
15060 is_whitespace: true,
15061 })
15062 } else {
15063 Some(WordBreakToken {
15064 token,
15065 grapheme_len: graphemes,
15066 is_whitespace: false,
15067 })
15068 }
15069 } else {
15070 None
15071 }
15072 }
15073}
15074
15075#[test]
15076fn test_word_breaking_tokenizer() {
15077 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15078 ("", &[]),
15079 (" ", &[(" ", 1, true)]),
15080 ("Ʒ", &[("Ʒ", 1, false)]),
15081 ("Ǽ", &[("Ǽ", 1, false)]),
15082 ("⋑", &[("⋑", 1, false)]),
15083 ("⋑⋑", &[("⋑⋑", 2, false)]),
15084 (
15085 "原理,进而",
15086 &[
15087 ("原", 1, false),
15088 ("理,", 2, false),
15089 ("进", 1, false),
15090 ("而", 1, false),
15091 ],
15092 ),
15093 (
15094 "hello world",
15095 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15096 ),
15097 (
15098 "hello, world",
15099 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15100 ),
15101 (
15102 " hello world",
15103 &[
15104 (" ", 1, true),
15105 ("hello", 5, false),
15106 (" ", 1, true),
15107 ("world", 5, false),
15108 ],
15109 ),
15110 (
15111 "这是什么 \n 钢笔",
15112 &[
15113 ("这", 1, false),
15114 ("是", 1, false),
15115 ("什", 1, false),
15116 ("么", 1, false),
15117 (" ", 1, true),
15118 ("钢", 1, false),
15119 ("笔", 1, false),
15120 ],
15121 ),
15122 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15123 ];
15124
15125 for (input, result) in tests {
15126 assert_eq!(
15127 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15128 result
15129 .iter()
15130 .copied()
15131 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15132 token,
15133 grapheme_len,
15134 is_whitespace,
15135 })
15136 .collect::<Vec<_>>()
15137 );
15138 }
15139}
15140
15141fn wrap_with_prefix(
15142 line_prefix: String,
15143 unwrapped_text: String,
15144 wrap_column: usize,
15145 tab_size: NonZeroU32,
15146) -> String {
15147 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15148 let mut wrapped_text = String::new();
15149 let mut current_line = line_prefix.clone();
15150
15151 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15152 let mut current_line_len = line_prefix_len;
15153 for WordBreakToken {
15154 token,
15155 grapheme_len,
15156 is_whitespace,
15157 } in tokenizer
15158 {
15159 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15160 wrapped_text.push_str(current_line.trim_end());
15161 wrapped_text.push('\n');
15162 current_line.truncate(line_prefix.len());
15163 current_line_len = line_prefix_len;
15164 if !is_whitespace {
15165 current_line.push_str(token);
15166 current_line_len += grapheme_len;
15167 }
15168 } else if !is_whitespace {
15169 current_line.push_str(token);
15170 current_line_len += grapheme_len;
15171 } else if current_line_len != line_prefix_len {
15172 current_line.push(' ');
15173 current_line_len += 1;
15174 }
15175 }
15176
15177 if !current_line.is_empty() {
15178 wrapped_text.push_str(¤t_line);
15179 }
15180 wrapped_text
15181}
15182
15183#[test]
15184fn test_wrap_with_prefix() {
15185 assert_eq!(
15186 wrap_with_prefix(
15187 "# ".to_string(),
15188 "abcdefg".to_string(),
15189 4,
15190 NonZeroU32::new(4).unwrap()
15191 ),
15192 "# abcdefg"
15193 );
15194 assert_eq!(
15195 wrap_with_prefix(
15196 "".to_string(),
15197 "\thello world".to_string(),
15198 8,
15199 NonZeroU32::new(4).unwrap()
15200 ),
15201 "hello\nworld"
15202 );
15203 assert_eq!(
15204 wrap_with_prefix(
15205 "// ".to_string(),
15206 "xx \nyy zz aa bb cc".to_string(),
15207 12,
15208 NonZeroU32::new(4).unwrap()
15209 ),
15210 "// xx yy zz\n// aa bb cc"
15211 );
15212 assert_eq!(
15213 wrap_with_prefix(
15214 String::new(),
15215 "这是什么 \n 钢笔".to_string(),
15216 3,
15217 NonZeroU32::new(4).unwrap()
15218 ),
15219 "这是什\n么 钢\n笔"
15220 );
15221}
15222
15223pub trait CollaborationHub {
15224 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15225 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15226 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15227}
15228
15229impl CollaborationHub for Entity<Project> {
15230 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15231 self.read(cx).collaborators()
15232 }
15233
15234 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15235 self.read(cx).user_store().read(cx).participant_indices()
15236 }
15237
15238 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15239 let this = self.read(cx);
15240 let user_ids = this.collaborators().values().map(|c| c.user_id);
15241 this.user_store().read_with(cx, |user_store, cx| {
15242 user_store.participant_names(user_ids, cx)
15243 })
15244 }
15245}
15246
15247pub trait SemanticsProvider {
15248 fn hover(
15249 &self,
15250 buffer: &Entity<Buffer>,
15251 position: text::Anchor,
15252 cx: &mut App,
15253 ) -> Option<Task<Vec<project::Hover>>>;
15254
15255 fn inlay_hints(
15256 &self,
15257 buffer_handle: Entity<Buffer>,
15258 range: Range<text::Anchor>,
15259 cx: &mut App,
15260 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15261
15262 fn resolve_inlay_hint(
15263 &self,
15264 hint: InlayHint,
15265 buffer_handle: Entity<Buffer>,
15266 server_id: LanguageServerId,
15267 cx: &mut App,
15268 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15269
15270 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15271
15272 fn document_highlights(
15273 &self,
15274 buffer: &Entity<Buffer>,
15275 position: text::Anchor,
15276 cx: &mut App,
15277 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15278
15279 fn definitions(
15280 &self,
15281 buffer: &Entity<Buffer>,
15282 position: text::Anchor,
15283 kind: GotoDefinitionKind,
15284 cx: &mut App,
15285 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15286
15287 fn range_for_rename(
15288 &self,
15289 buffer: &Entity<Buffer>,
15290 position: text::Anchor,
15291 cx: &mut App,
15292 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15293
15294 fn perform_rename(
15295 &self,
15296 buffer: &Entity<Buffer>,
15297 position: text::Anchor,
15298 new_name: String,
15299 cx: &mut App,
15300 ) -> Option<Task<Result<ProjectTransaction>>>;
15301}
15302
15303pub trait CompletionProvider {
15304 fn completions(
15305 &self,
15306 buffer: &Entity<Buffer>,
15307 buffer_position: text::Anchor,
15308 trigger: CompletionContext,
15309 window: &mut Window,
15310 cx: &mut Context<Editor>,
15311 ) -> Task<Result<Vec<Completion>>>;
15312
15313 fn resolve_completions(
15314 &self,
15315 buffer: Entity<Buffer>,
15316 completion_indices: Vec<usize>,
15317 completions: Rc<RefCell<Box<[Completion]>>>,
15318 cx: &mut Context<Editor>,
15319 ) -> Task<Result<bool>>;
15320
15321 fn apply_additional_edits_for_completion(
15322 &self,
15323 _buffer: Entity<Buffer>,
15324 _completions: Rc<RefCell<Box<[Completion]>>>,
15325 _completion_index: usize,
15326 _push_to_history: bool,
15327 _cx: &mut Context<Editor>,
15328 ) -> Task<Result<Option<language::Transaction>>> {
15329 Task::ready(Ok(None))
15330 }
15331
15332 fn is_completion_trigger(
15333 &self,
15334 buffer: &Entity<Buffer>,
15335 position: language::Anchor,
15336 text: &str,
15337 trigger_in_words: bool,
15338 cx: &mut Context<Editor>,
15339 ) -> bool;
15340
15341 fn sort_completions(&self) -> bool {
15342 true
15343 }
15344}
15345
15346pub trait CodeActionProvider {
15347 fn id(&self) -> Arc<str>;
15348
15349 fn code_actions(
15350 &self,
15351 buffer: &Entity<Buffer>,
15352 range: Range<text::Anchor>,
15353 window: &mut Window,
15354 cx: &mut App,
15355 ) -> Task<Result<Vec<CodeAction>>>;
15356
15357 fn apply_code_action(
15358 &self,
15359 buffer_handle: Entity<Buffer>,
15360 action: CodeAction,
15361 excerpt_id: ExcerptId,
15362 push_to_history: bool,
15363 window: &mut Window,
15364 cx: &mut App,
15365 ) -> Task<Result<ProjectTransaction>>;
15366}
15367
15368impl CodeActionProvider for Entity<Project> {
15369 fn id(&self) -> Arc<str> {
15370 "project".into()
15371 }
15372
15373 fn code_actions(
15374 &self,
15375 buffer: &Entity<Buffer>,
15376 range: Range<text::Anchor>,
15377 _window: &mut Window,
15378 cx: &mut App,
15379 ) -> Task<Result<Vec<CodeAction>>> {
15380 self.update(cx, |project, cx| {
15381 project.code_actions(buffer, range, None, cx)
15382 })
15383 }
15384
15385 fn apply_code_action(
15386 &self,
15387 buffer_handle: Entity<Buffer>,
15388 action: CodeAction,
15389 _excerpt_id: ExcerptId,
15390 push_to_history: bool,
15391 _window: &mut Window,
15392 cx: &mut App,
15393 ) -> Task<Result<ProjectTransaction>> {
15394 self.update(cx, |project, cx| {
15395 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15396 })
15397 }
15398}
15399
15400fn snippet_completions(
15401 project: &Project,
15402 buffer: &Entity<Buffer>,
15403 buffer_position: text::Anchor,
15404 cx: &mut App,
15405) -> Task<Result<Vec<Completion>>> {
15406 let language = buffer.read(cx).language_at(buffer_position);
15407 let language_name = language.as_ref().map(|language| language.lsp_id());
15408 let snippet_store = project.snippets().read(cx);
15409 let snippets = snippet_store.snippets_for(language_name, cx);
15410
15411 if snippets.is_empty() {
15412 return Task::ready(Ok(vec![]));
15413 }
15414 let snapshot = buffer.read(cx).text_snapshot();
15415 let chars: String = snapshot
15416 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15417 .collect();
15418
15419 let scope = language.map(|language| language.default_scope());
15420 let executor = cx.background_executor().clone();
15421
15422 cx.background_executor().spawn(async move {
15423 let classifier = CharClassifier::new(scope).for_completion(true);
15424 let mut last_word = chars
15425 .chars()
15426 .take_while(|c| classifier.is_word(*c))
15427 .collect::<String>();
15428 last_word = last_word.chars().rev().collect();
15429
15430 if last_word.is_empty() {
15431 return Ok(vec![]);
15432 }
15433
15434 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15435 let to_lsp = |point: &text::Anchor| {
15436 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15437 point_to_lsp(end)
15438 };
15439 let lsp_end = to_lsp(&buffer_position);
15440
15441 let candidates = snippets
15442 .iter()
15443 .enumerate()
15444 .flat_map(|(ix, snippet)| {
15445 snippet
15446 .prefix
15447 .iter()
15448 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15449 })
15450 .collect::<Vec<StringMatchCandidate>>();
15451
15452 let mut matches = fuzzy::match_strings(
15453 &candidates,
15454 &last_word,
15455 last_word.chars().any(|c| c.is_uppercase()),
15456 100,
15457 &Default::default(),
15458 executor,
15459 )
15460 .await;
15461
15462 // Remove all candidates where the query's start does not match the start of any word in the candidate
15463 if let Some(query_start) = last_word.chars().next() {
15464 matches.retain(|string_match| {
15465 split_words(&string_match.string).any(|word| {
15466 // Check that the first codepoint of the word as lowercase matches the first
15467 // codepoint of the query as lowercase
15468 word.chars()
15469 .flat_map(|codepoint| codepoint.to_lowercase())
15470 .zip(query_start.to_lowercase())
15471 .all(|(word_cp, query_cp)| word_cp == query_cp)
15472 })
15473 });
15474 }
15475
15476 let matched_strings = matches
15477 .into_iter()
15478 .map(|m| m.string)
15479 .collect::<HashSet<_>>();
15480
15481 let result: Vec<Completion> = snippets
15482 .into_iter()
15483 .filter_map(|snippet| {
15484 let matching_prefix = snippet
15485 .prefix
15486 .iter()
15487 .find(|prefix| matched_strings.contains(*prefix))?;
15488 let start = as_offset - last_word.len();
15489 let start = snapshot.anchor_before(start);
15490 let range = start..buffer_position;
15491 let lsp_start = to_lsp(&start);
15492 let lsp_range = lsp::Range {
15493 start: lsp_start,
15494 end: lsp_end,
15495 };
15496 Some(Completion {
15497 old_range: range,
15498 new_text: snippet.body.clone(),
15499 resolved: false,
15500 label: CodeLabel {
15501 text: matching_prefix.clone(),
15502 runs: vec![],
15503 filter_range: 0..matching_prefix.len(),
15504 },
15505 server_id: LanguageServerId(usize::MAX),
15506 documentation: snippet
15507 .description
15508 .clone()
15509 .map(CompletionDocumentation::SingleLine),
15510 lsp_completion: lsp::CompletionItem {
15511 label: snippet.prefix.first().unwrap().clone(),
15512 kind: Some(CompletionItemKind::SNIPPET),
15513 label_details: snippet.description.as_ref().map(|description| {
15514 lsp::CompletionItemLabelDetails {
15515 detail: Some(description.clone()),
15516 description: None,
15517 }
15518 }),
15519 insert_text_format: Some(InsertTextFormat::SNIPPET),
15520 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15521 lsp::InsertReplaceEdit {
15522 new_text: snippet.body.clone(),
15523 insert: lsp_range,
15524 replace: lsp_range,
15525 },
15526 )),
15527 filter_text: Some(snippet.body.clone()),
15528 sort_text: Some(char::MAX.to_string()),
15529 ..Default::default()
15530 },
15531 confirm: None,
15532 })
15533 })
15534 .collect();
15535
15536 Ok(result)
15537 })
15538}
15539
15540impl CompletionProvider for Entity<Project> {
15541 fn completions(
15542 &self,
15543 buffer: &Entity<Buffer>,
15544 buffer_position: text::Anchor,
15545 options: CompletionContext,
15546 _window: &mut Window,
15547 cx: &mut Context<Editor>,
15548 ) -> Task<Result<Vec<Completion>>> {
15549 self.update(cx, |project, cx| {
15550 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15551 let project_completions = project.completions(buffer, buffer_position, options, cx);
15552 cx.background_executor().spawn(async move {
15553 let mut completions = project_completions.await?;
15554 let snippets_completions = snippets.await?;
15555 completions.extend(snippets_completions);
15556 Ok(completions)
15557 })
15558 })
15559 }
15560
15561 fn resolve_completions(
15562 &self,
15563 buffer: Entity<Buffer>,
15564 completion_indices: Vec<usize>,
15565 completions: Rc<RefCell<Box<[Completion]>>>,
15566 cx: &mut Context<Editor>,
15567 ) -> Task<Result<bool>> {
15568 self.update(cx, |project, cx| {
15569 project.lsp_store().update(cx, |lsp_store, cx| {
15570 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15571 })
15572 })
15573 }
15574
15575 fn apply_additional_edits_for_completion(
15576 &self,
15577 buffer: Entity<Buffer>,
15578 completions: Rc<RefCell<Box<[Completion]>>>,
15579 completion_index: usize,
15580 push_to_history: bool,
15581 cx: &mut Context<Editor>,
15582 ) -> Task<Result<Option<language::Transaction>>> {
15583 self.update(cx, |project, cx| {
15584 project.lsp_store().update(cx, |lsp_store, cx| {
15585 lsp_store.apply_additional_edits_for_completion(
15586 buffer,
15587 completions,
15588 completion_index,
15589 push_to_history,
15590 cx,
15591 )
15592 })
15593 })
15594 }
15595
15596 fn is_completion_trigger(
15597 &self,
15598 buffer: &Entity<Buffer>,
15599 position: language::Anchor,
15600 text: &str,
15601 trigger_in_words: bool,
15602 cx: &mut Context<Editor>,
15603 ) -> bool {
15604 let mut chars = text.chars();
15605 let char = if let Some(char) = chars.next() {
15606 char
15607 } else {
15608 return false;
15609 };
15610 if chars.next().is_some() {
15611 return false;
15612 }
15613
15614 let buffer = buffer.read(cx);
15615 let snapshot = buffer.snapshot();
15616 if !snapshot.settings_at(position, cx).show_completions_on_input {
15617 return false;
15618 }
15619 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15620 if trigger_in_words && classifier.is_word(char) {
15621 return true;
15622 }
15623
15624 buffer.completion_triggers().contains(text)
15625 }
15626}
15627
15628impl SemanticsProvider for Entity<Project> {
15629 fn hover(
15630 &self,
15631 buffer: &Entity<Buffer>,
15632 position: text::Anchor,
15633 cx: &mut App,
15634 ) -> Option<Task<Vec<project::Hover>>> {
15635 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15636 }
15637
15638 fn document_highlights(
15639 &self,
15640 buffer: &Entity<Buffer>,
15641 position: text::Anchor,
15642 cx: &mut App,
15643 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15644 Some(self.update(cx, |project, cx| {
15645 project.document_highlights(buffer, position, cx)
15646 }))
15647 }
15648
15649 fn definitions(
15650 &self,
15651 buffer: &Entity<Buffer>,
15652 position: text::Anchor,
15653 kind: GotoDefinitionKind,
15654 cx: &mut App,
15655 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15656 Some(self.update(cx, |project, cx| match kind {
15657 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15658 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15659 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15660 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15661 }))
15662 }
15663
15664 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15665 // TODO: make this work for remote projects
15666 self.read(cx)
15667 .language_servers_for_local_buffer(buffer.read(cx), cx)
15668 .any(
15669 |(_, server)| match server.capabilities().inlay_hint_provider {
15670 Some(lsp::OneOf::Left(enabled)) => enabled,
15671 Some(lsp::OneOf::Right(_)) => true,
15672 None => false,
15673 },
15674 )
15675 }
15676
15677 fn inlay_hints(
15678 &self,
15679 buffer_handle: Entity<Buffer>,
15680 range: Range<text::Anchor>,
15681 cx: &mut App,
15682 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15683 Some(self.update(cx, |project, cx| {
15684 project.inlay_hints(buffer_handle, range, cx)
15685 }))
15686 }
15687
15688 fn resolve_inlay_hint(
15689 &self,
15690 hint: InlayHint,
15691 buffer_handle: Entity<Buffer>,
15692 server_id: LanguageServerId,
15693 cx: &mut App,
15694 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15695 Some(self.update(cx, |project, cx| {
15696 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15697 }))
15698 }
15699
15700 fn range_for_rename(
15701 &self,
15702 buffer: &Entity<Buffer>,
15703 position: text::Anchor,
15704 cx: &mut App,
15705 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15706 Some(self.update(cx, |project, cx| {
15707 let buffer = buffer.clone();
15708 let task = project.prepare_rename(buffer.clone(), position, cx);
15709 cx.spawn(|_, mut cx| async move {
15710 Ok(match task.await? {
15711 PrepareRenameResponse::Success(range) => Some(range),
15712 PrepareRenameResponse::InvalidPosition => None,
15713 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15714 // Fallback on using TreeSitter info to determine identifier range
15715 buffer.update(&mut cx, |buffer, _| {
15716 let snapshot = buffer.snapshot();
15717 let (range, kind) = snapshot.surrounding_word(position);
15718 if kind != Some(CharKind::Word) {
15719 return None;
15720 }
15721 Some(
15722 snapshot.anchor_before(range.start)
15723 ..snapshot.anchor_after(range.end),
15724 )
15725 })?
15726 }
15727 })
15728 })
15729 }))
15730 }
15731
15732 fn perform_rename(
15733 &self,
15734 buffer: &Entity<Buffer>,
15735 position: text::Anchor,
15736 new_name: String,
15737 cx: &mut App,
15738 ) -> Option<Task<Result<ProjectTransaction>>> {
15739 Some(self.update(cx, |project, cx| {
15740 project.perform_rename(buffer.clone(), position, new_name, cx)
15741 }))
15742 }
15743}
15744
15745fn inlay_hint_settings(
15746 location: Anchor,
15747 snapshot: &MultiBufferSnapshot,
15748 cx: &mut Context<Editor>,
15749) -> InlayHintSettings {
15750 let file = snapshot.file_at(location);
15751 let language = snapshot.language_at(location).map(|l| l.name());
15752 language_settings(language, file, cx).inlay_hints
15753}
15754
15755fn consume_contiguous_rows(
15756 contiguous_row_selections: &mut Vec<Selection<Point>>,
15757 selection: &Selection<Point>,
15758 display_map: &DisplaySnapshot,
15759 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15760) -> (MultiBufferRow, MultiBufferRow) {
15761 contiguous_row_selections.push(selection.clone());
15762 let start_row = MultiBufferRow(selection.start.row);
15763 let mut end_row = ending_row(selection, display_map);
15764
15765 while let Some(next_selection) = selections.peek() {
15766 if next_selection.start.row <= end_row.0 {
15767 end_row = ending_row(next_selection, display_map);
15768 contiguous_row_selections.push(selections.next().unwrap().clone());
15769 } else {
15770 break;
15771 }
15772 }
15773 (start_row, end_row)
15774}
15775
15776fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15777 if next_selection.end.column > 0 || next_selection.is_empty() {
15778 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15779 } else {
15780 MultiBufferRow(next_selection.end.row)
15781 }
15782}
15783
15784impl EditorSnapshot {
15785 pub fn remote_selections_in_range<'a>(
15786 &'a self,
15787 range: &'a Range<Anchor>,
15788 collaboration_hub: &dyn CollaborationHub,
15789 cx: &'a App,
15790 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15791 let participant_names = collaboration_hub.user_names(cx);
15792 let participant_indices = collaboration_hub.user_participant_indices(cx);
15793 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15794 let collaborators_by_replica_id = collaborators_by_peer_id
15795 .iter()
15796 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15797 .collect::<HashMap<_, _>>();
15798 self.buffer_snapshot
15799 .selections_in_range(range, false)
15800 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15801 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15802 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15803 let user_name = participant_names.get(&collaborator.user_id).cloned();
15804 Some(RemoteSelection {
15805 replica_id,
15806 selection,
15807 cursor_shape,
15808 line_mode,
15809 participant_index,
15810 peer_id: collaborator.peer_id,
15811 user_name,
15812 })
15813 })
15814 }
15815
15816 pub fn hunks_for_ranges(
15817 &self,
15818 ranges: impl Iterator<Item = Range<Point>>,
15819 ) -> Vec<MultiBufferDiffHunk> {
15820 let mut hunks = Vec::new();
15821 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15822 HashMap::default();
15823 for query_range in ranges {
15824 let query_rows =
15825 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15826 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15827 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15828 ) {
15829 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15830 // when the caret is just above or just below the deleted hunk.
15831 let allow_adjacent = hunk.status().is_removed();
15832 let related_to_selection = if allow_adjacent {
15833 hunk.row_range.overlaps(&query_rows)
15834 || hunk.row_range.start == query_rows.end
15835 || hunk.row_range.end == query_rows.start
15836 } else {
15837 hunk.row_range.overlaps(&query_rows)
15838 };
15839 if related_to_selection {
15840 if !processed_buffer_rows
15841 .entry(hunk.buffer_id)
15842 .or_default()
15843 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15844 {
15845 continue;
15846 }
15847 hunks.push(hunk);
15848 }
15849 }
15850 }
15851
15852 hunks
15853 }
15854
15855 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15856 self.display_snapshot.buffer_snapshot.language_at(position)
15857 }
15858
15859 pub fn is_focused(&self) -> bool {
15860 self.is_focused
15861 }
15862
15863 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15864 self.placeholder_text.as_ref()
15865 }
15866
15867 pub fn scroll_position(&self) -> gpui::Point<f32> {
15868 self.scroll_anchor.scroll_position(&self.display_snapshot)
15869 }
15870
15871 fn gutter_dimensions(
15872 &self,
15873 font_id: FontId,
15874 font_size: Pixels,
15875 max_line_number_width: Pixels,
15876 cx: &App,
15877 ) -> Option<GutterDimensions> {
15878 if !self.show_gutter {
15879 return None;
15880 }
15881
15882 let descent = cx.text_system().descent(font_id, font_size);
15883 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15884 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15885
15886 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15887 matches!(
15888 ProjectSettings::get_global(cx).git.git_gutter,
15889 Some(GitGutterSetting::TrackedFiles)
15890 )
15891 });
15892 let gutter_settings = EditorSettings::get_global(cx).gutter;
15893 let show_line_numbers = self
15894 .show_line_numbers
15895 .unwrap_or(gutter_settings.line_numbers);
15896 let line_gutter_width = if show_line_numbers {
15897 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15898 let min_width_for_number_on_gutter = em_advance * 4.0;
15899 max_line_number_width.max(min_width_for_number_on_gutter)
15900 } else {
15901 0.0.into()
15902 };
15903
15904 let show_code_actions = self
15905 .show_code_actions
15906 .unwrap_or(gutter_settings.code_actions);
15907
15908 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15909
15910 let git_blame_entries_width =
15911 self.git_blame_gutter_max_author_length
15912 .map(|max_author_length| {
15913 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15914
15915 /// The number of characters to dedicate to gaps and margins.
15916 const SPACING_WIDTH: usize = 4;
15917
15918 let max_char_count = max_author_length
15919 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15920 + ::git::SHORT_SHA_LENGTH
15921 + MAX_RELATIVE_TIMESTAMP.len()
15922 + SPACING_WIDTH;
15923
15924 em_advance * max_char_count
15925 });
15926
15927 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15928 left_padding += if show_code_actions || show_runnables {
15929 em_width * 3.0
15930 } else if show_git_gutter && show_line_numbers {
15931 em_width * 2.0
15932 } else if show_git_gutter || show_line_numbers {
15933 em_width
15934 } else {
15935 px(0.)
15936 };
15937
15938 let right_padding = if gutter_settings.folds && show_line_numbers {
15939 em_width * 4.0
15940 } else if gutter_settings.folds {
15941 em_width * 3.0
15942 } else if show_line_numbers {
15943 em_width
15944 } else {
15945 px(0.)
15946 };
15947
15948 Some(GutterDimensions {
15949 left_padding,
15950 right_padding,
15951 width: line_gutter_width + left_padding + right_padding,
15952 margin: -descent,
15953 git_blame_entries_width,
15954 })
15955 }
15956
15957 pub fn render_crease_toggle(
15958 &self,
15959 buffer_row: MultiBufferRow,
15960 row_contains_cursor: bool,
15961 editor: Entity<Editor>,
15962 window: &mut Window,
15963 cx: &mut App,
15964 ) -> Option<AnyElement> {
15965 let folded = self.is_line_folded(buffer_row);
15966 let mut is_foldable = false;
15967
15968 if let Some(crease) = self
15969 .crease_snapshot
15970 .query_row(buffer_row, &self.buffer_snapshot)
15971 {
15972 is_foldable = true;
15973 match crease {
15974 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15975 if let Some(render_toggle) = render_toggle {
15976 let toggle_callback =
15977 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15978 if folded {
15979 editor.update(cx, |editor, cx| {
15980 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15981 });
15982 } else {
15983 editor.update(cx, |editor, cx| {
15984 editor.unfold_at(
15985 &crate::UnfoldAt { buffer_row },
15986 window,
15987 cx,
15988 )
15989 });
15990 }
15991 });
15992 return Some((render_toggle)(
15993 buffer_row,
15994 folded,
15995 toggle_callback,
15996 window,
15997 cx,
15998 ));
15999 }
16000 }
16001 }
16002 }
16003
16004 is_foldable |= self.starts_indent(buffer_row);
16005
16006 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16007 Some(
16008 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16009 .toggle_state(folded)
16010 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16011 if folded {
16012 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16013 } else {
16014 this.fold_at(&FoldAt { buffer_row }, window, cx);
16015 }
16016 }))
16017 .into_any_element(),
16018 )
16019 } else {
16020 None
16021 }
16022 }
16023
16024 pub fn render_crease_trailer(
16025 &self,
16026 buffer_row: MultiBufferRow,
16027 window: &mut Window,
16028 cx: &mut App,
16029 ) -> Option<AnyElement> {
16030 let folded = self.is_line_folded(buffer_row);
16031 if let Crease::Inline { render_trailer, .. } = self
16032 .crease_snapshot
16033 .query_row(buffer_row, &self.buffer_snapshot)?
16034 {
16035 let render_trailer = render_trailer.as_ref()?;
16036 Some(render_trailer(buffer_row, folded, window, cx))
16037 } else {
16038 None
16039 }
16040 }
16041}
16042
16043impl Deref for EditorSnapshot {
16044 type Target = DisplaySnapshot;
16045
16046 fn deref(&self) -> &Self::Target {
16047 &self.display_snapshot
16048 }
16049}
16050
16051#[derive(Clone, Debug, PartialEq, Eq)]
16052pub enum EditorEvent {
16053 InputIgnored {
16054 text: Arc<str>,
16055 },
16056 InputHandled {
16057 utf16_range_to_replace: Option<Range<isize>>,
16058 text: Arc<str>,
16059 },
16060 ExcerptsAdded {
16061 buffer: Entity<Buffer>,
16062 predecessor: ExcerptId,
16063 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16064 },
16065 ExcerptsRemoved {
16066 ids: Vec<ExcerptId>,
16067 },
16068 BufferFoldToggled {
16069 ids: Vec<ExcerptId>,
16070 folded: bool,
16071 },
16072 ExcerptsEdited {
16073 ids: Vec<ExcerptId>,
16074 },
16075 ExcerptsExpanded {
16076 ids: Vec<ExcerptId>,
16077 },
16078 BufferEdited,
16079 Edited {
16080 transaction_id: clock::Lamport,
16081 },
16082 Reparsed(BufferId),
16083 Focused,
16084 FocusedIn,
16085 Blurred,
16086 DirtyChanged,
16087 Saved,
16088 TitleChanged,
16089 DiffBaseChanged,
16090 SelectionsChanged {
16091 local: bool,
16092 },
16093 ScrollPositionChanged {
16094 local: bool,
16095 autoscroll: bool,
16096 },
16097 Closed,
16098 TransactionUndone {
16099 transaction_id: clock::Lamport,
16100 },
16101 TransactionBegun {
16102 transaction_id: clock::Lamport,
16103 },
16104 Reloaded,
16105 CursorShapeChanged,
16106}
16107
16108impl EventEmitter<EditorEvent> for Editor {}
16109
16110impl Focusable for Editor {
16111 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16112 self.focus_handle.clone()
16113 }
16114}
16115
16116impl Render for Editor {
16117 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16118 let settings = ThemeSettings::get_global(cx);
16119
16120 let mut text_style = match self.mode {
16121 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16122 color: cx.theme().colors().editor_foreground,
16123 font_family: settings.ui_font.family.clone(),
16124 font_features: settings.ui_font.features.clone(),
16125 font_fallbacks: settings.ui_font.fallbacks.clone(),
16126 font_size: rems(0.875).into(),
16127 font_weight: settings.ui_font.weight,
16128 line_height: relative(settings.buffer_line_height.value()),
16129 ..Default::default()
16130 },
16131 EditorMode::Full => TextStyle {
16132 color: cx.theme().colors().editor_foreground,
16133 font_family: settings.buffer_font.family.clone(),
16134 font_features: settings.buffer_font.features.clone(),
16135 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16136 font_size: settings.buffer_font_size().into(),
16137 font_weight: settings.buffer_font.weight,
16138 line_height: relative(settings.buffer_line_height.value()),
16139 ..Default::default()
16140 },
16141 };
16142 if let Some(text_style_refinement) = &self.text_style_refinement {
16143 text_style.refine(text_style_refinement)
16144 }
16145
16146 let background = match self.mode {
16147 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16148 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16149 EditorMode::Full => cx.theme().colors().editor_background,
16150 };
16151
16152 EditorElement::new(
16153 &cx.entity(),
16154 EditorStyle {
16155 background,
16156 local_player: cx.theme().players().local(),
16157 text: text_style,
16158 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16159 syntax: cx.theme().syntax().clone(),
16160 status: cx.theme().status().clone(),
16161 inlay_hints_style: make_inlay_hints_style(cx),
16162 inline_completion_styles: make_suggestion_styles(cx),
16163 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16164 },
16165 )
16166 }
16167}
16168
16169impl EntityInputHandler for Editor {
16170 fn text_for_range(
16171 &mut self,
16172 range_utf16: Range<usize>,
16173 adjusted_range: &mut Option<Range<usize>>,
16174 _: &mut Window,
16175 cx: &mut Context<Self>,
16176 ) -> Option<String> {
16177 let snapshot = self.buffer.read(cx).read(cx);
16178 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16179 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16180 if (start.0..end.0) != range_utf16 {
16181 adjusted_range.replace(start.0..end.0);
16182 }
16183 Some(snapshot.text_for_range(start..end).collect())
16184 }
16185
16186 fn selected_text_range(
16187 &mut self,
16188 ignore_disabled_input: bool,
16189 _: &mut Window,
16190 cx: &mut Context<Self>,
16191 ) -> Option<UTF16Selection> {
16192 // Prevent the IME menu from appearing when holding down an alphabetic key
16193 // while input is disabled.
16194 if !ignore_disabled_input && !self.input_enabled {
16195 return None;
16196 }
16197
16198 let selection = self.selections.newest::<OffsetUtf16>(cx);
16199 let range = selection.range();
16200
16201 Some(UTF16Selection {
16202 range: range.start.0..range.end.0,
16203 reversed: selection.reversed,
16204 })
16205 }
16206
16207 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16208 let snapshot = self.buffer.read(cx).read(cx);
16209 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16210 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16211 }
16212
16213 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16214 self.clear_highlights::<InputComposition>(cx);
16215 self.ime_transaction.take();
16216 }
16217
16218 fn replace_text_in_range(
16219 &mut self,
16220 range_utf16: Option<Range<usize>>,
16221 text: &str,
16222 window: &mut Window,
16223 cx: &mut Context<Self>,
16224 ) {
16225 if !self.input_enabled {
16226 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16227 return;
16228 }
16229
16230 self.transact(window, cx, |this, window, cx| {
16231 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16232 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16233 Some(this.selection_replacement_ranges(range_utf16, cx))
16234 } else {
16235 this.marked_text_ranges(cx)
16236 };
16237
16238 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16239 let newest_selection_id = this.selections.newest_anchor().id;
16240 this.selections
16241 .all::<OffsetUtf16>(cx)
16242 .iter()
16243 .zip(ranges_to_replace.iter())
16244 .find_map(|(selection, range)| {
16245 if selection.id == newest_selection_id {
16246 Some(
16247 (range.start.0 as isize - selection.head().0 as isize)
16248 ..(range.end.0 as isize - selection.head().0 as isize),
16249 )
16250 } else {
16251 None
16252 }
16253 })
16254 });
16255
16256 cx.emit(EditorEvent::InputHandled {
16257 utf16_range_to_replace: range_to_replace,
16258 text: text.into(),
16259 });
16260
16261 if let Some(new_selected_ranges) = new_selected_ranges {
16262 this.change_selections(None, window, cx, |selections| {
16263 selections.select_ranges(new_selected_ranges)
16264 });
16265 this.backspace(&Default::default(), window, cx);
16266 }
16267
16268 this.handle_input(text, window, cx);
16269 });
16270
16271 if let Some(transaction) = self.ime_transaction {
16272 self.buffer.update(cx, |buffer, cx| {
16273 buffer.group_until_transaction(transaction, cx);
16274 });
16275 }
16276
16277 self.unmark_text(window, cx);
16278 }
16279
16280 fn replace_and_mark_text_in_range(
16281 &mut self,
16282 range_utf16: Option<Range<usize>>,
16283 text: &str,
16284 new_selected_range_utf16: Option<Range<usize>>,
16285 window: &mut Window,
16286 cx: &mut Context<Self>,
16287 ) {
16288 if !self.input_enabled {
16289 return;
16290 }
16291
16292 let transaction = self.transact(window, cx, |this, window, cx| {
16293 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16294 let snapshot = this.buffer.read(cx).read(cx);
16295 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16296 for marked_range in &mut marked_ranges {
16297 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16298 marked_range.start.0 += relative_range_utf16.start;
16299 marked_range.start =
16300 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16301 marked_range.end =
16302 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16303 }
16304 }
16305 Some(marked_ranges)
16306 } else if let Some(range_utf16) = range_utf16 {
16307 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16308 Some(this.selection_replacement_ranges(range_utf16, cx))
16309 } else {
16310 None
16311 };
16312
16313 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16314 let newest_selection_id = this.selections.newest_anchor().id;
16315 this.selections
16316 .all::<OffsetUtf16>(cx)
16317 .iter()
16318 .zip(ranges_to_replace.iter())
16319 .find_map(|(selection, range)| {
16320 if selection.id == newest_selection_id {
16321 Some(
16322 (range.start.0 as isize - selection.head().0 as isize)
16323 ..(range.end.0 as isize - selection.head().0 as isize),
16324 )
16325 } else {
16326 None
16327 }
16328 })
16329 });
16330
16331 cx.emit(EditorEvent::InputHandled {
16332 utf16_range_to_replace: range_to_replace,
16333 text: text.into(),
16334 });
16335
16336 if let Some(ranges) = ranges_to_replace {
16337 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16338 }
16339
16340 let marked_ranges = {
16341 let snapshot = this.buffer.read(cx).read(cx);
16342 this.selections
16343 .disjoint_anchors()
16344 .iter()
16345 .map(|selection| {
16346 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16347 })
16348 .collect::<Vec<_>>()
16349 };
16350
16351 if text.is_empty() {
16352 this.unmark_text(window, cx);
16353 } else {
16354 this.highlight_text::<InputComposition>(
16355 marked_ranges.clone(),
16356 HighlightStyle {
16357 underline: Some(UnderlineStyle {
16358 thickness: px(1.),
16359 color: None,
16360 wavy: false,
16361 }),
16362 ..Default::default()
16363 },
16364 cx,
16365 );
16366 }
16367
16368 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16369 let use_autoclose = this.use_autoclose;
16370 let use_auto_surround = this.use_auto_surround;
16371 this.set_use_autoclose(false);
16372 this.set_use_auto_surround(false);
16373 this.handle_input(text, window, cx);
16374 this.set_use_autoclose(use_autoclose);
16375 this.set_use_auto_surround(use_auto_surround);
16376
16377 if let Some(new_selected_range) = new_selected_range_utf16 {
16378 let snapshot = this.buffer.read(cx).read(cx);
16379 let new_selected_ranges = marked_ranges
16380 .into_iter()
16381 .map(|marked_range| {
16382 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16383 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16384 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16385 snapshot.clip_offset_utf16(new_start, Bias::Left)
16386 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16387 })
16388 .collect::<Vec<_>>();
16389
16390 drop(snapshot);
16391 this.change_selections(None, window, cx, |selections| {
16392 selections.select_ranges(new_selected_ranges)
16393 });
16394 }
16395 });
16396
16397 self.ime_transaction = self.ime_transaction.or(transaction);
16398 if let Some(transaction) = self.ime_transaction {
16399 self.buffer.update(cx, |buffer, cx| {
16400 buffer.group_until_transaction(transaction, cx);
16401 });
16402 }
16403
16404 if self.text_highlights::<InputComposition>(cx).is_none() {
16405 self.ime_transaction.take();
16406 }
16407 }
16408
16409 fn bounds_for_range(
16410 &mut self,
16411 range_utf16: Range<usize>,
16412 element_bounds: gpui::Bounds<Pixels>,
16413 window: &mut Window,
16414 cx: &mut Context<Self>,
16415 ) -> Option<gpui::Bounds<Pixels>> {
16416 let text_layout_details = self.text_layout_details(window);
16417 let gpui::Size {
16418 width: em_width,
16419 height: line_height,
16420 } = self.character_size(window);
16421
16422 let snapshot = self.snapshot(window, cx);
16423 let scroll_position = snapshot.scroll_position();
16424 let scroll_left = scroll_position.x * em_width;
16425
16426 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16427 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16428 + self.gutter_dimensions.width
16429 + self.gutter_dimensions.margin;
16430 let y = line_height * (start.row().as_f32() - scroll_position.y);
16431
16432 Some(Bounds {
16433 origin: element_bounds.origin + point(x, y),
16434 size: size(em_width, line_height),
16435 })
16436 }
16437
16438 fn character_index_for_point(
16439 &mut self,
16440 point: gpui::Point<Pixels>,
16441 _window: &mut Window,
16442 _cx: &mut Context<Self>,
16443 ) -> Option<usize> {
16444 let position_map = self.last_position_map.as_ref()?;
16445 if !position_map.text_hitbox.contains(&point) {
16446 return None;
16447 }
16448 let display_point = position_map.point_for_position(point).previous_valid;
16449 let anchor = position_map
16450 .snapshot
16451 .display_point_to_anchor(display_point, Bias::Left);
16452 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16453 Some(utf16_offset.0)
16454 }
16455}
16456
16457trait SelectionExt {
16458 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16459 fn spanned_rows(
16460 &self,
16461 include_end_if_at_line_start: bool,
16462 map: &DisplaySnapshot,
16463 ) -> Range<MultiBufferRow>;
16464}
16465
16466impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16467 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16468 let start = self
16469 .start
16470 .to_point(&map.buffer_snapshot)
16471 .to_display_point(map);
16472 let end = self
16473 .end
16474 .to_point(&map.buffer_snapshot)
16475 .to_display_point(map);
16476 if self.reversed {
16477 end..start
16478 } else {
16479 start..end
16480 }
16481 }
16482
16483 fn spanned_rows(
16484 &self,
16485 include_end_if_at_line_start: bool,
16486 map: &DisplaySnapshot,
16487 ) -> Range<MultiBufferRow> {
16488 let start = self.start.to_point(&map.buffer_snapshot);
16489 let mut end = self.end.to_point(&map.buffer_snapshot);
16490 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16491 end.row -= 1;
16492 }
16493
16494 let buffer_start = map.prev_line_boundary(start).0;
16495 let buffer_end = map.next_line_boundary(end).0;
16496 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16497 }
16498}
16499
16500impl<T: InvalidationRegion> InvalidationStack<T> {
16501 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16502 where
16503 S: Clone + ToOffset,
16504 {
16505 while let Some(region) = self.last() {
16506 let all_selections_inside_invalidation_ranges =
16507 if selections.len() == region.ranges().len() {
16508 selections
16509 .iter()
16510 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16511 .all(|(selection, invalidation_range)| {
16512 let head = selection.head().to_offset(buffer);
16513 invalidation_range.start <= head && invalidation_range.end >= head
16514 })
16515 } else {
16516 false
16517 };
16518
16519 if all_selections_inside_invalidation_ranges {
16520 break;
16521 } else {
16522 self.pop();
16523 }
16524 }
16525 }
16526}
16527
16528impl<T> Default for InvalidationStack<T> {
16529 fn default() -> Self {
16530 Self(Default::default())
16531 }
16532}
16533
16534impl<T> Deref for InvalidationStack<T> {
16535 type Target = Vec<T>;
16536
16537 fn deref(&self) -> &Self::Target {
16538 &self.0
16539 }
16540}
16541
16542impl<T> DerefMut for InvalidationStack<T> {
16543 fn deref_mut(&mut self) -> &mut Self::Target {
16544 &mut self.0
16545 }
16546}
16547
16548impl InvalidationRegion for SnippetState {
16549 fn ranges(&self) -> &[Range<Anchor>] {
16550 &self.ranges[self.active_index]
16551 }
16552}
16553
16554pub fn diagnostic_block_renderer(
16555 diagnostic: Diagnostic,
16556 max_message_rows: Option<u8>,
16557 allow_closing: bool,
16558 _is_valid: bool,
16559) -> RenderBlock {
16560 let (text_without_backticks, code_ranges) =
16561 highlight_diagnostic_message(&diagnostic, max_message_rows);
16562
16563 Arc::new(move |cx: &mut BlockContext| {
16564 let group_id: SharedString = cx.block_id.to_string().into();
16565
16566 let mut text_style = cx.window.text_style().clone();
16567 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16568 let theme_settings = ThemeSettings::get_global(cx);
16569 text_style.font_family = theme_settings.buffer_font.family.clone();
16570 text_style.font_style = theme_settings.buffer_font.style;
16571 text_style.font_features = theme_settings.buffer_font.features.clone();
16572 text_style.font_weight = theme_settings.buffer_font.weight;
16573
16574 let multi_line_diagnostic = diagnostic.message.contains('\n');
16575
16576 let buttons = |diagnostic: &Diagnostic| {
16577 if multi_line_diagnostic {
16578 v_flex()
16579 } else {
16580 h_flex()
16581 }
16582 .when(allow_closing, |div| {
16583 div.children(diagnostic.is_primary.then(|| {
16584 IconButton::new("close-block", IconName::XCircle)
16585 .icon_color(Color::Muted)
16586 .size(ButtonSize::Compact)
16587 .style(ButtonStyle::Transparent)
16588 .visible_on_hover(group_id.clone())
16589 .on_click(move |_click, window, cx| {
16590 window.dispatch_action(Box::new(Cancel), cx)
16591 })
16592 .tooltip(|window, cx| {
16593 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16594 })
16595 }))
16596 })
16597 .child(
16598 IconButton::new("copy-block", IconName::Copy)
16599 .icon_color(Color::Muted)
16600 .size(ButtonSize::Compact)
16601 .style(ButtonStyle::Transparent)
16602 .visible_on_hover(group_id.clone())
16603 .on_click({
16604 let message = diagnostic.message.clone();
16605 move |_click, _, cx| {
16606 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16607 }
16608 })
16609 .tooltip(Tooltip::text("Copy diagnostic message")),
16610 )
16611 };
16612
16613 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16614 AvailableSpace::min_size(),
16615 cx.window,
16616 cx.app,
16617 );
16618
16619 h_flex()
16620 .id(cx.block_id)
16621 .group(group_id.clone())
16622 .relative()
16623 .size_full()
16624 .block_mouse_down()
16625 .pl(cx.gutter_dimensions.width)
16626 .w(cx.max_width - cx.gutter_dimensions.full_width())
16627 .child(
16628 div()
16629 .flex()
16630 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16631 .flex_shrink(),
16632 )
16633 .child(buttons(&diagnostic))
16634 .child(div().flex().flex_shrink_0().child(
16635 StyledText::new(text_without_backticks.clone()).with_highlights(
16636 &text_style,
16637 code_ranges.iter().map(|range| {
16638 (
16639 range.clone(),
16640 HighlightStyle {
16641 font_weight: Some(FontWeight::BOLD),
16642 ..Default::default()
16643 },
16644 )
16645 }),
16646 ),
16647 ))
16648 .into_any_element()
16649 })
16650}
16651
16652fn inline_completion_edit_text(
16653 current_snapshot: &BufferSnapshot,
16654 edits: &[(Range<Anchor>, String)],
16655 edit_preview: &EditPreview,
16656 include_deletions: bool,
16657 cx: &App,
16658) -> HighlightedText {
16659 let edits = edits
16660 .iter()
16661 .map(|(anchor, text)| {
16662 (
16663 anchor.start.text_anchor..anchor.end.text_anchor,
16664 text.clone(),
16665 )
16666 })
16667 .collect::<Vec<_>>();
16668
16669 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16670}
16671
16672pub fn highlight_diagnostic_message(
16673 diagnostic: &Diagnostic,
16674 mut max_message_rows: Option<u8>,
16675) -> (SharedString, Vec<Range<usize>>) {
16676 let mut text_without_backticks = String::new();
16677 let mut code_ranges = Vec::new();
16678
16679 if let Some(source) = &diagnostic.source {
16680 text_without_backticks.push_str(source);
16681 code_ranges.push(0..source.len());
16682 text_without_backticks.push_str(": ");
16683 }
16684
16685 let mut prev_offset = 0;
16686 let mut in_code_block = false;
16687 let has_row_limit = max_message_rows.is_some();
16688 let mut newline_indices = diagnostic
16689 .message
16690 .match_indices('\n')
16691 .filter(|_| has_row_limit)
16692 .map(|(ix, _)| ix)
16693 .fuse()
16694 .peekable();
16695
16696 for (quote_ix, _) in diagnostic
16697 .message
16698 .match_indices('`')
16699 .chain([(diagnostic.message.len(), "")])
16700 {
16701 let mut first_newline_ix = None;
16702 let mut last_newline_ix = None;
16703 while let Some(newline_ix) = newline_indices.peek() {
16704 if *newline_ix < quote_ix {
16705 if first_newline_ix.is_none() {
16706 first_newline_ix = Some(*newline_ix);
16707 }
16708 last_newline_ix = Some(*newline_ix);
16709
16710 if let Some(rows_left) = &mut max_message_rows {
16711 if *rows_left == 0 {
16712 break;
16713 } else {
16714 *rows_left -= 1;
16715 }
16716 }
16717 let _ = newline_indices.next();
16718 } else {
16719 break;
16720 }
16721 }
16722 let prev_len = text_without_backticks.len();
16723 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16724 text_without_backticks.push_str(new_text);
16725 if in_code_block {
16726 code_ranges.push(prev_len..text_without_backticks.len());
16727 }
16728 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16729 in_code_block = !in_code_block;
16730 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16731 text_without_backticks.push_str("...");
16732 break;
16733 }
16734 }
16735
16736 (text_without_backticks.into(), code_ranges)
16737}
16738
16739fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16740 match severity {
16741 DiagnosticSeverity::ERROR => colors.error,
16742 DiagnosticSeverity::WARNING => colors.warning,
16743 DiagnosticSeverity::INFORMATION => colors.info,
16744 DiagnosticSeverity::HINT => colors.info,
16745 _ => colors.ignored,
16746 }
16747}
16748
16749pub fn styled_runs_for_code_label<'a>(
16750 label: &'a CodeLabel,
16751 syntax_theme: &'a theme::SyntaxTheme,
16752) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16753 let fade_out = HighlightStyle {
16754 fade_out: Some(0.35),
16755 ..Default::default()
16756 };
16757
16758 let mut prev_end = label.filter_range.end;
16759 label
16760 .runs
16761 .iter()
16762 .enumerate()
16763 .flat_map(move |(ix, (range, highlight_id))| {
16764 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16765 style
16766 } else {
16767 return Default::default();
16768 };
16769 let mut muted_style = style;
16770 muted_style.highlight(fade_out);
16771
16772 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16773 if range.start >= label.filter_range.end {
16774 if range.start > prev_end {
16775 runs.push((prev_end..range.start, fade_out));
16776 }
16777 runs.push((range.clone(), muted_style));
16778 } else if range.end <= label.filter_range.end {
16779 runs.push((range.clone(), style));
16780 } else {
16781 runs.push((range.start..label.filter_range.end, style));
16782 runs.push((label.filter_range.end..range.end, muted_style));
16783 }
16784 prev_end = cmp::max(prev_end, range.end);
16785
16786 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16787 runs.push((prev_end..label.text.len(), fade_out));
16788 }
16789
16790 runs
16791 })
16792}
16793
16794pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16795 let mut prev_index = 0;
16796 let mut prev_codepoint: Option<char> = None;
16797 text.char_indices()
16798 .chain([(text.len(), '\0')])
16799 .filter_map(move |(index, codepoint)| {
16800 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16801 let is_boundary = index == text.len()
16802 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16803 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16804 if is_boundary {
16805 let chunk = &text[prev_index..index];
16806 prev_index = index;
16807 Some(chunk)
16808 } else {
16809 None
16810 }
16811 })
16812}
16813
16814pub trait RangeToAnchorExt: Sized {
16815 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16816
16817 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16818 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16819 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16820 }
16821}
16822
16823impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16824 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16825 let start_offset = self.start.to_offset(snapshot);
16826 let end_offset = self.end.to_offset(snapshot);
16827 if start_offset == end_offset {
16828 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16829 } else {
16830 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16831 }
16832 }
16833}
16834
16835pub trait RowExt {
16836 fn as_f32(&self) -> f32;
16837
16838 fn next_row(&self) -> Self;
16839
16840 fn previous_row(&self) -> Self;
16841
16842 fn minus(&self, other: Self) -> u32;
16843}
16844
16845impl RowExt for DisplayRow {
16846 fn as_f32(&self) -> f32 {
16847 self.0 as f32
16848 }
16849
16850 fn next_row(&self) -> Self {
16851 Self(self.0 + 1)
16852 }
16853
16854 fn previous_row(&self) -> Self {
16855 Self(self.0.saturating_sub(1))
16856 }
16857
16858 fn minus(&self, other: Self) -> u32 {
16859 self.0 - other.0
16860 }
16861}
16862
16863impl RowExt for MultiBufferRow {
16864 fn as_f32(&self) -> f32 {
16865 self.0 as f32
16866 }
16867
16868 fn next_row(&self) -> Self {
16869 Self(self.0 + 1)
16870 }
16871
16872 fn previous_row(&self) -> Self {
16873 Self(self.0.saturating_sub(1))
16874 }
16875
16876 fn minus(&self, other: Self) -> u32 {
16877 self.0 - other.0
16878 }
16879}
16880
16881trait RowRangeExt {
16882 type Row;
16883
16884 fn len(&self) -> usize;
16885
16886 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16887}
16888
16889impl RowRangeExt for Range<MultiBufferRow> {
16890 type Row = MultiBufferRow;
16891
16892 fn len(&self) -> usize {
16893 (self.end.0 - self.start.0) as usize
16894 }
16895
16896 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16897 (self.start.0..self.end.0).map(MultiBufferRow)
16898 }
16899}
16900
16901impl RowRangeExt for Range<DisplayRow> {
16902 type Row = DisplayRow;
16903
16904 fn len(&self) -> usize {
16905 (self.end.0 - self.start.0) as usize
16906 }
16907
16908 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16909 (self.start.0..self.end.0).map(DisplayRow)
16910 }
16911}
16912
16913/// If select range has more than one line, we
16914/// just point the cursor to range.start.
16915fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16916 if range.start.row == range.end.row {
16917 range
16918 } else {
16919 range.start..range.start
16920 }
16921}
16922pub struct KillRing(ClipboardItem);
16923impl Global for KillRing {}
16924
16925const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16926
16927fn all_edits_insertions_or_deletions(
16928 edits: &Vec<(Range<Anchor>, String)>,
16929 snapshot: &MultiBufferSnapshot,
16930) -> bool {
16931 let mut all_insertions = true;
16932 let mut all_deletions = true;
16933
16934 for (range, new_text) in edits.iter() {
16935 let range_is_empty = range.to_offset(&snapshot).is_empty();
16936 let text_is_empty = new_text.is_empty();
16937
16938 if range_is_empty != text_is_empty {
16939 if range_is_empty {
16940 all_deletions = false;
16941 } else {
16942 all_insertions = false;
16943 }
16944 } else {
16945 return false;
16946 }
16947
16948 if !all_insertions && !all_deletions {
16949 return false;
16950 }
16951 }
16952 all_insertions || all_deletions
16953}