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_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
198 "edit_prediction_requires_modifier";
199
200pub fn render_parsed_markdown(
201 element_id: impl Into<ElementId>,
202 parsed: &language::ParsedMarkdown,
203 editor_style: &EditorStyle,
204 workspace: Option<WeakEntity<Workspace>>,
205 cx: &mut App,
206) -> InteractiveText {
207 let code_span_background_color = cx
208 .theme()
209 .colors()
210 .editor_document_highlight_read_background;
211
212 let highlights = gpui::combine_highlights(
213 parsed.highlights.iter().filter_map(|(range, highlight)| {
214 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
215 Some((range.clone(), highlight))
216 }),
217 parsed
218 .regions
219 .iter()
220 .zip(&parsed.region_ranges)
221 .filter_map(|(region, range)| {
222 if region.code {
223 Some((
224 range.clone(),
225 HighlightStyle {
226 background_color: Some(code_span_background_color),
227 ..Default::default()
228 },
229 ))
230 } else {
231 None
232 }
233 }),
234 );
235
236 let mut links = Vec::new();
237 let mut link_ranges = Vec::new();
238 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
239 if let Some(link) = region.link.clone() {
240 links.push(link);
241 link_ranges.push(range.clone());
242 }
243 }
244
245 InteractiveText::new(
246 element_id,
247 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
248 )
249 .on_click(
250 link_ranges,
251 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
252 markdown::Link::Web { url } => cx.open_url(url),
253 markdown::Link::Path { path } => {
254 if let Some(workspace) = &workspace {
255 _ = workspace.update(cx, |workspace, cx| {
256 workspace
257 .open_abs_path(path.clone(), false, window, cx)
258 .detach();
259 });
260 }
261 }
262 },
263 )
264}
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
267pub enum InlayId {
268 InlineCompletion(usize),
269 Hint(usize),
270}
271
272impl InlayId {
273 fn id(&self) -> usize {
274 match self {
275 Self::InlineCompletion(id) => *id,
276 Self::Hint(id) => *id,
277 }
278 }
279}
280
281enum DocumentHighlightRead {}
282enum DocumentHighlightWrite {}
283enum InputComposition {}
284
285#[derive(Debug, Copy, Clone, PartialEq, Eq)]
286pub enum Navigated {
287 Yes,
288 No,
289}
290
291impl Navigated {
292 pub fn from_bool(yes: bool) -> Navigated {
293 if yes {
294 Navigated::Yes
295 } else {
296 Navigated::No
297 }
298 }
299}
300
301pub fn init_settings(cx: &mut App) {
302 EditorSettings::register(cx);
303}
304
305pub fn init(cx: &mut App) {
306 init_settings(cx);
307
308 workspace::register_project_item::<Editor>(cx);
309 workspace::FollowableViewRegistry::register::<Editor>(cx);
310 workspace::register_serializable_item::<Editor>(cx);
311
312 cx.observe_new(
313 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
314 workspace.register_action(Editor::new_file);
315 workspace.register_action(Editor::new_file_vertical);
316 workspace.register_action(Editor::new_file_horizontal);
317 workspace.register_action(Editor::cancel_language_server_work);
318 },
319 )
320 .detach();
321
322 cx.on_action(move |_: &workspace::NewFile, cx| {
323 let app_state = workspace::AppState::global(cx);
324 if let Some(app_state) = app_state.upgrade() {
325 workspace::open_new(
326 Default::default(),
327 app_state,
328 cx,
329 |workspace, window, cx| {
330 Editor::new_file(workspace, &Default::default(), window, cx)
331 },
332 )
333 .detach();
334 }
335 });
336 cx.on_action(move |_: &workspace::NewWindow, cx| {
337 let app_state = workspace::AppState::global(cx);
338 if let Some(app_state) = app_state.upgrade() {
339 workspace::open_new(
340 Default::default(),
341 app_state,
342 cx,
343 |workspace, window, cx| {
344 cx.activate(true);
345 Editor::new_file(workspace, &Default::default(), window, cx)
346 },
347 )
348 .detach();
349 }
350 });
351}
352
353pub struct SearchWithinRange;
354
355trait InvalidationRegion {
356 fn ranges(&self) -> &[Range<Anchor>];
357}
358
359#[derive(Clone, Debug, PartialEq)]
360pub enum SelectPhase {
361 Begin {
362 position: DisplayPoint,
363 add: bool,
364 click_count: usize,
365 },
366 BeginColumnar {
367 position: DisplayPoint,
368 reset: bool,
369 goal_column: u32,
370 },
371 Extend {
372 position: DisplayPoint,
373 click_count: usize,
374 },
375 Update {
376 position: DisplayPoint,
377 goal_column: u32,
378 scroll_delta: gpui::Point<f32>,
379 },
380 End,
381}
382
383#[derive(Clone, Debug)]
384pub enum SelectMode {
385 Character,
386 Word(Range<Anchor>),
387 Line(Range<Anchor>),
388 All,
389}
390
391#[derive(Copy, Clone, PartialEq, Eq, Debug)]
392pub enum EditorMode {
393 SingleLine { auto_width: bool },
394 AutoHeight { max_lines: usize },
395 Full,
396}
397
398#[derive(Copy, Clone, Debug)]
399pub enum SoftWrap {
400 /// Prefer not to wrap at all.
401 ///
402 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
403 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
404 GitDiff,
405 /// Prefer a single line generally, unless an overly long line is encountered.
406 None,
407 /// Soft wrap lines that exceed the editor width.
408 EditorWidth,
409 /// Soft wrap lines at the preferred line length.
410 Column(u32),
411 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
412 Bounded(u32),
413}
414
415#[derive(Clone)]
416pub struct EditorStyle {
417 pub background: Hsla,
418 pub local_player: PlayerColor,
419 pub text: TextStyle,
420 pub scrollbar_width: Pixels,
421 pub syntax: Arc<SyntaxTheme>,
422 pub status: StatusColors,
423 pub inlay_hints_style: HighlightStyle,
424 pub inline_completion_styles: InlineCompletionStyles,
425 pub unnecessary_code_fade: f32,
426}
427
428impl Default for EditorStyle {
429 fn default() -> Self {
430 Self {
431 background: Hsla::default(),
432 local_player: PlayerColor::default(),
433 text: TextStyle::default(),
434 scrollbar_width: Pixels::default(),
435 syntax: Default::default(),
436 // HACK: Status colors don't have a real default.
437 // We should look into removing the status colors from the editor
438 // style and retrieve them directly from the theme.
439 status: StatusColors::dark(),
440 inlay_hints_style: HighlightStyle::default(),
441 inline_completion_styles: InlineCompletionStyles {
442 insertion: HighlightStyle::default(),
443 whitespace: HighlightStyle::default(),
444 },
445 unnecessary_code_fade: Default::default(),
446 }
447 }
448}
449
450pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
451 let show_background = language_settings::language_settings(None, None, cx)
452 .inlay_hints
453 .show_background;
454
455 HighlightStyle {
456 color: Some(cx.theme().status().hint),
457 background_color: show_background.then(|| cx.theme().status().hint_background),
458 ..HighlightStyle::default()
459 }
460}
461
462pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
463 InlineCompletionStyles {
464 insertion: HighlightStyle {
465 color: Some(cx.theme().status().predictive),
466 ..HighlightStyle::default()
467 },
468 whitespace: HighlightStyle {
469 background_color: Some(cx.theme().status().created_background),
470 ..HighlightStyle::default()
471 },
472 }
473}
474
475type CompletionId = usize;
476
477pub(crate) enum EditDisplayMode {
478 TabAccept,
479 DiffPopover,
480 Inline,
481}
482
483enum InlineCompletion {
484 Edit {
485 edits: Vec<(Range<Anchor>, String)>,
486 edit_preview: Option<EditPreview>,
487 display_mode: EditDisplayMode,
488 snapshot: BufferSnapshot,
489 },
490 Move {
491 target: Anchor,
492 snapshot: BufferSnapshot,
493 },
494}
495
496struct InlineCompletionState {
497 inlay_ids: Vec<InlayId>,
498 completion: InlineCompletion,
499 completion_id: Option<SharedString>,
500 invalidation_range: Range<Anchor>,
501}
502
503enum EditPredictionSettings {
504 Disabled,
505 Enabled {
506 show_in_menu: bool,
507 preview_requires_modifier: bool,
508 },
509}
510
511impl EditPredictionSettings {
512 pub fn is_enabled(&self) -> bool {
513 match self {
514 EditPredictionSettings::Disabled => false,
515 EditPredictionSettings::Enabled { .. } => true,
516 }
517 }
518}
519
520enum InlineCompletionHighlight {}
521
522pub enum MenuInlineCompletionsPolicy {
523 Never,
524 ByProvider,
525}
526
527pub enum EditPredictionPreview {
528 /// Modifier is not pressed
529 Inactive,
530 /// Modifier pressed
531 Active {
532 previous_scroll_position: Option<ScrollAnchor>,
533 },
534}
535
536#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
537struct EditorActionId(usize);
538
539impl EditorActionId {
540 pub fn post_inc(&mut self) -> Self {
541 let answer = self.0;
542
543 *self = Self(answer + 1);
544
545 Self(answer)
546 }
547}
548
549// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
550// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
551
552type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
553type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
554
555#[derive(Default)]
556struct ScrollbarMarkerState {
557 scrollbar_size: Size<Pixels>,
558 dirty: bool,
559 markers: Arc<[PaintQuad]>,
560 pending_refresh: Option<Task<Result<()>>>,
561}
562
563impl ScrollbarMarkerState {
564 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
565 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
566 }
567}
568
569#[derive(Clone, Debug)]
570struct RunnableTasks {
571 templates: Vec<(TaskSourceKind, TaskTemplate)>,
572 offset: MultiBufferOffset,
573 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
574 column: u32,
575 // Values of all named captures, including those starting with '_'
576 extra_variables: HashMap<String, String>,
577 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
578 context_range: Range<BufferOffset>,
579}
580
581impl RunnableTasks {
582 fn resolve<'a>(
583 &'a self,
584 cx: &'a task::TaskContext,
585 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
586 self.templates.iter().filter_map(|(kind, template)| {
587 template
588 .resolve_task(&kind.to_id_base(), cx)
589 .map(|task| (kind.clone(), task))
590 })
591 }
592}
593
594#[derive(Clone)]
595struct ResolvedTasks {
596 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
597 position: Anchor,
598}
599#[derive(Copy, Clone, Debug)]
600struct MultiBufferOffset(usize);
601#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
602struct BufferOffset(usize);
603
604// Addons allow storing per-editor state in other crates (e.g. Vim)
605pub trait Addon: 'static {
606 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
607
608 fn render_buffer_header_controls(
609 &self,
610 _: &ExcerptInfo,
611 _: &Window,
612 _: &App,
613 ) -> Option<AnyElement> {
614 None
615 }
616
617 fn to_any(&self) -> &dyn std::any::Any;
618}
619
620#[derive(Debug, Copy, Clone, PartialEq, Eq)]
621pub enum IsVimMode {
622 Yes,
623 No,
624}
625
626/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
627///
628/// See the [module level documentation](self) for more information.
629pub struct Editor {
630 focus_handle: FocusHandle,
631 last_focused_descendant: Option<WeakFocusHandle>,
632 /// The text buffer being edited
633 buffer: Entity<MultiBuffer>,
634 /// Map of how text in the buffer should be displayed.
635 /// Handles soft wraps, folds, fake inlay text insertions, etc.
636 pub display_map: Entity<DisplayMap>,
637 pub selections: SelectionsCollection,
638 pub scroll_manager: ScrollManager,
639 /// When inline assist editors are linked, they all render cursors because
640 /// typing enters text into each of them, even the ones that aren't focused.
641 pub(crate) show_cursor_when_unfocused: bool,
642 columnar_selection_tail: Option<Anchor>,
643 add_selections_state: Option<AddSelectionsState>,
644 select_next_state: Option<SelectNextState>,
645 select_prev_state: Option<SelectNextState>,
646 selection_history: SelectionHistory,
647 autoclose_regions: Vec<AutocloseRegion>,
648 snippet_stack: InvalidationStack<SnippetState>,
649 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
650 ime_transaction: Option<TransactionId>,
651 active_diagnostics: Option<ActiveDiagnosticGroup>,
652 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
653
654 // TODO: make this a access method
655 pub project: Option<Entity<Project>>,
656 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
657 completion_provider: Option<Box<dyn CompletionProvider>>,
658 collaboration_hub: Option<Box<dyn CollaborationHub>>,
659 blink_manager: Entity<BlinkManager>,
660 show_cursor_names: bool,
661 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
662 pub show_local_selections: bool,
663 mode: EditorMode,
664 show_breadcrumbs: bool,
665 show_gutter: bool,
666 show_scrollbars: bool,
667 show_line_numbers: Option<bool>,
668 use_relative_line_numbers: Option<bool>,
669 show_git_diff_gutter: Option<bool>,
670 show_code_actions: Option<bool>,
671 show_runnables: Option<bool>,
672 show_wrap_guides: Option<bool>,
673 show_indent_guides: Option<bool>,
674 placeholder_text: Option<Arc<str>>,
675 highlight_order: usize,
676 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
677 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
678 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
679 scrollbar_marker_state: ScrollbarMarkerState,
680 active_indent_guides_state: ActiveIndentGuidesState,
681 nav_history: Option<ItemNavHistory>,
682 context_menu: RefCell<Option<CodeContextMenu>>,
683 mouse_context_menu: Option<MouseContextMenu>,
684 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
685 signature_help_state: SignatureHelpState,
686 auto_signature_help: Option<bool>,
687 find_all_references_task_sources: Vec<Anchor>,
688 next_completion_id: CompletionId,
689 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
690 code_actions_task: Option<Task<Result<()>>>,
691 document_highlights_task: Option<Task<()>>,
692 linked_editing_range_task: Option<Task<Option<()>>>,
693 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
694 pending_rename: Option<RenameState>,
695 searchable: bool,
696 cursor_shape: CursorShape,
697 current_line_highlight: Option<CurrentLineHighlight>,
698 collapse_matches: bool,
699 autoindent_mode: Option<AutoindentMode>,
700 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
701 input_enabled: bool,
702 use_modal_editing: bool,
703 read_only: bool,
704 leader_peer_id: Option<PeerId>,
705 remote_id: Option<ViewId>,
706 hover_state: HoverState,
707 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
708 gutter_hovered: bool,
709 hovered_link_state: Option<HoveredLinkState>,
710 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
711 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
712 active_inline_completion: Option<InlineCompletionState>,
713 /// Used to prevent flickering as the user types while the menu is open
714 stale_inline_completion_in_menu: Option<InlineCompletionState>,
715 edit_prediction_settings: EditPredictionSettings,
716 inline_completions_hidden_for_vim_mode: bool,
717 show_inline_completions_override: Option<bool>,
718 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
719 edit_prediction_preview: EditPredictionPreview,
720 edit_prediction_cursor_on_leading_whitespace: bool,
721 edit_prediction_requires_modifier_in_leading_space: bool,
722 inlay_hint_cache: InlayHintCache,
723 next_inlay_id: usize,
724 _subscriptions: Vec<Subscription>,
725 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
726 gutter_dimensions: GutterDimensions,
727 style: Option<EditorStyle>,
728 text_style_refinement: Option<TextStyleRefinement>,
729 next_editor_action_id: EditorActionId,
730 editor_actions:
731 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
732 use_autoclose: bool,
733 use_auto_surround: bool,
734 auto_replace_emoji_shortcode: bool,
735 show_git_blame_gutter: bool,
736 show_git_blame_inline: bool,
737 show_git_blame_inline_delay_task: Option<Task<()>>,
738 distinguish_unstaged_diff_hunks: bool,
739 git_blame_inline_enabled: bool,
740 serialize_dirty_buffers: bool,
741 show_selection_menu: Option<bool>,
742 blame: Option<Entity<GitBlame>>,
743 blame_subscription: Option<Subscription>,
744 custom_context_menu: Option<
745 Box<
746 dyn 'static
747 + Fn(
748 &mut Self,
749 DisplayPoint,
750 &mut Window,
751 &mut Context<Self>,
752 ) -> Option<Entity<ui::ContextMenu>>,
753 >,
754 >,
755 last_bounds: Option<Bounds<Pixels>>,
756 last_position_map: Option<Rc<PositionMap>>,
757 expect_bounds_change: Option<Bounds<Pixels>>,
758 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
759 tasks_update_task: Option<Task<()>>,
760 in_project_search: bool,
761 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
762 breadcrumb_header: Option<String>,
763 focused_block: Option<FocusedBlock>,
764 next_scroll_position: NextScrollCursorCenterTopBottom,
765 addons: HashMap<TypeId, Box<dyn Addon>>,
766 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
767 load_diff_task: Option<Shared<Task<()>>>,
768 selection_mark_mode: bool,
769 toggle_fold_multiple_buffers: Task<()>,
770 _scroll_cursor_center_top_bottom_task: Task<()>,
771}
772
773#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
774enum NextScrollCursorCenterTopBottom {
775 #[default]
776 Center,
777 Top,
778 Bottom,
779}
780
781impl NextScrollCursorCenterTopBottom {
782 fn next(&self) -> Self {
783 match self {
784 Self::Center => Self::Top,
785 Self::Top => Self::Bottom,
786 Self::Bottom => Self::Center,
787 }
788 }
789}
790
791#[derive(Clone)]
792pub struct EditorSnapshot {
793 pub mode: EditorMode,
794 show_gutter: bool,
795 show_line_numbers: Option<bool>,
796 show_git_diff_gutter: Option<bool>,
797 show_code_actions: Option<bool>,
798 show_runnables: Option<bool>,
799 git_blame_gutter_max_author_length: Option<usize>,
800 pub display_snapshot: DisplaySnapshot,
801 pub placeholder_text: Option<Arc<str>>,
802 is_focused: bool,
803 scroll_anchor: ScrollAnchor,
804 ongoing_scroll: OngoingScroll,
805 current_line_highlight: CurrentLineHighlight,
806 gutter_hovered: bool,
807}
808
809const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
810
811#[derive(Default, Debug, Clone, Copy)]
812pub struct GutterDimensions {
813 pub left_padding: Pixels,
814 pub right_padding: Pixels,
815 pub width: Pixels,
816 pub margin: Pixels,
817 pub git_blame_entries_width: Option<Pixels>,
818}
819
820impl GutterDimensions {
821 /// The full width of the space taken up by the gutter.
822 pub fn full_width(&self) -> Pixels {
823 self.margin + self.width
824 }
825
826 /// The width of the space reserved for the fold indicators,
827 /// use alongside 'justify_end' and `gutter_width` to
828 /// right align content with the line numbers
829 pub fn fold_area_width(&self) -> Pixels {
830 self.margin + self.right_padding
831 }
832}
833
834#[derive(Debug)]
835pub struct RemoteSelection {
836 pub replica_id: ReplicaId,
837 pub selection: Selection<Anchor>,
838 pub cursor_shape: CursorShape,
839 pub peer_id: PeerId,
840 pub line_mode: bool,
841 pub participant_index: Option<ParticipantIndex>,
842 pub user_name: Option<SharedString>,
843}
844
845#[derive(Clone, Debug)]
846struct SelectionHistoryEntry {
847 selections: Arc<[Selection<Anchor>]>,
848 select_next_state: Option<SelectNextState>,
849 select_prev_state: Option<SelectNextState>,
850 add_selections_state: Option<AddSelectionsState>,
851}
852
853enum SelectionHistoryMode {
854 Normal,
855 Undoing,
856 Redoing,
857}
858
859#[derive(Clone, PartialEq, Eq, Hash)]
860struct HoveredCursor {
861 replica_id: u16,
862 selection_id: usize,
863}
864
865impl Default for SelectionHistoryMode {
866 fn default() -> Self {
867 Self::Normal
868 }
869}
870
871#[derive(Default)]
872struct SelectionHistory {
873 #[allow(clippy::type_complexity)]
874 selections_by_transaction:
875 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
876 mode: SelectionHistoryMode,
877 undo_stack: VecDeque<SelectionHistoryEntry>,
878 redo_stack: VecDeque<SelectionHistoryEntry>,
879}
880
881impl SelectionHistory {
882 fn insert_transaction(
883 &mut self,
884 transaction_id: TransactionId,
885 selections: Arc<[Selection<Anchor>]>,
886 ) {
887 self.selections_by_transaction
888 .insert(transaction_id, (selections, None));
889 }
890
891 #[allow(clippy::type_complexity)]
892 fn transaction(
893 &self,
894 transaction_id: TransactionId,
895 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
896 self.selections_by_transaction.get(&transaction_id)
897 }
898
899 #[allow(clippy::type_complexity)]
900 fn transaction_mut(
901 &mut self,
902 transaction_id: TransactionId,
903 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
904 self.selections_by_transaction.get_mut(&transaction_id)
905 }
906
907 fn push(&mut self, entry: SelectionHistoryEntry) {
908 if !entry.selections.is_empty() {
909 match self.mode {
910 SelectionHistoryMode::Normal => {
911 self.push_undo(entry);
912 self.redo_stack.clear();
913 }
914 SelectionHistoryMode::Undoing => self.push_redo(entry),
915 SelectionHistoryMode::Redoing => self.push_undo(entry),
916 }
917 }
918 }
919
920 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
921 if self
922 .undo_stack
923 .back()
924 .map_or(true, |e| e.selections != entry.selections)
925 {
926 self.undo_stack.push_back(entry);
927 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
928 self.undo_stack.pop_front();
929 }
930 }
931 }
932
933 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
934 if self
935 .redo_stack
936 .back()
937 .map_or(true, |e| e.selections != entry.selections)
938 {
939 self.redo_stack.push_back(entry);
940 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
941 self.redo_stack.pop_front();
942 }
943 }
944 }
945}
946
947struct RowHighlight {
948 index: usize,
949 range: Range<Anchor>,
950 color: Hsla,
951 should_autoscroll: bool,
952}
953
954#[derive(Clone, Debug)]
955struct AddSelectionsState {
956 above: bool,
957 stack: Vec<usize>,
958}
959
960#[derive(Clone)]
961struct SelectNextState {
962 query: AhoCorasick,
963 wordwise: bool,
964 done: bool,
965}
966
967impl std::fmt::Debug for SelectNextState {
968 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969 f.debug_struct(std::any::type_name::<Self>())
970 .field("wordwise", &self.wordwise)
971 .field("done", &self.done)
972 .finish()
973 }
974}
975
976#[derive(Debug)]
977struct AutocloseRegion {
978 selection_id: usize,
979 range: Range<Anchor>,
980 pair: BracketPair,
981}
982
983#[derive(Debug)]
984struct SnippetState {
985 ranges: Vec<Vec<Range<Anchor>>>,
986 active_index: usize,
987 choices: Vec<Option<Vec<String>>>,
988}
989
990#[doc(hidden)]
991pub struct RenameState {
992 pub range: Range<Anchor>,
993 pub old_name: Arc<str>,
994 pub editor: Entity<Editor>,
995 block_id: CustomBlockId,
996}
997
998struct InvalidationStack<T>(Vec<T>);
999
1000struct RegisteredInlineCompletionProvider {
1001 provider: Arc<dyn InlineCompletionProviderHandle>,
1002 _subscription: Subscription,
1003}
1004
1005#[derive(Debug)]
1006struct ActiveDiagnosticGroup {
1007 primary_range: Range<Anchor>,
1008 primary_message: String,
1009 group_id: usize,
1010 blocks: HashMap<CustomBlockId, Diagnostic>,
1011 is_valid: bool,
1012}
1013
1014#[derive(Serialize, Deserialize, Clone, Debug)]
1015pub struct ClipboardSelection {
1016 pub len: usize,
1017 pub is_entire_line: bool,
1018 pub first_line_indent: u32,
1019}
1020
1021#[derive(Debug)]
1022pub(crate) struct NavigationData {
1023 cursor_anchor: Anchor,
1024 cursor_position: Point,
1025 scroll_anchor: ScrollAnchor,
1026 scroll_top_row: u32,
1027}
1028
1029#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1030pub enum GotoDefinitionKind {
1031 Symbol,
1032 Declaration,
1033 Type,
1034 Implementation,
1035}
1036
1037#[derive(Debug, Clone)]
1038enum InlayHintRefreshReason {
1039 Toggle(bool),
1040 SettingsChange(InlayHintSettings),
1041 NewLinesShown,
1042 BufferEdited(HashSet<Arc<Language>>),
1043 RefreshRequested,
1044 ExcerptsRemoved(Vec<ExcerptId>),
1045}
1046
1047impl InlayHintRefreshReason {
1048 fn description(&self) -> &'static str {
1049 match self {
1050 Self::Toggle(_) => "toggle",
1051 Self::SettingsChange(_) => "settings change",
1052 Self::NewLinesShown => "new lines shown",
1053 Self::BufferEdited(_) => "buffer edited",
1054 Self::RefreshRequested => "refresh requested",
1055 Self::ExcerptsRemoved(_) => "excerpts removed",
1056 }
1057 }
1058}
1059
1060pub enum FormatTarget {
1061 Buffers,
1062 Ranges(Vec<Range<MultiBufferPoint>>),
1063}
1064
1065pub(crate) struct FocusedBlock {
1066 id: BlockId,
1067 focus_handle: WeakFocusHandle,
1068}
1069
1070#[derive(Clone)]
1071enum JumpData {
1072 MultiBufferRow {
1073 row: MultiBufferRow,
1074 line_offset_from_top: u32,
1075 },
1076 MultiBufferPoint {
1077 excerpt_id: ExcerptId,
1078 position: Point,
1079 anchor: text::Anchor,
1080 line_offset_from_top: u32,
1081 },
1082}
1083
1084pub enum MultibufferSelectionMode {
1085 First,
1086 All,
1087}
1088
1089impl Editor {
1090 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1091 let buffer = cx.new(|cx| Buffer::local("", cx));
1092 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1093 Self::new(
1094 EditorMode::SingleLine { auto_width: false },
1095 buffer,
1096 None,
1097 false,
1098 window,
1099 cx,
1100 )
1101 }
1102
1103 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1104 let buffer = cx.new(|cx| Buffer::local("", cx));
1105 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1106 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1107 }
1108
1109 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1110 let buffer = cx.new(|cx| Buffer::local("", cx));
1111 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1112 Self::new(
1113 EditorMode::SingleLine { auto_width: true },
1114 buffer,
1115 None,
1116 false,
1117 window,
1118 cx,
1119 )
1120 }
1121
1122 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1123 let buffer = cx.new(|cx| Buffer::local("", cx));
1124 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1125 Self::new(
1126 EditorMode::AutoHeight { max_lines },
1127 buffer,
1128 None,
1129 false,
1130 window,
1131 cx,
1132 )
1133 }
1134
1135 pub fn for_buffer(
1136 buffer: Entity<Buffer>,
1137 project: Option<Entity<Project>>,
1138 window: &mut Window,
1139 cx: &mut Context<Self>,
1140 ) -> Self {
1141 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1142 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1143 }
1144
1145 pub fn for_multibuffer(
1146 buffer: Entity<MultiBuffer>,
1147 project: Option<Entity<Project>>,
1148 show_excerpt_controls: bool,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 Self::new(
1153 EditorMode::Full,
1154 buffer,
1155 project,
1156 show_excerpt_controls,
1157 window,
1158 cx,
1159 )
1160 }
1161
1162 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1163 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1164 let mut clone = Self::new(
1165 self.mode,
1166 self.buffer.clone(),
1167 self.project.clone(),
1168 show_excerpt_controls,
1169 window,
1170 cx,
1171 );
1172 self.display_map.update(cx, |display_map, cx| {
1173 let snapshot = display_map.snapshot(cx);
1174 clone.display_map.update(cx, |display_map, cx| {
1175 display_map.set_state(&snapshot, cx);
1176 });
1177 });
1178 clone.selections.clone_state(&self.selections);
1179 clone.scroll_manager.clone_state(&self.scroll_manager);
1180 clone.searchable = self.searchable;
1181 clone
1182 }
1183
1184 pub fn new(
1185 mode: EditorMode,
1186 buffer: Entity<MultiBuffer>,
1187 project: Option<Entity<Project>>,
1188 show_excerpt_controls: bool,
1189 window: &mut Window,
1190 cx: &mut Context<Self>,
1191 ) -> Self {
1192 let style = window.text_style();
1193 let font_size = style.font_size.to_pixels(window.rem_size());
1194 let editor = cx.entity().downgrade();
1195 let fold_placeholder = FoldPlaceholder {
1196 constrain_width: true,
1197 render: Arc::new(move |fold_id, fold_range, _, cx| {
1198 let editor = editor.clone();
1199 div()
1200 .id(fold_id)
1201 .bg(cx.theme().colors().ghost_element_background)
1202 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1203 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1204 .rounded_sm()
1205 .size_full()
1206 .cursor_pointer()
1207 .child("⋯")
1208 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1209 .on_click(move |_, _window, cx| {
1210 editor
1211 .update(cx, |editor, cx| {
1212 editor.unfold_ranges(
1213 &[fold_range.start..fold_range.end],
1214 true,
1215 false,
1216 cx,
1217 );
1218 cx.stop_propagation();
1219 })
1220 .ok();
1221 })
1222 .into_any()
1223 }),
1224 merge_adjacent: true,
1225 ..Default::default()
1226 };
1227 let display_map = cx.new(|cx| {
1228 DisplayMap::new(
1229 buffer.clone(),
1230 style.font(),
1231 font_size,
1232 None,
1233 show_excerpt_controls,
1234 FILE_HEADER_HEIGHT,
1235 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1236 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1237 fold_placeholder,
1238 cx,
1239 )
1240 });
1241
1242 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1243
1244 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1245
1246 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1247 .then(|| language_settings::SoftWrap::None);
1248
1249 let mut project_subscriptions = Vec::new();
1250 if mode == EditorMode::Full {
1251 if let Some(project) = project.as_ref() {
1252 if buffer.read(cx).is_singleton() {
1253 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1254 cx.emit(EditorEvent::TitleChanged);
1255 }));
1256 }
1257 project_subscriptions.push(cx.subscribe_in(
1258 project,
1259 window,
1260 |editor, _, event, window, cx| {
1261 if let project::Event::RefreshInlayHints = event {
1262 editor
1263 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1264 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1265 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1266 let focus_handle = editor.focus_handle(cx);
1267 if focus_handle.is_focused(window) {
1268 let snapshot = buffer.read(cx).snapshot();
1269 for (range, snippet) in snippet_edits {
1270 let editor_range =
1271 language::range_from_lsp(*range).to_offset(&snapshot);
1272 editor
1273 .insert_snippet(
1274 &[editor_range],
1275 snippet.clone(),
1276 window,
1277 cx,
1278 )
1279 .ok();
1280 }
1281 }
1282 }
1283 }
1284 },
1285 ));
1286 if let Some(task_inventory) = project
1287 .read(cx)
1288 .task_store()
1289 .read(cx)
1290 .task_inventory()
1291 .cloned()
1292 {
1293 project_subscriptions.push(cx.observe_in(
1294 &task_inventory,
1295 window,
1296 |editor, _, window, cx| {
1297 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1298 },
1299 ));
1300 }
1301 }
1302 }
1303
1304 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1305
1306 let inlay_hint_settings =
1307 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1308 let focus_handle = cx.focus_handle();
1309 cx.on_focus(&focus_handle, window, Self::handle_focus)
1310 .detach();
1311 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1312 .detach();
1313 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1314 .detach();
1315 cx.on_blur(&focus_handle, window, Self::handle_blur)
1316 .detach();
1317
1318 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1319 Some(false)
1320 } else {
1321 None
1322 };
1323
1324 let mut code_action_providers = Vec::new();
1325 let mut load_uncommitted_diff = None;
1326 if let Some(project) = project.clone() {
1327 load_uncommitted_diff = Some(
1328 get_uncommitted_diff_for_buffer(
1329 &project,
1330 buffer.read(cx).all_buffers(),
1331 buffer.clone(),
1332 cx,
1333 )
1334 .shared(),
1335 );
1336 code_action_providers.push(Rc::new(project) as Rc<_>);
1337 }
1338
1339 let mut this = Self {
1340 focus_handle,
1341 show_cursor_when_unfocused: false,
1342 last_focused_descendant: None,
1343 buffer: buffer.clone(),
1344 display_map: display_map.clone(),
1345 selections,
1346 scroll_manager: ScrollManager::new(cx),
1347 columnar_selection_tail: None,
1348 add_selections_state: None,
1349 select_next_state: None,
1350 select_prev_state: None,
1351 selection_history: Default::default(),
1352 autoclose_regions: Default::default(),
1353 snippet_stack: Default::default(),
1354 select_larger_syntax_node_stack: Vec::new(),
1355 ime_transaction: Default::default(),
1356 active_diagnostics: None,
1357 soft_wrap_mode_override,
1358 completion_provider: project.clone().map(|project| Box::new(project) as _),
1359 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1360 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1361 project,
1362 blink_manager: blink_manager.clone(),
1363 show_local_selections: true,
1364 show_scrollbars: true,
1365 mode,
1366 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1367 show_gutter: mode == EditorMode::Full,
1368 show_line_numbers: None,
1369 use_relative_line_numbers: None,
1370 show_git_diff_gutter: None,
1371 show_code_actions: None,
1372 show_runnables: None,
1373 show_wrap_guides: None,
1374 show_indent_guides,
1375 placeholder_text: None,
1376 highlight_order: 0,
1377 highlighted_rows: HashMap::default(),
1378 background_highlights: Default::default(),
1379 gutter_highlights: TreeMap::default(),
1380 scrollbar_marker_state: ScrollbarMarkerState::default(),
1381 active_indent_guides_state: ActiveIndentGuidesState::default(),
1382 nav_history: None,
1383 context_menu: RefCell::new(None),
1384 mouse_context_menu: None,
1385 completion_tasks: Default::default(),
1386 signature_help_state: SignatureHelpState::default(),
1387 auto_signature_help: None,
1388 find_all_references_task_sources: Vec::new(),
1389 next_completion_id: 0,
1390 next_inlay_id: 0,
1391 code_action_providers,
1392 available_code_actions: Default::default(),
1393 code_actions_task: Default::default(),
1394 document_highlights_task: Default::default(),
1395 linked_editing_range_task: Default::default(),
1396 pending_rename: Default::default(),
1397 searchable: true,
1398 cursor_shape: EditorSettings::get_global(cx)
1399 .cursor_shape
1400 .unwrap_or_default(),
1401 current_line_highlight: None,
1402 autoindent_mode: Some(AutoindentMode::EachLine),
1403 collapse_matches: false,
1404 workspace: None,
1405 input_enabled: true,
1406 use_modal_editing: mode == EditorMode::Full,
1407 read_only: false,
1408 use_autoclose: true,
1409 use_auto_surround: true,
1410 auto_replace_emoji_shortcode: false,
1411 leader_peer_id: None,
1412 remote_id: None,
1413 hover_state: Default::default(),
1414 pending_mouse_down: None,
1415 hovered_link_state: Default::default(),
1416 edit_prediction_provider: None,
1417 active_inline_completion: None,
1418 stale_inline_completion_in_menu: None,
1419 edit_prediction_preview: EditPredictionPreview::Inactive,
1420 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1421
1422 gutter_hovered: false,
1423 pixel_position_of_newest_cursor: None,
1424 last_bounds: None,
1425 last_position_map: None,
1426 expect_bounds_change: None,
1427 gutter_dimensions: GutterDimensions::default(),
1428 style: None,
1429 show_cursor_names: false,
1430 hovered_cursors: Default::default(),
1431 next_editor_action_id: EditorActionId::default(),
1432 editor_actions: Rc::default(),
1433 inline_completions_hidden_for_vim_mode: false,
1434 show_inline_completions_override: None,
1435 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1436 edit_prediction_settings: EditPredictionSettings::Disabled,
1437 edit_prediction_cursor_on_leading_whitespace: false,
1438 edit_prediction_requires_modifier_in_leading_space: true,
1439 custom_context_menu: None,
1440 show_git_blame_gutter: false,
1441 show_git_blame_inline: false,
1442 distinguish_unstaged_diff_hunks: false,
1443 show_selection_menu: None,
1444 show_git_blame_inline_delay_task: None,
1445 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1446 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1447 .session
1448 .restore_unsaved_buffers,
1449 blame: None,
1450 blame_subscription: None,
1451 tasks: Default::default(),
1452 _subscriptions: vec![
1453 cx.observe(&buffer, Self::on_buffer_changed),
1454 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1455 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1456 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1457 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1458 cx.observe_window_activation(window, |editor, window, cx| {
1459 let active = window.is_window_active();
1460 editor.blink_manager.update(cx, |blink_manager, cx| {
1461 if active {
1462 blink_manager.enable(cx);
1463 } else {
1464 blink_manager.disable(cx);
1465 }
1466 });
1467 }),
1468 ],
1469 tasks_update_task: None,
1470 linked_edit_ranges: Default::default(),
1471 in_project_search: false,
1472 previous_search_ranges: None,
1473 breadcrumb_header: None,
1474 focused_block: None,
1475 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1476 addons: HashMap::default(),
1477 registered_buffers: HashMap::default(),
1478 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1479 selection_mark_mode: false,
1480 toggle_fold_multiple_buffers: Task::ready(()),
1481 text_style_refinement: None,
1482 load_diff_task: load_uncommitted_diff,
1483 };
1484 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1485 this._subscriptions.extend(project_subscriptions);
1486
1487 this.end_selection(window, cx);
1488 this.scroll_manager.show_scrollbar(window, cx);
1489
1490 if mode == EditorMode::Full {
1491 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1492 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1493
1494 if this.git_blame_inline_enabled {
1495 this.git_blame_inline_enabled = true;
1496 this.start_git_blame_inline(false, window, cx);
1497 }
1498
1499 if let Some(buffer) = buffer.read(cx).as_singleton() {
1500 if let Some(project) = this.project.as_ref() {
1501 let lsp_store = project.read(cx).lsp_store();
1502 let handle = lsp_store.update(cx, |lsp_store, cx| {
1503 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1504 });
1505 this.registered_buffers
1506 .insert(buffer.read(cx).remote_id(), handle);
1507 }
1508 }
1509 }
1510
1511 this.report_editor_event("Editor Opened", None, cx);
1512 this
1513 }
1514
1515 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1516 self.mouse_context_menu
1517 .as_ref()
1518 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1519 }
1520
1521 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1522 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1523 }
1524
1525 fn key_context_internal(
1526 &self,
1527 has_active_edit_prediction: bool,
1528 window: &Window,
1529 cx: &App,
1530 ) -> KeyContext {
1531 let mut key_context = KeyContext::new_with_defaults();
1532 key_context.add("Editor");
1533 let mode = match self.mode {
1534 EditorMode::SingleLine { .. } => "single_line",
1535 EditorMode::AutoHeight { .. } => "auto_height",
1536 EditorMode::Full => "full",
1537 };
1538
1539 if EditorSettings::jupyter_enabled(cx) {
1540 key_context.add("jupyter");
1541 }
1542
1543 key_context.set("mode", mode);
1544 if self.pending_rename.is_some() {
1545 key_context.add("renaming");
1546 }
1547
1548 let mut showing_completions = false;
1549
1550 match self.context_menu.borrow().as_ref() {
1551 Some(CodeContextMenu::Completions(_)) => {
1552 key_context.add("menu");
1553 key_context.add("showing_completions");
1554 showing_completions = true;
1555 }
1556 Some(CodeContextMenu::CodeActions(_)) => {
1557 key_context.add("menu");
1558 key_context.add("showing_code_actions")
1559 }
1560 None => {}
1561 }
1562
1563 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1564 if !self.focus_handle(cx).contains_focused(window, cx)
1565 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1566 {
1567 for addon in self.addons.values() {
1568 addon.extend_key_context(&mut key_context, cx)
1569 }
1570 }
1571
1572 if let Some(extension) = self
1573 .buffer
1574 .read(cx)
1575 .as_singleton()
1576 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1577 {
1578 key_context.set("extension", extension.to_string());
1579 }
1580
1581 if has_active_edit_prediction {
1582 key_context.add("copilot_suggestion");
1583 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1584 if showing_completions
1585 || self.edit_prediction_requires_modifier()
1586 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1587 // bindings to insert tab characters.
1588 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1589 {
1590 key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
1591 }
1592 }
1593
1594 if self.selection_mark_mode {
1595 key_context.add("selection_mode");
1596 }
1597
1598 key_context
1599 }
1600
1601 pub fn accept_edit_prediction_keybind(
1602 &self,
1603 window: &Window,
1604 cx: &App,
1605 ) -> AcceptEditPredictionBinding {
1606 let key_context = self.key_context_internal(true, window, cx);
1607 AcceptEditPredictionBinding(
1608 window
1609 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1610 .into_iter()
1611 .rev()
1612 .next(),
1613 )
1614 }
1615
1616 pub fn new_file(
1617 workspace: &mut Workspace,
1618 _: &workspace::NewFile,
1619 window: &mut Window,
1620 cx: &mut Context<Workspace>,
1621 ) {
1622 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1623 "Failed to create buffer",
1624 window,
1625 cx,
1626 |e, _, _| match e.error_code() {
1627 ErrorCode::RemoteUpgradeRequired => Some(format!(
1628 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1629 e.error_tag("required").unwrap_or("the latest version")
1630 )),
1631 _ => None,
1632 },
1633 );
1634 }
1635
1636 pub fn new_in_workspace(
1637 workspace: &mut Workspace,
1638 window: &mut Window,
1639 cx: &mut Context<Workspace>,
1640 ) -> Task<Result<Entity<Editor>>> {
1641 let project = workspace.project().clone();
1642 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1643
1644 cx.spawn_in(window, |workspace, mut cx| async move {
1645 let buffer = create.await?;
1646 workspace.update_in(&mut cx, |workspace, window, cx| {
1647 let editor =
1648 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1649 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1650 editor
1651 })
1652 })
1653 }
1654
1655 fn new_file_vertical(
1656 workspace: &mut Workspace,
1657 _: &workspace::NewFileSplitVertical,
1658 window: &mut Window,
1659 cx: &mut Context<Workspace>,
1660 ) {
1661 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1662 }
1663
1664 fn new_file_horizontal(
1665 workspace: &mut Workspace,
1666 _: &workspace::NewFileSplitHorizontal,
1667 window: &mut Window,
1668 cx: &mut Context<Workspace>,
1669 ) {
1670 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1671 }
1672
1673 fn new_file_in_direction(
1674 workspace: &mut Workspace,
1675 direction: SplitDirection,
1676 window: &mut Window,
1677 cx: &mut Context<Workspace>,
1678 ) {
1679 let project = workspace.project().clone();
1680 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1681
1682 cx.spawn_in(window, |workspace, mut cx| async move {
1683 let buffer = create.await?;
1684 workspace.update_in(&mut cx, move |workspace, window, cx| {
1685 workspace.split_item(
1686 direction,
1687 Box::new(
1688 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1689 ),
1690 window,
1691 cx,
1692 )
1693 })?;
1694 anyhow::Ok(())
1695 })
1696 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1697 match e.error_code() {
1698 ErrorCode::RemoteUpgradeRequired => Some(format!(
1699 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1700 e.error_tag("required").unwrap_or("the latest version")
1701 )),
1702 _ => None,
1703 }
1704 });
1705 }
1706
1707 pub fn leader_peer_id(&self) -> Option<PeerId> {
1708 self.leader_peer_id
1709 }
1710
1711 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1712 &self.buffer
1713 }
1714
1715 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1716 self.workspace.as_ref()?.0.upgrade()
1717 }
1718
1719 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1720 self.buffer().read(cx).title(cx)
1721 }
1722
1723 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1724 let git_blame_gutter_max_author_length = self
1725 .render_git_blame_gutter(cx)
1726 .then(|| {
1727 if let Some(blame) = self.blame.as_ref() {
1728 let max_author_length =
1729 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1730 Some(max_author_length)
1731 } else {
1732 None
1733 }
1734 })
1735 .flatten();
1736
1737 EditorSnapshot {
1738 mode: self.mode,
1739 show_gutter: self.show_gutter,
1740 show_line_numbers: self.show_line_numbers,
1741 show_git_diff_gutter: self.show_git_diff_gutter,
1742 show_code_actions: self.show_code_actions,
1743 show_runnables: self.show_runnables,
1744 git_blame_gutter_max_author_length,
1745 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1746 scroll_anchor: self.scroll_manager.anchor(),
1747 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1748 placeholder_text: self.placeholder_text.clone(),
1749 is_focused: self.focus_handle.is_focused(window),
1750 current_line_highlight: self
1751 .current_line_highlight
1752 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1753 gutter_hovered: self.gutter_hovered,
1754 }
1755 }
1756
1757 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1758 self.buffer.read(cx).language_at(point, cx)
1759 }
1760
1761 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1762 self.buffer.read(cx).read(cx).file_at(point).cloned()
1763 }
1764
1765 pub fn active_excerpt(
1766 &self,
1767 cx: &App,
1768 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1769 self.buffer
1770 .read(cx)
1771 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1772 }
1773
1774 pub fn mode(&self) -> EditorMode {
1775 self.mode
1776 }
1777
1778 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1779 self.collaboration_hub.as_deref()
1780 }
1781
1782 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1783 self.collaboration_hub = Some(hub);
1784 }
1785
1786 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1787 self.in_project_search = in_project_search;
1788 }
1789
1790 pub fn set_custom_context_menu(
1791 &mut self,
1792 f: impl 'static
1793 + Fn(
1794 &mut Self,
1795 DisplayPoint,
1796 &mut Window,
1797 &mut Context<Self>,
1798 ) -> Option<Entity<ui::ContextMenu>>,
1799 ) {
1800 self.custom_context_menu = Some(Box::new(f))
1801 }
1802
1803 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1804 self.completion_provider = provider;
1805 }
1806
1807 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1808 self.semantics_provider.clone()
1809 }
1810
1811 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1812 self.semantics_provider = provider;
1813 }
1814
1815 pub fn set_edit_prediction_provider<T>(
1816 &mut self,
1817 provider: Option<Entity<T>>,
1818 window: &mut Window,
1819 cx: &mut Context<Self>,
1820 ) where
1821 T: EditPredictionProvider,
1822 {
1823 self.edit_prediction_provider =
1824 provider.map(|provider| RegisteredInlineCompletionProvider {
1825 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1826 if this.focus_handle.is_focused(window) {
1827 this.update_visible_inline_completion(window, cx);
1828 }
1829 }),
1830 provider: Arc::new(provider),
1831 });
1832 self.refresh_inline_completion(false, false, window, cx);
1833 }
1834
1835 pub fn placeholder_text(&self) -> Option<&str> {
1836 self.placeholder_text.as_deref()
1837 }
1838
1839 pub fn set_placeholder_text(
1840 &mut self,
1841 placeholder_text: impl Into<Arc<str>>,
1842 cx: &mut Context<Self>,
1843 ) {
1844 let placeholder_text = Some(placeholder_text.into());
1845 if self.placeholder_text != placeholder_text {
1846 self.placeholder_text = placeholder_text;
1847 cx.notify();
1848 }
1849 }
1850
1851 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1852 self.cursor_shape = cursor_shape;
1853
1854 // Disrupt blink for immediate user feedback that the cursor shape has changed
1855 self.blink_manager.update(cx, BlinkManager::show_cursor);
1856
1857 cx.notify();
1858 }
1859
1860 pub fn set_current_line_highlight(
1861 &mut self,
1862 current_line_highlight: Option<CurrentLineHighlight>,
1863 ) {
1864 self.current_line_highlight = current_line_highlight;
1865 }
1866
1867 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1868 self.collapse_matches = collapse_matches;
1869 }
1870
1871 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1872 let buffers = self.buffer.read(cx).all_buffers();
1873 let Some(lsp_store) = self.lsp_store(cx) else {
1874 return;
1875 };
1876 lsp_store.update(cx, |lsp_store, cx| {
1877 for buffer in buffers {
1878 self.registered_buffers
1879 .entry(buffer.read(cx).remote_id())
1880 .or_insert_with(|| {
1881 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1882 });
1883 }
1884 })
1885 }
1886
1887 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1888 if self.collapse_matches {
1889 return range.start..range.start;
1890 }
1891 range.clone()
1892 }
1893
1894 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1895 if self.display_map.read(cx).clip_at_line_ends != clip {
1896 self.display_map
1897 .update(cx, |map, _| map.clip_at_line_ends = clip);
1898 }
1899 }
1900
1901 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1902 self.input_enabled = input_enabled;
1903 }
1904
1905 pub fn set_inline_completions_hidden_for_vim_mode(
1906 &mut self,
1907 hidden: bool,
1908 window: &mut Window,
1909 cx: &mut Context<Self>,
1910 ) {
1911 if hidden != self.inline_completions_hidden_for_vim_mode {
1912 self.inline_completions_hidden_for_vim_mode = hidden;
1913 if hidden {
1914 self.update_visible_inline_completion(window, cx);
1915 } else {
1916 self.refresh_inline_completion(true, false, window, cx);
1917 }
1918 }
1919 }
1920
1921 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1922 self.menu_inline_completions_policy = value;
1923 }
1924
1925 pub fn set_autoindent(&mut self, autoindent: bool) {
1926 if autoindent {
1927 self.autoindent_mode = Some(AutoindentMode::EachLine);
1928 } else {
1929 self.autoindent_mode = None;
1930 }
1931 }
1932
1933 pub fn read_only(&self, cx: &App) -> bool {
1934 self.read_only || self.buffer.read(cx).read_only()
1935 }
1936
1937 pub fn set_read_only(&mut self, read_only: bool) {
1938 self.read_only = read_only;
1939 }
1940
1941 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1942 self.use_autoclose = autoclose;
1943 }
1944
1945 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1946 self.use_auto_surround = auto_surround;
1947 }
1948
1949 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1950 self.auto_replace_emoji_shortcode = auto_replace;
1951 }
1952
1953 pub fn toggle_inline_completions(
1954 &mut self,
1955 _: &ToggleEditPrediction,
1956 window: &mut Window,
1957 cx: &mut Context<Self>,
1958 ) {
1959 if self.show_inline_completions_override.is_some() {
1960 self.set_show_edit_predictions(None, window, cx);
1961 } else {
1962 let show_edit_predictions = !self.edit_predictions_enabled();
1963 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1964 }
1965 }
1966
1967 pub fn set_show_edit_predictions(
1968 &mut self,
1969 show_edit_predictions: Option<bool>,
1970 window: &mut Window,
1971 cx: &mut Context<Self>,
1972 ) {
1973 self.show_inline_completions_override = show_edit_predictions;
1974 self.refresh_inline_completion(false, true, window, cx);
1975 }
1976
1977 fn inline_completions_disabled_in_scope(
1978 &self,
1979 buffer: &Entity<Buffer>,
1980 buffer_position: language::Anchor,
1981 cx: &App,
1982 ) -> bool {
1983 let snapshot = buffer.read(cx).snapshot();
1984 let settings = snapshot.settings_at(buffer_position, cx);
1985
1986 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1987 return false;
1988 };
1989
1990 scope.override_name().map_or(false, |scope_name| {
1991 settings
1992 .edit_predictions_disabled_in
1993 .iter()
1994 .any(|s| s == scope_name)
1995 })
1996 }
1997
1998 pub fn set_use_modal_editing(&mut self, to: bool) {
1999 self.use_modal_editing = to;
2000 }
2001
2002 pub fn use_modal_editing(&self) -> bool {
2003 self.use_modal_editing
2004 }
2005
2006 fn selections_did_change(
2007 &mut self,
2008 local: bool,
2009 old_cursor_position: &Anchor,
2010 show_completions: bool,
2011 window: &mut Window,
2012 cx: &mut Context<Self>,
2013 ) {
2014 window.invalidate_character_coordinates();
2015
2016 // Copy selections to primary selection buffer
2017 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2018 if local {
2019 let selections = self.selections.all::<usize>(cx);
2020 let buffer_handle = self.buffer.read(cx).read(cx);
2021
2022 let mut text = String::new();
2023 for (index, selection) in selections.iter().enumerate() {
2024 let text_for_selection = buffer_handle
2025 .text_for_range(selection.start..selection.end)
2026 .collect::<String>();
2027
2028 text.push_str(&text_for_selection);
2029 if index != selections.len() - 1 {
2030 text.push('\n');
2031 }
2032 }
2033
2034 if !text.is_empty() {
2035 cx.write_to_primary(ClipboardItem::new_string(text));
2036 }
2037 }
2038
2039 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2040 self.buffer.update(cx, |buffer, cx| {
2041 buffer.set_active_selections(
2042 &self.selections.disjoint_anchors(),
2043 self.selections.line_mode,
2044 self.cursor_shape,
2045 cx,
2046 )
2047 });
2048 }
2049 let display_map = self
2050 .display_map
2051 .update(cx, |display_map, cx| display_map.snapshot(cx));
2052 let buffer = &display_map.buffer_snapshot;
2053 self.add_selections_state = None;
2054 self.select_next_state = None;
2055 self.select_prev_state = None;
2056 self.select_larger_syntax_node_stack.clear();
2057 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2058 self.snippet_stack
2059 .invalidate(&self.selections.disjoint_anchors(), buffer);
2060 self.take_rename(false, window, cx);
2061
2062 let new_cursor_position = self.selections.newest_anchor().head();
2063
2064 self.push_to_nav_history(
2065 *old_cursor_position,
2066 Some(new_cursor_position.to_point(buffer)),
2067 cx,
2068 );
2069
2070 if local {
2071 let new_cursor_position = self.selections.newest_anchor().head();
2072 let mut context_menu = self.context_menu.borrow_mut();
2073 let completion_menu = match context_menu.as_ref() {
2074 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2075 _ => {
2076 *context_menu = None;
2077 None
2078 }
2079 };
2080 if let Some(buffer_id) = new_cursor_position.buffer_id {
2081 if !self.registered_buffers.contains_key(&buffer_id) {
2082 if let Some(lsp_store) = self.lsp_store(cx) {
2083 lsp_store.update(cx, |lsp_store, cx| {
2084 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2085 return;
2086 };
2087 self.registered_buffers.insert(
2088 buffer_id,
2089 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2090 );
2091 })
2092 }
2093 }
2094 }
2095
2096 if let Some(completion_menu) = completion_menu {
2097 let cursor_position = new_cursor_position.to_offset(buffer);
2098 let (word_range, kind) =
2099 buffer.surrounding_word(completion_menu.initial_position, true);
2100 if kind == Some(CharKind::Word)
2101 && word_range.to_inclusive().contains(&cursor_position)
2102 {
2103 let mut completion_menu = completion_menu.clone();
2104 drop(context_menu);
2105
2106 let query = Self::completion_query(buffer, cursor_position);
2107 cx.spawn(move |this, mut cx| async move {
2108 completion_menu
2109 .filter(query.as_deref(), cx.background_executor().clone())
2110 .await;
2111
2112 this.update(&mut cx, |this, cx| {
2113 let mut context_menu = this.context_menu.borrow_mut();
2114 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2115 else {
2116 return;
2117 };
2118
2119 if menu.id > completion_menu.id {
2120 return;
2121 }
2122
2123 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2124 drop(context_menu);
2125 cx.notify();
2126 })
2127 })
2128 .detach();
2129
2130 if show_completions {
2131 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2132 }
2133 } else {
2134 drop(context_menu);
2135 self.hide_context_menu(window, cx);
2136 }
2137 } else {
2138 drop(context_menu);
2139 }
2140
2141 hide_hover(self, cx);
2142
2143 if old_cursor_position.to_display_point(&display_map).row()
2144 != new_cursor_position.to_display_point(&display_map).row()
2145 {
2146 self.available_code_actions.take();
2147 }
2148 self.refresh_code_actions(window, cx);
2149 self.refresh_document_highlights(cx);
2150 refresh_matching_bracket_highlights(self, window, cx);
2151 self.update_visible_inline_completion(window, cx);
2152 self.edit_prediction_requires_modifier_in_leading_space = true;
2153 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2154 if self.git_blame_inline_enabled {
2155 self.start_inline_blame_timer(window, cx);
2156 }
2157 }
2158
2159 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2160 cx.emit(EditorEvent::SelectionsChanged { local });
2161
2162 if self.selections.disjoint_anchors().len() == 1 {
2163 cx.emit(SearchEvent::ActiveMatchChanged)
2164 }
2165 cx.notify();
2166 }
2167
2168 pub fn change_selections<R>(
2169 &mut self,
2170 autoscroll: Option<Autoscroll>,
2171 window: &mut Window,
2172 cx: &mut Context<Self>,
2173 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2174 ) -> R {
2175 self.change_selections_inner(autoscroll, true, window, cx, change)
2176 }
2177
2178 pub fn change_selections_inner<R>(
2179 &mut self,
2180 autoscroll: Option<Autoscroll>,
2181 request_completions: bool,
2182 window: &mut Window,
2183 cx: &mut Context<Self>,
2184 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2185 ) -> R {
2186 let old_cursor_position = self.selections.newest_anchor().head();
2187 self.push_to_selection_history();
2188
2189 let (changed, result) = self.selections.change_with(cx, change);
2190
2191 if changed {
2192 if let Some(autoscroll) = autoscroll {
2193 self.request_autoscroll(autoscroll, cx);
2194 }
2195 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2196
2197 if self.should_open_signature_help_automatically(
2198 &old_cursor_position,
2199 self.signature_help_state.backspace_pressed(),
2200 cx,
2201 ) {
2202 self.show_signature_help(&ShowSignatureHelp, window, cx);
2203 }
2204 self.signature_help_state.set_backspace_pressed(false);
2205 }
2206
2207 result
2208 }
2209
2210 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2211 where
2212 I: IntoIterator<Item = (Range<S>, T)>,
2213 S: ToOffset,
2214 T: Into<Arc<str>>,
2215 {
2216 if self.read_only(cx) {
2217 return;
2218 }
2219
2220 self.buffer
2221 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2222 }
2223
2224 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2225 where
2226 I: IntoIterator<Item = (Range<S>, T)>,
2227 S: ToOffset,
2228 T: Into<Arc<str>>,
2229 {
2230 if self.read_only(cx) {
2231 return;
2232 }
2233
2234 self.buffer.update(cx, |buffer, cx| {
2235 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2236 });
2237 }
2238
2239 pub fn edit_with_block_indent<I, S, T>(
2240 &mut self,
2241 edits: I,
2242 original_indent_columns: Vec<u32>,
2243 cx: &mut Context<Self>,
2244 ) where
2245 I: IntoIterator<Item = (Range<S>, T)>,
2246 S: ToOffset,
2247 T: Into<Arc<str>>,
2248 {
2249 if self.read_only(cx) {
2250 return;
2251 }
2252
2253 self.buffer.update(cx, |buffer, cx| {
2254 buffer.edit(
2255 edits,
2256 Some(AutoindentMode::Block {
2257 original_indent_columns,
2258 }),
2259 cx,
2260 )
2261 });
2262 }
2263
2264 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2265 self.hide_context_menu(window, cx);
2266
2267 match phase {
2268 SelectPhase::Begin {
2269 position,
2270 add,
2271 click_count,
2272 } => self.begin_selection(position, add, click_count, window, cx),
2273 SelectPhase::BeginColumnar {
2274 position,
2275 goal_column,
2276 reset,
2277 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2278 SelectPhase::Extend {
2279 position,
2280 click_count,
2281 } => self.extend_selection(position, click_count, window, cx),
2282 SelectPhase::Update {
2283 position,
2284 goal_column,
2285 scroll_delta,
2286 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2287 SelectPhase::End => self.end_selection(window, cx),
2288 }
2289 }
2290
2291 fn extend_selection(
2292 &mut self,
2293 position: DisplayPoint,
2294 click_count: usize,
2295 window: &mut Window,
2296 cx: &mut Context<Self>,
2297 ) {
2298 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2299 let tail = self.selections.newest::<usize>(cx).tail();
2300 self.begin_selection(position, false, click_count, window, cx);
2301
2302 let position = position.to_offset(&display_map, Bias::Left);
2303 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2304
2305 let mut pending_selection = self
2306 .selections
2307 .pending_anchor()
2308 .expect("extend_selection not called with pending selection");
2309 if position >= tail {
2310 pending_selection.start = tail_anchor;
2311 } else {
2312 pending_selection.end = tail_anchor;
2313 pending_selection.reversed = true;
2314 }
2315
2316 let mut pending_mode = self.selections.pending_mode().unwrap();
2317 match &mut pending_mode {
2318 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2319 _ => {}
2320 }
2321
2322 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2323 s.set_pending(pending_selection, pending_mode)
2324 });
2325 }
2326
2327 fn begin_selection(
2328 &mut self,
2329 position: DisplayPoint,
2330 add: bool,
2331 click_count: usize,
2332 window: &mut Window,
2333 cx: &mut Context<Self>,
2334 ) {
2335 if !self.focus_handle.is_focused(window) {
2336 self.last_focused_descendant = None;
2337 window.focus(&self.focus_handle);
2338 }
2339
2340 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2341 let buffer = &display_map.buffer_snapshot;
2342 let newest_selection = self.selections.newest_anchor().clone();
2343 let position = display_map.clip_point(position, Bias::Left);
2344
2345 let start;
2346 let end;
2347 let mode;
2348 let mut auto_scroll;
2349 match click_count {
2350 1 => {
2351 start = buffer.anchor_before(position.to_point(&display_map));
2352 end = start;
2353 mode = SelectMode::Character;
2354 auto_scroll = true;
2355 }
2356 2 => {
2357 let range = movement::surrounding_word(&display_map, position);
2358 start = buffer.anchor_before(range.start.to_point(&display_map));
2359 end = buffer.anchor_before(range.end.to_point(&display_map));
2360 mode = SelectMode::Word(start..end);
2361 auto_scroll = true;
2362 }
2363 3 => {
2364 let position = display_map
2365 .clip_point(position, Bias::Left)
2366 .to_point(&display_map);
2367 let line_start = display_map.prev_line_boundary(position).0;
2368 let next_line_start = buffer.clip_point(
2369 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2370 Bias::Left,
2371 );
2372 start = buffer.anchor_before(line_start);
2373 end = buffer.anchor_before(next_line_start);
2374 mode = SelectMode::Line(start..end);
2375 auto_scroll = true;
2376 }
2377 _ => {
2378 start = buffer.anchor_before(0);
2379 end = buffer.anchor_before(buffer.len());
2380 mode = SelectMode::All;
2381 auto_scroll = false;
2382 }
2383 }
2384 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2385
2386 let point_to_delete: Option<usize> = {
2387 let selected_points: Vec<Selection<Point>> =
2388 self.selections.disjoint_in_range(start..end, cx);
2389
2390 if !add || click_count > 1 {
2391 None
2392 } else if !selected_points.is_empty() {
2393 Some(selected_points[0].id)
2394 } else {
2395 let clicked_point_already_selected =
2396 self.selections.disjoint.iter().find(|selection| {
2397 selection.start.to_point(buffer) == start.to_point(buffer)
2398 || selection.end.to_point(buffer) == end.to_point(buffer)
2399 });
2400
2401 clicked_point_already_selected.map(|selection| selection.id)
2402 }
2403 };
2404
2405 let selections_count = self.selections.count();
2406
2407 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2408 if let Some(point_to_delete) = point_to_delete {
2409 s.delete(point_to_delete);
2410
2411 if selections_count == 1 {
2412 s.set_pending_anchor_range(start..end, mode);
2413 }
2414 } else {
2415 if !add {
2416 s.clear_disjoint();
2417 } else if click_count > 1 {
2418 s.delete(newest_selection.id)
2419 }
2420
2421 s.set_pending_anchor_range(start..end, mode);
2422 }
2423 });
2424 }
2425
2426 fn begin_columnar_selection(
2427 &mut self,
2428 position: DisplayPoint,
2429 goal_column: u32,
2430 reset: bool,
2431 window: &mut Window,
2432 cx: &mut Context<Self>,
2433 ) {
2434 if !self.focus_handle.is_focused(window) {
2435 self.last_focused_descendant = None;
2436 window.focus(&self.focus_handle);
2437 }
2438
2439 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2440
2441 if reset {
2442 let pointer_position = display_map
2443 .buffer_snapshot
2444 .anchor_before(position.to_point(&display_map));
2445
2446 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2447 s.clear_disjoint();
2448 s.set_pending_anchor_range(
2449 pointer_position..pointer_position,
2450 SelectMode::Character,
2451 );
2452 });
2453 }
2454
2455 let tail = self.selections.newest::<Point>(cx).tail();
2456 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2457
2458 if !reset {
2459 self.select_columns(
2460 tail.to_display_point(&display_map),
2461 position,
2462 goal_column,
2463 &display_map,
2464 window,
2465 cx,
2466 );
2467 }
2468 }
2469
2470 fn update_selection(
2471 &mut self,
2472 position: DisplayPoint,
2473 goal_column: u32,
2474 scroll_delta: gpui::Point<f32>,
2475 window: &mut Window,
2476 cx: &mut Context<Self>,
2477 ) {
2478 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2479
2480 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2481 let tail = tail.to_display_point(&display_map);
2482 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2483 } else if let Some(mut pending) = self.selections.pending_anchor() {
2484 let buffer = self.buffer.read(cx).snapshot(cx);
2485 let head;
2486 let tail;
2487 let mode = self.selections.pending_mode().unwrap();
2488 match &mode {
2489 SelectMode::Character => {
2490 head = position.to_point(&display_map);
2491 tail = pending.tail().to_point(&buffer);
2492 }
2493 SelectMode::Word(original_range) => {
2494 let original_display_range = original_range.start.to_display_point(&display_map)
2495 ..original_range.end.to_display_point(&display_map);
2496 let original_buffer_range = original_display_range.start.to_point(&display_map)
2497 ..original_display_range.end.to_point(&display_map);
2498 if movement::is_inside_word(&display_map, position)
2499 || original_display_range.contains(&position)
2500 {
2501 let word_range = movement::surrounding_word(&display_map, position);
2502 if word_range.start < original_display_range.start {
2503 head = word_range.start.to_point(&display_map);
2504 } else {
2505 head = word_range.end.to_point(&display_map);
2506 }
2507 } else {
2508 head = position.to_point(&display_map);
2509 }
2510
2511 if head <= original_buffer_range.start {
2512 tail = original_buffer_range.end;
2513 } else {
2514 tail = original_buffer_range.start;
2515 }
2516 }
2517 SelectMode::Line(original_range) => {
2518 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2519
2520 let position = display_map
2521 .clip_point(position, Bias::Left)
2522 .to_point(&display_map);
2523 let line_start = display_map.prev_line_boundary(position).0;
2524 let next_line_start = buffer.clip_point(
2525 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2526 Bias::Left,
2527 );
2528
2529 if line_start < original_range.start {
2530 head = line_start
2531 } else {
2532 head = next_line_start
2533 }
2534
2535 if head <= original_range.start {
2536 tail = original_range.end;
2537 } else {
2538 tail = original_range.start;
2539 }
2540 }
2541 SelectMode::All => {
2542 return;
2543 }
2544 };
2545
2546 if head < tail {
2547 pending.start = buffer.anchor_before(head);
2548 pending.end = buffer.anchor_before(tail);
2549 pending.reversed = true;
2550 } else {
2551 pending.start = buffer.anchor_before(tail);
2552 pending.end = buffer.anchor_before(head);
2553 pending.reversed = false;
2554 }
2555
2556 self.change_selections(None, window, cx, |s| {
2557 s.set_pending(pending, mode);
2558 });
2559 } else {
2560 log::error!("update_selection dispatched with no pending selection");
2561 return;
2562 }
2563
2564 self.apply_scroll_delta(scroll_delta, window, cx);
2565 cx.notify();
2566 }
2567
2568 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2569 self.columnar_selection_tail.take();
2570 if self.selections.pending_anchor().is_some() {
2571 let selections = self.selections.all::<usize>(cx);
2572 self.change_selections(None, window, cx, |s| {
2573 s.select(selections);
2574 s.clear_pending();
2575 });
2576 }
2577 }
2578
2579 fn select_columns(
2580 &mut self,
2581 tail: DisplayPoint,
2582 head: DisplayPoint,
2583 goal_column: u32,
2584 display_map: &DisplaySnapshot,
2585 window: &mut Window,
2586 cx: &mut Context<Self>,
2587 ) {
2588 let start_row = cmp::min(tail.row(), head.row());
2589 let end_row = cmp::max(tail.row(), head.row());
2590 let start_column = cmp::min(tail.column(), goal_column);
2591 let end_column = cmp::max(tail.column(), goal_column);
2592 let reversed = start_column < tail.column();
2593
2594 let selection_ranges = (start_row.0..=end_row.0)
2595 .map(DisplayRow)
2596 .filter_map(|row| {
2597 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2598 let start = display_map
2599 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2600 .to_point(display_map);
2601 let end = display_map
2602 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2603 .to_point(display_map);
2604 if reversed {
2605 Some(end..start)
2606 } else {
2607 Some(start..end)
2608 }
2609 } else {
2610 None
2611 }
2612 })
2613 .collect::<Vec<_>>();
2614
2615 self.change_selections(None, window, cx, |s| {
2616 s.select_ranges(selection_ranges);
2617 });
2618 cx.notify();
2619 }
2620
2621 pub fn has_pending_nonempty_selection(&self) -> bool {
2622 let pending_nonempty_selection = match self.selections.pending_anchor() {
2623 Some(Selection { start, end, .. }) => start != end,
2624 None => false,
2625 };
2626
2627 pending_nonempty_selection
2628 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2629 }
2630
2631 pub fn has_pending_selection(&self) -> bool {
2632 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2633 }
2634
2635 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2636 self.selection_mark_mode = false;
2637
2638 if self.clear_expanded_diff_hunks(cx) {
2639 cx.notify();
2640 return;
2641 }
2642 if self.dismiss_menus_and_popups(true, window, cx) {
2643 return;
2644 }
2645
2646 if self.mode == EditorMode::Full
2647 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2648 {
2649 return;
2650 }
2651
2652 cx.propagate();
2653 }
2654
2655 pub fn dismiss_menus_and_popups(
2656 &mut self,
2657 is_user_requested: bool,
2658 window: &mut Window,
2659 cx: &mut Context<Self>,
2660 ) -> bool {
2661 if self.take_rename(false, window, cx).is_some() {
2662 return true;
2663 }
2664
2665 if hide_hover(self, cx) {
2666 return true;
2667 }
2668
2669 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2670 return true;
2671 }
2672
2673 if self.hide_context_menu(window, cx).is_some() {
2674 return true;
2675 }
2676
2677 if self.mouse_context_menu.take().is_some() {
2678 return true;
2679 }
2680
2681 if is_user_requested && self.discard_inline_completion(true, cx) {
2682 return true;
2683 }
2684
2685 if self.snippet_stack.pop().is_some() {
2686 return true;
2687 }
2688
2689 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2690 self.dismiss_diagnostics(cx);
2691 return true;
2692 }
2693
2694 false
2695 }
2696
2697 fn linked_editing_ranges_for(
2698 &self,
2699 selection: Range<text::Anchor>,
2700 cx: &App,
2701 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2702 if self.linked_edit_ranges.is_empty() {
2703 return None;
2704 }
2705 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2706 selection.end.buffer_id.and_then(|end_buffer_id| {
2707 if selection.start.buffer_id != Some(end_buffer_id) {
2708 return None;
2709 }
2710 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2711 let snapshot = buffer.read(cx).snapshot();
2712 self.linked_edit_ranges
2713 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2714 .map(|ranges| (ranges, snapshot, buffer))
2715 })?;
2716 use text::ToOffset as TO;
2717 // find offset from the start of current range to current cursor position
2718 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2719
2720 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2721 let start_difference = start_offset - start_byte_offset;
2722 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2723 let end_difference = end_offset - start_byte_offset;
2724 // Current range has associated linked ranges.
2725 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2726 for range in linked_ranges.iter() {
2727 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2728 let end_offset = start_offset + end_difference;
2729 let start_offset = start_offset + start_difference;
2730 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2731 continue;
2732 }
2733 if self.selections.disjoint_anchor_ranges().any(|s| {
2734 if s.start.buffer_id != selection.start.buffer_id
2735 || s.end.buffer_id != selection.end.buffer_id
2736 {
2737 return false;
2738 }
2739 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2740 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2741 }) {
2742 continue;
2743 }
2744 let start = buffer_snapshot.anchor_after(start_offset);
2745 let end = buffer_snapshot.anchor_after(end_offset);
2746 linked_edits
2747 .entry(buffer.clone())
2748 .or_default()
2749 .push(start..end);
2750 }
2751 Some(linked_edits)
2752 }
2753
2754 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2755 let text: Arc<str> = text.into();
2756
2757 if self.read_only(cx) {
2758 return;
2759 }
2760
2761 let selections = self.selections.all_adjusted(cx);
2762 let mut bracket_inserted = false;
2763 let mut edits = Vec::new();
2764 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2765 let mut new_selections = Vec::with_capacity(selections.len());
2766 let mut new_autoclose_regions = Vec::new();
2767 let snapshot = self.buffer.read(cx).read(cx);
2768
2769 for (selection, autoclose_region) in
2770 self.selections_with_autoclose_regions(selections, &snapshot)
2771 {
2772 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2773 // Determine if the inserted text matches the opening or closing
2774 // bracket of any of this language's bracket pairs.
2775 let mut bracket_pair = None;
2776 let mut is_bracket_pair_start = false;
2777 let mut is_bracket_pair_end = false;
2778 if !text.is_empty() {
2779 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2780 // and they are removing the character that triggered IME popup.
2781 for (pair, enabled) in scope.brackets() {
2782 if !pair.close && !pair.surround {
2783 continue;
2784 }
2785
2786 if enabled && pair.start.ends_with(text.as_ref()) {
2787 let prefix_len = pair.start.len() - text.len();
2788 let preceding_text_matches_prefix = prefix_len == 0
2789 || (selection.start.column >= (prefix_len as u32)
2790 && snapshot.contains_str_at(
2791 Point::new(
2792 selection.start.row,
2793 selection.start.column - (prefix_len as u32),
2794 ),
2795 &pair.start[..prefix_len],
2796 ));
2797 if preceding_text_matches_prefix {
2798 bracket_pair = Some(pair.clone());
2799 is_bracket_pair_start = true;
2800 break;
2801 }
2802 }
2803 if pair.end.as_str() == text.as_ref() {
2804 bracket_pair = Some(pair.clone());
2805 is_bracket_pair_end = true;
2806 break;
2807 }
2808 }
2809 }
2810
2811 if let Some(bracket_pair) = bracket_pair {
2812 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2813 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2814 let auto_surround =
2815 self.use_auto_surround && snapshot_settings.use_auto_surround;
2816 if selection.is_empty() {
2817 if is_bracket_pair_start {
2818 // If the inserted text is a suffix of an opening bracket and the
2819 // selection is preceded by the rest of the opening bracket, then
2820 // insert the closing bracket.
2821 let following_text_allows_autoclose = snapshot
2822 .chars_at(selection.start)
2823 .next()
2824 .map_or(true, |c| scope.should_autoclose_before(c));
2825
2826 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2827 && bracket_pair.start.len() == 1
2828 {
2829 let target = bracket_pair.start.chars().next().unwrap();
2830 let current_line_count = snapshot
2831 .reversed_chars_at(selection.start)
2832 .take_while(|&c| c != '\n')
2833 .filter(|&c| c == target)
2834 .count();
2835 current_line_count % 2 == 1
2836 } else {
2837 false
2838 };
2839
2840 if autoclose
2841 && bracket_pair.close
2842 && following_text_allows_autoclose
2843 && !is_closing_quote
2844 {
2845 let anchor = snapshot.anchor_before(selection.end);
2846 new_selections.push((selection.map(|_| anchor), text.len()));
2847 new_autoclose_regions.push((
2848 anchor,
2849 text.len(),
2850 selection.id,
2851 bracket_pair.clone(),
2852 ));
2853 edits.push((
2854 selection.range(),
2855 format!("{}{}", text, bracket_pair.end).into(),
2856 ));
2857 bracket_inserted = true;
2858 continue;
2859 }
2860 }
2861
2862 if let Some(region) = autoclose_region {
2863 // If the selection is followed by an auto-inserted closing bracket,
2864 // then don't insert that closing bracket again; just move the selection
2865 // past the closing bracket.
2866 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2867 && text.as_ref() == region.pair.end.as_str();
2868 if should_skip {
2869 let anchor = snapshot.anchor_after(selection.end);
2870 new_selections
2871 .push((selection.map(|_| anchor), region.pair.end.len()));
2872 continue;
2873 }
2874 }
2875
2876 let always_treat_brackets_as_autoclosed = snapshot
2877 .settings_at(selection.start, cx)
2878 .always_treat_brackets_as_autoclosed;
2879 if always_treat_brackets_as_autoclosed
2880 && is_bracket_pair_end
2881 && snapshot.contains_str_at(selection.end, text.as_ref())
2882 {
2883 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2884 // and the inserted text is a closing bracket and the selection is followed
2885 // by the closing bracket then move the selection past the closing bracket.
2886 let anchor = snapshot.anchor_after(selection.end);
2887 new_selections.push((selection.map(|_| anchor), text.len()));
2888 continue;
2889 }
2890 }
2891 // If an opening bracket is 1 character long and is typed while
2892 // text is selected, then surround that text with the bracket pair.
2893 else if auto_surround
2894 && bracket_pair.surround
2895 && is_bracket_pair_start
2896 && bracket_pair.start.chars().count() == 1
2897 {
2898 edits.push((selection.start..selection.start, text.clone()));
2899 edits.push((
2900 selection.end..selection.end,
2901 bracket_pair.end.as_str().into(),
2902 ));
2903 bracket_inserted = true;
2904 new_selections.push((
2905 Selection {
2906 id: selection.id,
2907 start: snapshot.anchor_after(selection.start),
2908 end: snapshot.anchor_before(selection.end),
2909 reversed: selection.reversed,
2910 goal: selection.goal,
2911 },
2912 0,
2913 ));
2914 continue;
2915 }
2916 }
2917 }
2918
2919 if self.auto_replace_emoji_shortcode
2920 && selection.is_empty()
2921 && text.as_ref().ends_with(':')
2922 {
2923 if let Some(possible_emoji_short_code) =
2924 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2925 {
2926 if !possible_emoji_short_code.is_empty() {
2927 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2928 let emoji_shortcode_start = Point::new(
2929 selection.start.row,
2930 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2931 );
2932
2933 // Remove shortcode from buffer
2934 edits.push((
2935 emoji_shortcode_start..selection.start,
2936 "".to_string().into(),
2937 ));
2938 new_selections.push((
2939 Selection {
2940 id: selection.id,
2941 start: snapshot.anchor_after(emoji_shortcode_start),
2942 end: snapshot.anchor_before(selection.start),
2943 reversed: selection.reversed,
2944 goal: selection.goal,
2945 },
2946 0,
2947 ));
2948
2949 // Insert emoji
2950 let selection_start_anchor = snapshot.anchor_after(selection.start);
2951 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2952 edits.push((selection.start..selection.end, emoji.to_string().into()));
2953
2954 continue;
2955 }
2956 }
2957 }
2958 }
2959
2960 // If not handling any auto-close operation, then just replace the selected
2961 // text with the given input and move the selection to the end of the
2962 // newly inserted text.
2963 let anchor = snapshot.anchor_after(selection.end);
2964 if !self.linked_edit_ranges.is_empty() {
2965 let start_anchor = snapshot.anchor_before(selection.start);
2966
2967 let is_word_char = text.chars().next().map_or(true, |char| {
2968 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2969 classifier.is_word(char)
2970 });
2971
2972 if is_word_char {
2973 if let Some(ranges) = self
2974 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2975 {
2976 for (buffer, edits) in ranges {
2977 linked_edits
2978 .entry(buffer.clone())
2979 .or_default()
2980 .extend(edits.into_iter().map(|range| (range, text.clone())));
2981 }
2982 }
2983 }
2984 }
2985
2986 new_selections.push((selection.map(|_| anchor), 0));
2987 edits.push((selection.start..selection.end, text.clone()));
2988 }
2989
2990 drop(snapshot);
2991
2992 self.transact(window, cx, |this, window, cx| {
2993 this.buffer.update(cx, |buffer, cx| {
2994 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2995 });
2996 for (buffer, edits) in linked_edits {
2997 buffer.update(cx, |buffer, cx| {
2998 let snapshot = buffer.snapshot();
2999 let edits = edits
3000 .into_iter()
3001 .map(|(range, text)| {
3002 use text::ToPoint as TP;
3003 let end_point = TP::to_point(&range.end, &snapshot);
3004 let start_point = TP::to_point(&range.start, &snapshot);
3005 (start_point..end_point, text)
3006 })
3007 .sorted_by_key(|(range, _)| range.start)
3008 .collect::<Vec<_>>();
3009 buffer.edit(edits, None, cx);
3010 })
3011 }
3012 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3013 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3014 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3015 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3016 .zip(new_selection_deltas)
3017 .map(|(selection, delta)| Selection {
3018 id: selection.id,
3019 start: selection.start + delta,
3020 end: selection.end + delta,
3021 reversed: selection.reversed,
3022 goal: SelectionGoal::None,
3023 })
3024 .collect::<Vec<_>>();
3025
3026 let mut i = 0;
3027 for (position, delta, selection_id, pair) in new_autoclose_regions {
3028 let position = position.to_offset(&map.buffer_snapshot) + delta;
3029 let start = map.buffer_snapshot.anchor_before(position);
3030 let end = map.buffer_snapshot.anchor_after(position);
3031 while let Some(existing_state) = this.autoclose_regions.get(i) {
3032 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3033 Ordering::Less => i += 1,
3034 Ordering::Greater => break,
3035 Ordering::Equal => {
3036 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3037 Ordering::Less => i += 1,
3038 Ordering::Equal => break,
3039 Ordering::Greater => break,
3040 }
3041 }
3042 }
3043 }
3044 this.autoclose_regions.insert(
3045 i,
3046 AutocloseRegion {
3047 selection_id,
3048 range: start..end,
3049 pair,
3050 },
3051 );
3052 }
3053
3054 let had_active_inline_completion = this.has_active_inline_completion();
3055 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3056 s.select(new_selections)
3057 });
3058
3059 if !bracket_inserted {
3060 if let Some(on_type_format_task) =
3061 this.trigger_on_type_formatting(text.to_string(), window, cx)
3062 {
3063 on_type_format_task.detach_and_log_err(cx);
3064 }
3065 }
3066
3067 let editor_settings = EditorSettings::get_global(cx);
3068 if bracket_inserted
3069 && (editor_settings.auto_signature_help
3070 || editor_settings.show_signature_help_after_edits)
3071 {
3072 this.show_signature_help(&ShowSignatureHelp, window, cx);
3073 }
3074
3075 let trigger_in_words =
3076 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3077 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3078 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3079 this.refresh_inline_completion(true, false, window, cx);
3080 });
3081 }
3082
3083 fn find_possible_emoji_shortcode_at_position(
3084 snapshot: &MultiBufferSnapshot,
3085 position: Point,
3086 ) -> Option<String> {
3087 let mut chars = Vec::new();
3088 let mut found_colon = false;
3089 for char in snapshot.reversed_chars_at(position).take(100) {
3090 // Found a possible emoji shortcode in the middle of the buffer
3091 if found_colon {
3092 if char.is_whitespace() {
3093 chars.reverse();
3094 return Some(chars.iter().collect());
3095 }
3096 // If the previous character is not a whitespace, we are in the middle of a word
3097 // and we only want to complete the shortcode if the word is made up of other emojis
3098 let mut containing_word = String::new();
3099 for ch in snapshot
3100 .reversed_chars_at(position)
3101 .skip(chars.len() + 1)
3102 .take(100)
3103 {
3104 if ch.is_whitespace() {
3105 break;
3106 }
3107 containing_word.push(ch);
3108 }
3109 let containing_word = containing_word.chars().rev().collect::<String>();
3110 if util::word_consists_of_emojis(containing_word.as_str()) {
3111 chars.reverse();
3112 return Some(chars.iter().collect());
3113 }
3114 }
3115
3116 if char.is_whitespace() || !char.is_ascii() {
3117 return None;
3118 }
3119 if char == ':' {
3120 found_colon = true;
3121 } else {
3122 chars.push(char);
3123 }
3124 }
3125 // Found a possible emoji shortcode at the beginning of the buffer
3126 chars.reverse();
3127 Some(chars.iter().collect())
3128 }
3129
3130 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3131 self.transact(window, cx, |this, window, cx| {
3132 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3133 let selections = this.selections.all::<usize>(cx);
3134 let multi_buffer = this.buffer.read(cx);
3135 let buffer = multi_buffer.snapshot(cx);
3136 selections
3137 .iter()
3138 .map(|selection| {
3139 let start_point = selection.start.to_point(&buffer);
3140 let mut indent =
3141 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3142 indent.len = cmp::min(indent.len, start_point.column);
3143 let start = selection.start;
3144 let end = selection.end;
3145 let selection_is_empty = start == end;
3146 let language_scope = buffer.language_scope_at(start);
3147 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3148 &language_scope
3149 {
3150 let leading_whitespace_len = buffer
3151 .reversed_chars_at(start)
3152 .take_while(|c| c.is_whitespace() && *c != '\n')
3153 .map(|c| c.len_utf8())
3154 .sum::<usize>();
3155
3156 let trailing_whitespace_len = buffer
3157 .chars_at(end)
3158 .take_while(|c| c.is_whitespace() && *c != '\n')
3159 .map(|c| c.len_utf8())
3160 .sum::<usize>();
3161
3162 let insert_extra_newline =
3163 language.brackets().any(|(pair, enabled)| {
3164 let pair_start = pair.start.trim_end();
3165 let pair_end = pair.end.trim_start();
3166
3167 enabled
3168 && pair.newline
3169 && buffer.contains_str_at(
3170 end + trailing_whitespace_len,
3171 pair_end,
3172 )
3173 && buffer.contains_str_at(
3174 (start - leading_whitespace_len)
3175 .saturating_sub(pair_start.len()),
3176 pair_start,
3177 )
3178 });
3179
3180 // Comment extension on newline is allowed only for cursor selections
3181 let comment_delimiter = maybe!({
3182 if !selection_is_empty {
3183 return None;
3184 }
3185
3186 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3187 return None;
3188 }
3189
3190 let delimiters = language.line_comment_prefixes();
3191 let max_len_of_delimiter =
3192 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3193 let (snapshot, range) =
3194 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3195
3196 let mut index_of_first_non_whitespace = 0;
3197 let comment_candidate = snapshot
3198 .chars_for_range(range)
3199 .skip_while(|c| {
3200 let should_skip = c.is_whitespace();
3201 if should_skip {
3202 index_of_first_non_whitespace += 1;
3203 }
3204 should_skip
3205 })
3206 .take(max_len_of_delimiter)
3207 .collect::<String>();
3208 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3209 comment_candidate.starts_with(comment_prefix.as_ref())
3210 })?;
3211 let cursor_is_placed_after_comment_marker =
3212 index_of_first_non_whitespace + comment_prefix.len()
3213 <= start_point.column as usize;
3214 if cursor_is_placed_after_comment_marker {
3215 Some(comment_prefix.clone())
3216 } else {
3217 None
3218 }
3219 });
3220 (comment_delimiter, insert_extra_newline)
3221 } else {
3222 (None, false)
3223 };
3224
3225 let capacity_for_delimiter = comment_delimiter
3226 .as_deref()
3227 .map(str::len)
3228 .unwrap_or_default();
3229 let mut new_text =
3230 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3231 new_text.push('\n');
3232 new_text.extend(indent.chars());
3233 if let Some(delimiter) = &comment_delimiter {
3234 new_text.push_str(delimiter);
3235 }
3236 if insert_extra_newline {
3237 new_text = new_text.repeat(2);
3238 }
3239
3240 let anchor = buffer.anchor_after(end);
3241 let new_selection = selection.map(|_| anchor);
3242 (
3243 (start..end, new_text),
3244 (insert_extra_newline, new_selection),
3245 )
3246 })
3247 .unzip()
3248 };
3249
3250 this.edit_with_autoindent(edits, cx);
3251 let buffer = this.buffer.read(cx).snapshot(cx);
3252 let new_selections = selection_fixup_info
3253 .into_iter()
3254 .map(|(extra_newline_inserted, new_selection)| {
3255 let mut cursor = new_selection.end.to_point(&buffer);
3256 if extra_newline_inserted {
3257 cursor.row -= 1;
3258 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3259 }
3260 new_selection.map(|_| cursor)
3261 })
3262 .collect();
3263
3264 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3265 s.select(new_selections)
3266 });
3267 this.refresh_inline_completion(true, false, window, cx);
3268 });
3269 }
3270
3271 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3272 let buffer = self.buffer.read(cx);
3273 let snapshot = buffer.snapshot(cx);
3274
3275 let mut edits = Vec::new();
3276 let mut rows = Vec::new();
3277
3278 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3279 let cursor = selection.head();
3280 let row = cursor.row;
3281
3282 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3283
3284 let newline = "\n".to_string();
3285 edits.push((start_of_line..start_of_line, newline));
3286
3287 rows.push(row + rows_inserted as u32);
3288 }
3289
3290 self.transact(window, cx, |editor, window, cx| {
3291 editor.edit(edits, cx);
3292
3293 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3294 let mut index = 0;
3295 s.move_cursors_with(|map, _, _| {
3296 let row = rows[index];
3297 index += 1;
3298
3299 let point = Point::new(row, 0);
3300 let boundary = map.next_line_boundary(point).1;
3301 let clipped = map.clip_point(boundary, Bias::Left);
3302
3303 (clipped, SelectionGoal::None)
3304 });
3305 });
3306
3307 let mut indent_edits = Vec::new();
3308 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3309 for row in rows {
3310 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3311 for (row, indent) in indents {
3312 if indent.len == 0 {
3313 continue;
3314 }
3315
3316 let text = match indent.kind {
3317 IndentKind::Space => " ".repeat(indent.len as usize),
3318 IndentKind::Tab => "\t".repeat(indent.len as usize),
3319 };
3320 let point = Point::new(row.0, 0);
3321 indent_edits.push((point..point, text));
3322 }
3323 }
3324 editor.edit(indent_edits, cx);
3325 });
3326 }
3327
3328 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3329 let buffer = self.buffer.read(cx);
3330 let snapshot = buffer.snapshot(cx);
3331
3332 let mut edits = Vec::new();
3333 let mut rows = Vec::new();
3334 let mut rows_inserted = 0;
3335
3336 for selection in self.selections.all_adjusted(cx) {
3337 let cursor = selection.head();
3338 let row = cursor.row;
3339
3340 let point = Point::new(row + 1, 0);
3341 let start_of_line = snapshot.clip_point(point, Bias::Left);
3342
3343 let newline = "\n".to_string();
3344 edits.push((start_of_line..start_of_line, newline));
3345
3346 rows_inserted += 1;
3347 rows.push(row + rows_inserted);
3348 }
3349
3350 self.transact(window, cx, |editor, window, cx| {
3351 editor.edit(edits, cx);
3352
3353 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3354 let mut index = 0;
3355 s.move_cursors_with(|map, _, _| {
3356 let row = rows[index];
3357 index += 1;
3358
3359 let point = Point::new(row, 0);
3360 let boundary = map.next_line_boundary(point).1;
3361 let clipped = map.clip_point(boundary, Bias::Left);
3362
3363 (clipped, SelectionGoal::None)
3364 });
3365 });
3366
3367 let mut indent_edits = Vec::new();
3368 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3369 for row in rows {
3370 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3371 for (row, indent) in indents {
3372 if indent.len == 0 {
3373 continue;
3374 }
3375
3376 let text = match indent.kind {
3377 IndentKind::Space => " ".repeat(indent.len as usize),
3378 IndentKind::Tab => "\t".repeat(indent.len as usize),
3379 };
3380 let point = Point::new(row.0, 0);
3381 indent_edits.push((point..point, text));
3382 }
3383 }
3384 editor.edit(indent_edits, cx);
3385 });
3386 }
3387
3388 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3389 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3390 original_indent_columns: Vec::new(),
3391 });
3392 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3393 }
3394
3395 fn insert_with_autoindent_mode(
3396 &mut self,
3397 text: &str,
3398 autoindent_mode: Option<AutoindentMode>,
3399 window: &mut Window,
3400 cx: &mut Context<Self>,
3401 ) {
3402 if self.read_only(cx) {
3403 return;
3404 }
3405
3406 let text: Arc<str> = text.into();
3407 self.transact(window, cx, |this, window, cx| {
3408 let old_selections = this.selections.all_adjusted(cx);
3409 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3410 let anchors = {
3411 let snapshot = buffer.read(cx);
3412 old_selections
3413 .iter()
3414 .map(|s| {
3415 let anchor = snapshot.anchor_after(s.head());
3416 s.map(|_| anchor)
3417 })
3418 .collect::<Vec<_>>()
3419 };
3420 buffer.edit(
3421 old_selections
3422 .iter()
3423 .map(|s| (s.start..s.end, text.clone())),
3424 autoindent_mode,
3425 cx,
3426 );
3427 anchors
3428 });
3429
3430 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3431 s.select_anchors(selection_anchors);
3432 });
3433
3434 cx.notify();
3435 });
3436 }
3437
3438 fn trigger_completion_on_input(
3439 &mut self,
3440 text: &str,
3441 trigger_in_words: bool,
3442 window: &mut Window,
3443 cx: &mut Context<Self>,
3444 ) {
3445 if self.is_completion_trigger(text, trigger_in_words, cx) {
3446 self.show_completions(
3447 &ShowCompletions {
3448 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3449 },
3450 window,
3451 cx,
3452 );
3453 } else {
3454 self.hide_context_menu(window, cx);
3455 }
3456 }
3457
3458 fn is_completion_trigger(
3459 &self,
3460 text: &str,
3461 trigger_in_words: bool,
3462 cx: &mut Context<Self>,
3463 ) -> bool {
3464 let position = self.selections.newest_anchor().head();
3465 let multibuffer = self.buffer.read(cx);
3466 let Some(buffer) = position
3467 .buffer_id
3468 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3469 else {
3470 return false;
3471 };
3472
3473 if let Some(completion_provider) = &self.completion_provider {
3474 completion_provider.is_completion_trigger(
3475 &buffer,
3476 position.text_anchor,
3477 text,
3478 trigger_in_words,
3479 cx,
3480 )
3481 } else {
3482 false
3483 }
3484 }
3485
3486 /// If any empty selections is touching the start of its innermost containing autoclose
3487 /// region, expand it to select the brackets.
3488 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3489 let selections = self.selections.all::<usize>(cx);
3490 let buffer = self.buffer.read(cx).read(cx);
3491 let new_selections = self
3492 .selections_with_autoclose_regions(selections, &buffer)
3493 .map(|(mut selection, region)| {
3494 if !selection.is_empty() {
3495 return selection;
3496 }
3497
3498 if let Some(region) = region {
3499 let mut range = region.range.to_offset(&buffer);
3500 if selection.start == range.start && range.start >= region.pair.start.len() {
3501 range.start -= region.pair.start.len();
3502 if buffer.contains_str_at(range.start, ®ion.pair.start)
3503 && buffer.contains_str_at(range.end, ®ion.pair.end)
3504 {
3505 range.end += region.pair.end.len();
3506 selection.start = range.start;
3507 selection.end = range.end;
3508
3509 return selection;
3510 }
3511 }
3512 }
3513
3514 let always_treat_brackets_as_autoclosed = buffer
3515 .settings_at(selection.start, cx)
3516 .always_treat_brackets_as_autoclosed;
3517
3518 if !always_treat_brackets_as_autoclosed {
3519 return selection;
3520 }
3521
3522 if let Some(scope) = buffer.language_scope_at(selection.start) {
3523 for (pair, enabled) in scope.brackets() {
3524 if !enabled || !pair.close {
3525 continue;
3526 }
3527
3528 if buffer.contains_str_at(selection.start, &pair.end) {
3529 let pair_start_len = pair.start.len();
3530 if buffer.contains_str_at(
3531 selection.start.saturating_sub(pair_start_len),
3532 &pair.start,
3533 ) {
3534 selection.start -= pair_start_len;
3535 selection.end += pair.end.len();
3536
3537 return selection;
3538 }
3539 }
3540 }
3541 }
3542
3543 selection
3544 })
3545 .collect();
3546
3547 drop(buffer);
3548 self.change_selections(None, window, cx, |selections| {
3549 selections.select(new_selections)
3550 });
3551 }
3552
3553 /// Iterate the given selections, and for each one, find the smallest surrounding
3554 /// autoclose region. This uses the ordering of the selections and the autoclose
3555 /// regions to avoid repeated comparisons.
3556 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3557 &'a self,
3558 selections: impl IntoIterator<Item = Selection<D>>,
3559 buffer: &'a MultiBufferSnapshot,
3560 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3561 let mut i = 0;
3562 let mut regions = self.autoclose_regions.as_slice();
3563 selections.into_iter().map(move |selection| {
3564 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3565
3566 let mut enclosing = None;
3567 while let Some(pair_state) = regions.get(i) {
3568 if pair_state.range.end.to_offset(buffer) < range.start {
3569 regions = ®ions[i + 1..];
3570 i = 0;
3571 } else if pair_state.range.start.to_offset(buffer) > range.end {
3572 break;
3573 } else {
3574 if pair_state.selection_id == selection.id {
3575 enclosing = Some(pair_state);
3576 }
3577 i += 1;
3578 }
3579 }
3580
3581 (selection, enclosing)
3582 })
3583 }
3584
3585 /// Remove any autoclose regions that no longer contain their selection.
3586 fn invalidate_autoclose_regions(
3587 &mut self,
3588 mut selections: &[Selection<Anchor>],
3589 buffer: &MultiBufferSnapshot,
3590 ) {
3591 self.autoclose_regions.retain(|state| {
3592 let mut i = 0;
3593 while let Some(selection) = selections.get(i) {
3594 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3595 selections = &selections[1..];
3596 continue;
3597 }
3598 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3599 break;
3600 }
3601 if selection.id == state.selection_id {
3602 return true;
3603 } else {
3604 i += 1;
3605 }
3606 }
3607 false
3608 });
3609 }
3610
3611 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3612 let offset = position.to_offset(buffer);
3613 let (word_range, kind) = buffer.surrounding_word(offset, true);
3614 if offset > word_range.start && kind == Some(CharKind::Word) {
3615 Some(
3616 buffer
3617 .text_for_range(word_range.start..offset)
3618 .collect::<String>(),
3619 )
3620 } else {
3621 None
3622 }
3623 }
3624
3625 pub fn toggle_inlay_hints(
3626 &mut self,
3627 _: &ToggleInlayHints,
3628 _: &mut Window,
3629 cx: &mut Context<Self>,
3630 ) {
3631 self.refresh_inlay_hints(
3632 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3633 cx,
3634 );
3635 }
3636
3637 pub fn inlay_hints_enabled(&self) -> bool {
3638 self.inlay_hint_cache.enabled
3639 }
3640
3641 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3642 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3643 return;
3644 }
3645
3646 let reason_description = reason.description();
3647 let ignore_debounce = matches!(
3648 reason,
3649 InlayHintRefreshReason::SettingsChange(_)
3650 | InlayHintRefreshReason::Toggle(_)
3651 | InlayHintRefreshReason::ExcerptsRemoved(_)
3652 );
3653 let (invalidate_cache, required_languages) = match reason {
3654 InlayHintRefreshReason::Toggle(enabled) => {
3655 self.inlay_hint_cache.enabled = enabled;
3656 if enabled {
3657 (InvalidationStrategy::RefreshRequested, None)
3658 } else {
3659 self.inlay_hint_cache.clear();
3660 self.splice_inlays(
3661 &self
3662 .visible_inlay_hints(cx)
3663 .iter()
3664 .map(|inlay| inlay.id)
3665 .collect::<Vec<InlayId>>(),
3666 Vec::new(),
3667 cx,
3668 );
3669 return;
3670 }
3671 }
3672 InlayHintRefreshReason::SettingsChange(new_settings) => {
3673 match self.inlay_hint_cache.update_settings(
3674 &self.buffer,
3675 new_settings,
3676 self.visible_inlay_hints(cx),
3677 cx,
3678 ) {
3679 ControlFlow::Break(Some(InlaySplice {
3680 to_remove,
3681 to_insert,
3682 })) => {
3683 self.splice_inlays(&to_remove, to_insert, cx);
3684 return;
3685 }
3686 ControlFlow::Break(None) => return,
3687 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3688 }
3689 }
3690 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3691 if let Some(InlaySplice {
3692 to_remove,
3693 to_insert,
3694 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3695 {
3696 self.splice_inlays(&to_remove, to_insert, cx);
3697 }
3698 return;
3699 }
3700 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3701 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3702 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3703 }
3704 InlayHintRefreshReason::RefreshRequested => {
3705 (InvalidationStrategy::RefreshRequested, None)
3706 }
3707 };
3708
3709 if let Some(InlaySplice {
3710 to_remove,
3711 to_insert,
3712 }) = self.inlay_hint_cache.spawn_hint_refresh(
3713 reason_description,
3714 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3715 invalidate_cache,
3716 ignore_debounce,
3717 cx,
3718 ) {
3719 self.splice_inlays(&to_remove, to_insert, cx);
3720 }
3721 }
3722
3723 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3724 self.display_map
3725 .read(cx)
3726 .current_inlays()
3727 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3728 .cloned()
3729 .collect()
3730 }
3731
3732 pub fn excerpts_for_inlay_hints_query(
3733 &self,
3734 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3735 cx: &mut Context<Editor>,
3736 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3737 let Some(project) = self.project.as_ref() else {
3738 return HashMap::default();
3739 };
3740 let project = project.read(cx);
3741 let multi_buffer = self.buffer().read(cx);
3742 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3743 let multi_buffer_visible_start = self
3744 .scroll_manager
3745 .anchor()
3746 .anchor
3747 .to_point(&multi_buffer_snapshot);
3748 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3749 multi_buffer_visible_start
3750 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3751 Bias::Left,
3752 );
3753 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3754 multi_buffer_snapshot
3755 .range_to_buffer_ranges(multi_buffer_visible_range)
3756 .into_iter()
3757 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3758 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3759 let buffer_file = project::File::from_dyn(buffer.file())?;
3760 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3761 let worktree_entry = buffer_worktree
3762 .read(cx)
3763 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3764 if worktree_entry.is_ignored {
3765 return None;
3766 }
3767
3768 let language = buffer.language()?;
3769 if let Some(restrict_to_languages) = restrict_to_languages {
3770 if !restrict_to_languages.contains(language) {
3771 return None;
3772 }
3773 }
3774 Some((
3775 excerpt_id,
3776 (
3777 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3778 buffer.version().clone(),
3779 excerpt_visible_range,
3780 ),
3781 ))
3782 })
3783 .collect()
3784 }
3785
3786 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3787 TextLayoutDetails {
3788 text_system: window.text_system().clone(),
3789 editor_style: self.style.clone().unwrap(),
3790 rem_size: window.rem_size(),
3791 scroll_anchor: self.scroll_manager.anchor(),
3792 visible_rows: self.visible_line_count(),
3793 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3794 }
3795 }
3796
3797 pub fn splice_inlays(
3798 &self,
3799 to_remove: &[InlayId],
3800 to_insert: Vec<Inlay>,
3801 cx: &mut Context<Self>,
3802 ) {
3803 self.display_map.update(cx, |display_map, cx| {
3804 display_map.splice_inlays(to_remove, to_insert, cx)
3805 });
3806 cx.notify();
3807 }
3808
3809 fn trigger_on_type_formatting(
3810 &self,
3811 input: String,
3812 window: &mut Window,
3813 cx: &mut Context<Self>,
3814 ) -> Option<Task<Result<()>>> {
3815 if input.len() != 1 {
3816 return None;
3817 }
3818
3819 let project = self.project.as_ref()?;
3820 let position = self.selections.newest_anchor().head();
3821 let (buffer, buffer_position) = self
3822 .buffer
3823 .read(cx)
3824 .text_anchor_for_position(position, cx)?;
3825
3826 let settings = language_settings::language_settings(
3827 buffer
3828 .read(cx)
3829 .language_at(buffer_position)
3830 .map(|l| l.name()),
3831 buffer.read(cx).file(),
3832 cx,
3833 );
3834 if !settings.use_on_type_format {
3835 return None;
3836 }
3837
3838 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3839 // hence we do LSP request & edit on host side only — add formats to host's history.
3840 let push_to_lsp_host_history = true;
3841 // If this is not the host, append its history with new edits.
3842 let push_to_client_history = project.read(cx).is_via_collab();
3843
3844 let on_type_formatting = project.update(cx, |project, cx| {
3845 project.on_type_format(
3846 buffer.clone(),
3847 buffer_position,
3848 input,
3849 push_to_lsp_host_history,
3850 cx,
3851 )
3852 });
3853 Some(cx.spawn_in(window, |editor, mut cx| async move {
3854 if let Some(transaction) = on_type_formatting.await? {
3855 if push_to_client_history {
3856 buffer
3857 .update(&mut cx, |buffer, _| {
3858 buffer.push_transaction(transaction, Instant::now());
3859 })
3860 .ok();
3861 }
3862 editor.update(&mut cx, |editor, cx| {
3863 editor.refresh_document_highlights(cx);
3864 })?;
3865 }
3866 Ok(())
3867 }))
3868 }
3869
3870 pub fn show_completions(
3871 &mut self,
3872 options: &ShowCompletions,
3873 window: &mut Window,
3874 cx: &mut Context<Self>,
3875 ) {
3876 if self.pending_rename.is_some() {
3877 return;
3878 }
3879
3880 let Some(provider) = self.completion_provider.as_ref() else {
3881 return;
3882 };
3883
3884 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3885 return;
3886 }
3887
3888 let position = self.selections.newest_anchor().head();
3889 if position.diff_base_anchor.is_some() {
3890 return;
3891 }
3892 let (buffer, buffer_position) =
3893 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3894 output
3895 } else {
3896 return;
3897 };
3898 let show_completion_documentation = buffer
3899 .read(cx)
3900 .snapshot()
3901 .settings_at(buffer_position, cx)
3902 .show_completion_documentation;
3903
3904 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3905
3906 let trigger_kind = match &options.trigger {
3907 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3908 CompletionTriggerKind::TRIGGER_CHARACTER
3909 }
3910 _ => CompletionTriggerKind::INVOKED,
3911 };
3912 let completion_context = CompletionContext {
3913 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3914 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3915 Some(String::from(trigger))
3916 } else {
3917 None
3918 }
3919 }),
3920 trigger_kind,
3921 };
3922 let completions =
3923 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3924 let sort_completions = provider.sort_completions();
3925
3926 let id = post_inc(&mut self.next_completion_id);
3927 let task = cx.spawn_in(window, |editor, mut cx| {
3928 async move {
3929 editor.update(&mut cx, |this, _| {
3930 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3931 })?;
3932 let completions = completions.await.log_err();
3933 let menu = if let Some(completions) = completions {
3934 let mut menu = CompletionsMenu::new(
3935 id,
3936 sort_completions,
3937 show_completion_documentation,
3938 position,
3939 buffer.clone(),
3940 completions.into(),
3941 );
3942
3943 menu.filter(query.as_deref(), cx.background_executor().clone())
3944 .await;
3945
3946 menu.visible().then_some(menu)
3947 } else {
3948 None
3949 };
3950
3951 editor.update_in(&mut cx, |editor, window, cx| {
3952 match editor.context_menu.borrow().as_ref() {
3953 None => {}
3954 Some(CodeContextMenu::Completions(prev_menu)) => {
3955 if prev_menu.id > id {
3956 return;
3957 }
3958 }
3959 _ => return,
3960 }
3961
3962 if editor.focus_handle.is_focused(window) && menu.is_some() {
3963 let mut menu = menu.unwrap();
3964 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3965
3966 *editor.context_menu.borrow_mut() =
3967 Some(CodeContextMenu::Completions(menu));
3968
3969 if editor.show_edit_predictions_in_menu() {
3970 editor.update_visible_inline_completion(window, cx);
3971 } else {
3972 editor.discard_inline_completion(false, cx);
3973 }
3974
3975 cx.notify();
3976 } else if editor.completion_tasks.len() <= 1 {
3977 // If there are no more completion tasks and the last menu was
3978 // empty, we should hide it.
3979 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3980 // If it was already hidden and we don't show inline
3981 // completions in the menu, we should also show the
3982 // inline-completion when available.
3983 if was_hidden && editor.show_edit_predictions_in_menu() {
3984 editor.update_visible_inline_completion(window, cx);
3985 }
3986 }
3987 })?;
3988
3989 Ok::<_, anyhow::Error>(())
3990 }
3991 .log_err()
3992 });
3993
3994 self.completion_tasks.push((id, task));
3995 }
3996
3997 pub fn confirm_completion(
3998 &mut self,
3999 action: &ConfirmCompletion,
4000 window: &mut Window,
4001 cx: &mut Context<Self>,
4002 ) -> Option<Task<Result<()>>> {
4003 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4004 }
4005
4006 pub fn compose_completion(
4007 &mut self,
4008 action: &ComposeCompletion,
4009 window: &mut Window,
4010 cx: &mut Context<Self>,
4011 ) -> Option<Task<Result<()>>> {
4012 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4013 }
4014
4015 fn do_completion(
4016 &mut self,
4017 item_ix: Option<usize>,
4018 intent: CompletionIntent,
4019 window: &mut Window,
4020 cx: &mut Context<Editor>,
4021 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4022 use language::ToOffset as _;
4023
4024 let completions_menu =
4025 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4026 menu
4027 } else {
4028 return None;
4029 };
4030
4031 let entries = completions_menu.entries.borrow();
4032 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4033 if self.show_edit_predictions_in_menu() {
4034 self.discard_inline_completion(true, cx);
4035 }
4036 let candidate_id = mat.candidate_id;
4037 drop(entries);
4038
4039 let buffer_handle = completions_menu.buffer;
4040 let completion = completions_menu
4041 .completions
4042 .borrow()
4043 .get(candidate_id)?
4044 .clone();
4045 cx.stop_propagation();
4046
4047 let snippet;
4048 let text;
4049
4050 if completion.is_snippet() {
4051 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4052 text = snippet.as_ref().unwrap().text.clone();
4053 } else {
4054 snippet = None;
4055 text = completion.new_text.clone();
4056 };
4057 let selections = self.selections.all::<usize>(cx);
4058 let buffer = buffer_handle.read(cx);
4059 let old_range = completion.old_range.to_offset(buffer);
4060 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4061
4062 let newest_selection = self.selections.newest_anchor();
4063 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4064 return None;
4065 }
4066
4067 let lookbehind = newest_selection
4068 .start
4069 .text_anchor
4070 .to_offset(buffer)
4071 .saturating_sub(old_range.start);
4072 let lookahead = old_range
4073 .end
4074 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4075 let mut common_prefix_len = old_text
4076 .bytes()
4077 .zip(text.bytes())
4078 .take_while(|(a, b)| a == b)
4079 .count();
4080
4081 let snapshot = self.buffer.read(cx).snapshot(cx);
4082 let mut range_to_replace: Option<Range<isize>> = None;
4083 let mut ranges = Vec::new();
4084 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4085 for selection in &selections {
4086 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4087 let start = selection.start.saturating_sub(lookbehind);
4088 let end = selection.end + lookahead;
4089 if selection.id == newest_selection.id {
4090 range_to_replace = Some(
4091 ((start + common_prefix_len) as isize - selection.start as isize)
4092 ..(end as isize - selection.start as isize),
4093 );
4094 }
4095 ranges.push(start + common_prefix_len..end);
4096 } else {
4097 common_prefix_len = 0;
4098 ranges.clear();
4099 ranges.extend(selections.iter().map(|s| {
4100 if s.id == newest_selection.id {
4101 range_to_replace = Some(
4102 old_range.start.to_offset_utf16(&snapshot).0 as isize
4103 - selection.start as isize
4104 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4105 - selection.start as isize,
4106 );
4107 old_range.clone()
4108 } else {
4109 s.start..s.end
4110 }
4111 }));
4112 break;
4113 }
4114 if !self.linked_edit_ranges.is_empty() {
4115 let start_anchor = snapshot.anchor_before(selection.head());
4116 let end_anchor = snapshot.anchor_after(selection.tail());
4117 if let Some(ranges) = self
4118 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4119 {
4120 for (buffer, edits) in ranges {
4121 linked_edits.entry(buffer.clone()).or_default().extend(
4122 edits
4123 .into_iter()
4124 .map(|range| (range, text[common_prefix_len..].to_owned())),
4125 );
4126 }
4127 }
4128 }
4129 }
4130 let text = &text[common_prefix_len..];
4131
4132 cx.emit(EditorEvent::InputHandled {
4133 utf16_range_to_replace: range_to_replace,
4134 text: text.into(),
4135 });
4136
4137 self.transact(window, cx, |this, window, cx| {
4138 if let Some(mut snippet) = snippet {
4139 snippet.text = text.to_string();
4140 for tabstop in snippet
4141 .tabstops
4142 .iter_mut()
4143 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4144 {
4145 tabstop.start -= common_prefix_len as isize;
4146 tabstop.end -= common_prefix_len as isize;
4147 }
4148
4149 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4150 } else {
4151 this.buffer.update(cx, |buffer, cx| {
4152 buffer.edit(
4153 ranges.iter().map(|range| (range.clone(), text)),
4154 this.autoindent_mode.clone(),
4155 cx,
4156 );
4157 });
4158 }
4159 for (buffer, edits) in linked_edits {
4160 buffer.update(cx, |buffer, cx| {
4161 let snapshot = buffer.snapshot();
4162 let edits = edits
4163 .into_iter()
4164 .map(|(range, text)| {
4165 use text::ToPoint as TP;
4166 let end_point = TP::to_point(&range.end, &snapshot);
4167 let start_point = TP::to_point(&range.start, &snapshot);
4168 (start_point..end_point, text)
4169 })
4170 .sorted_by_key(|(range, _)| range.start)
4171 .collect::<Vec<_>>();
4172 buffer.edit(edits, None, cx);
4173 })
4174 }
4175
4176 this.refresh_inline_completion(true, false, window, cx);
4177 });
4178
4179 let show_new_completions_on_confirm = completion
4180 .confirm
4181 .as_ref()
4182 .map_or(false, |confirm| confirm(intent, window, cx));
4183 if show_new_completions_on_confirm {
4184 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4185 }
4186
4187 let provider = self.completion_provider.as_ref()?;
4188 drop(completion);
4189 let apply_edits = provider.apply_additional_edits_for_completion(
4190 buffer_handle,
4191 completions_menu.completions.clone(),
4192 candidate_id,
4193 true,
4194 cx,
4195 );
4196
4197 let editor_settings = EditorSettings::get_global(cx);
4198 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4199 // After the code completion is finished, users often want to know what signatures are needed.
4200 // so we should automatically call signature_help
4201 self.show_signature_help(&ShowSignatureHelp, window, cx);
4202 }
4203
4204 Some(cx.foreground_executor().spawn(async move {
4205 apply_edits.await?;
4206 Ok(())
4207 }))
4208 }
4209
4210 pub fn toggle_code_actions(
4211 &mut self,
4212 action: &ToggleCodeActions,
4213 window: &mut Window,
4214 cx: &mut Context<Self>,
4215 ) {
4216 let mut context_menu = self.context_menu.borrow_mut();
4217 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4218 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4219 // Toggle if we're selecting the same one
4220 *context_menu = None;
4221 cx.notify();
4222 return;
4223 } else {
4224 // Otherwise, clear it and start a new one
4225 *context_menu = None;
4226 cx.notify();
4227 }
4228 }
4229 drop(context_menu);
4230 let snapshot = self.snapshot(window, cx);
4231 let deployed_from_indicator = action.deployed_from_indicator;
4232 let mut task = self.code_actions_task.take();
4233 let action = action.clone();
4234 cx.spawn_in(window, |editor, mut cx| async move {
4235 while let Some(prev_task) = task {
4236 prev_task.await.log_err();
4237 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4238 }
4239
4240 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4241 if editor.focus_handle.is_focused(window) {
4242 let multibuffer_point = action
4243 .deployed_from_indicator
4244 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4245 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4246 let (buffer, buffer_row) = snapshot
4247 .buffer_snapshot
4248 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4249 .and_then(|(buffer_snapshot, range)| {
4250 editor
4251 .buffer
4252 .read(cx)
4253 .buffer(buffer_snapshot.remote_id())
4254 .map(|buffer| (buffer, range.start.row))
4255 })?;
4256 let (_, code_actions) = editor
4257 .available_code_actions
4258 .clone()
4259 .and_then(|(location, code_actions)| {
4260 let snapshot = location.buffer.read(cx).snapshot();
4261 let point_range = location.range.to_point(&snapshot);
4262 let point_range = point_range.start.row..=point_range.end.row;
4263 if point_range.contains(&buffer_row) {
4264 Some((location, code_actions))
4265 } else {
4266 None
4267 }
4268 })
4269 .unzip();
4270 let buffer_id = buffer.read(cx).remote_id();
4271 let tasks = editor
4272 .tasks
4273 .get(&(buffer_id, buffer_row))
4274 .map(|t| Arc::new(t.to_owned()));
4275 if tasks.is_none() && code_actions.is_none() {
4276 return None;
4277 }
4278
4279 editor.completion_tasks.clear();
4280 editor.discard_inline_completion(false, cx);
4281 let task_context =
4282 tasks
4283 .as_ref()
4284 .zip(editor.project.clone())
4285 .map(|(tasks, project)| {
4286 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4287 });
4288
4289 Some(cx.spawn_in(window, |editor, mut cx| async move {
4290 let task_context = match task_context {
4291 Some(task_context) => task_context.await,
4292 None => None,
4293 };
4294 let resolved_tasks =
4295 tasks.zip(task_context).map(|(tasks, task_context)| {
4296 Rc::new(ResolvedTasks {
4297 templates: tasks.resolve(&task_context).collect(),
4298 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4299 multibuffer_point.row,
4300 tasks.column,
4301 )),
4302 })
4303 });
4304 let spawn_straight_away = resolved_tasks
4305 .as_ref()
4306 .map_or(false, |tasks| tasks.templates.len() == 1)
4307 && code_actions
4308 .as_ref()
4309 .map_or(true, |actions| actions.is_empty());
4310 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4311 *editor.context_menu.borrow_mut() =
4312 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4313 buffer,
4314 actions: CodeActionContents {
4315 tasks: resolved_tasks,
4316 actions: code_actions,
4317 },
4318 selected_item: Default::default(),
4319 scroll_handle: UniformListScrollHandle::default(),
4320 deployed_from_indicator,
4321 }));
4322 if spawn_straight_away {
4323 if let Some(task) = editor.confirm_code_action(
4324 &ConfirmCodeAction { item_ix: Some(0) },
4325 window,
4326 cx,
4327 ) {
4328 cx.notify();
4329 return task;
4330 }
4331 }
4332 cx.notify();
4333 Task::ready(Ok(()))
4334 }) {
4335 task.await
4336 } else {
4337 Ok(())
4338 }
4339 }))
4340 } else {
4341 Some(Task::ready(Ok(())))
4342 }
4343 })?;
4344 if let Some(task) = spawned_test_task {
4345 task.await?;
4346 }
4347
4348 Ok::<_, anyhow::Error>(())
4349 })
4350 .detach_and_log_err(cx);
4351 }
4352
4353 pub fn confirm_code_action(
4354 &mut self,
4355 action: &ConfirmCodeAction,
4356 window: &mut Window,
4357 cx: &mut Context<Self>,
4358 ) -> Option<Task<Result<()>>> {
4359 let actions_menu =
4360 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4361 menu
4362 } else {
4363 return None;
4364 };
4365 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4366 let action = actions_menu.actions.get(action_ix)?;
4367 let title = action.label();
4368 let buffer = actions_menu.buffer;
4369 let workspace = self.workspace()?;
4370
4371 match action {
4372 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4373 workspace.update(cx, |workspace, cx| {
4374 workspace::tasks::schedule_resolved_task(
4375 workspace,
4376 task_source_kind,
4377 resolved_task,
4378 false,
4379 cx,
4380 );
4381
4382 Some(Task::ready(Ok(())))
4383 })
4384 }
4385 CodeActionsItem::CodeAction {
4386 excerpt_id,
4387 action,
4388 provider,
4389 } => {
4390 let apply_code_action =
4391 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4392 let workspace = workspace.downgrade();
4393 Some(cx.spawn_in(window, |editor, cx| async move {
4394 let project_transaction = apply_code_action.await?;
4395 Self::open_project_transaction(
4396 &editor,
4397 workspace,
4398 project_transaction,
4399 title,
4400 cx,
4401 )
4402 .await
4403 }))
4404 }
4405 }
4406 }
4407
4408 pub async fn open_project_transaction(
4409 this: &WeakEntity<Editor>,
4410 workspace: WeakEntity<Workspace>,
4411 transaction: ProjectTransaction,
4412 title: String,
4413 mut cx: AsyncWindowContext,
4414 ) -> Result<()> {
4415 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4416 cx.update(|_, cx| {
4417 entries.sort_unstable_by_key(|(buffer, _)| {
4418 buffer.read(cx).file().map(|f| f.path().clone())
4419 });
4420 })?;
4421
4422 // If the project transaction's edits are all contained within this editor, then
4423 // avoid opening a new editor to display them.
4424
4425 if let Some((buffer, transaction)) = entries.first() {
4426 if entries.len() == 1 {
4427 let excerpt = this.update(&mut cx, |editor, cx| {
4428 editor
4429 .buffer()
4430 .read(cx)
4431 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4432 })?;
4433 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4434 if excerpted_buffer == *buffer {
4435 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4436 let excerpt_range = excerpt_range.to_offset(buffer);
4437 buffer
4438 .edited_ranges_for_transaction::<usize>(transaction)
4439 .all(|range| {
4440 excerpt_range.start <= range.start
4441 && excerpt_range.end >= range.end
4442 })
4443 })?;
4444
4445 if all_edits_within_excerpt {
4446 return Ok(());
4447 }
4448 }
4449 }
4450 }
4451 } else {
4452 return Ok(());
4453 }
4454
4455 let mut ranges_to_highlight = Vec::new();
4456 let excerpt_buffer = cx.new(|cx| {
4457 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4458 for (buffer_handle, transaction) in &entries {
4459 let buffer = buffer_handle.read(cx);
4460 ranges_to_highlight.extend(
4461 multibuffer.push_excerpts_with_context_lines(
4462 buffer_handle.clone(),
4463 buffer
4464 .edited_ranges_for_transaction::<usize>(transaction)
4465 .collect(),
4466 DEFAULT_MULTIBUFFER_CONTEXT,
4467 cx,
4468 ),
4469 );
4470 }
4471 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4472 multibuffer
4473 })?;
4474
4475 workspace.update_in(&mut cx, |workspace, window, cx| {
4476 let project = workspace.project().clone();
4477 let editor = cx
4478 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4479 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4480 editor.update(cx, |editor, cx| {
4481 editor.highlight_background::<Self>(
4482 &ranges_to_highlight,
4483 |theme| theme.editor_highlighted_line_background,
4484 cx,
4485 );
4486 });
4487 })?;
4488
4489 Ok(())
4490 }
4491
4492 pub fn clear_code_action_providers(&mut self) {
4493 self.code_action_providers.clear();
4494 self.available_code_actions.take();
4495 }
4496
4497 pub fn add_code_action_provider(
4498 &mut self,
4499 provider: Rc<dyn CodeActionProvider>,
4500 window: &mut Window,
4501 cx: &mut Context<Self>,
4502 ) {
4503 if self
4504 .code_action_providers
4505 .iter()
4506 .any(|existing_provider| existing_provider.id() == provider.id())
4507 {
4508 return;
4509 }
4510
4511 self.code_action_providers.push(provider);
4512 self.refresh_code_actions(window, cx);
4513 }
4514
4515 pub fn remove_code_action_provider(
4516 &mut self,
4517 id: Arc<str>,
4518 window: &mut Window,
4519 cx: &mut Context<Self>,
4520 ) {
4521 self.code_action_providers
4522 .retain(|provider| provider.id() != id);
4523 self.refresh_code_actions(window, cx);
4524 }
4525
4526 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4527 let buffer = self.buffer.read(cx);
4528 let newest_selection = self.selections.newest_anchor().clone();
4529 if newest_selection.head().diff_base_anchor.is_some() {
4530 return None;
4531 }
4532 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4533 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4534 if start_buffer != end_buffer {
4535 return None;
4536 }
4537
4538 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4539 cx.background_executor()
4540 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4541 .await;
4542
4543 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4544 let providers = this.code_action_providers.clone();
4545 let tasks = this
4546 .code_action_providers
4547 .iter()
4548 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4549 .collect::<Vec<_>>();
4550 (providers, tasks)
4551 })?;
4552
4553 let mut actions = Vec::new();
4554 for (provider, provider_actions) in
4555 providers.into_iter().zip(future::join_all(tasks).await)
4556 {
4557 if let Some(provider_actions) = provider_actions.log_err() {
4558 actions.extend(provider_actions.into_iter().map(|action| {
4559 AvailableCodeAction {
4560 excerpt_id: newest_selection.start.excerpt_id,
4561 action,
4562 provider: provider.clone(),
4563 }
4564 }));
4565 }
4566 }
4567
4568 this.update(&mut cx, |this, cx| {
4569 this.available_code_actions = if actions.is_empty() {
4570 None
4571 } else {
4572 Some((
4573 Location {
4574 buffer: start_buffer,
4575 range: start..end,
4576 },
4577 actions.into(),
4578 ))
4579 };
4580 cx.notify();
4581 })
4582 }));
4583 None
4584 }
4585
4586 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4587 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4588 self.show_git_blame_inline = false;
4589
4590 self.show_git_blame_inline_delay_task =
4591 Some(cx.spawn_in(window, |this, mut cx| async move {
4592 cx.background_executor().timer(delay).await;
4593
4594 this.update(&mut cx, |this, cx| {
4595 this.show_git_blame_inline = true;
4596 cx.notify();
4597 })
4598 .log_err();
4599 }));
4600 }
4601 }
4602
4603 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4604 if self.pending_rename.is_some() {
4605 return None;
4606 }
4607
4608 let provider = self.semantics_provider.clone()?;
4609 let buffer = self.buffer.read(cx);
4610 let newest_selection = self.selections.newest_anchor().clone();
4611 let cursor_position = newest_selection.head();
4612 let (cursor_buffer, cursor_buffer_position) =
4613 buffer.text_anchor_for_position(cursor_position, cx)?;
4614 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4615 if cursor_buffer != tail_buffer {
4616 return None;
4617 }
4618 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4619 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4620 cx.background_executor()
4621 .timer(Duration::from_millis(debounce))
4622 .await;
4623
4624 let highlights = if let Some(highlights) = cx
4625 .update(|cx| {
4626 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4627 })
4628 .ok()
4629 .flatten()
4630 {
4631 highlights.await.log_err()
4632 } else {
4633 None
4634 };
4635
4636 if let Some(highlights) = highlights {
4637 this.update(&mut cx, |this, cx| {
4638 if this.pending_rename.is_some() {
4639 return;
4640 }
4641
4642 let buffer_id = cursor_position.buffer_id;
4643 let buffer = this.buffer.read(cx);
4644 if !buffer
4645 .text_anchor_for_position(cursor_position, cx)
4646 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4647 {
4648 return;
4649 }
4650
4651 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4652 let mut write_ranges = Vec::new();
4653 let mut read_ranges = Vec::new();
4654 for highlight in highlights {
4655 for (excerpt_id, excerpt_range) in
4656 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4657 {
4658 let start = highlight
4659 .range
4660 .start
4661 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4662 let end = highlight
4663 .range
4664 .end
4665 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4666 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4667 continue;
4668 }
4669
4670 let range = Anchor {
4671 buffer_id,
4672 excerpt_id,
4673 text_anchor: start,
4674 diff_base_anchor: None,
4675 }..Anchor {
4676 buffer_id,
4677 excerpt_id,
4678 text_anchor: end,
4679 diff_base_anchor: None,
4680 };
4681 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4682 write_ranges.push(range);
4683 } else {
4684 read_ranges.push(range);
4685 }
4686 }
4687 }
4688
4689 this.highlight_background::<DocumentHighlightRead>(
4690 &read_ranges,
4691 |theme| theme.editor_document_highlight_read_background,
4692 cx,
4693 );
4694 this.highlight_background::<DocumentHighlightWrite>(
4695 &write_ranges,
4696 |theme| theme.editor_document_highlight_write_background,
4697 cx,
4698 );
4699 cx.notify();
4700 })
4701 .log_err();
4702 }
4703 }));
4704 None
4705 }
4706
4707 pub fn refresh_inline_completion(
4708 &mut self,
4709 debounce: bool,
4710 user_requested: bool,
4711 window: &mut Window,
4712 cx: &mut Context<Self>,
4713 ) -> Option<()> {
4714 let provider = self.edit_prediction_provider()?;
4715 let cursor = self.selections.newest_anchor().head();
4716 let (buffer, cursor_buffer_position) =
4717 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4718
4719 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4720 self.discard_inline_completion(false, cx);
4721 return None;
4722 }
4723
4724 if !user_requested
4725 && (!self.should_show_edit_predictions()
4726 || !self.is_focused(window)
4727 || buffer.read(cx).is_empty())
4728 {
4729 self.discard_inline_completion(false, cx);
4730 return None;
4731 }
4732
4733 self.update_visible_inline_completion(window, cx);
4734 provider.refresh(
4735 self.project.clone(),
4736 buffer,
4737 cursor_buffer_position,
4738 debounce,
4739 cx,
4740 );
4741 Some(())
4742 }
4743
4744 fn show_edit_predictions_in_menu(&self) -> bool {
4745 match self.edit_prediction_settings {
4746 EditPredictionSettings::Disabled => false,
4747 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4748 }
4749 }
4750
4751 pub fn edit_predictions_enabled(&self) -> bool {
4752 match self.edit_prediction_settings {
4753 EditPredictionSettings::Disabled => false,
4754 EditPredictionSettings::Enabled { .. } => true,
4755 }
4756 }
4757
4758 fn edit_prediction_requires_modifier(&self) -> bool {
4759 match self.edit_prediction_settings {
4760 EditPredictionSettings::Disabled => false,
4761 EditPredictionSettings::Enabled {
4762 preview_requires_modifier,
4763 ..
4764 } => preview_requires_modifier,
4765 }
4766 }
4767
4768 fn edit_prediction_settings_at_position(
4769 &self,
4770 buffer: &Entity<Buffer>,
4771 buffer_position: language::Anchor,
4772 cx: &App,
4773 ) -> EditPredictionSettings {
4774 if self.mode != EditorMode::Full
4775 || !self.show_inline_completions_override.unwrap_or(true)
4776 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4777 {
4778 return EditPredictionSettings::Disabled;
4779 }
4780
4781 let buffer = buffer.read(cx);
4782
4783 let file = buffer.file();
4784
4785 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4786 return EditPredictionSettings::Disabled;
4787 };
4788
4789 let by_provider = matches!(
4790 self.menu_inline_completions_policy,
4791 MenuInlineCompletionsPolicy::ByProvider
4792 );
4793
4794 let show_in_menu = by_provider
4795 && self
4796 .edit_prediction_provider
4797 .as_ref()
4798 .map_or(false, |provider| {
4799 provider.provider.show_completions_in_menu()
4800 });
4801
4802 let preview_requires_modifier =
4803 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4804
4805 EditPredictionSettings::Enabled {
4806 show_in_menu,
4807 preview_requires_modifier,
4808 }
4809 }
4810
4811 fn should_show_edit_predictions(&self) -> bool {
4812 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4813 }
4814
4815 pub fn edit_prediction_preview_is_active(&self) -> bool {
4816 matches!(
4817 self.edit_prediction_preview,
4818 EditPredictionPreview::Active { .. }
4819 )
4820 }
4821
4822 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4823 let cursor = self.selections.newest_anchor().head();
4824 if let Some((buffer, cursor_position)) =
4825 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4826 {
4827 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4828 } else {
4829 false
4830 }
4831 }
4832
4833 fn inline_completions_enabled_in_buffer(
4834 &self,
4835 buffer: &Entity<Buffer>,
4836 buffer_position: language::Anchor,
4837 cx: &App,
4838 ) -> bool {
4839 maybe!({
4840 let provider = self.edit_prediction_provider()?;
4841 if !provider.is_enabled(&buffer, buffer_position, cx) {
4842 return Some(false);
4843 }
4844 let buffer = buffer.read(cx);
4845 let Some(file) = buffer.file() else {
4846 return Some(true);
4847 };
4848 let settings = all_language_settings(Some(file), cx);
4849 Some(settings.inline_completions_enabled_for_path(file.path()))
4850 })
4851 .unwrap_or(false)
4852 }
4853
4854 fn cycle_inline_completion(
4855 &mut self,
4856 direction: Direction,
4857 window: &mut Window,
4858 cx: &mut Context<Self>,
4859 ) -> Option<()> {
4860 let provider = self.edit_prediction_provider()?;
4861 let cursor = self.selections.newest_anchor().head();
4862 let (buffer, cursor_buffer_position) =
4863 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4864 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4865 return None;
4866 }
4867
4868 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4869 self.update_visible_inline_completion(window, cx);
4870
4871 Some(())
4872 }
4873
4874 pub fn show_inline_completion(
4875 &mut self,
4876 _: &ShowEditPrediction,
4877 window: &mut Window,
4878 cx: &mut Context<Self>,
4879 ) {
4880 if !self.has_active_inline_completion() {
4881 self.refresh_inline_completion(false, true, window, cx);
4882 return;
4883 }
4884
4885 self.update_visible_inline_completion(window, cx);
4886 }
4887
4888 pub fn display_cursor_names(
4889 &mut self,
4890 _: &DisplayCursorNames,
4891 window: &mut Window,
4892 cx: &mut Context<Self>,
4893 ) {
4894 self.show_cursor_names(window, cx);
4895 }
4896
4897 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4898 self.show_cursor_names = true;
4899 cx.notify();
4900 cx.spawn_in(window, |this, mut cx| async move {
4901 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4902 this.update(&mut cx, |this, cx| {
4903 this.show_cursor_names = false;
4904 cx.notify()
4905 })
4906 .ok()
4907 })
4908 .detach();
4909 }
4910
4911 pub fn next_edit_prediction(
4912 &mut self,
4913 _: &NextEditPrediction,
4914 window: &mut Window,
4915 cx: &mut Context<Self>,
4916 ) {
4917 if self.has_active_inline_completion() {
4918 self.cycle_inline_completion(Direction::Next, window, cx);
4919 } else {
4920 let is_copilot_disabled = self
4921 .refresh_inline_completion(false, true, window, cx)
4922 .is_none();
4923 if is_copilot_disabled {
4924 cx.propagate();
4925 }
4926 }
4927 }
4928
4929 pub fn previous_edit_prediction(
4930 &mut self,
4931 _: &PreviousEditPrediction,
4932 window: &mut Window,
4933 cx: &mut Context<Self>,
4934 ) {
4935 if self.has_active_inline_completion() {
4936 self.cycle_inline_completion(Direction::Prev, window, cx);
4937 } else {
4938 let is_copilot_disabled = self
4939 .refresh_inline_completion(false, true, window, cx)
4940 .is_none();
4941 if is_copilot_disabled {
4942 cx.propagate();
4943 }
4944 }
4945 }
4946
4947 pub fn accept_edit_prediction(
4948 &mut self,
4949 _: &AcceptEditPrediction,
4950 window: &mut Window,
4951 cx: &mut Context<Self>,
4952 ) {
4953 if self.show_edit_predictions_in_menu() {
4954 self.hide_context_menu(window, cx);
4955 }
4956
4957 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4958 return;
4959 };
4960
4961 self.report_inline_completion_event(
4962 active_inline_completion.completion_id.clone(),
4963 true,
4964 cx,
4965 );
4966
4967 match &active_inline_completion.completion {
4968 InlineCompletion::Move { target, .. } => {
4969 let target = *target;
4970
4971 if let Some(position_map) = &self.last_position_map {
4972 if position_map
4973 .visible_row_range
4974 .contains(&target.to_display_point(&position_map.snapshot).row())
4975 || !self.edit_prediction_requires_modifier()
4976 {
4977 // Note that this is also done in vim's handler of the Tab action.
4978 self.change_selections(
4979 Some(Autoscroll::newest()),
4980 window,
4981 cx,
4982 |selections| {
4983 selections.select_anchor_ranges([target..target]);
4984 },
4985 );
4986 self.clear_row_highlights::<EditPredictionPreview>();
4987
4988 self.edit_prediction_preview = EditPredictionPreview::Active {
4989 previous_scroll_position: None,
4990 };
4991 } else {
4992 self.edit_prediction_preview = EditPredictionPreview::Active {
4993 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
4994 };
4995 self.highlight_rows::<EditPredictionPreview>(
4996 target..target,
4997 cx.theme().colors().editor_highlighted_line_background,
4998 true,
4999 cx,
5000 );
5001 self.request_autoscroll(Autoscroll::fit(), cx);
5002 }
5003 }
5004 }
5005 InlineCompletion::Edit { edits, .. } => {
5006 if let Some(provider) = self.edit_prediction_provider() {
5007 provider.accept(cx);
5008 }
5009
5010 let snapshot = self.buffer.read(cx).snapshot(cx);
5011 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5012
5013 self.buffer.update(cx, |buffer, cx| {
5014 buffer.edit(edits.iter().cloned(), None, cx)
5015 });
5016
5017 self.change_selections(None, window, cx, |s| {
5018 s.select_anchor_ranges([last_edit_end..last_edit_end])
5019 });
5020
5021 self.update_visible_inline_completion(window, cx);
5022 if self.active_inline_completion.is_none() {
5023 self.refresh_inline_completion(true, true, window, cx);
5024 }
5025
5026 cx.notify();
5027 }
5028 }
5029
5030 self.edit_prediction_requires_modifier_in_leading_space = false;
5031 }
5032
5033 pub fn accept_partial_inline_completion(
5034 &mut self,
5035 _: &AcceptPartialEditPrediction,
5036 window: &mut Window,
5037 cx: &mut Context<Self>,
5038 ) {
5039 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5040 return;
5041 };
5042 if self.selections.count() != 1 {
5043 return;
5044 }
5045
5046 self.report_inline_completion_event(
5047 active_inline_completion.completion_id.clone(),
5048 true,
5049 cx,
5050 );
5051
5052 match &active_inline_completion.completion {
5053 InlineCompletion::Move { target, .. } => {
5054 let target = *target;
5055 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5056 selections.select_anchor_ranges([target..target]);
5057 });
5058 }
5059 InlineCompletion::Edit { edits, .. } => {
5060 // Find an insertion that starts at the cursor position.
5061 let snapshot = self.buffer.read(cx).snapshot(cx);
5062 let cursor_offset = self.selections.newest::<usize>(cx).head();
5063 let insertion = edits.iter().find_map(|(range, text)| {
5064 let range = range.to_offset(&snapshot);
5065 if range.is_empty() && range.start == cursor_offset {
5066 Some(text)
5067 } else {
5068 None
5069 }
5070 });
5071
5072 if let Some(text) = insertion {
5073 let mut partial_completion = text
5074 .chars()
5075 .by_ref()
5076 .take_while(|c| c.is_alphabetic())
5077 .collect::<String>();
5078 if partial_completion.is_empty() {
5079 partial_completion = text
5080 .chars()
5081 .by_ref()
5082 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5083 .collect::<String>();
5084 }
5085
5086 cx.emit(EditorEvent::InputHandled {
5087 utf16_range_to_replace: None,
5088 text: partial_completion.clone().into(),
5089 });
5090
5091 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5092
5093 self.refresh_inline_completion(true, true, window, cx);
5094 cx.notify();
5095 } else {
5096 self.accept_edit_prediction(&Default::default(), window, cx);
5097 }
5098 }
5099 }
5100 }
5101
5102 fn discard_inline_completion(
5103 &mut self,
5104 should_report_inline_completion_event: bool,
5105 cx: &mut Context<Self>,
5106 ) -> bool {
5107 if should_report_inline_completion_event {
5108 let completion_id = self
5109 .active_inline_completion
5110 .as_ref()
5111 .and_then(|active_completion| active_completion.completion_id.clone());
5112
5113 self.report_inline_completion_event(completion_id, false, cx);
5114 }
5115
5116 if let Some(provider) = self.edit_prediction_provider() {
5117 provider.discard(cx);
5118 }
5119
5120 self.take_active_inline_completion(cx)
5121 }
5122
5123 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5124 let Some(provider) = self.edit_prediction_provider() else {
5125 return;
5126 };
5127
5128 let Some((_, buffer, _)) = self
5129 .buffer
5130 .read(cx)
5131 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5132 else {
5133 return;
5134 };
5135
5136 let extension = buffer
5137 .read(cx)
5138 .file()
5139 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5140
5141 let event_type = match accepted {
5142 true => "Edit Prediction Accepted",
5143 false => "Edit Prediction Discarded",
5144 };
5145 telemetry::event!(
5146 event_type,
5147 provider = provider.name(),
5148 prediction_id = id,
5149 suggestion_accepted = accepted,
5150 file_extension = extension,
5151 );
5152 }
5153
5154 pub fn has_active_inline_completion(&self) -> bool {
5155 self.active_inline_completion.is_some()
5156 }
5157
5158 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5159 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5160 return false;
5161 };
5162
5163 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5164 self.clear_highlights::<InlineCompletionHighlight>(cx);
5165 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5166 true
5167 }
5168
5169 /// Returns true when we're displaying the edit prediction popover below the cursor
5170 /// like we are not previewing and the LSP autocomplete menu is visible
5171 /// or we are in `when_holding_modifier` mode.
5172 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5173 if self.edit_prediction_preview_is_active()
5174 || !self.show_edit_predictions_in_menu()
5175 || !self.edit_predictions_enabled()
5176 {
5177 return false;
5178 }
5179
5180 if self.has_visible_completions_menu() {
5181 return true;
5182 }
5183
5184 has_completion && self.edit_prediction_requires_modifier()
5185 }
5186
5187 fn handle_modifiers_changed(
5188 &mut self,
5189 modifiers: Modifiers,
5190 position_map: &PositionMap,
5191 window: &mut Window,
5192 cx: &mut Context<Self>,
5193 ) {
5194 if self.show_edit_predictions_in_menu() {
5195 self.update_edit_prediction_preview(&modifiers, window, cx);
5196 }
5197
5198 let mouse_position = window.mouse_position();
5199 if !position_map.text_hitbox.is_hovered(window) {
5200 return;
5201 }
5202
5203 self.update_hovered_link(
5204 position_map.point_for_position(mouse_position),
5205 &position_map.snapshot,
5206 modifiers,
5207 window,
5208 cx,
5209 )
5210 }
5211
5212 fn update_edit_prediction_preview(
5213 &mut self,
5214 modifiers: &Modifiers,
5215 window: &mut Window,
5216 cx: &mut Context<Self>,
5217 ) {
5218 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5219 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5220 return;
5221 };
5222
5223 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5224 if matches!(
5225 self.edit_prediction_preview,
5226 EditPredictionPreview::Inactive
5227 ) {
5228 self.edit_prediction_preview = EditPredictionPreview::Active {
5229 previous_scroll_position: None,
5230 };
5231
5232 self.update_visible_inline_completion(window, cx);
5233 cx.notify();
5234 }
5235 } else if let EditPredictionPreview::Active {
5236 previous_scroll_position,
5237 } = self.edit_prediction_preview
5238 {
5239 if let (Some(previous_scroll_position), Some(position_map)) =
5240 (previous_scroll_position, self.last_position_map.as_ref())
5241 {
5242 self.set_scroll_position(
5243 previous_scroll_position
5244 .scroll_position(&position_map.snapshot.display_snapshot),
5245 window,
5246 cx,
5247 );
5248 }
5249
5250 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5251 self.clear_row_highlights::<EditPredictionPreview>();
5252 self.update_visible_inline_completion(window, cx);
5253 cx.notify();
5254 }
5255 }
5256
5257 fn update_visible_inline_completion(
5258 &mut self,
5259 _window: &mut Window,
5260 cx: &mut Context<Self>,
5261 ) -> Option<()> {
5262 let selection = self.selections.newest_anchor();
5263 let cursor = selection.head();
5264 let multibuffer = self.buffer.read(cx).snapshot(cx);
5265 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5266 let excerpt_id = cursor.excerpt_id;
5267
5268 let show_in_menu = self.show_edit_predictions_in_menu();
5269 let completions_menu_has_precedence = !show_in_menu
5270 && (self.context_menu.borrow().is_some()
5271 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5272
5273 if completions_menu_has_precedence
5274 || !offset_selection.is_empty()
5275 || self
5276 .active_inline_completion
5277 .as_ref()
5278 .map_or(false, |completion| {
5279 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5280 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5281 !invalidation_range.contains(&offset_selection.head())
5282 })
5283 {
5284 self.discard_inline_completion(false, cx);
5285 return None;
5286 }
5287
5288 self.take_active_inline_completion(cx);
5289 let Some(provider) = self.edit_prediction_provider() else {
5290 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5291 return None;
5292 };
5293
5294 let (buffer, cursor_buffer_position) =
5295 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5296
5297 self.edit_prediction_settings =
5298 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5299
5300 if !self.edit_prediction_settings.is_enabled() {
5301 self.discard_inline_completion(false, cx);
5302 return None;
5303 }
5304
5305 self.edit_prediction_cursor_on_leading_whitespace =
5306 multibuffer.is_line_whitespace_upto(cursor);
5307
5308 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5309 let edits = inline_completion
5310 .edits
5311 .into_iter()
5312 .flat_map(|(range, new_text)| {
5313 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5314 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5315 Some((start..end, new_text))
5316 })
5317 .collect::<Vec<_>>();
5318 if edits.is_empty() {
5319 return None;
5320 }
5321
5322 let first_edit_start = edits.first().unwrap().0.start;
5323 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5324 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5325
5326 let last_edit_end = edits.last().unwrap().0.end;
5327 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5328 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5329
5330 let cursor_row = cursor.to_point(&multibuffer).row;
5331
5332 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5333
5334 let mut inlay_ids = Vec::new();
5335 let invalidation_row_range;
5336 let move_invalidation_row_range = if cursor_row < edit_start_row {
5337 Some(cursor_row..edit_end_row)
5338 } else if cursor_row > edit_end_row {
5339 Some(edit_start_row..cursor_row)
5340 } else {
5341 None
5342 };
5343 let is_move =
5344 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5345 let completion = if is_move {
5346 invalidation_row_range =
5347 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5348 let target = first_edit_start;
5349 InlineCompletion::Move { target, snapshot }
5350 } else {
5351 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5352 && !self.inline_completions_hidden_for_vim_mode;
5353
5354 if show_completions_in_buffer {
5355 if edits
5356 .iter()
5357 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5358 {
5359 let mut inlays = Vec::new();
5360 for (range, new_text) in &edits {
5361 let inlay = Inlay::inline_completion(
5362 post_inc(&mut self.next_inlay_id),
5363 range.start,
5364 new_text.as_str(),
5365 );
5366 inlay_ids.push(inlay.id);
5367 inlays.push(inlay);
5368 }
5369
5370 self.splice_inlays(&[], inlays, cx);
5371 } else {
5372 let background_color = cx.theme().status().deleted_background;
5373 self.highlight_text::<InlineCompletionHighlight>(
5374 edits.iter().map(|(range, _)| range.clone()).collect(),
5375 HighlightStyle {
5376 background_color: Some(background_color),
5377 ..Default::default()
5378 },
5379 cx,
5380 );
5381 }
5382 }
5383
5384 invalidation_row_range = edit_start_row..edit_end_row;
5385
5386 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5387 if provider.show_tab_accept_marker() {
5388 EditDisplayMode::TabAccept
5389 } else {
5390 EditDisplayMode::Inline
5391 }
5392 } else {
5393 EditDisplayMode::DiffPopover
5394 };
5395
5396 InlineCompletion::Edit {
5397 edits,
5398 edit_preview: inline_completion.edit_preview,
5399 display_mode,
5400 snapshot,
5401 }
5402 };
5403
5404 let invalidation_range = multibuffer
5405 .anchor_before(Point::new(invalidation_row_range.start, 0))
5406 ..multibuffer.anchor_after(Point::new(
5407 invalidation_row_range.end,
5408 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5409 ));
5410
5411 self.stale_inline_completion_in_menu = None;
5412 self.active_inline_completion = Some(InlineCompletionState {
5413 inlay_ids,
5414 completion,
5415 completion_id: inline_completion.id,
5416 invalidation_range,
5417 });
5418
5419 cx.notify();
5420
5421 Some(())
5422 }
5423
5424 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5425 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5426 }
5427
5428 fn render_code_actions_indicator(
5429 &self,
5430 _style: &EditorStyle,
5431 row: DisplayRow,
5432 is_active: bool,
5433 cx: &mut Context<Self>,
5434 ) -> Option<IconButton> {
5435 if self.available_code_actions.is_some() {
5436 Some(
5437 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5438 .shape(ui::IconButtonShape::Square)
5439 .icon_size(IconSize::XSmall)
5440 .icon_color(Color::Muted)
5441 .toggle_state(is_active)
5442 .tooltip({
5443 let focus_handle = self.focus_handle.clone();
5444 move |window, cx| {
5445 Tooltip::for_action_in(
5446 "Toggle Code Actions",
5447 &ToggleCodeActions {
5448 deployed_from_indicator: None,
5449 },
5450 &focus_handle,
5451 window,
5452 cx,
5453 )
5454 }
5455 })
5456 .on_click(cx.listener(move |editor, _e, window, cx| {
5457 window.focus(&editor.focus_handle(cx));
5458 editor.toggle_code_actions(
5459 &ToggleCodeActions {
5460 deployed_from_indicator: Some(row),
5461 },
5462 window,
5463 cx,
5464 );
5465 })),
5466 )
5467 } else {
5468 None
5469 }
5470 }
5471
5472 fn clear_tasks(&mut self) {
5473 self.tasks.clear()
5474 }
5475
5476 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5477 if self.tasks.insert(key, value).is_some() {
5478 // This case should hopefully be rare, but just in case...
5479 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5480 }
5481 }
5482
5483 fn build_tasks_context(
5484 project: &Entity<Project>,
5485 buffer: &Entity<Buffer>,
5486 buffer_row: u32,
5487 tasks: &Arc<RunnableTasks>,
5488 cx: &mut Context<Self>,
5489 ) -> Task<Option<task::TaskContext>> {
5490 let position = Point::new(buffer_row, tasks.column);
5491 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5492 let location = Location {
5493 buffer: buffer.clone(),
5494 range: range_start..range_start,
5495 };
5496 // Fill in the environmental variables from the tree-sitter captures
5497 let mut captured_task_variables = TaskVariables::default();
5498 for (capture_name, value) in tasks.extra_variables.clone() {
5499 captured_task_variables.insert(
5500 task::VariableName::Custom(capture_name.into()),
5501 value.clone(),
5502 );
5503 }
5504 project.update(cx, |project, cx| {
5505 project.task_store().update(cx, |task_store, cx| {
5506 task_store.task_context_for_location(captured_task_variables, location, cx)
5507 })
5508 })
5509 }
5510
5511 pub fn spawn_nearest_task(
5512 &mut self,
5513 action: &SpawnNearestTask,
5514 window: &mut Window,
5515 cx: &mut Context<Self>,
5516 ) {
5517 let Some((workspace, _)) = self.workspace.clone() else {
5518 return;
5519 };
5520 let Some(project) = self.project.clone() else {
5521 return;
5522 };
5523
5524 // Try to find a closest, enclosing node using tree-sitter that has a
5525 // task
5526 let Some((buffer, buffer_row, tasks)) = self
5527 .find_enclosing_node_task(cx)
5528 // Or find the task that's closest in row-distance.
5529 .or_else(|| self.find_closest_task(cx))
5530 else {
5531 return;
5532 };
5533
5534 let reveal_strategy = action.reveal;
5535 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5536 cx.spawn_in(window, |_, mut cx| async move {
5537 let context = task_context.await?;
5538 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5539
5540 let resolved = resolved_task.resolved.as_mut()?;
5541 resolved.reveal = reveal_strategy;
5542
5543 workspace
5544 .update(&mut cx, |workspace, cx| {
5545 workspace::tasks::schedule_resolved_task(
5546 workspace,
5547 task_source_kind,
5548 resolved_task,
5549 false,
5550 cx,
5551 );
5552 })
5553 .ok()
5554 })
5555 .detach();
5556 }
5557
5558 fn find_closest_task(
5559 &mut self,
5560 cx: &mut Context<Self>,
5561 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5562 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5563
5564 let ((buffer_id, row), tasks) = self
5565 .tasks
5566 .iter()
5567 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5568
5569 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5570 let tasks = Arc::new(tasks.to_owned());
5571 Some((buffer, *row, tasks))
5572 }
5573
5574 fn find_enclosing_node_task(
5575 &mut self,
5576 cx: &mut Context<Self>,
5577 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5578 let snapshot = self.buffer.read(cx).snapshot(cx);
5579 let offset = self.selections.newest::<usize>(cx).head();
5580 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5581 let buffer_id = excerpt.buffer().remote_id();
5582
5583 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5584 let mut cursor = layer.node().walk();
5585
5586 while cursor.goto_first_child_for_byte(offset).is_some() {
5587 if cursor.node().end_byte() == offset {
5588 cursor.goto_next_sibling();
5589 }
5590 }
5591
5592 // Ascend to the smallest ancestor that contains the range and has a task.
5593 loop {
5594 let node = cursor.node();
5595 let node_range = node.byte_range();
5596 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5597
5598 // Check if this node contains our offset
5599 if node_range.start <= offset && node_range.end >= offset {
5600 // If it contains offset, check for task
5601 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5602 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5603 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5604 }
5605 }
5606
5607 if !cursor.goto_parent() {
5608 break;
5609 }
5610 }
5611 None
5612 }
5613
5614 fn render_run_indicator(
5615 &self,
5616 _style: &EditorStyle,
5617 is_active: bool,
5618 row: DisplayRow,
5619 cx: &mut Context<Self>,
5620 ) -> IconButton {
5621 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5622 .shape(ui::IconButtonShape::Square)
5623 .icon_size(IconSize::XSmall)
5624 .icon_color(Color::Muted)
5625 .toggle_state(is_active)
5626 .on_click(cx.listener(move |editor, _e, window, cx| {
5627 window.focus(&editor.focus_handle(cx));
5628 editor.toggle_code_actions(
5629 &ToggleCodeActions {
5630 deployed_from_indicator: Some(row),
5631 },
5632 window,
5633 cx,
5634 );
5635 }))
5636 }
5637
5638 pub fn context_menu_visible(&self) -> bool {
5639 !self.edit_prediction_preview_is_active()
5640 && self
5641 .context_menu
5642 .borrow()
5643 .as_ref()
5644 .map_or(false, |menu| menu.visible())
5645 }
5646
5647 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5648 self.context_menu
5649 .borrow()
5650 .as_ref()
5651 .map(|menu| menu.origin())
5652 }
5653
5654 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5655 px(30.)
5656 }
5657
5658 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5659 if self.read_only(cx) {
5660 cx.theme().players().read_only()
5661 } else {
5662 self.style.as_ref().unwrap().local_player
5663 }
5664 }
5665
5666 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5667 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5668 let accept_keystroke = accept_binding.keystroke()?;
5669
5670 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5671
5672 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5673 Color::Accent
5674 } else {
5675 Color::Muted
5676 };
5677
5678 h_flex()
5679 .px_0p5()
5680 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5681 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5682 .text_size(TextSize::XSmall.rems(cx))
5683 .child(h_flex().children(ui::render_modifiers(
5684 &accept_keystroke.modifiers,
5685 PlatformStyle::platform(),
5686 Some(modifiers_color),
5687 Some(IconSize::XSmall.rems().into()),
5688 true,
5689 )))
5690 .when(is_platform_style_mac, |parent| {
5691 parent.child(accept_keystroke.key.clone())
5692 })
5693 .when(!is_platform_style_mac, |parent| {
5694 parent.child(
5695 Key::new(
5696 util::capitalize(&accept_keystroke.key),
5697 Some(Color::Default),
5698 )
5699 .size(Some(IconSize::XSmall.rems().into())),
5700 )
5701 })
5702 .into()
5703 }
5704
5705 fn render_edit_prediction_line_popover(
5706 &self,
5707 label: impl Into<SharedString>,
5708 icon: Option<IconName>,
5709 window: &mut Window,
5710 cx: &App,
5711 ) -> Option<Div> {
5712 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5713
5714 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5715
5716 let result = h_flex()
5717 .gap_1()
5718 .border_1()
5719 .rounded_lg()
5720 .shadow_sm()
5721 .bg(bg_color)
5722 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5723 .py_0p5()
5724 .pl_1()
5725 .pr(padding_right)
5726 .children(self.render_edit_prediction_accept_keybind(window, cx))
5727 .child(Label::new(label).size(LabelSize::Small))
5728 .when_some(icon, |element, icon| {
5729 element.child(
5730 div()
5731 .mt(px(1.5))
5732 .child(Icon::new(icon).size(IconSize::Small)),
5733 )
5734 });
5735
5736 Some(result)
5737 }
5738
5739 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5740 let accent_color = cx.theme().colors().text_accent;
5741 let editor_bg_color = cx.theme().colors().editor_background;
5742 editor_bg_color.blend(accent_color.opacity(0.1))
5743 }
5744
5745 #[allow(clippy::too_many_arguments)]
5746 fn render_edit_prediction_cursor_popover(
5747 &self,
5748 min_width: Pixels,
5749 max_width: Pixels,
5750 cursor_point: Point,
5751 style: &EditorStyle,
5752 accept_keystroke: &gpui::Keystroke,
5753 _window: &Window,
5754 cx: &mut Context<Editor>,
5755 ) -> Option<AnyElement> {
5756 let provider = self.edit_prediction_provider.as_ref()?;
5757
5758 if provider.provider.needs_terms_acceptance(cx) {
5759 return Some(
5760 h_flex()
5761 .min_w(min_width)
5762 .flex_1()
5763 .px_2()
5764 .py_1()
5765 .gap_3()
5766 .elevation_2(cx)
5767 .hover(|style| style.bg(cx.theme().colors().element_hover))
5768 .id("accept-terms")
5769 .cursor_pointer()
5770 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5771 .on_click(cx.listener(|this, _event, window, cx| {
5772 cx.stop_propagation();
5773 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5774 window.dispatch_action(
5775 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5776 cx,
5777 );
5778 }))
5779 .child(
5780 h_flex()
5781 .flex_1()
5782 .gap_2()
5783 .child(Icon::new(IconName::ZedPredict))
5784 .child(Label::new("Accept Terms of Service"))
5785 .child(div().w_full())
5786 .child(
5787 Icon::new(IconName::ArrowUpRight)
5788 .color(Color::Muted)
5789 .size(IconSize::Small),
5790 )
5791 .into_any_element(),
5792 )
5793 .into_any(),
5794 );
5795 }
5796
5797 let is_refreshing = provider.provider.is_refreshing(cx);
5798
5799 fn pending_completion_container() -> Div {
5800 h_flex()
5801 .h_full()
5802 .flex_1()
5803 .gap_2()
5804 .child(Icon::new(IconName::ZedPredict))
5805 }
5806
5807 let completion = match &self.active_inline_completion {
5808 Some(completion) => match &completion.completion {
5809 InlineCompletion::Move {
5810 target, snapshot, ..
5811 } if !self.has_visible_completions_menu() => {
5812 use text::ToPoint as _;
5813
5814 return Some(
5815 h_flex()
5816 .px_2()
5817 .py_1()
5818 .elevation_2(cx)
5819 .border_color(cx.theme().colors().border)
5820 .rounded_tl(px(0.))
5821 .gap_2()
5822 .child(
5823 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5824 Icon::new(IconName::ZedPredictDown)
5825 } else {
5826 Icon::new(IconName::ZedPredictUp)
5827 },
5828 )
5829 .child(Label::new("Hold").size(LabelSize::Small))
5830 .child(h_flex().children(ui::render_modifiers(
5831 &accept_keystroke.modifiers,
5832 PlatformStyle::platform(),
5833 Some(Color::Default),
5834 Some(IconSize::Small.rems().into()),
5835 false,
5836 )))
5837 .into_any(),
5838 );
5839 }
5840 _ => self.render_edit_prediction_cursor_popover_preview(
5841 completion,
5842 cursor_point,
5843 style,
5844 cx,
5845 )?,
5846 },
5847
5848 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5849 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5850 stale_completion,
5851 cursor_point,
5852 style,
5853 cx,
5854 )?,
5855
5856 None => {
5857 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5858 }
5859 },
5860
5861 None => pending_completion_container().child(Label::new("No Prediction")),
5862 };
5863
5864 let completion = if is_refreshing {
5865 completion
5866 .with_animation(
5867 "loading-completion",
5868 Animation::new(Duration::from_secs(2))
5869 .repeat()
5870 .with_easing(pulsating_between(0.4, 0.8)),
5871 |label, delta| label.opacity(delta),
5872 )
5873 .into_any_element()
5874 } else {
5875 completion.into_any_element()
5876 };
5877
5878 let has_completion = self.active_inline_completion.is_some();
5879
5880 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5881 Some(
5882 h_flex()
5883 .min_w(min_width)
5884 .max_w(max_width)
5885 .flex_1()
5886 .elevation_2(cx)
5887 .border_color(cx.theme().colors().border)
5888 .child(
5889 div()
5890 .flex_1()
5891 .py_1()
5892 .px_2()
5893 .overflow_hidden()
5894 .child(completion),
5895 )
5896 .child(
5897 h_flex()
5898 .h_full()
5899 .border_l_1()
5900 .rounded_r_lg()
5901 .border_color(cx.theme().colors().border)
5902 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5903 .gap_1()
5904 .py_1()
5905 .px_2()
5906 .child(
5907 h_flex()
5908 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5909 .when(is_platform_style_mac, |parent| parent.gap_1())
5910 .child(h_flex().children(ui::render_modifiers(
5911 &accept_keystroke.modifiers,
5912 PlatformStyle::platform(),
5913 Some(if !has_completion {
5914 Color::Muted
5915 } else {
5916 Color::Default
5917 }),
5918 None,
5919 false,
5920 ))),
5921 )
5922 .child(Label::new("Preview").into_any_element())
5923 .opacity(if has_completion { 1.0 } else { 0.4 }),
5924 )
5925 .into_any(),
5926 )
5927 }
5928
5929 fn render_edit_prediction_cursor_popover_preview(
5930 &self,
5931 completion: &InlineCompletionState,
5932 cursor_point: Point,
5933 style: &EditorStyle,
5934 cx: &mut Context<Editor>,
5935 ) -> Option<Div> {
5936 use text::ToPoint as _;
5937
5938 fn render_relative_row_jump(
5939 prefix: impl Into<String>,
5940 current_row: u32,
5941 target_row: u32,
5942 ) -> Div {
5943 let (row_diff, arrow) = if target_row < current_row {
5944 (current_row - target_row, IconName::ArrowUp)
5945 } else {
5946 (target_row - current_row, IconName::ArrowDown)
5947 };
5948
5949 h_flex()
5950 .child(
5951 Label::new(format!("{}{}", prefix.into(), row_diff))
5952 .color(Color::Muted)
5953 .size(LabelSize::Small),
5954 )
5955 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5956 }
5957
5958 match &completion.completion {
5959 InlineCompletion::Move {
5960 target, snapshot, ..
5961 } => Some(
5962 h_flex()
5963 .px_2()
5964 .gap_2()
5965 .flex_1()
5966 .child(
5967 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5968 Icon::new(IconName::ZedPredictDown)
5969 } else {
5970 Icon::new(IconName::ZedPredictUp)
5971 },
5972 )
5973 .child(Label::new("Jump to Edit")),
5974 ),
5975
5976 InlineCompletion::Edit {
5977 edits,
5978 edit_preview,
5979 snapshot,
5980 display_mode: _,
5981 } => {
5982 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5983
5984 let highlighted_edits = crate::inline_completion_edit_text(
5985 &snapshot,
5986 &edits,
5987 edit_preview.as_ref()?,
5988 true,
5989 cx,
5990 );
5991
5992 let len_total = highlighted_edits.text.len();
5993 let first_line = &highlighted_edits.text
5994 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5995 let first_line_len = first_line.len();
5996
5997 let first_highlight_start = highlighted_edits
5998 .highlights
5999 .first()
6000 .map_or(0, |(range, _)| range.start);
6001 let drop_prefix_len = first_line
6002 .char_indices()
6003 .find(|(_, c)| !c.is_whitespace())
6004 .map_or(first_highlight_start, |(ix, _)| {
6005 ix.min(first_highlight_start)
6006 });
6007
6008 let preview_text = &first_line[drop_prefix_len..];
6009 let preview_len = preview_text.len();
6010 let highlights = highlighted_edits
6011 .highlights
6012 .into_iter()
6013 .take_until(|(range, _)| range.start > first_line_len)
6014 .map(|(range, style)| {
6015 (
6016 range.start - drop_prefix_len
6017 ..(range.end - drop_prefix_len).min(preview_len),
6018 style,
6019 )
6020 });
6021
6022 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
6023 .with_highlights(&style.text, highlights);
6024
6025 let preview = h_flex()
6026 .gap_1()
6027 .min_w_16()
6028 .child(styled_text)
6029 .when(len_total > first_line_len, |parent| parent.child("…"));
6030
6031 let left = if first_edit_row != cursor_point.row {
6032 render_relative_row_jump("", cursor_point.row, first_edit_row)
6033 .into_any_element()
6034 } else {
6035 Icon::new(IconName::ZedPredict).into_any_element()
6036 };
6037
6038 Some(
6039 h_flex()
6040 .h_full()
6041 .flex_1()
6042 .gap_2()
6043 .pr_1()
6044 .overflow_x_hidden()
6045 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6046 .child(left)
6047 .child(preview),
6048 )
6049 }
6050 }
6051 }
6052
6053 fn render_context_menu(
6054 &self,
6055 style: &EditorStyle,
6056 max_height_in_lines: u32,
6057 y_flipped: bool,
6058 window: &mut Window,
6059 cx: &mut Context<Editor>,
6060 ) -> Option<AnyElement> {
6061 let menu = self.context_menu.borrow();
6062 let menu = menu.as_ref()?;
6063 if !menu.visible() {
6064 return None;
6065 };
6066 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6067 }
6068
6069 fn render_context_menu_aside(
6070 &self,
6071 style: &EditorStyle,
6072 max_size: Size<Pixels>,
6073 cx: &mut Context<Editor>,
6074 ) -> Option<AnyElement> {
6075 self.context_menu.borrow().as_ref().and_then(|menu| {
6076 if menu.visible() {
6077 menu.render_aside(
6078 style,
6079 max_size,
6080 self.workspace.as_ref().map(|(w, _)| w.clone()),
6081 cx,
6082 )
6083 } else {
6084 None
6085 }
6086 })
6087 }
6088
6089 fn hide_context_menu(
6090 &mut self,
6091 window: &mut Window,
6092 cx: &mut Context<Self>,
6093 ) -> Option<CodeContextMenu> {
6094 cx.notify();
6095 self.completion_tasks.clear();
6096 let context_menu = self.context_menu.borrow_mut().take();
6097 self.stale_inline_completion_in_menu.take();
6098 self.update_visible_inline_completion(window, cx);
6099 context_menu
6100 }
6101
6102 fn show_snippet_choices(
6103 &mut self,
6104 choices: &Vec<String>,
6105 selection: Range<Anchor>,
6106 cx: &mut Context<Self>,
6107 ) {
6108 if selection.start.buffer_id.is_none() {
6109 return;
6110 }
6111 let buffer_id = selection.start.buffer_id.unwrap();
6112 let buffer = self.buffer().read(cx).buffer(buffer_id);
6113 let id = post_inc(&mut self.next_completion_id);
6114
6115 if let Some(buffer) = buffer {
6116 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6117 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6118 ));
6119 }
6120 }
6121
6122 pub fn insert_snippet(
6123 &mut self,
6124 insertion_ranges: &[Range<usize>],
6125 snippet: Snippet,
6126 window: &mut Window,
6127 cx: &mut Context<Self>,
6128 ) -> Result<()> {
6129 struct Tabstop<T> {
6130 is_end_tabstop: bool,
6131 ranges: Vec<Range<T>>,
6132 choices: Option<Vec<String>>,
6133 }
6134
6135 let tabstops = self.buffer.update(cx, |buffer, cx| {
6136 let snippet_text: Arc<str> = snippet.text.clone().into();
6137 buffer.edit(
6138 insertion_ranges
6139 .iter()
6140 .cloned()
6141 .map(|range| (range, snippet_text.clone())),
6142 Some(AutoindentMode::EachLine),
6143 cx,
6144 );
6145
6146 let snapshot = &*buffer.read(cx);
6147 let snippet = &snippet;
6148 snippet
6149 .tabstops
6150 .iter()
6151 .map(|tabstop| {
6152 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6153 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6154 });
6155 let mut tabstop_ranges = tabstop
6156 .ranges
6157 .iter()
6158 .flat_map(|tabstop_range| {
6159 let mut delta = 0_isize;
6160 insertion_ranges.iter().map(move |insertion_range| {
6161 let insertion_start = insertion_range.start as isize + delta;
6162 delta +=
6163 snippet.text.len() as isize - insertion_range.len() as isize;
6164
6165 let start = ((insertion_start + tabstop_range.start) as usize)
6166 .min(snapshot.len());
6167 let end = ((insertion_start + tabstop_range.end) as usize)
6168 .min(snapshot.len());
6169 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6170 })
6171 })
6172 .collect::<Vec<_>>();
6173 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6174
6175 Tabstop {
6176 is_end_tabstop,
6177 ranges: tabstop_ranges,
6178 choices: tabstop.choices.clone(),
6179 }
6180 })
6181 .collect::<Vec<_>>()
6182 });
6183 if let Some(tabstop) = tabstops.first() {
6184 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6185 s.select_ranges(tabstop.ranges.iter().cloned());
6186 });
6187
6188 if let Some(choices) = &tabstop.choices {
6189 if let Some(selection) = tabstop.ranges.first() {
6190 self.show_snippet_choices(choices, selection.clone(), cx)
6191 }
6192 }
6193
6194 // If we're already at the last tabstop and it's at the end of the snippet,
6195 // we're done, we don't need to keep the state around.
6196 if !tabstop.is_end_tabstop {
6197 let choices = tabstops
6198 .iter()
6199 .map(|tabstop| tabstop.choices.clone())
6200 .collect();
6201
6202 let ranges = tabstops
6203 .into_iter()
6204 .map(|tabstop| tabstop.ranges)
6205 .collect::<Vec<_>>();
6206
6207 self.snippet_stack.push(SnippetState {
6208 active_index: 0,
6209 ranges,
6210 choices,
6211 });
6212 }
6213
6214 // Check whether the just-entered snippet ends with an auto-closable bracket.
6215 if self.autoclose_regions.is_empty() {
6216 let snapshot = self.buffer.read(cx).snapshot(cx);
6217 for selection in &mut self.selections.all::<Point>(cx) {
6218 let selection_head = selection.head();
6219 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6220 continue;
6221 };
6222
6223 let mut bracket_pair = None;
6224 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6225 let prev_chars = snapshot
6226 .reversed_chars_at(selection_head)
6227 .collect::<String>();
6228 for (pair, enabled) in scope.brackets() {
6229 if enabled
6230 && pair.close
6231 && prev_chars.starts_with(pair.start.as_str())
6232 && next_chars.starts_with(pair.end.as_str())
6233 {
6234 bracket_pair = Some(pair.clone());
6235 break;
6236 }
6237 }
6238 if let Some(pair) = bracket_pair {
6239 let start = snapshot.anchor_after(selection_head);
6240 let end = snapshot.anchor_after(selection_head);
6241 self.autoclose_regions.push(AutocloseRegion {
6242 selection_id: selection.id,
6243 range: start..end,
6244 pair,
6245 });
6246 }
6247 }
6248 }
6249 }
6250 Ok(())
6251 }
6252
6253 pub fn move_to_next_snippet_tabstop(
6254 &mut self,
6255 window: &mut Window,
6256 cx: &mut Context<Self>,
6257 ) -> bool {
6258 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6259 }
6260
6261 pub fn move_to_prev_snippet_tabstop(
6262 &mut self,
6263 window: &mut Window,
6264 cx: &mut Context<Self>,
6265 ) -> bool {
6266 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6267 }
6268
6269 pub fn move_to_snippet_tabstop(
6270 &mut self,
6271 bias: Bias,
6272 window: &mut Window,
6273 cx: &mut Context<Self>,
6274 ) -> bool {
6275 if let Some(mut snippet) = self.snippet_stack.pop() {
6276 match bias {
6277 Bias::Left => {
6278 if snippet.active_index > 0 {
6279 snippet.active_index -= 1;
6280 } else {
6281 self.snippet_stack.push(snippet);
6282 return false;
6283 }
6284 }
6285 Bias::Right => {
6286 if snippet.active_index + 1 < snippet.ranges.len() {
6287 snippet.active_index += 1;
6288 } else {
6289 self.snippet_stack.push(snippet);
6290 return false;
6291 }
6292 }
6293 }
6294 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6295 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6296 s.select_anchor_ranges(current_ranges.iter().cloned())
6297 });
6298
6299 if let Some(choices) = &snippet.choices[snippet.active_index] {
6300 if let Some(selection) = current_ranges.first() {
6301 self.show_snippet_choices(&choices, selection.clone(), cx);
6302 }
6303 }
6304
6305 // If snippet state is not at the last tabstop, push it back on the stack
6306 if snippet.active_index + 1 < snippet.ranges.len() {
6307 self.snippet_stack.push(snippet);
6308 }
6309 return true;
6310 }
6311 }
6312
6313 false
6314 }
6315
6316 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6317 self.transact(window, cx, |this, window, cx| {
6318 this.select_all(&SelectAll, window, cx);
6319 this.insert("", window, cx);
6320 });
6321 }
6322
6323 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6324 self.transact(window, cx, |this, window, cx| {
6325 this.select_autoclose_pair(window, cx);
6326 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6327 if !this.linked_edit_ranges.is_empty() {
6328 let selections = this.selections.all::<MultiBufferPoint>(cx);
6329 let snapshot = this.buffer.read(cx).snapshot(cx);
6330
6331 for selection in selections.iter() {
6332 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6333 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6334 if selection_start.buffer_id != selection_end.buffer_id {
6335 continue;
6336 }
6337 if let Some(ranges) =
6338 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6339 {
6340 for (buffer, entries) in ranges {
6341 linked_ranges.entry(buffer).or_default().extend(entries);
6342 }
6343 }
6344 }
6345 }
6346
6347 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6348 if !this.selections.line_mode {
6349 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6350 for selection in &mut selections {
6351 if selection.is_empty() {
6352 let old_head = selection.head();
6353 let mut new_head =
6354 movement::left(&display_map, old_head.to_display_point(&display_map))
6355 .to_point(&display_map);
6356 if let Some((buffer, line_buffer_range)) = display_map
6357 .buffer_snapshot
6358 .buffer_line_for_row(MultiBufferRow(old_head.row))
6359 {
6360 let indent_size =
6361 buffer.indent_size_for_line(line_buffer_range.start.row);
6362 let indent_len = match indent_size.kind {
6363 IndentKind::Space => {
6364 buffer.settings_at(line_buffer_range.start, cx).tab_size
6365 }
6366 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6367 };
6368 if old_head.column <= indent_size.len && old_head.column > 0 {
6369 let indent_len = indent_len.get();
6370 new_head = cmp::min(
6371 new_head,
6372 MultiBufferPoint::new(
6373 old_head.row,
6374 ((old_head.column - 1) / indent_len) * indent_len,
6375 ),
6376 );
6377 }
6378 }
6379
6380 selection.set_head(new_head, SelectionGoal::None);
6381 }
6382 }
6383 }
6384
6385 this.signature_help_state.set_backspace_pressed(true);
6386 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6387 s.select(selections)
6388 });
6389 this.insert("", window, cx);
6390 let empty_str: Arc<str> = Arc::from("");
6391 for (buffer, edits) in linked_ranges {
6392 let snapshot = buffer.read(cx).snapshot();
6393 use text::ToPoint as TP;
6394
6395 let edits = edits
6396 .into_iter()
6397 .map(|range| {
6398 let end_point = TP::to_point(&range.end, &snapshot);
6399 let mut start_point = TP::to_point(&range.start, &snapshot);
6400
6401 if end_point == start_point {
6402 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6403 .saturating_sub(1);
6404 start_point =
6405 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6406 };
6407
6408 (start_point..end_point, empty_str.clone())
6409 })
6410 .sorted_by_key(|(range, _)| range.start)
6411 .collect::<Vec<_>>();
6412 buffer.update(cx, |this, cx| {
6413 this.edit(edits, None, cx);
6414 })
6415 }
6416 this.refresh_inline_completion(true, false, window, cx);
6417 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6418 });
6419 }
6420
6421 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6422 self.transact(window, cx, |this, window, cx| {
6423 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6424 let line_mode = s.line_mode;
6425 s.move_with(|map, selection| {
6426 if selection.is_empty() && !line_mode {
6427 let cursor = movement::right(map, selection.head());
6428 selection.end = cursor;
6429 selection.reversed = true;
6430 selection.goal = SelectionGoal::None;
6431 }
6432 })
6433 });
6434 this.insert("", window, cx);
6435 this.refresh_inline_completion(true, false, window, cx);
6436 });
6437 }
6438
6439 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6440 if self.move_to_prev_snippet_tabstop(window, cx) {
6441 return;
6442 }
6443
6444 self.outdent(&Outdent, window, cx);
6445 }
6446
6447 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6448 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6449 return;
6450 }
6451
6452 let mut selections = self.selections.all_adjusted(cx);
6453 let buffer = self.buffer.read(cx);
6454 let snapshot = buffer.snapshot(cx);
6455 let rows_iter = selections.iter().map(|s| s.head().row);
6456 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6457
6458 let mut edits = Vec::new();
6459 let mut prev_edited_row = 0;
6460 let mut row_delta = 0;
6461 for selection in &mut selections {
6462 if selection.start.row != prev_edited_row {
6463 row_delta = 0;
6464 }
6465 prev_edited_row = selection.end.row;
6466
6467 // If the selection is non-empty, then increase the indentation of the selected lines.
6468 if !selection.is_empty() {
6469 row_delta =
6470 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6471 continue;
6472 }
6473
6474 // If the selection is empty and the cursor is in the leading whitespace before the
6475 // suggested indentation, then auto-indent the line.
6476 let cursor = selection.head();
6477 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6478 if let Some(suggested_indent) =
6479 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6480 {
6481 if cursor.column < suggested_indent.len
6482 && cursor.column <= current_indent.len
6483 && current_indent.len <= suggested_indent.len
6484 {
6485 selection.start = Point::new(cursor.row, suggested_indent.len);
6486 selection.end = selection.start;
6487 if row_delta == 0 {
6488 edits.extend(Buffer::edit_for_indent_size_adjustment(
6489 cursor.row,
6490 current_indent,
6491 suggested_indent,
6492 ));
6493 row_delta = suggested_indent.len - current_indent.len;
6494 }
6495 continue;
6496 }
6497 }
6498
6499 // Otherwise, insert a hard or soft tab.
6500 let settings = buffer.settings_at(cursor, cx);
6501 let tab_size = if settings.hard_tabs {
6502 IndentSize::tab()
6503 } else {
6504 let tab_size = settings.tab_size.get();
6505 let char_column = snapshot
6506 .text_for_range(Point::new(cursor.row, 0)..cursor)
6507 .flat_map(str::chars)
6508 .count()
6509 + row_delta as usize;
6510 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6511 IndentSize::spaces(chars_to_next_tab_stop)
6512 };
6513 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6514 selection.end = selection.start;
6515 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6516 row_delta += tab_size.len;
6517 }
6518
6519 self.transact(window, cx, |this, window, cx| {
6520 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6521 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6522 s.select(selections)
6523 });
6524 this.refresh_inline_completion(true, false, window, cx);
6525 });
6526 }
6527
6528 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6529 if self.read_only(cx) {
6530 return;
6531 }
6532 let mut selections = self.selections.all::<Point>(cx);
6533 let mut prev_edited_row = 0;
6534 let mut row_delta = 0;
6535 let mut edits = Vec::new();
6536 let buffer = self.buffer.read(cx);
6537 let snapshot = buffer.snapshot(cx);
6538 for selection in &mut selections {
6539 if selection.start.row != prev_edited_row {
6540 row_delta = 0;
6541 }
6542 prev_edited_row = selection.end.row;
6543
6544 row_delta =
6545 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6546 }
6547
6548 self.transact(window, cx, |this, window, cx| {
6549 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6550 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6551 s.select(selections)
6552 });
6553 });
6554 }
6555
6556 fn indent_selection(
6557 buffer: &MultiBuffer,
6558 snapshot: &MultiBufferSnapshot,
6559 selection: &mut Selection<Point>,
6560 edits: &mut Vec<(Range<Point>, String)>,
6561 delta_for_start_row: u32,
6562 cx: &App,
6563 ) -> u32 {
6564 let settings = buffer.settings_at(selection.start, cx);
6565 let tab_size = settings.tab_size.get();
6566 let indent_kind = if settings.hard_tabs {
6567 IndentKind::Tab
6568 } else {
6569 IndentKind::Space
6570 };
6571 let mut start_row = selection.start.row;
6572 let mut end_row = selection.end.row + 1;
6573
6574 // If a selection ends at the beginning of a line, don't indent
6575 // that last line.
6576 if selection.end.column == 0 && selection.end.row > selection.start.row {
6577 end_row -= 1;
6578 }
6579
6580 // Avoid re-indenting a row that has already been indented by a
6581 // previous selection, but still update this selection's column
6582 // to reflect that indentation.
6583 if delta_for_start_row > 0 {
6584 start_row += 1;
6585 selection.start.column += delta_for_start_row;
6586 if selection.end.row == selection.start.row {
6587 selection.end.column += delta_for_start_row;
6588 }
6589 }
6590
6591 let mut delta_for_end_row = 0;
6592 let has_multiple_rows = start_row + 1 != end_row;
6593 for row in start_row..end_row {
6594 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6595 let indent_delta = match (current_indent.kind, indent_kind) {
6596 (IndentKind::Space, IndentKind::Space) => {
6597 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6598 IndentSize::spaces(columns_to_next_tab_stop)
6599 }
6600 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6601 (_, IndentKind::Tab) => IndentSize::tab(),
6602 };
6603
6604 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6605 0
6606 } else {
6607 selection.start.column
6608 };
6609 let row_start = Point::new(row, start);
6610 edits.push((
6611 row_start..row_start,
6612 indent_delta.chars().collect::<String>(),
6613 ));
6614
6615 // Update this selection's endpoints to reflect the indentation.
6616 if row == selection.start.row {
6617 selection.start.column += indent_delta.len;
6618 }
6619 if row == selection.end.row {
6620 selection.end.column += indent_delta.len;
6621 delta_for_end_row = indent_delta.len;
6622 }
6623 }
6624
6625 if selection.start.row == selection.end.row {
6626 delta_for_start_row + delta_for_end_row
6627 } else {
6628 delta_for_end_row
6629 }
6630 }
6631
6632 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6633 if self.read_only(cx) {
6634 return;
6635 }
6636 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6637 let selections = self.selections.all::<Point>(cx);
6638 let mut deletion_ranges = Vec::new();
6639 let mut last_outdent = None;
6640 {
6641 let buffer = self.buffer.read(cx);
6642 let snapshot = buffer.snapshot(cx);
6643 for selection in &selections {
6644 let settings = buffer.settings_at(selection.start, cx);
6645 let tab_size = settings.tab_size.get();
6646 let mut rows = selection.spanned_rows(false, &display_map);
6647
6648 // Avoid re-outdenting a row that has already been outdented by a
6649 // previous selection.
6650 if let Some(last_row) = last_outdent {
6651 if last_row == rows.start {
6652 rows.start = rows.start.next_row();
6653 }
6654 }
6655 let has_multiple_rows = rows.len() > 1;
6656 for row in rows.iter_rows() {
6657 let indent_size = snapshot.indent_size_for_line(row);
6658 if indent_size.len > 0 {
6659 let deletion_len = match indent_size.kind {
6660 IndentKind::Space => {
6661 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6662 if columns_to_prev_tab_stop == 0 {
6663 tab_size
6664 } else {
6665 columns_to_prev_tab_stop
6666 }
6667 }
6668 IndentKind::Tab => 1,
6669 };
6670 let start = if has_multiple_rows
6671 || deletion_len > selection.start.column
6672 || indent_size.len < selection.start.column
6673 {
6674 0
6675 } else {
6676 selection.start.column - deletion_len
6677 };
6678 deletion_ranges.push(
6679 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6680 );
6681 last_outdent = Some(row);
6682 }
6683 }
6684 }
6685 }
6686
6687 self.transact(window, cx, |this, window, cx| {
6688 this.buffer.update(cx, |buffer, cx| {
6689 let empty_str: Arc<str> = Arc::default();
6690 buffer.edit(
6691 deletion_ranges
6692 .into_iter()
6693 .map(|range| (range, empty_str.clone())),
6694 None,
6695 cx,
6696 );
6697 });
6698 let selections = this.selections.all::<usize>(cx);
6699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6700 s.select(selections)
6701 });
6702 });
6703 }
6704
6705 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6706 if self.read_only(cx) {
6707 return;
6708 }
6709 let selections = self
6710 .selections
6711 .all::<usize>(cx)
6712 .into_iter()
6713 .map(|s| s.range());
6714
6715 self.transact(window, cx, |this, window, cx| {
6716 this.buffer.update(cx, |buffer, cx| {
6717 buffer.autoindent_ranges(selections, cx);
6718 });
6719 let selections = this.selections.all::<usize>(cx);
6720 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6721 s.select(selections)
6722 });
6723 });
6724 }
6725
6726 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6727 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6728 let selections = self.selections.all::<Point>(cx);
6729
6730 let mut new_cursors = Vec::new();
6731 let mut edit_ranges = Vec::new();
6732 let mut selections = selections.iter().peekable();
6733 while let Some(selection) = selections.next() {
6734 let mut rows = selection.spanned_rows(false, &display_map);
6735 let goal_display_column = selection.head().to_display_point(&display_map).column();
6736
6737 // Accumulate contiguous regions of rows that we want to delete.
6738 while let Some(next_selection) = selections.peek() {
6739 let next_rows = next_selection.spanned_rows(false, &display_map);
6740 if next_rows.start <= rows.end {
6741 rows.end = next_rows.end;
6742 selections.next().unwrap();
6743 } else {
6744 break;
6745 }
6746 }
6747
6748 let buffer = &display_map.buffer_snapshot;
6749 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6750 let edit_end;
6751 let cursor_buffer_row;
6752 if buffer.max_point().row >= rows.end.0 {
6753 // If there's a line after the range, delete the \n from the end of the row range
6754 // and position the cursor on the next line.
6755 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6756 cursor_buffer_row = rows.end;
6757 } else {
6758 // If there isn't a line after the range, delete the \n from the line before the
6759 // start of the row range and position the cursor there.
6760 edit_start = edit_start.saturating_sub(1);
6761 edit_end = buffer.len();
6762 cursor_buffer_row = rows.start.previous_row();
6763 }
6764
6765 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6766 *cursor.column_mut() =
6767 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6768
6769 new_cursors.push((
6770 selection.id,
6771 buffer.anchor_after(cursor.to_point(&display_map)),
6772 ));
6773 edit_ranges.push(edit_start..edit_end);
6774 }
6775
6776 self.transact(window, cx, |this, window, cx| {
6777 let buffer = this.buffer.update(cx, |buffer, cx| {
6778 let empty_str: Arc<str> = Arc::default();
6779 buffer.edit(
6780 edit_ranges
6781 .into_iter()
6782 .map(|range| (range, empty_str.clone())),
6783 None,
6784 cx,
6785 );
6786 buffer.snapshot(cx)
6787 });
6788 let new_selections = new_cursors
6789 .into_iter()
6790 .map(|(id, cursor)| {
6791 let cursor = cursor.to_point(&buffer);
6792 Selection {
6793 id,
6794 start: cursor,
6795 end: cursor,
6796 reversed: false,
6797 goal: SelectionGoal::None,
6798 }
6799 })
6800 .collect();
6801
6802 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6803 s.select(new_selections);
6804 });
6805 });
6806 }
6807
6808 pub fn join_lines_impl(
6809 &mut self,
6810 insert_whitespace: bool,
6811 window: &mut Window,
6812 cx: &mut Context<Self>,
6813 ) {
6814 if self.read_only(cx) {
6815 return;
6816 }
6817 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6818 for selection in self.selections.all::<Point>(cx) {
6819 let start = MultiBufferRow(selection.start.row);
6820 // Treat single line selections as if they include the next line. Otherwise this action
6821 // would do nothing for single line selections individual cursors.
6822 let end = if selection.start.row == selection.end.row {
6823 MultiBufferRow(selection.start.row + 1)
6824 } else {
6825 MultiBufferRow(selection.end.row)
6826 };
6827
6828 if let Some(last_row_range) = row_ranges.last_mut() {
6829 if start <= last_row_range.end {
6830 last_row_range.end = end;
6831 continue;
6832 }
6833 }
6834 row_ranges.push(start..end);
6835 }
6836
6837 let snapshot = self.buffer.read(cx).snapshot(cx);
6838 let mut cursor_positions = Vec::new();
6839 for row_range in &row_ranges {
6840 let anchor = snapshot.anchor_before(Point::new(
6841 row_range.end.previous_row().0,
6842 snapshot.line_len(row_range.end.previous_row()),
6843 ));
6844 cursor_positions.push(anchor..anchor);
6845 }
6846
6847 self.transact(window, cx, |this, window, cx| {
6848 for row_range in row_ranges.into_iter().rev() {
6849 for row in row_range.iter_rows().rev() {
6850 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6851 let next_line_row = row.next_row();
6852 let indent = snapshot.indent_size_for_line(next_line_row);
6853 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6854
6855 let replace =
6856 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6857 " "
6858 } else {
6859 ""
6860 };
6861
6862 this.buffer.update(cx, |buffer, cx| {
6863 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6864 });
6865 }
6866 }
6867
6868 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6869 s.select_anchor_ranges(cursor_positions)
6870 });
6871 });
6872 }
6873
6874 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6875 self.join_lines_impl(true, window, cx);
6876 }
6877
6878 pub fn sort_lines_case_sensitive(
6879 &mut self,
6880 _: &SortLinesCaseSensitive,
6881 window: &mut Window,
6882 cx: &mut Context<Self>,
6883 ) {
6884 self.manipulate_lines(window, cx, |lines| lines.sort())
6885 }
6886
6887 pub fn sort_lines_case_insensitive(
6888 &mut self,
6889 _: &SortLinesCaseInsensitive,
6890 window: &mut Window,
6891 cx: &mut Context<Self>,
6892 ) {
6893 self.manipulate_lines(window, cx, |lines| {
6894 lines.sort_by_key(|line| line.to_lowercase())
6895 })
6896 }
6897
6898 pub fn unique_lines_case_insensitive(
6899 &mut self,
6900 _: &UniqueLinesCaseInsensitive,
6901 window: &mut Window,
6902 cx: &mut Context<Self>,
6903 ) {
6904 self.manipulate_lines(window, cx, |lines| {
6905 let mut seen = HashSet::default();
6906 lines.retain(|line| seen.insert(line.to_lowercase()));
6907 })
6908 }
6909
6910 pub fn unique_lines_case_sensitive(
6911 &mut self,
6912 _: &UniqueLinesCaseSensitive,
6913 window: &mut Window,
6914 cx: &mut Context<Self>,
6915 ) {
6916 self.manipulate_lines(window, cx, |lines| {
6917 let mut seen = HashSet::default();
6918 lines.retain(|line| seen.insert(*line));
6919 })
6920 }
6921
6922 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6923 let mut revert_changes = HashMap::default();
6924 let snapshot = self.snapshot(window, cx);
6925 for hunk in snapshot
6926 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6927 {
6928 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6929 }
6930 if !revert_changes.is_empty() {
6931 self.transact(window, cx, |editor, window, cx| {
6932 editor.revert(revert_changes, window, cx);
6933 });
6934 }
6935 }
6936
6937 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6938 let Some(project) = self.project.clone() else {
6939 return;
6940 };
6941 self.reload(project, window, cx)
6942 .detach_and_notify_err(window, cx);
6943 }
6944
6945 pub fn revert_selected_hunks(
6946 &mut self,
6947 _: &RevertSelectedHunks,
6948 window: &mut Window,
6949 cx: &mut Context<Self>,
6950 ) {
6951 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6952 self.revert_hunks_in_ranges(selections, window, cx);
6953 }
6954
6955 fn revert_hunks_in_ranges(
6956 &mut self,
6957 ranges: impl Iterator<Item = Range<Point>>,
6958 window: &mut Window,
6959 cx: &mut Context<Editor>,
6960 ) {
6961 let mut revert_changes = HashMap::default();
6962 let snapshot = self.snapshot(window, cx);
6963 for hunk in &snapshot.hunks_for_ranges(ranges) {
6964 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6965 }
6966 if !revert_changes.is_empty() {
6967 self.transact(window, cx, |editor, window, cx| {
6968 editor.revert(revert_changes, window, cx);
6969 });
6970 }
6971 }
6972
6973 pub fn open_active_item_in_terminal(
6974 &mut self,
6975 _: &OpenInTerminal,
6976 window: &mut Window,
6977 cx: &mut Context<Self>,
6978 ) {
6979 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6980 let project_path = buffer.read(cx).project_path(cx)?;
6981 let project = self.project.as_ref()?.read(cx);
6982 let entry = project.entry_for_path(&project_path, cx)?;
6983 let parent = match &entry.canonical_path {
6984 Some(canonical_path) => canonical_path.to_path_buf(),
6985 None => project.absolute_path(&project_path, cx)?,
6986 }
6987 .parent()?
6988 .to_path_buf();
6989 Some(parent)
6990 }) {
6991 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6992 }
6993 }
6994
6995 pub fn prepare_revert_change(
6996 &self,
6997 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6998 hunk: &MultiBufferDiffHunk,
6999 cx: &mut App,
7000 ) -> Option<()> {
7001 let buffer = self.buffer.read(cx);
7002 let diff = buffer.diff_for(hunk.buffer_id)?;
7003 let buffer = buffer.buffer(hunk.buffer_id)?;
7004 let buffer = buffer.read(cx);
7005 let original_text = diff
7006 .read(cx)
7007 .base_text()
7008 .as_ref()?
7009 .as_rope()
7010 .slice(hunk.diff_base_byte_range.clone());
7011 let buffer_snapshot = buffer.snapshot();
7012 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7013 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7014 probe
7015 .0
7016 .start
7017 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7018 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7019 }) {
7020 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7021 Some(())
7022 } else {
7023 None
7024 }
7025 }
7026
7027 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7028 self.manipulate_lines(window, cx, |lines| lines.reverse())
7029 }
7030
7031 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7032 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7033 }
7034
7035 fn manipulate_lines<Fn>(
7036 &mut self,
7037 window: &mut Window,
7038 cx: &mut Context<Self>,
7039 mut callback: Fn,
7040 ) where
7041 Fn: FnMut(&mut Vec<&str>),
7042 {
7043 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7044 let buffer = self.buffer.read(cx).snapshot(cx);
7045
7046 let mut edits = Vec::new();
7047
7048 let selections = self.selections.all::<Point>(cx);
7049 let mut selections = selections.iter().peekable();
7050 let mut contiguous_row_selections = Vec::new();
7051 let mut new_selections = Vec::new();
7052 let mut added_lines = 0;
7053 let mut removed_lines = 0;
7054
7055 while let Some(selection) = selections.next() {
7056 let (start_row, end_row) = consume_contiguous_rows(
7057 &mut contiguous_row_selections,
7058 selection,
7059 &display_map,
7060 &mut selections,
7061 );
7062
7063 let start_point = Point::new(start_row.0, 0);
7064 let end_point = Point::new(
7065 end_row.previous_row().0,
7066 buffer.line_len(end_row.previous_row()),
7067 );
7068 let text = buffer
7069 .text_for_range(start_point..end_point)
7070 .collect::<String>();
7071
7072 let mut lines = text.split('\n').collect_vec();
7073
7074 let lines_before = lines.len();
7075 callback(&mut lines);
7076 let lines_after = lines.len();
7077
7078 edits.push((start_point..end_point, lines.join("\n")));
7079
7080 // Selections must change based on added and removed line count
7081 let start_row =
7082 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7083 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7084 new_selections.push(Selection {
7085 id: selection.id,
7086 start: start_row,
7087 end: end_row,
7088 goal: SelectionGoal::None,
7089 reversed: selection.reversed,
7090 });
7091
7092 if lines_after > lines_before {
7093 added_lines += lines_after - lines_before;
7094 } else if lines_before > lines_after {
7095 removed_lines += lines_before - lines_after;
7096 }
7097 }
7098
7099 self.transact(window, cx, |this, window, cx| {
7100 let buffer = this.buffer.update(cx, |buffer, cx| {
7101 buffer.edit(edits, None, cx);
7102 buffer.snapshot(cx)
7103 });
7104
7105 // Recalculate offsets on newly edited buffer
7106 let new_selections = new_selections
7107 .iter()
7108 .map(|s| {
7109 let start_point = Point::new(s.start.0, 0);
7110 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7111 Selection {
7112 id: s.id,
7113 start: buffer.point_to_offset(start_point),
7114 end: buffer.point_to_offset(end_point),
7115 goal: s.goal,
7116 reversed: s.reversed,
7117 }
7118 })
7119 .collect();
7120
7121 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7122 s.select(new_selections);
7123 });
7124
7125 this.request_autoscroll(Autoscroll::fit(), cx);
7126 });
7127 }
7128
7129 pub fn convert_to_upper_case(
7130 &mut self,
7131 _: &ConvertToUpperCase,
7132 window: &mut Window,
7133 cx: &mut Context<Self>,
7134 ) {
7135 self.manipulate_text(window, cx, |text| text.to_uppercase())
7136 }
7137
7138 pub fn convert_to_lower_case(
7139 &mut self,
7140 _: &ConvertToLowerCase,
7141 window: &mut Window,
7142 cx: &mut Context<Self>,
7143 ) {
7144 self.manipulate_text(window, cx, |text| text.to_lowercase())
7145 }
7146
7147 pub fn convert_to_title_case(
7148 &mut self,
7149 _: &ConvertToTitleCase,
7150 window: &mut Window,
7151 cx: &mut Context<Self>,
7152 ) {
7153 self.manipulate_text(window, cx, |text| {
7154 text.split('\n')
7155 .map(|line| line.to_case(Case::Title))
7156 .join("\n")
7157 })
7158 }
7159
7160 pub fn convert_to_snake_case(
7161 &mut self,
7162 _: &ConvertToSnakeCase,
7163 window: &mut Window,
7164 cx: &mut Context<Self>,
7165 ) {
7166 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7167 }
7168
7169 pub fn convert_to_kebab_case(
7170 &mut self,
7171 _: &ConvertToKebabCase,
7172 window: &mut Window,
7173 cx: &mut Context<Self>,
7174 ) {
7175 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7176 }
7177
7178 pub fn convert_to_upper_camel_case(
7179 &mut self,
7180 _: &ConvertToUpperCamelCase,
7181 window: &mut Window,
7182 cx: &mut Context<Self>,
7183 ) {
7184 self.manipulate_text(window, cx, |text| {
7185 text.split('\n')
7186 .map(|line| line.to_case(Case::UpperCamel))
7187 .join("\n")
7188 })
7189 }
7190
7191 pub fn convert_to_lower_camel_case(
7192 &mut self,
7193 _: &ConvertToLowerCamelCase,
7194 window: &mut Window,
7195 cx: &mut Context<Self>,
7196 ) {
7197 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7198 }
7199
7200 pub fn convert_to_opposite_case(
7201 &mut self,
7202 _: &ConvertToOppositeCase,
7203 window: &mut Window,
7204 cx: &mut Context<Self>,
7205 ) {
7206 self.manipulate_text(window, cx, |text| {
7207 text.chars()
7208 .fold(String::with_capacity(text.len()), |mut t, c| {
7209 if c.is_uppercase() {
7210 t.extend(c.to_lowercase());
7211 } else {
7212 t.extend(c.to_uppercase());
7213 }
7214 t
7215 })
7216 })
7217 }
7218
7219 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7220 where
7221 Fn: FnMut(&str) -> String,
7222 {
7223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7224 let buffer = self.buffer.read(cx).snapshot(cx);
7225
7226 let mut new_selections = Vec::new();
7227 let mut edits = Vec::new();
7228 let mut selection_adjustment = 0i32;
7229
7230 for selection in self.selections.all::<usize>(cx) {
7231 let selection_is_empty = selection.is_empty();
7232
7233 let (start, end) = if selection_is_empty {
7234 let word_range = movement::surrounding_word(
7235 &display_map,
7236 selection.start.to_display_point(&display_map),
7237 );
7238 let start = word_range.start.to_offset(&display_map, Bias::Left);
7239 let end = word_range.end.to_offset(&display_map, Bias::Left);
7240 (start, end)
7241 } else {
7242 (selection.start, selection.end)
7243 };
7244
7245 let text = buffer.text_for_range(start..end).collect::<String>();
7246 let old_length = text.len() as i32;
7247 let text = callback(&text);
7248
7249 new_selections.push(Selection {
7250 start: (start as i32 - selection_adjustment) as usize,
7251 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7252 goal: SelectionGoal::None,
7253 ..selection
7254 });
7255
7256 selection_adjustment += old_length - text.len() as i32;
7257
7258 edits.push((start..end, text));
7259 }
7260
7261 self.transact(window, cx, |this, window, cx| {
7262 this.buffer.update(cx, |buffer, cx| {
7263 buffer.edit(edits, None, cx);
7264 });
7265
7266 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7267 s.select(new_selections);
7268 });
7269
7270 this.request_autoscroll(Autoscroll::fit(), cx);
7271 });
7272 }
7273
7274 pub fn duplicate(
7275 &mut self,
7276 upwards: bool,
7277 whole_lines: bool,
7278 window: &mut Window,
7279 cx: &mut Context<Self>,
7280 ) {
7281 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7282 let buffer = &display_map.buffer_snapshot;
7283 let selections = self.selections.all::<Point>(cx);
7284
7285 let mut edits = Vec::new();
7286 let mut selections_iter = selections.iter().peekable();
7287 while let Some(selection) = selections_iter.next() {
7288 let mut rows = selection.spanned_rows(false, &display_map);
7289 // duplicate line-wise
7290 if whole_lines || selection.start == selection.end {
7291 // Avoid duplicating the same lines twice.
7292 while let Some(next_selection) = selections_iter.peek() {
7293 let next_rows = next_selection.spanned_rows(false, &display_map);
7294 if next_rows.start < rows.end {
7295 rows.end = next_rows.end;
7296 selections_iter.next().unwrap();
7297 } else {
7298 break;
7299 }
7300 }
7301
7302 // Copy the text from the selected row region and splice it either at the start
7303 // or end of the region.
7304 let start = Point::new(rows.start.0, 0);
7305 let end = Point::new(
7306 rows.end.previous_row().0,
7307 buffer.line_len(rows.end.previous_row()),
7308 );
7309 let text = buffer
7310 .text_for_range(start..end)
7311 .chain(Some("\n"))
7312 .collect::<String>();
7313 let insert_location = if upwards {
7314 Point::new(rows.end.0, 0)
7315 } else {
7316 start
7317 };
7318 edits.push((insert_location..insert_location, text));
7319 } else {
7320 // duplicate character-wise
7321 let start = selection.start;
7322 let end = selection.end;
7323 let text = buffer.text_for_range(start..end).collect::<String>();
7324 edits.push((selection.end..selection.end, text));
7325 }
7326 }
7327
7328 self.transact(window, cx, |this, _, cx| {
7329 this.buffer.update(cx, |buffer, cx| {
7330 buffer.edit(edits, None, cx);
7331 });
7332
7333 this.request_autoscroll(Autoscroll::fit(), cx);
7334 });
7335 }
7336
7337 pub fn duplicate_line_up(
7338 &mut self,
7339 _: &DuplicateLineUp,
7340 window: &mut Window,
7341 cx: &mut Context<Self>,
7342 ) {
7343 self.duplicate(true, true, window, cx);
7344 }
7345
7346 pub fn duplicate_line_down(
7347 &mut self,
7348 _: &DuplicateLineDown,
7349 window: &mut Window,
7350 cx: &mut Context<Self>,
7351 ) {
7352 self.duplicate(false, true, window, cx);
7353 }
7354
7355 pub fn duplicate_selection(
7356 &mut self,
7357 _: &DuplicateSelection,
7358 window: &mut Window,
7359 cx: &mut Context<Self>,
7360 ) {
7361 self.duplicate(false, false, window, cx);
7362 }
7363
7364 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7366 let buffer = self.buffer.read(cx).snapshot(cx);
7367
7368 let mut edits = Vec::new();
7369 let mut unfold_ranges = Vec::new();
7370 let mut refold_creases = Vec::new();
7371
7372 let selections = self.selections.all::<Point>(cx);
7373 let mut selections = selections.iter().peekable();
7374 let mut contiguous_row_selections = Vec::new();
7375 let mut new_selections = Vec::new();
7376
7377 while let Some(selection) = selections.next() {
7378 // Find all the selections that span a contiguous row range
7379 let (start_row, end_row) = consume_contiguous_rows(
7380 &mut contiguous_row_selections,
7381 selection,
7382 &display_map,
7383 &mut selections,
7384 );
7385
7386 // Move the text spanned by the row range to be before the line preceding the row range
7387 if start_row.0 > 0 {
7388 let range_to_move = Point::new(
7389 start_row.previous_row().0,
7390 buffer.line_len(start_row.previous_row()),
7391 )
7392 ..Point::new(
7393 end_row.previous_row().0,
7394 buffer.line_len(end_row.previous_row()),
7395 );
7396 let insertion_point = display_map
7397 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7398 .0;
7399
7400 // Don't move lines across excerpts
7401 if buffer
7402 .excerpt_containing(insertion_point..range_to_move.end)
7403 .is_some()
7404 {
7405 let text = buffer
7406 .text_for_range(range_to_move.clone())
7407 .flat_map(|s| s.chars())
7408 .skip(1)
7409 .chain(['\n'])
7410 .collect::<String>();
7411
7412 edits.push((
7413 buffer.anchor_after(range_to_move.start)
7414 ..buffer.anchor_before(range_to_move.end),
7415 String::new(),
7416 ));
7417 let insertion_anchor = buffer.anchor_after(insertion_point);
7418 edits.push((insertion_anchor..insertion_anchor, text));
7419
7420 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7421
7422 // Move selections up
7423 new_selections.extend(contiguous_row_selections.drain(..).map(
7424 |mut selection| {
7425 selection.start.row -= row_delta;
7426 selection.end.row -= row_delta;
7427 selection
7428 },
7429 ));
7430
7431 // Move folds up
7432 unfold_ranges.push(range_to_move.clone());
7433 for fold in display_map.folds_in_range(
7434 buffer.anchor_before(range_to_move.start)
7435 ..buffer.anchor_after(range_to_move.end),
7436 ) {
7437 let mut start = fold.range.start.to_point(&buffer);
7438 let mut end = fold.range.end.to_point(&buffer);
7439 start.row -= row_delta;
7440 end.row -= row_delta;
7441 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7442 }
7443 }
7444 }
7445
7446 // If we didn't move line(s), preserve the existing selections
7447 new_selections.append(&mut contiguous_row_selections);
7448 }
7449
7450 self.transact(window, cx, |this, window, cx| {
7451 this.unfold_ranges(&unfold_ranges, true, true, cx);
7452 this.buffer.update(cx, |buffer, cx| {
7453 for (range, text) in edits {
7454 buffer.edit([(range, text)], None, cx);
7455 }
7456 });
7457 this.fold_creases(refold_creases, true, window, cx);
7458 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7459 s.select(new_selections);
7460 })
7461 });
7462 }
7463
7464 pub fn move_line_down(
7465 &mut self,
7466 _: &MoveLineDown,
7467 window: &mut Window,
7468 cx: &mut Context<Self>,
7469 ) {
7470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7471 let buffer = self.buffer.read(cx).snapshot(cx);
7472
7473 let mut edits = Vec::new();
7474 let mut unfold_ranges = Vec::new();
7475 let mut refold_creases = Vec::new();
7476
7477 let selections = self.selections.all::<Point>(cx);
7478 let mut selections = selections.iter().peekable();
7479 let mut contiguous_row_selections = Vec::new();
7480 let mut new_selections = Vec::new();
7481
7482 while let Some(selection) = selections.next() {
7483 // Find all the selections that span a contiguous row range
7484 let (start_row, end_row) = consume_contiguous_rows(
7485 &mut contiguous_row_selections,
7486 selection,
7487 &display_map,
7488 &mut selections,
7489 );
7490
7491 // Move the text spanned by the row range to be after the last line of the row range
7492 if end_row.0 <= buffer.max_point().row {
7493 let range_to_move =
7494 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7495 let insertion_point = display_map
7496 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7497 .0;
7498
7499 // Don't move lines across excerpt boundaries
7500 if buffer
7501 .excerpt_containing(range_to_move.start..insertion_point)
7502 .is_some()
7503 {
7504 let mut text = String::from("\n");
7505 text.extend(buffer.text_for_range(range_to_move.clone()));
7506 text.pop(); // Drop trailing newline
7507 edits.push((
7508 buffer.anchor_after(range_to_move.start)
7509 ..buffer.anchor_before(range_to_move.end),
7510 String::new(),
7511 ));
7512 let insertion_anchor = buffer.anchor_after(insertion_point);
7513 edits.push((insertion_anchor..insertion_anchor, text));
7514
7515 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7516
7517 // Move selections down
7518 new_selections.extend(contiguous_row_selections.drain(..).map(
7519 |mut selection| {
7520 selection.start.row += row_delta;
7521 selection.end.row += row_delta;
7522 selection
7523 },
7524 ));
7525
7526 // Move folds down
7527 unfold_ranges.push(range_to_move.clone());
7528 for fold in display_map.folds_in_range(
7529 buffer.anchor_before(range_to_move.start)
7530 ..buffer.anchor_after(range_to_move.end),
7531 ) {
7532 let mut start = fold.range.start.to_point(&buffer);
7533 let mut end = fold.range.end.to_point(&buffer);
7534 start.row += row_delta;
7535 end.row += row_delta;
7536 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7537 }
7538 }
7539 }
7540
7541 // If we didn't move line(s), preserve the existing selections
7542 new_selections.append(&mut contiguous_row_selections);
7543 }
7544
7545 self.transact(window, cx, |this, window, cx| {
7546 this.unfold_ranges(&unfold_ranges, true, true, cx);
7547 this.buffer.update(cx, |buffer, cx| {
7548 for (range, text) in edits {
7549 buffer.edit([(range, text)], None, cx);
7550 }
7551 });
7552 this.fold_creases(refold_creases, true, window, cx);
7553 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7554 s.select(new_selections)
7555 });
7556 });
7557 }
7558
7559 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7560 let text_layout_details = &self.text_layout_details(window);
7561 self.transact(window, cx, |this, window, cx| {
7562 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7563 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7564 let line_mode = s.line_mode;
7565 s.move_with(|display_map, selection| {
7566 if !selection.is_empty() || line_mode {
7567 return;
7568 }
7569
7570 let mut head = selection.head();
7571 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7572 if head.column() == display_map.line_len(head.row()) {
7573 transpose_offset = display_map
7574 .buffer_snapshot
7575 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7576 }
7577
7578 if transpose_offset == 0 {
7579 return;
7580 }
7581
7582 *head.column_mut() += 1;
7583 head = display_map.clip_point(head, Bias::Right);
7584 let goal = SelectionGoal::HorizontalPosition(
7585 display_map
7586 .x_for_display_point(head, text_layout_details)
7587 .into(),
7588 );
7589 selection.collapse_to(head, goal);
7590
7591 let transpose_start = display_map
7592 .buffer_snapshot
7593 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7594 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7595 let transpose_end = display_map
7596 .buffer_snapshot
7597 .clip_offset(transpose_offset + 1, Bias::Right);
7598 if let Some(ch) =
7599 display_map.buffer_snapshot.chars_at(transpose_start).next()
7600 {
7601 edits.push((transpose_start..transpose_offset, String::new()));
7602 edits.push((transpose_end..transpose_end, ch.to_string()));
7603 }
7604 }
7605 });
7606 edits
7607 });
7608 this.buffer
7609 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7610 let selections = this.selections.all::<usize>(cx);
7611 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7612 s.select(selections);
7613 });
7614 });
7615 }
7616
7617 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7618 self.rewrap_impl(IsVimMode::No, cx)
7619 }
7620
7621 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7622 let buffer = self.buffer.read(cx).snapshot(cx);
7623 let selections = self.selections.all::<Point>(cx);
7624 let mut selections = selections.iter().peekable();
7625
7626 let mut edits = Vec::new();
7627 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7628
7629 while let Some(selection) = selections.next() {
7630 let mut start_row = selection.start.row;
7631 let mut end_row = selection.end.row;
7632
7633 // Skip selections that overlap with a range that has already been rewrapped.
7634 let selection_range = start_row..end_row;
7635 if rewrapped_row_ranges
7636 .iter()
7637 .any(|range| range.overlaps(&selection_range))
7638 {
7639 continue;
7640 }
7641
7642 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7643
7644 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7645 match language_scope.language_name().as_ref() {
7646 "Markdown" | "Plain Text" => {
7647 should_rewrap = true;
7648 }
7649 _ => {}
7650 }
7651 }
7652
7653 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7654
7655 // Since not all lines in the selection may be at the same indent
7656 // level, choose the indent size that is the most common between all
7657 // of the lines.
7658 //
7659 // If there is a tie, we use the deepest indent.
7660 let (indent_size, indent_end) = {
7661 let mut indent_size_occurrences = HashMap::default();
7662 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7663
7664 for row in start_row..=end_row {
7665 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7666 rows_by_indent_size.entry(indent).or_default().push(row);
7667 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7668 }
7669
7670 let indent_size = indent_size_occurrences
7671 .into_iter()
7672 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7673 .map(|(indent, _)| indent)
7674 .unwrap_or_default();
7675 let row = rows_by_indent_size[&indent_size][0];
7676 let indent_end = Point::new(row, indent_size.len);
7677
7678 (indent_size, indent_end)
7679 };
7680
7681 let mut line_prefix = indent_size.chars().collect::<String>();
7682
7683 if let Some(comment_prefix) =
7684 buffer
7685 .language_scope_at(selection.head())
7686 .and_then(|language| {
7687 language
7688 .line_comment_prefixes()
7689 .iter()
7690 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7691 .cloned()
7692 })
7693 {
7694 line_prefix.push_str(&comment_prefix);
7695 should_rewrap = true;
7696 }
7697
7698 if !should_rewrap {
7699 continue;
7700 }
7701
7702 if selection.is_empty() {
7703 'expand_upwards: while start_row > 0 {
7704 let prev_row = start_row - 1;
7705 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7706 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7707 {
7708 start_row = prev_row;
7709 } else {
7710 break 'expand_upwards;
7711 }
7712 }
7713
7714 'expand_downwards: while end_row < buffer.max_point().row {
7715 let next_row = end_row + 1;
7716 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7717 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7718 {
7719 end_row = next_row;
7720 } else {
7721 break 'expand_downwards;
7722 }
7723 }
7724 }
7725
7726 let start = Point::new(start_row, 0);
7727 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7728 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7729 let Some(lines_without_prefixes) = selection_text
7730 .lines()
7731 .map(|line| {
7732 line.strip_prefix(&line_prefix)
7733 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7734 .ok_or_else(|| {
7735 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7736 })
7737 })
7738 .collect::<Result<Vec<_>, _>>()
7739 .log_err()
7740 else {
7741 continue;
7742 };
7743
7744 let wrap_column = buffer
7745 .settings_at(Point::new(start_row, 0), cx)
7746 .preferred_line_length as usize;
7747 let wrapped_text = wrap_with_prefix(
7748 line_prefix,
7749 lines_without_prefixes.join(" "),
7750 wrap_column,
7751 tab_size,
7752 );
7753
7754 // TODO: should always use char-based diff while still supporting cursor behavior that
7755 // matches vim.
7756 let diff = match is_vim_mode {
7757 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7758 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7759 };
7760 let mut offset = start.to_offset(&buffer);
7761 let mut moved_since_edit = true;
7762
7763 for change in diff.iter_all_changes() {
7764 let value = change.value();
7765 match change.tag() {
7766 ChangeTag::Equal => {
7767 offset += value.len();
7768 moved_since_edit = true;
7769 }
7770 ChangeTag::Delete => {
7771 let start = buffer.anchor_after(offset);
7772 let end = buffer.anchor_before(offset + value.len());
7773
7774 if moved_since_edit {
7775 edits.push((start..end, String::new()));
7776 } else {
7777 edits.last_mut().unwrap().0.end = end;
7778 }
7779
7780 offset += value.len();
7781 moved_since_edit = false;
7782 }
7783 ChangeTag::Insert => {
7784 if moved_since_edit {
7785 let anchor = buffer.anchor_after(offset);
7786 edits.push((anchor..anchor, value.to_string()));
7787 } else {
7788 edits.last_mut().unwrap().1.push_str(value);
7789 }
7790
7791 moved_since_edit = false;
7792 }
7793 }
7794 }
7795
7796 rewrapped_row_ranges.push(start_row..=end_row);
7797 }
7798
7799 self.buffer
7800 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7801 }
7802
7803 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7804 let mut text = String::new();
7805 let buffer = self.buffer.read(cx).snapshot(cx);
7806 let mut selections = self.selections.all::<Point>(cx);
7807 let mut clipboard_selections = Vec::with_capacity(selections.len());
7808 {
7809 let max_point = buffer.max_point();
7810 let mut is_first = true;
7811 for selection in &mut selections {
7812 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7813 if is_entire_line {
7814 selection.start = Point::new(selection.start.row, 0);
7815 if !selection.is_empty() && selection.end.column == 0 {
7816 selection.end = cmp::min(max_point, selection.end);
7817 } else {
7818 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7819 }
7820 selection.goal = SelectionGoal::None;
7821 }
7822 if is_first {
7823 is_first = false;
7824 } else {
7825 text += "\n";
7826 }
7827 let mut len = 0;
7828 for chunk in buffer.text_for_range(selection.start..selection.end) {
7829 text.push_str(chunk);
7830 len += chunk.len();
7831 }
7832 clipboard_selections.push(ClipboardSelection {
7833 len,
7834 is_entire_line,
7835 first_line_indent: buffer
7836 .indent_size_for_line(MultiBufferRow(selection.start.row))
7837 .len,
7838 });
7839 }
7840 }
7841
7842 self.transact(window, cx, |this, window, cx| {
7843 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7844 s.select(selections);
7845 });
7846 this.insert("", window, cx);
7847 });
7848 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7849 }
7850
7851 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7852 let item = self.cut_common(window, cx);
7853 cx.write_to_clipboard(item);
7854 }
7855
7856 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7857 self.change_selections(None, window, cx, |s| {
7858 s.move_with(|snapshot, sel| {
7859 if sel.is_empty() {
7860 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7861 }
7862 });
7863 });
7864 let item = self.cut_common(window, cx);
7865 cx.set_global(KillRing(item))
7866 }
7867
7868 pub fn kill_ring_yank(
7869 &mut self,
7870 _: &KillRingYank,
7871 window: &mut Window,
7872 cx: &mut Context<Self>,
7873 ) {
7874 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7875 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7876 (kill_ring.text().to_string(), kill_ring.metadata_json())
7877 } else {
7878 return;
7879 }
7880 } else {
7881 return;
7882 };
7883 self.do_paste(&text, metadata, false, window, cx);
7884 }
7885
7886 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7887 let selections = self.selections.all::<Point>(cx);
7888 let buffer = self.buffer.read(cx).read(cx);
7889 let mut text = String::new();
7890
7891 let mut clipboard_selections = Vec::with_capacity(selections.len());
7892 {
7893 let max_point = buffer.max_point();
7894 let mut is_first = true;
7895 for selection in selections.iter() {
7896 let mut start = selection.start;
7897 let mut end = selection.end;
7898 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7899 if is_entire_line {
7900 start = Point::new(start.row, 0);
7901 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7902 }
7903 if is_first {
7904 is_first = false;
7905 } else {
7906 text += "\n";
7907 }
7908 let mut len = 0;
7909 for chunk in buffer.text_for_range(start..end) {
7910 text.push_str(chunk);
7911 len += chunk.len();
7912 }
7913 clipboard_selections.push(ClipboardSelection {
7914 len,
7915 is_entire_line,
7916 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7917 });
7918 }
7919 }
7920
7921 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7922 text,
7923 clipboard_selections,
7924 ));
7925 }
7926
7927 pub fn do_paste(
7928 &mut self,
7929 text: &String,
7930 clipboard_selections: Option<Vec<ClipboardSelection>>,
7931 handle_entire_lines: bool,
7932 window: &mut Window,
7933 cx: &mut Context<Self>,
7934 ) {
7935 if self.read_only(cx) {
7936 return;
7937 }
7938
7939 let clipboard_text = Cow::Borrowed(text);
7940
7941 self.transact(window, cx, |this, window, cx| {
7942 if let Some(mut clipboard_selections) = clipboard_selections {
7943 let old_selections = this.selections.all::<usize>(cx);
7944 let all_selections_were_entire_line =
7945 clipboard_selections.iter().all(|s| s.is_entire_line);
7946 let first_selection_indent_column =
7947 clipboard_selections.first().map(|s| s.first_line_indent);
7948 if clipboard_selections.len() != old_selections.len() {
7949 clipboard_selections.drain(..);
7950 }
7951 let cursor_offset = this.selections.last::<usize>(cx).head();
7952 let mut auto_indent_on_paste = true;
7953
7954 this.buffer.update(cx, |buffer, cx| {
7955 let snapshot = buffer.read(cx);
7956 auto_indent_on_paste =
7957 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7958
7959 let mut start_offset = 0;
7960 let mut edits = Vec::new();
7961 let mut original_indent_columns = Vec::new();
7962 for (ix, selection) in old_selections.iter().enumerate() {
7963 let to_insert;
7964 let entire_line;
7965 let original_indent_column;
7966 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7967 let end_offset = start_offset + clipboard_selection.len;
7968 to_insert = &clipboard_text[start_offset..end_offset];
7969 entire_line = clipboard_selection.is_entire_line;
7970 start_offset = end_offset + 1;
7971 original_indent_column = Some(clipboard_selection.first_line_indent);
7972 } else {
7973 to_insert = clipboard_text.as_str();
7974 entire_line = all_selections_were_entire_line;
7975 original_indent_column = first_selection_indent_column
7976 }
7977
7978 // If the corresponding selection was empty when this slice of the
7979 // clipboard text was written, then the entire line containing the
7980 // selection was copied. If this selection is also currently empty,
7981 // then paste the line before the current line of the buffer.
7982 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7983 let column = selection.start.to_point(&snapshot).column as usize;
7984 let line_start = selection.start - column;
7985 line_start..line_start
7986 } else {
7987 selection.range()
7988 };
7989
7990 edits.push((range, to_insert));
7991 original_indent_columns.extend(original_indent_column);
7992 }
7993 drop(snapshot);
7994
7995 buffer.edit(
7996 edits,
7997 if auto_indent_on_paste {
7998 Some(AutoindentMode::Block {
7999 original_indent_columns,
8000 })
8001 } else {
8002 None
8003 },
8004 cx,
8005 );
8006 });
8007
8008 let selections = this.selections.all::<usize>(cx);
8009 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8010 s.select(selections)
8011 });
8012 } else {
8013 this.insert(&clipboard_text, window, cx);
8014 }
8015 });
8016 }
8017
8018 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8019 if let Some(item) = cx.read_from_clipboard() {
8020 let entries = item.entries();
8021
8022 match entries.first() {
8023 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8024 // of all the pasted entries.
8025 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8026 .do_paste(
8027 clipboard_string.text(),
8028 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8029 true,
8030 window,
8031 cx,
8032 ),
8033 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8034 }
8035 }
8036 }
8037
8038 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8039 if self.read_only(cx) {
8040 return;
8041 }
8042
8043 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8044 if let Some((selections, _)) =
8045 self.selection_history.transaction(transaction_id).cloned()
8046 {
8047 self.change_selections(None, window, cx, |s| {
8048 s.select_anchors(selections.to_vec());
8049 });
8050 }
8051 self.request_autoscroll(Autoscroll::fit(), cx);
8052 self.unmark_text(window, cx);
8053 self.refresh_inline_completion(true, false, window, cx);
8054 cx.emit(EditorEvent::Edited { transaction_id });
8055 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8056 }
8057 }
8058
8059 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8060 if self.read_only(cx) {
8061 return;
8062 }
8063
8064 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8065 if let Some((_, Some(selections))) =
8066 self.selection_history.transaction(transaction_id).cloned()
8067 {
8068 self.change_selections(None, window, cx, |s| {
8069 s.select_anchors(selections.to_vec());
8070 });
8071 }
8072 self.request_autoscroll(Autoscroll::fit(), cx);
8073 self.unmark_text(window, cx);
8074 self.refresh_inline_completion(true, false, window, cx);
8075 cx.emit(EditorEvent::Edited { transaction_id });
8076 }
8077 }
8078
8079 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8080 self.buffer
8081 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8082 }
8083
8084 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8085 self.buffer
8086 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8087 }
8088
8089 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8091 let line_mode = s.line_mode;
8092 s.move_with(|map, selection| {
8093 let cursor = if selection.is_empty() && !line_mode {
8094 movement::left(map, selection.start)
8095 } else {
8096 selection.start
8097 };
8098 selection.collapse_to(cursor, SelectionGoal::None);
8099 });
8100 })
8101 }
8102
8103 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8105 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8106 })
8107 }
8108
8109 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8111 let line_mode = s.line_mode;
8112 s.move_with(|map, selection| {
8113 let cursor = if selection.is_empty() && !line_mode {
8114 movement::right(map, selection.end)
8115 } else {
8116 selection.end
8117 };
8118 selection.collapse_to(cursor, SelectionGoal::None)
8119 });
8120 })
8121 }
8122
8123 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8124 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8125 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8126 })
8127 }
8128
8129 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8130 if self.take_rename(true, window, cx).is_some() {
8131 return;
8132 }
8133
8134 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8135 cx.propagate();
8136 return;
8137 }
8138
8139 let text_layout_details = &self.text_layout_details(window);
8140 let selection_count = self.selections.count();
8141 let first_selection = self.selections.first_anchor();
8142
8143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8144 let line_mode = s.line_mode;
8145 s.move_with(|map, selection| {
8146 if !selection.is_empty() && !line_mode {
8147 selection.goal = SelectionGoal::None;
8148 }
8149 let (cursor, goal) = movement::up(
8150 map,
8151 selection.start,
8152 selection.goal,
8153 false,
8154 text_layout_details,
8155 );
8156 selection.collapse_to(cursor, goal);
8157 });
8158 });
8159
8160 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8161 {
8162 cx.propagate();
8163 }
8164 }
8165
8166 pub fn move_up_by_lines(
8167 &mut self,
8168 action: &MoveUpByLines,
8169 window: &mut Window,
8170 cx: &mut Context<Self>,
8171 ) {
8172 if self.take_rename(true, window, cx).is_some() {
8173 return;
8174 }
8175
8176 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8177 cx.propagate();
8178 return;
8179 }
8180
8181 let text_layout_details = &self.text_layout_details(window);
8182
8183 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8184 let line_mode = s.line_mode;
8185 s.move_with(|map, selection| {
8186 if !selection.is_empty() && !line_mode {
8187 selection.goal = SelectionGoal::None;
8188 }
8189 let (cursor, goal) = movement::up_by_rows(
8190 map,
8191 selection.start,
8192 action.lines,
8193 selection.goal,
8194 false,
8195 text_layout_details,
8196 );
8197 selection.collapse_to(cursor, goal);
8198 });
8199 })
8200 }
8201
8202 pub fn move_down_by_lines(
8203 &mut self,
8204 action: &MoveDownByLines,
8205 window: &mut Window,
8206 cx: &mut Context<Self>,
8207 ) {
8208 if self.take_rename(true, window, cx).is_some() {
8209 return;
8210 }
8211
8212 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8213 cx.propagate();
8214 return;
8215 }
8216
8217 let text_layout_details = &self.text_layout_details(window);
8218
8219 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8220 let line_mode = s.line_mode;
8221 s.move_with(|map, selection| {
8222 if !selection.is_empty() && !line_mode {
8223 selection.goal = SelectionGoal::None;
8224 }
8225 let (cursor, goal) = movement::down_by_rows(
8226 map,
8227 selection.start,
8228 action.lines,
8229 selection.goal,
8230 false,
8231 text_layout_details,
8232 );
8233 selection.collapse_to(cursor, goal);
8234 });
8235 })
8236 }
8237
8238 pub fn select_down_by_lines(
8239 &mut self,
8240 action: &SelectDownByLines,
8241 window: &mut Window,
8242 cx: &mut Context<Self>,
8243 ) {
8244 let text_layout_details = &self.text_layout_details(window);
8245 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8246 s.move_heads_with(|map, head, goal| {
8247 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8248 })
8249 })
8250 }
8251
8252 pub fn select_up_by_lines(
8253 &mut self,
8254 action: &SelectUpByLines,
8255 window: &mut Window,
8256 cx: &mut Context<Self>,
8257 ) {
8258 let text_layout_details = &self.text_layout_details(window);
8259 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8260 s.move_heads_with(|map, head, goal| {
8261 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8262 })
8263 })
8264 }
8265
8266 pub fn select_page_up(
8267 &mut self,
8268 _: &SelectPageUp,
8269 window: &mut Window,
8270 cx: &mut Context<Self>,
8271 ) {
8272 let Some(row_count) = self.visible_row_count() else {
8273 return;
8274 };
8275
8276 let text_layout_details = &self.text_layout_details(window);
8277
8278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8279 s.move_heads_with(|map, head, goal| {
8280 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8281 })
8282 })
8283 }
8284
8285 pub fn move_page_up(
8286 &mut self,
8287 action: &MovePageUp,
8288 window: &mut Window,
8289 cx: &mut Context<Self>,
8290 ) {
8291 if self.take_rename(true, window, cx).is_some() {
8292 return;
8293 }
8294
8295 if self
8296 .context_menu
8297 .borrow_mut()
8298 .as_mut()
8299 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8300 .unwrap_or(false)
8301 {
8302 return;
8303 }
8304
8305 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8306 cx.propagate();
8307 return;
8308 }
8309
8310 let Some(row_count) = self.visible_row_count() else {
8311 return;
8312 };
8313
8314 let autoscroll = if action.center_cursor {
8315 Autoscroll::center()
8316 } else {
8317 Autoscroll::fit()
8318 };
8319
8320 let text_layout_details = &self.text_layout_details(window);
8321
8322 self.change_selections(Some(autoscroll), window, cx, |s| {
8323 let line_mode = s.line_mode;
8324 s.move_with(|map, selection| {
8325 if !selection.is_empty() && !line_mode {
8326 selection.goal = SelectionGoal::None;
8327 }
8328 let (cursor, goal) = movement::up_by_rows(
8329 map,
8330 selection.end,
8331 row_count,
8332 selection.goal,
8333 false,
8334 text_layout_details,
8335 );
8336 selection.collapse_to(cursor, goal);
8337 });
8338 });
8339 }
8340
8341 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8342 let text_layout_details = &self.text_layout_details(window);
8343 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8344 s.move_heads_with(|map, head, goal| {
8345 movement::up(map, head, goal, false, text_layout_details)
8346 })
8347 })
8348 }
8349
8350 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8351 self.take_rename(true, window, cx);
8352
8353 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8354 cx.propagate();
8355 return;
8356 }
8357
8358 let text_layout_details = &self.text_layout_details(window);
8359 let selection_count = self.selections.count();
8360 let first_selection = self.selections.first_anchor();
8361
8362 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8363 let line_mode = s.line_mode;
8364 s.move_with(|map, selection| {
8365 if !selection.is_empty() && !line_mode {
8366 selection.goal = SelectionGoal::None;
8367 }
8368 let (cursor, goal) = movement::down(
8369 map,
8370 selection.end,
8371 selection.goal,
8372 false,
8373 text_layout_details,
8374 );
8375 selection.collapse_to(cursor, goal);
8376 });
8377 });
8378
8379 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8380 {
8381 cx.propagate();
8382 }
8383 }
8384
8385 pub fn select_page_down(
8386 &mut self,
8387 _: &SelectPageDown,
8388 window: &mut Window,
8389 cx: &mut Context<Self>,
8390 ) {
8391 let Some(row_count) = self.visible_row_count() else {
8392 return;
8393 };
8394
8395 let text_layout_details = &self.text_layout_details(window);
8396
8397 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8398 s.move_heads_with(|map, head, goal| {
8399 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8400 })
8401 })
8402 }
8403
8404 pub fn move_page_down(
8405 &mut self,
8406 action: &MovePageDown,
8407 window: &mut Window,
8408 cx: &mut Context<Self>,
8409 ) {
8410 if self.take_rename(true, window, cx).is_some() {
8411 return;
8412 }
8413
8414 if self
8415 .context_menu
8416 .borrow_mut()
8417 .as_mut()
8418 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8419 .unwrap_or(false)
8420 {
8421 return;
8422 }
8423
8424 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8425 cx.propagate();
8426 return;
8427 }
8428
8429 let Some(row_count) = self.visible_row_count() else {
8430 return;
8431 };
8432
8433 let autoscroll = if action.center_cursor {
8434 Autoscroll::center()
8435 } else {
8436 Autoscroll::fit()
8437 };
8438
8439 let text_layout_details = &self.text_layout_details(window);
8440 self.change_selections(Some(autoscroll), window, cx, |s| {
8441 let line_mode = s.line_mode;
8442 s.move_with(|map, selection| {
8443 if !selection.is_empty() && !line_mode {
8444 selection.goal = SelectionGoal::None;
8445 }
8446 let (cursor, goal) = movement::down_by_rows(
8447 map,
8448 selection.end,
8449 row_count,
8450 selection.goal,
8451 false,
8452 text_layout_details,
8453 );
8454 selection.collapse_to(cursor, goal);
8455 });
8456 });
8457 }
8458
8459 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8460 let text_layout_details = &self.text_layout_details(window);
8461 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8462 s.move_heads_with(|map, head, goal| {
8463 movement::down(map, head, goal, false, text_layout_details)
8464 })
8465 });
8466 }
8467
8468 pub fn context_menu_first(
8469 &mut self,
8470 _: &ContextMenuFirst,
8471 _window: &mut Window,
8472 cx: &mut Context<Self>,
8473 ) {
8474 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8475 context_menu.select_first(self.completion_provider.as_deref(), cx);
8476 }
8477 }
8478
8479 pub fn context_menu_prev(
8480 &mut self,
8481 _: &ContextMenuPrev,
8482 _window: &mut Window,
8483 cx: &mut Context<Self>,
8484 ) {
8485 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8486 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8487 }
8488 }
8489
8490 pub fn context_menu_next(
8491 &mut self,
8492 _: &ContextMenuNext,
8493 _window: &mut Window,
8494 cx: &mut Context<Self>,
8495 ) {
8496 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8497 context_menu.select_next(self.completion_provider.as_deref(), cx);
8498 }
8499 }
8500
8501 pub fn context_menu_last(
8502 &mut self,
8503 _: &ContextMenuLast,
8504 _window: &mut Window,
8505 cx: &mut Context<Self>,
8506 ) {
8507 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8508 context_menu.select_last(self.completion_provider.as_deref(), cx);
8509 }
8510 }
8511
8512 pub fn move_to_previous_word_start(
8513 &mut self,
8514 _: &MoveToPreviousWordStart,
8515 window: &mut Window,
8516 cx: &mut Context<Self>,
8517 ) {
8518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8519 s.move_cursors_with(|map, head, _| {
8520 (
8521 movement::previous_word_start(map, head),
8522 SelectionGoal::None,
8523 )
8524 });
8525 })
8526 }
8527
8528 pub fn move_to_previous_subword_start(
8529 &mut self,
8530 _: &MoveToPreviousSubwordStart,
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_subword_start(map, head),
8538 SelectionGoal::None,
8539 )
8540 });
8541 })
8542 }
8543
8544 pub fn select_to_previous_word_start(
8545 &mut self,
8546 _: &SelectToPreviousWordStart,
8547 window: &mut Window,
8548 cx: &mut Context<Self>,
8549 ) {
8550 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8551 s.move_heads_with(|map, head, _| {
8552 (
8553 movement::previous_word_start(map, head),
8554 SelectionGoal::None,
8555 )
8556 });
8557 })
8558 }
8559
8560 pub fn select_to_previous_subword_start(
8561 &mut self,
8562 _: &SelectToPreviousSubwordStart,
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_subword_start(map, head),
8570 SelectionGoal::None,
8571 )
8572 });
8573 })
8574 }
8575
8576 pub fn delete_to_previous_word_start(
8577 &mut self,
8578 action: &DeleteToPreviousWordStart,
8579 window: &mut Window,
8580 cx: &mut Context<Self>,
8581 ) {
8582 self.transact(window, cx, |this, window, cx| {
8583 this.select_autoclose_pair(window, cx);
8584 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8585 let line_mode = s.line_mode;
8586 s.move_with(|map, selection| {
8587 if selection.is_empty() && !line_mode {
8588 let cursor = if action.ignore_newlines {
8589 movement::previous_word_start(map, selection.head())
8590 } else {
8591 movement::previous_word_start_or_newline(map, selection.head())
8592 };
8593 selection.set_head(cursor, SelectionGoal::None);
8594 }
8595 });
8596 });
8597 this.insert("", window, cx);
8598 });
8599 }
8600
8601 pub fn delete_to_previous_subword_start(
8602 &mut self,
8603 _: &DeleteToPreviousSubwordStart,
8604 window: &mut Window,
8605 cx: &mut Context<Self>,
8606 ) {
8607 self.transact(window, cx, |this, window, cx| {
8608 this.select_autoclose_pair(window, cx);
8609 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8610 let line_mode = s.line_mode;
8611 s.move_with(|map, selection| {
8612 if selection.is_empty() && !line_mode {
8613 let cursor = movement::previous_subword_start(map, selection.head());
8614 selection.set_head(cursor, SelectionGoal::None);
8615 }
8616 });
8617 });
8618 this.insert("", window, cx);
8619 });
8620 }
8621
8622 pub fn move_to_next_word_end(
8623 &mut self,
8624 _: &MoveToNextWordEnd,
8625 window: &mut Window,
8626 cx: &mut Context<Self>,
8627 ) {
8628 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8629 s.move_cursors_with(|map, head, _| {
8630 (movement::next_word_end(map, head), SelectionGoal::None)
8631 });
8632 })
8633 }
8634
8635 pub fn move_to_next_subword_end(
8636 &mut self,
8637 _: &MoveToNextSubwordEnd,
8638 window: &mut Window,
8639 cx: &mut Context<Self>,
8640 ) {
8641 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8642 s.move_cursors_with(|map, head, _| {
8643 (movement::next_subword_end(map, head), SelectionGoal::None)
8644 });
8645 })
8646 }
8647
8648 pub fn select_to_next_word_end(
8649 &mut self,
8650 _: &SelectToNextWordEnd,
8651 window: &mut Window,
8652 cx: &mut Context<Self>,
8653 ) {
8654 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8655 s.move_heads_with(|map, head, _| {
8656 (movement::next_word_end(map, head), SelectionGoal::None)
8657 });
8658 })
8659 }
8660
8661 pub fn select_to_next_subword_end(
8662 &mut self,
8663 _: &SelectToNextSubwordEnd,
8664 window: &mut Window,
8665 cx: &mut Context<Self>,
8666 ) {
8667 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8668 s.move_heads_with(|map, head, _| {
8669 (movement::next_subword_end(map, head), SelectionGoal::None)
8670 });
8671 })
8672 }
8673
8674 pub fn delete_to_next_word_end(
8675 &mut self,
8676 action: &DeleteToNextWordEnd,
8677 window: &mut Window,
8678 cx: &mut Context<Self>,
8679 ) {
8680 self.transact(window, cx, |this, window, cx| {
8681 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8682 let line_mode = s.line_mode;
8683 s.move_with(|map, selection| {
8684 if selection.is_empty() && !line_mode {
8685 let cursor = if action.ignore_newlines {
8686 movement::next_word_end(map, selection.head())
8687 } else {
8688 movement::next_word_end_or_newline(map, selection.head())
8689 };
8690 selection.set_head(cursor, SelectionGoal::None);
8691 }
8692 });
8693 });
8694 this.insert("", window, cx);
8695 });
8696 }
8697
8698 pub fn delete_to_next_subword_end(
8699 &mut self,
8700 _: &DeleteToNextSubwordEnd,
8701 window: &mut Window,
8702 cx: &mut Context<Self>,
8703 ) {
8704 self.transact(window, cx, |this, window, cx| {
8705 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8706 s.move_with(|map, selection| {
8707 if selection.is_empty() {
8708 let cursor = movement::next_subword_end(map, selection.head());
8709 selection.set_head(cursor, SelectionGoal::None);
8710 }
8711 });
8712 });
8713 this.insert("", window, cx);
8714 });
8715 }
8716
8717 pub fn move_to_beginning_of_line(
8718 &mut self,
8719 action: &MoveToBeginningOfLine,
8720 window: &mut Window,
8721 cx: &mut Context<Self>,
8722 ) {
8723 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8724 s.move_cursors_with(|map, head, _| {
8725 (
8726 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8727 SelectionGoal::None,
8728 )
8729 });
8730 })
8731 }
8732
8733 pub fn select_to_beginning_of_line(
8734 &mut self,
8735 action: &SelectToBeginningOfLine,
8736 window: &mut Window,
8737 cx: &mut Context<Self>,
8738 ) {
8739 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8740 s.move_heads_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 delete_to_beginning_of_line(
8750 &mut self,
8751 _: &DeleteToBeginningOfLine,
8752 window: &mut Window,
8753 cx: &mut Context<Self>,
8754 ) {
8755 self.transact(window, cx, |this, window, cx| {
8756 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8757 s.move_with(|_, selection| {
8758 selection.reversed = true;
8759 });
8760 });
8761
8762 this.select_to_beginning_of_line(
8763 &SelectToBeginningOfLine {
8764 stop_at_soft_wraps: false,
8765 },
8766 window,
8767 cx,
8768 );
8769 this.backspace(&Backspace, window, cx);
8770 });
8771 }
8772
8773 pub fn move_to_end_of_line(
8774 &mut self,
8775 action: &MoveToEndOfLine,
8776 window: &mut Window,
8777 cx: &mut Context<Self>,
8778 ) {
8779 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8780 s.move_cursors_with(|map, head, _| {
8781 (
8782 movement::line_end(map, head, action.stop_at_soft_wraps),
8783 SelectionGoal::None,
8784 )
8785 });
8786 })
8787 }
8788
8789 pub fn select_to_end_of_line(
8790 &mut self,
8791 action: &SelectToEndOfLine,
8792 window: &mut Window,
8793 cx: &mut Context<Self>,
8794 ) {
8795 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8796 s.move_heads_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 delete_to_end_of_line(
8806 &mut self,
8807 _: &DeleteToEndOfLine,
8808 window: &mut Window,
8809 cx: &mut Context<Self>,
8810 ) {
8811 self.transact(window, cx, |this, window, cx| {
8812 this.select_to_end_of_line(
8813 &SelectToEndOfLine {
8814 stop_at_soft_wraps: false,
8815 },
8816 window,
8817 cx,
8818 );
8819 this.delete(&Delete, window, cx);
8820 });
8821 }
8822
8823 pub fn cut_to_end_of_line(
8824 &mut self,
8825 _: &CutToEndOfLine,
8826 window: &mut Window,
8827 cx: &mut Context<Self>,
8828 ) {
8829 self.transact(window, cx, |this, window, cx| {
8830 this.select_to_end_of_line(
8831 &SelectToEndOfLine {
8832 stop_at_soft_wraps: false,
8833 },
8834 window,
8835 cx,
8836 );
8837 this.cut(&Cut, window, cx);
8838 });
8839 }
8840
8841 pub fn move_to_start_of_paragraph(
8842 &mut self,
8843 _: &MoveToStartOfParagraph,
8844 window: &mut Window,
8845 cx: &mut Context<Self>,
8846 ) {
8847 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8848 cx.propagate();
8849 return;
8850 }
8851
8852 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8853 s.move_with(|map, selection| {
8854 selection.collapse_to(
8855 movement::start_of_paragraph(map, selection.head(), 1),
8856 SelectionGoal::None,
8857 )
8858 });
8859 })
8860 }
8861
8862 pub fn move_to_end_of_paragraph(
8863 &mut self,
8864 _: &MoveToEndOfParagraph,
8865 window: &mut Window,
8866 cx: &mut Context<Self>,
8867 ) {
8868 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8869 cx.propagate();
8870 return;
8871 }
8872
8873 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8874 s.move_with(|map, selection| {
8875 selection.collapse_to(
8876 movement::end_of_paragraph(map, selection.head(), 1),
8877 SelectionGoal::None,
8878 )
8879 });
8880 })
8881 }
8882
8883 pub fn select_to_start_of_paragraph(
8884 &mut self,
8885 _: &SelectToStartOfParagraph,
8886 window: &mut Window,
8887 cx: &mut Context<Self>,
8888 ) {
8889 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8890 cx.propagate();
8891 return;
8892 }
8893
8894 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8895 s.move_heads_with(|map, head, _| {
8896 (
8897 movement::start_of_paragraph(map, head, 1),
8898 SelectionGoal::None,
8899 )
8900 });
8901 })
8902 }
8903
8904 pub fn select_to_end_of_paragraph(
8905 &mut self,
8906 _: &SelectToEndOfParagraph,
8907 window: &mut Window,
8908 cx: &mut Context<Self>,
8909 ) {
8910 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8911 cx.propagate();
8912 return;
8913 }
8914
8915 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8916 s.move_heads_with(|map, head, _| {
8917 (
8918 movement::end_of_paragraph(map, head, 1),
8919 SelectionGoal::None,
8920 )
8921 });
8922 })
8923 }
8924
8925 pub fn move_to_beginning(
8926 &mut self,
8927 _: &MoveToBeginning,
8928 window: &mut Window,
8929 cx: &mut Context<Self>,
8930 ) {
8931 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8932 cx.propagate();
8933 return;
8934 }
8935
8936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8937 s.select_ranges(vec![0..0]);
8938 });
8939 }
8940
8941 pub fn select_to_beginning(
8942 &mut self,
8943 _: &SelectToBeginning,
8944 window: &mut Window,
8945 cx: &mut Context<Self>,
8946 ) {
8947 let mut selection = self.selections.last::<Point>(cx);
8948 selection.set_head(Point::zero(), SelectionGoal::None);
8949
8950 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8951 s.select(vec![selection]);
8952 });
8953 }
8954
8955 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8956 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8957 cx.propagate();
8958 return;
8959 }
8960
8961 let cursor = self.buffer.read(cx).read(cx).len();
8962 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8963 s.select_ranges(vec![cursor..cursor])
8964 });
8965 }
8966
8967 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8968 self.nav_history = nav_history;
8969 }
8970
8971 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8972 self.nav_history.as_ref()
8973 }
8974
8975 fn push_to_nav_history(
8976 &mut self,
8977 cursor_anchor: Anchor,
8978 new_position: Option<Point>,
8979 cx: &mut Context<Self>,
8980 ) {
8981 if let Some(nav_history) = self.nav_history.as_mut() {
8982 let buffer = self.buffer.read(cx).read(cx);
8983 let cursor_position = cursor_anchor.to_point(&buffer);
8984 let scroll_state = self.scroll_manager.anchor();
8985 let scroll_top_row = scroll_state.top_row(&buffer);
8986 drop(buffer);
8987
8988 if let Some(new_position) = new_position {
8989 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8990 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8991 return;
8992 }
8993 }
8994
8995 nav_history.push(
8996 Some(NavigationData {
8997 cursor_anchor,
8998 cursor_position,
8999 scroll_anchor: scroll_state,
9000 scroll_top_row,
9001 }),
9002 cx,
9003 );
9004 }
9005 }
9006
9007 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9008 let buffer = self.buffer.read(cx).snapshot(cx);
9009 let mut selection = self.selections.first::<usize>(cx);
9010 selection.set_head(buffer.len(), SelectionGoal::None);
9011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9012 s.select(vec![selection]);
9013 });
9014 }
9015
9016 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9017 let end = self.buffer.read(cx).read(cx).len();
9018 self.change_selections(None, window, cx, |s| {
9019 s.select_ranges(vec![0..end]);
9020 });
9021 }
9022
9023 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9024 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9025 let mut selections = self.selections.all::<Point>(cx);
9026 let max_point = display_map.buffer_snapshot.max_point();
9027 for selection in &mut selections {
9028 let rows = selection.spanned_rows(true, &display_map);
9029 selection.start = Point::new(rows.start.0, 0);
9030 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9031 selection.reversed = false;
9032 }
9033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9034 s.select(selections);
9035 });
9036 }
9037
9038 pub fn split_selection_into_lines(
9039 &mut self,
9040 _: &SplitSelectionIntoLines,
9041 window: &mut Window,
9042 cx: &mut Context<Self>,
9043 ) {
9044 let mut to_unfold = Vec::new();
9045 let mut new_selection_ranges = Vec::new();
9046 {
9047 let selections = self.selections.all::<Point>(cx);
9048 let buffer = self.buffer.read(cx).read(cx);
9049 for selection in selections {
9050 for row in selection.start.row..selection.end.row {
9051 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9052 new_selection_ranges.push(cursor..cursor);
9053 }
9054 new_selection_ranges.push(selection.end..selection.end);
9055 to_unfold.push(selection.start..selection.end);
9056 }
9057 }
9058 self.unfold_ranges(&to_unfold, true, true, cx);
9059 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9060 s.select_ranges(new_selection_ranges);
9061 });
9062 }
9063
9064 pub fn add_selection_above(
9065 &mut self,
9066 _: &AddSelectionAbove,
9067 window: &mut Window,
9068 cx: &mut Context<Self>,
9069 ) {
9070 self.add_selection(true, window, cx);
9071 }
9072
9073 pub fn add_selection_below(
9074 &mut self,
9075 _: &AddSelectionBelow,
9076 window: &mut Window,
9077 cx: &mut Context<Self>,
9078 ) {
9079 self.add_selection(false, window, cx);
9080 }
9081
9082 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9083 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9084 let mut selections = self.selections.all::<Point>(cx);
9085 let text_layout_details = self.text_layout_details(window);
9086 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9087 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9088 let range = oldest_selection.display_range(&display_map).sorted();
9089
9090 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9091 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9092 let positions = start_x.min(end_x)..start_x.max(end_x);
9093
9094 selections.clear();
9095 let mut stack = Vec::new();
9096 for row in range.start.row().0..=range.end.row().0 {
9097 if let Some(selection) = self.selections.build_columnar_selection(
9098 &display_map,
9099 DisplayRow(row),
9100 &positions,
9101 oldest_selection.reversed,
9102 &text_layout_details,
9103 ) {
9104 stack.push(selection.id);
9105 selections.push(selection);
9106 }
9107 }
9108
9109 if above {
9110 stack.reverse();
9111 }
9112
9113 AddSelectionsState { above, stack }
9114 });
9115
9116 let last_added_selection = *state.stack.last().unwrap();
9117 let mut new_selections = Vec::new();
9118 if above == state.above {
9119 let end_row = if above {
9120 DisplayRow(0)
9121 } else {
9122 display_map.max_point().row()
9123 };
9124
9125 'outer: for selection in selections {
9126 if selection.id == last_added_selection {
9127 let range = selection.display_range(&display_map).sorted();
9128 debug_assert_eq!(range.start.row(), range.end.row());
9129 let mut row = range.start.row();
9130 let positions =
9131 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9132 px(start)..px(end)
9133 } else {
9134 let start_x =
9135 display_map.x_for_display_point(range.start, &text_layout_details);
9136 let end_x =
9137 display_map.x_for_display_point(range.end, &text_layout_details);
9138 start_x.min(end_x)..start_x.max(end_x)
9139 };
9140
9141 while row != end_row {
9142 if above {
9143 row.0 -= 1;
9144 } else {
9145 row.0 += 1;
9146 }
9147
9148 if let Some(new_selection) = self.selections.build_columnar_selection(
9149 &display_map,
9150 row,
9151 &positions,
9152 selection.reversed,
9153 &text_layout_details,
9154 ) {
9155 state.stack.push(new_selection.id);
9156 if above {
9157 new_selections.push(new_selection);
9158 new_selections.push(selection);
9159 } else {
9160 new_selections.push(selection);
9161 new_selections.push(new_selection);
9162 }
9163
9164 continue 'outer;
9165 }
9166 }
9167 }
9168
9169 new_selections.push(selection);
9170 }
9171 } else {
9172 new_selections = selections;
9173 new_selections.retain(|s| s.id != last_added_selection);
9174 state.stack.pop();
9175 }
9176
9177 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9178 s.select(new_selections);
9179 });
9180 if state.stack.len() > 1 {
9181 self.add_selections_state = Some(state);
9182 }
9183 }
9184
9185 pub fn select_next_match_internal(
9186 &mut self,
9187 display_map: &DisplaySnapshot,
9188 replace_newest: bool,
9189 autoscroll: Option<Autoscroll>,
9190 window: &mut Window,
9191 cx: &mut Context<Self>,
9192 ) -> Result<()> {
9193 fn select_next_match_ranges(
9194 this: &mut Editor,
9195 range: Range<usize>,
9196 replace_newest: bool,
9197 auto_scroll: Option<Autoscroll>,
9198 window: &mut Window,
9199 cx: &mut Context<Editor>,
9200 ) {
9201 this.unfold_ranges(&[range.clone()], false, true, cx);
9202 this.change_selections(auto_scroll, window, cx, |s| {
9203 if replace_newest {
9204 s.delete(s.newest_anchor().id);
9205 }
9206 s.insert_range(range.clone());
9207 });
9208 }
9209
9210 let buffer = &display_map.buffer_snapshot;
9211 let mut selections = self.selections.all::<usize>(cx);
9212 if let Some(mut select_next_state) = self.select_next_state.take() {
9213 let query = &select_next_state.query;
9214 if !select_next_state.done {
9215 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9216 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9217 let mut next_selected_range = None;
9218
9219 let bytes_after_last_selection =
9220 buffer.bytes_in_range(last_selection.end..buffer.len());
9221 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9222 let query_matches = query
9223 .stream_find_iter(bytes_after_last_selection)
9224 .map(|result| (last_selection.end, result))
9225 .chain(
9226 query
9227 .stream_find_iter(bytes_before_first_selection)
9228 .map(|result| (0, result)),
9229 );
9230
9231 for (start_offset, query_match) in query_matches {
9232 let query_match = query_match.unwrap(); // can only fail due to I/O
9233 let offset_range =
9234 start_offset + query_match.start()..start_offset + query_match.end();
9235 let display_range = offset_range.start.to_display_point(display_map)
9236 ..offset_range.end.to_display_point(display_map);
9237
9238 if !select_next_state.wordwise
9239 || (!movement::is_inside_word(display_map, display_range.start)
9240 && !movement::is_inside_word(display_map, display_range.end))
9241 {
9242 // TODO: This is n^2, because we might check all the selections
9243 if !selections
9244 .iter()
9245 .any(|selection| selection.range().overlaps(&offset_range))
9246 {
9247 next_selected_range = Some(offset_range);
9248 break;
9249 }
9250 }
9251 }
9252
9253 if let Some(next_selected_range) = next_selected_range {
9254 select_next_match_ranges(
9255 self,
9256 next_selected_range,
9257 replace_newest,
9258 autoscroll,
9259 window,
9260 cx,
9261 );
9262 } else {
9263 select_next_state.done = true;
9264 }
9265 }
9266
9267 self.select_next_state = Some(select_next_state);
9268 } else {
9269 let mut only_carets = true;
9270 let mut same_text_selected = true;
9271 let mut selected_text = None;
9272
9273 let mut selections_iter = selections.iter().peekable();
9274 while let Some(selection) = selections_iter.next() {
9275 if selection.start != selection.end {
9276 only_carets = false;
9277 }
9278
9279 if same_text_selected {
9280 if selected_text.is_none() {
9281 selected_text =
9282 Some(buffer.text_for_range(selection.range()).collect::<String>());
9283 }
9284
9285 if let Some(next_selection) = selections_iter.peek() {
9286 if next_selection.range().len() == selection.range().len() {
9287 let next_selected_text = buffer
9288 .text_for_range(next_selection.range())
9289 .collect::<String>();
9290 if Some(next_selected_text) != selected_text {
9291 same_text_selected = false;
9292 selected_text = None;
9293 }
9294 } else {
9295 same_text_selected = false;
9296 selected_text = None;
9297 }
9298 }
9299 }
9300 }
9301
9302 if only_carets {
9303 for selection in &mut selections {
9304 let word_range = movement::surrounding_word(
9305 display_map,
9306 selection.start.to_display_point(display_map),
9307 );
9308 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9309 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9310 selection.goal = SelectionGoal::None;
9311 selection.reversed = false;
9312 select_next_match_ranges(
9313 self,
9314 selection.start..selection.end,
9315 replace_newest,
9316 autoscroll,
9317 window,
9318 cx,
9319 );
9320 }
9321
9322 if selections.len() == 1 {
9323 let selection = selections
9324 .last()
9325 .expect("ensured that there's only one selection");
9326 let query = buffer
9327 .text_for_range(selection.start..selection.end)
9328 .collect::<String>();
9329 let is_empty = query.is_empty();
9330 let select_state = SelectNextState {
9331 query: AhoCorasick::new(&[query])?,
9332 wordwise: true,
9333 done: is_empty,
9334 };
9335 self.select_next_state = Some(select_state);
9336 } else {
9337 self.select_next_state = None;
9338 }
9339 } else if let Some(selected_text) = selected_text {
9340 self.select_next_state = Some(SelectNextState {
9341 query: AhoCorasick::new(&[selected_text])?,
9342 wordwise: false,
9343 done: false,
9344 });
9345 self.select_next_match_internal(
9346 display_map,
9347 replace_newest,
9348 autoscroll,
9349 window,
9350 cx,
9351 )?;
9352 }
9353 }
9354 Ok(())
9355 }
9356
9357 pub fn select_all_matches(
9358 &mut self,
9359 _action: &SelectAllMatches,
9360 window: &mut Window,
9361 cx: &mut Context<Self>,
9362 ) -> Result<()> {
9363 self.push_to_selection_history();
9364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9365
9366 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9367 let Some(select_next_state) = self.select_next_state.as_mut() else {
9368 return Ok(());
9369 };
9370 if select_next_state.done {
9371 return Ok(());
9372 }
9373
9374 let mut new_selections = self.selections.all::<usize>(cx);
9375
9376 let buffer = &display_map.buffer_snapshot;
9377 let query_matches = select_next_state
9378 .query
9379 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9380
9381 for query_match in query_matches {
9382 let query_match = query_match.unwrap(); // can only fail due to I/O
9383 let offset_range = query_match.start()..query_match.end();
9384 let display_range = offset_range.start.to_display_point(&display_map)
9385 ..offset_range.end.to_display_point(&display_map);
9386
9387 if !select_next_state.wordwise
9388 || (!movement::is_inside_word(&display_map, display_range.start)
9389 && !movement::is_inside_word(&display_map, display_range.end))
9390 {
9391 self.selections.change_with(cx, |selections| {
9392 new_selections.push(Selection {
9393 id: selections.new_selection_id(),
9394 start: offset_range.start,
9395 end: offset_range.end,
9396 reversed: false,
9397 goal: SelectionGoal::None,
9398 });
9399 });
9400 }
9401 }
9402
9403 new_selections.sort_by_key(|selection| selection.start);
9404 let mut ix = 0;
9405 while ix + 1 < new_selections.len() {
9406 let current_selection = &new_selections[ix];
9407 let next_selection = &new_selections[ix + 1];
9408 if current_selection.range().overlaps(&next_selection.range()) {
9409 if current_selection.id < next_selection.id {
9410 new_selections.remove(ix + 1);
9411 } else {
9412 new_selections.remove(ix);
9413 }
9414 } else {
9415 ix += 1;
9416 }
9417 }
9418
9419 let reversed = self.selections.oldest::<usize>(cx).reversed;
9420
9421 for selection in new_selections.iter_mut() {
9422 selection.reversed = reversed;
9423 }
9424
9425 select_next_state.done = true;
9426 self.unfold_ranges(
9427 &new_selections
9428 .iter()
9429 .map(|selection| selection.range())
9430 .collect::<Vec<_>>(),
9431 false,
9432 false,
9433 cx,
9434 );
9435 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9436 selections.select(new_selections)
9437 });
9438
9439 Ok(())
9440 }
9441
9442 pub fn select_next(
9443 &mut self,
9444 action: &SelectNext,
9445 window: &mut Window,
9446 cx: &mut Context<Self>,
9447 ) -> Result<()> {
9448 self.push_to_selection_history();
9449 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9450 self.select_next_match_internal(
9451 &display_map,
9452 action.replace_newest,
9453 Some(Autoscroll::newest()),
9454 window,
9455 cx,
9456 )?;
9457 Ok(())
9458 }
9459
9460 pub fn select_previous(
9461 &mut self,
9462 action: &SelectPrevious,
9463 window: &mut Window,
9464 cx: &mut Context<Self>,
9465 ) -> Result<()> {
9466 self.push_to_selection_history();
9467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9468 let buffer = &display_map.buffer_snapshot;
9469 let mut selections = self.selections.all::<usize>(cx);
9470 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9471 let query = &select_prev_state.query;
9472 if !select_prev_state.done {
9473 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9474 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9475 let mut next_selected_range = None;
9476 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9477 let bytes_before_last_selection =
9478 buffer.reversed_bytes_in_range(0..last_selection.start);
9479 let bytes_after_first_selection =
9480 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9481 let query_matches = query
9482 .stream_find_iter(bytes_before_last_selection)
9483 .map(|result| (last_selection.start, result))
9484 .chain(
9485 query
9486 .stream_find_iter(bytes_after_first_selection)
9487 .map(|result| (buffer.len(), result)),
9488 );
9489 for (end_offset, query_match) in query_matches {
9490 let query_match = query_match.unwrap(); // can only fail due to I/O
9491 let offset_range =
9492 end_offset - query_match.end()..end_offset - query_match.start();
9493 let display_range = offset_range.start.to_display_point(&display_map)
9494 ..offset_range.end.to_display_point(&display_map);
9495
9496 if !select_prev_state.wordwise
9497 || (!movement::is_inside_word(&display_map, display_range.start)
9498 && !movement::is_inside_word(&display_map, display_range.end))
9499 {
9500 next_selected_range = Some(offset_range);
9501 break;
9502 }
9503 }
9504
9505 if let Some(next_selected_range) = next_selected_range {
9506 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9507 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9508 if action.replace_newest {
9509 s.delete(s.newest_anchor().id);
9510 }
9511 s.insert_range(next_selected_range);
9512 });
9513 } else {
9514 select_prev_state.done = true;
9515 }
9516 }
9517
9518 self.select_prev_state = Some(select_prev_state);
9519 } else {
9520 let mut only_carets = true;
9521 let mut same_text_selected = true;
9522 let mut selected_text = None;
9523
9524 let mut selections_iter = selections.iter().peekable();
9525 while let Some(selection) = selections_iter.next() {
9526 if selection.start != selection.end {
9527 only_carets = false;
9528 }
9529
9530 if same_text_selected {
9531 if selected_text.is_none() {
9532 selected_text =
9533 Some(buffer.text_for_range(selection.range()).collect::<String>());
9534 }
9535
9536 if let Some(next_selection) = selections_iter.peek() {
9537 if next_selection.range().len() == selection.range().len() {
9538 let next_selected_text = buffer
9539 .text_for_range(next_selection.range())
9540 .collect::<String>();
9541 if Some(next_selected_text) != selected_text {
9542 same_text_selected = false;
9543 selected_text = None;
9544 }
9545 } else {
9546 same_text_selected = false;
9547 selected_text = None;
9548 }
9549 }
9550 }
9551 }
9552
9553 if only_carets {
9554 for selection in &mut selections {
9555 let word_range = movement::surrounding_word(
9556 &display_map,
9557 selection.start.to_display_point(&display_map),
9558 );
9559 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9560 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9561 selection.goal = SelectionGoal::None;
9562 selection.reversed = false;
9563 }
9564 if selections.len() == 1 {
9565 let selection = selections
9566 .last()
9567 .expect("ensured that there's only one selection");
9568 let query = buffer
9569 .text_for_range(selection.start..selection.end)
9570 .collect::<String>();
9571 let is_empty = query.is_empty();
9572 let select_state = SelectNextState {
9573 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9574 wordwise: true,
9575 done: is_empty,
9576 };
9577 self.select_prev_state = Some(select_state);
9578 } else {
9579 self.select_prev_state = None;
9580 }
9581
9582 self.unfold_ranges(
9583 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9584 false,
9585 true,
9586 cx,
9587 );
9588 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9589 s.select(selections);
9590 });
9591 } else if let Some(selected_text) = selected_text {
9592 self.select_prev_state = Some(SelectNextState {
9593 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9594 wordwise: false,
9595 done: false,
9596 });
9597 self.select_previous(action, window, cx)?;
9598 }
9599 }
9600 Ok(())
9601 }
9602
9603 pub fn toggle_comments(
9604 &mut self,
9605 action: &ToggleComments,
9606 window: &mut Window,
9607 cx: &mut Context<Self>,
9608 ) {
9609 if self.read_only(cx) {
9610 return;
9611 }
9612 let text_layout_details = &self.text_layout_details(window);
9613 self.transact(window, cx, |this, window, cx| {
9614 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9615 let mut edits = Vec::new();
9616 let mut selection_edit_ranges = Vec::new();
9617 let mut last_toggled_row = None;
9618 let snapshot = this.buffer.read(cx).read(cx);
9619 let empty_str: Arc<str> = Arc::default();
9620 let mut suffixes_inserted = Vec::new();
9621 let ignore_indent = action.ignore_indent;
9622
9623 fn comment_prefix_range(
9624 snapshot: &MultiBufferSnapshot,
9625 row: MultiBufferRow,
9626 comment_prefix: &str,
9627 comment_prefix_whitespace: &str,
9628 ignore_indent: bool,
9629 ) -> Range<Point> {
9630 let indent_size = if ignore_indent {
9631 0
9632 } else {
9633 snapshot.indent_size_for_line(row).len
9634 };
9635
9636 let start = Point::new(row.0, indent_size);
9637
9638 let mut line_bytes = snapshot
9639 .bytes_in_range(start..snapshot.max_point())
9640 .flatten()
9641 .copied();
9642
9643 // If this line currently begins with the line comment prefix, then record
9644 // the range containing the prefix.
9645 if line_bytes
9646 .by_ref()
9647 .take(comment_prefix.len())
9648 .eq(comment_prefix.bytes())
9649 {
9650 // Include any whitespace that matches the comment prefix.
9651 let matching_whitespace_len = line_bytes
9652 .zip(comment_prefix_whitespace.bytes())
9653 .take_while(|(a, b)| a == b)
9654 .count() as u32;
9655 let end = Point::new(
9656 start.row,
9657 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9658 );
9659 start..end
9660 } else {
9661 start..start
9662 }
9663 }
9664
9665 fn comment_suffix_range(
9666 snapshot: &MultiBufferSnapshot,
9667 row: MultiBufferRow,
9668 comment_suffix: &str,
9669 comment_suffix_has_leading_space: bool,
9670 ) -> Range<Point> {
9671 let end = Point::new(row.0, snapshot.line_len(row));
9672 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9673
9674 let mut line_end_bytes = snapshot
9675 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9676 .flatten()
9677 .copied();
9678
9679 let leading_space_len = if suffix_start_column > 0
9680 && line_end_bytes.next() == Some(b' ')
9681 && comment_suffix_has_leading_space
9682 {
9683 1
9684 } else {
9685 0
9686 };
9687
9688 // If this line currently begins with the line comment prefix, then record
9689 // the range containing the prefix.
9690 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9691 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9692 start..end
9693 } else {
9694 end..end
9695 }
9696 }
9697
9698 // TODO: Handle selections that cross excerpts
9699 for selection in &mut selections {
9700 let start_column = snapshot
9701 .indent_size_for_line(MultiBufferRow(selection.start.row))
9702 .len;
9703 let language = if let Some(language) =
9704 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9705 {
9706 language
9707 } else {
9708 continue;
9709 };
9710
9711 selection_edit_ranges.clear();
9712
9713 // If multiple selections contain a given row, avoid processing that
9714 // row more than once.
9715 let mut start_row = MultiBufferRow(selection.start.row);
9716 if last_toggled_row == Some(start_row) {
9717 start_row = start_row.next_row();
9718 }
9719 let end_row =
9720 if selection.end.row > selection.start.row && selection.end.column == 0 {
9721 MultiBufferRow(selection.end.row - 1)
9722 } else {
9723 MultiBufferRow(selection.end.row)
9724 };
9725 last_toggled_row = Some(end_row);
9726
9727 if start_row > end_row {
9728 continue;
9729 }
9730
9731 // If the language has line comments, toggle those.
9732 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9733
9734 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9735 if ignore_indent {
9736 full_comment_prefixes = full_comment_prefixes
9737 .into_iter()
9738 .map(|s| Arc::from(s.trim_end()))
9739 .collect();
9740 }
9741
9742 if !full_comment_prefixes.is_empty() {
9743 let first_prefix = full_comment_prefixes
9744 .first()
9745 .expect("prefixes is non-empty");
9746 let prefix_trimmed_lengths = full_comment_prefixes
9747 .iter()
9748 .map(|p| p.trim_end_matches(' ').len())
9749 .collect::<SmallVec<[usize; 4]>>();
9750
9751 let mut all_selection_lines_are_comments = true;
9752
9753 for row in start_row.0..=end_row.0 {
9754 let row = MultiBufferRow(row);
9755 if start_row < end_row && snapshot.is_line_blank(row) {
9756 continue;
9757 }
9758
9759 let prefix_range = full_comment_prefixes
9760 .iter()
9761 .zip(prefix_trimmed_lengths.iter().copied())
9762 .map(|(prefix, trimmed_prefix_len)| {
9763 comment_prefix_range(
9764 snapshot.deref(),
9765 row,
9766 &prefix[..trimmed_prefix_len],
9767 &prefix[trimmed_prefix_len..],
9768 ignore_indent,
9769 )
9770 })
9771 .max_by_key(|range| range.end.column - range.start.column)
9772 .expect("prefixes is non-empty");
9773
9774 if prefix_range.is_empty() {
9775 all_selection_lines_are_comments = false;
9776 }
9777
9778 selection_edit_ranges.push(prefix_range);
9779 }
9780
9781 if all_selection_lines_are_comments {
9782 edits.extend(
9783 selection_edit_ranges
9784 .iter()
9785 .cloned()
9786 .map(|range| (range, empty_str.clone())),
9787 );
9788 } else {
9789 let min_column = selection_edit_ranges
9790 .iter()
9791 .map(|range| range.start.column)
9792 .min()
9793 .unwrap_or(0);
9794 edits.extend(selection_edit_ranges.iter().map(|range| {
9795 let position = Point::new(range.start.row, min_column);
9796 (position..position, first_prefix.clone())
9797 }));
9798 }
9799 } else if let Some((full_comment_prefix, comment_suffix)) =
9800 language.block_comment_delimiters()
9801 {
9802 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9803 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9804 let prefix_range = comment_prefix_range(
9805 snapshot.deref(),
9806 start_row,
9807 comment_prefix,
9808 comment_prefix_whitespace,
9809 ignore_indent,
9810 );
9811 let suffix_range = comment_suffix_range(
9812 snapshot.deref(),
9813 end_row,
9814 comment_suffix.trim_start_matches(' '),
9815 comment_suffix.starts_with(' '),
9816 );
9817
9818 if prefix_range.is_empty() || suffix_range.is_empty() {
9819 edits.push((
9820 prefix_range.start..prefix_range.start,
9821 full_comment_prefix.clone(),
9822 ));
9823 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9824 suffixes_inserted.push((end_row, comment_suffix.len()));
9825 } else {
9826 edits.push((prefix_range, empty_str.clone()));
9827 edits.push((suffix_range, empty_str.clone()));
9828 }
9829 } else {
9830 continue;
9831 }
9832 }
9833
9834 drop(snapshot);
9835 this.buffer.update(cx, |buffer, cx| {
9836 buffer.edit(edits, None, cx);
9837 });
9838
9839 // Adjust selections so that they end before any comment suffixes that
9840 // were inserted.
9841 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9842 let mut selections = this.selections.all::<Point>(cx);
9843 let snapshot = this.buffer.read(cx).read(cx);
9844 for selection in &mut selections {
9845 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9846 match row.cmp(&MultiBufferRow(selection.end.row)) {
9847 Ordering::Less => {
9848 suffixes_inserted.next();
9849 continue;
9850 }
9851 Ordering::Greater => break,
9852 Ordering::Equal => {
9853 if selection.end.column == snapshot.line_len(row) {
9854 if selection.is_empty() {
9855 selection.start.column -= suffix_len as u32;
9856 }
9857 selection.end.column -= suffix_len as u32;
9858 }
9859 break;
9860 }
9861 }
9862 }
9863 }
9864
9865 drop(snapshot);
9866 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9867 s.select(selections)
9868 });
9869
9870 let selections = this.selections.all::<Point>(cx);
9871 let selections_on_single_row = selections.windows(2).all(|selections| {
9872 selections[0].start.row == selections[1].start.row
9873 && selections[0].end.row == selections[1].end.row
9874 && selections[0].start.row == selections[0].end.row
9875 });
9876 let selections_selecting = selections
9877 .iter()
9878 .any(|selection| selection.start != selection.end);
9879 let advance_downwards = action.advance_downwards
9880 && selections_on_single_row
9881 && !selections_selecting
9882 && !matches!(this.mode, EditorMode::SingleLine { .. });
9883
9884 if advance_downwards {
9885 let snapshot = this.buffer.read(cx).snapshot(cx);
9886
9887 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9888 s.move_cursors_with(|display_snapshot, display_point, _| {
9889 let mut point = display_point.to_point(display_snapshot);
9890 point.row += 1;
9891 point = snapshot.clip_point(point, Bias::Left);
9892 let display_point = point.to_display_point(display_snapshot);
9893 let goal = SelectionGoal::HorizontalPosition(
9894 display_snapshot
9895 .x_for_display_point(display_point, text_layout_details)
9896 .into(),
9897 );
9898 (display_point, goal)
9899 })
9900 });
9901 }
9902 });
9903 }
9904
9905 pub fn select_enclosing_symbol(
9906 &mut self,
9907 _: &SelectEnclosingSymbol,
9908 window: &mut Window,
9909 cx: &mut Context<Self>,
9910 ) {
9911 let buffer = self.buffer.read(cx).snapshot(cx);
9912 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9913
9914 fn update_selection(
9915 selection: &Selection<usize>,
9916 buffer_snap: &MultiBufferSnapshot,
9917 ) -> Option<Selection<usize>> {
9918 let cursor = selection.head();
9919 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9920 for symbol in symbols.iter().rev() {
9921 let start = symbol.range.start.to_offset(buffer_snap);
9922 let end = symbol.range.end.to_offset(buffer_snap);
9923 let new_range = start..end;
9924 if start < selection.start || end > selection.end {
9925 return Some(Selection {
9926 id: selection.id,
9927 start: new_range.start,
9928 end: new_range.end,
9929 goal: SelectionGoal::None,
9930 reversed: selection.reversed,
9931 });
9932 }
9933 }
9934 None
9935 }
9936
9937 let mut selected_larger_symbol = false;
9938 let new_selections = old_selections
9939 .iter()
9940 .map(|selection| match update_selection(selection, &buffer) {
9941 Some(new_selection) => {
9942 if new_selection.range() != selection.range() {
9943 selected_larger_symbol = true;
9944 }
9945 new_selection
9946 }
9947 None => selection.clone(),
9948 })
9949 .collect::<Vec<_>>();
9950
9951 if selected_larger_symbol {
9952 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9953 s.select(new_selections);
9954 });
9955 }
9956 }
9957
9958 pub fn select_larger_syntax_node(
9959 &mut self,
9960 _: &SelectLargerSyntaxNode,
9961 window: &mut Window,
9962 cx: &mut Context<Self>,
9963 ) {
9964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9965 let buffer = self.buffer.read(cx).snapshot(cx);
9966 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9967
9968 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9969 let mut selected_larger_node = false;
9970 let new_selections = old_selections
9971 .iter()
9972 .map(|selection| {
9973 let old_range = selection.start..selection.end;
9974 let mut new_range = old_range.clone();
9975 let mut new_node = None;
9976 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9977 {
9978 new_node = Some(node);
9979 new_range = containing_range;
9980 if !display_map.intersects_fold(new_range.start)
9981 && !display_map.intersects_fold(new_range.end)
9982 {
9983 break;
9984 }
9985 }
9986
9987 if let Some(node) = new_node {
9988 // Log the ancestor, to support using this action as a way to explore TreeSitter
9989 // nodes. Parent and grandparent are also logged because this operation will not
9990 // visit nodes that have the same range as their parent.
9991 log::info!("Node: {node:?}");
9992 let parent = node.parent();
9993 log::info!("Parent: {parent:?}");
9994 let grandparent = parent.and_then(|x| x.parent());
9995 log::info!("Grandparent: {grandparent:?}");
9996 }
9997
9998 selected_larger_node |= new_range != old_range;
9999 Selection {
10000 id: selection.id,
10001 start: new_range.start,
10002 end: new_range.end,
10003 goal: SelectionGoal::None,
10004 reversed: selection.reversed,
10005 }
10006 })
10007 .collect::<Vec<_>>();
10008
10009 if selected_larger_node {
10010 stack.push(old_selections);
10011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10012 s.select(new_selections);
10013 });
10014 }
10015 self.select_larger_syntax_node_stack = stack;
10016 }
10017
10018 pub fn select_smaller_syntax_node(
10019 &mut self,
10020 _: &SelectSmallerSyntaxNode,
10021 window: &mut Window,
10022 cx: &mut Context<Self>,
10023 ) {
10024 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10025 if let Some(selections) = stack.pop() {
10026 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10027 s.select(selections.to_vec());
10028 });
10029 }
10030 self.select_larger_syntax_node_stack = stack;
10031 }
10032
10033 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10034 if !EditorSettings::get_global(cx).gutter.runnables {
10035 self.clear_tasks();
10036 return Task::ready(());
10037 }
10038 let project = self.project.as_ref().map(Entity::downgrade);
10039 cx.spawn_in(window, |this, mut cx| async move {
10040 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10041 let Some(project) = project.and_then(|p| p.upgrade()) else {
10042 return;
10043 };
10044 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10045 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10046 }) else {
10047 return;
10048 };
10049
10050 let hide_runnables = project
10051 .update(&mut cx, |project, cx| {
10052 // Do not display any test indicators in non-dev server remote projects.
10053 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10054 })
10055 .unwrap_or(true);
10056 if hide_runnables {
10057 return;
10058 }
10059 let new_rows =
10060 cx.background_executor()
10061 .spawn({
10062 let snapshot = display_snapshot.clone();
10063 async move {
10064 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10065 }
10066 })
10067 .await;
10068
10069 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10070 this.update(&mut cx, |this, _| {
10071 this.clear_tasks();
10072 for (key, value) in rows {
10073 this.insert_tasks(key, value);
10074 }
10075 })
10076 .ok();
10077 })
10078 }
10079 fn fetch_runnable_ranges(
10080 snapshot: &DisplaySnapshot,
10081 range: Range<Anchor>,
10082 ) -> Vec<language::RunnableRange> {
10083 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10084 }
10085
10086 fn runnable_rows(
10087 project: Entity<Project>,
10088 snapshot: DisplaySnapshot,
10089 runnable_ranges: Vec<RunnableRange>,
10090 mut cx: AsyncWindowContext,
10091 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10092 runnable_ranges
10093 .into_iter()
10094 .filter_map(|mut runnable| {
10095 let tasks = cx
10096 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10097 .ok()?;
10098 if tasks.is_empty() {
10099 return None;
10100 }
10101
10102 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10103
10104 let row = snapshot
10105 .buffer_snapshot
10106 .buffer_line_for_row(MultiBufferRow(point.row))?
10107 .1
10108 .start
10109 .row;
10110
10111 let context_range =
10112 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10113 Some((
10114 (runnable.buffer_id, row),
10115 RunnableTasks {
10116 templates: tasks,
10117 offset: MultiBufferOffset(runnable.run_range.start),
10118 context_range,
10119 column: point.column,
10120 extra_variables: runnable.extra_captures,
10121 },
10122 ))
10123 })
10124 .collect()
10125 }
10126
10127 fn templates_with_tags(
10128 project: &Entity<Project>,
10129 runnable: &mut Runnable,
10130 cx: &mut App,
10131 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10132 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10133 let (worktree_id, file) = project
10134 .buffer_for_id(runnable.buffer, cx)
10135 .and_then(|buffer| buffer.read(cx).file())
10136 .map(|file| (file.worktree_id(cx), file.clone()))
10137 .unzip();
10138
10139 (
10140 project.task_store().read(cx).task_inventory().cloned(),
10141 worktree_id,
10142 file,
10143 )
10144 });
10145
10146 let tags = mem::take(&mut runnable.tags);
10147 let mut tags: Vec<_> = tags
10148 .into_iter()
10149 .flat_map(|tag| {
10150 let tag = tag.0.clone();
10151 inventory
10152 .as_ref()
10153 .into_iter()
10154 .flat_map(|inventory| {
10155 inventory.read(cx).list_tasks(
10156 file.clone(),
10157 Some(runnable.language.clone()),
10158 worktree_id,
10159 cx,
10160 )
10161 })
10162 .filter(move |(_, template)| {
10163 template.tags.iter().any(|source_tag| source_tag == &tag)
10164 })
10165 })
10166 .sorted_by_key(|(kind, _)| kind.to_owned())
10167 .collect();
10168 if let Some((leading_tag_source, _)) = tags.first() {
10169 // Strongest source wins; if we have worktree tag binding, prefer that to
10170 // global and language bindings;
10171 // if we have a global binding, prefer that to language binding.
10172 let first_mismatch = tags
10173 .iter()
10174 .position(|(tag_source, _)| tag_source != leading_tag_source);
10175 if let Some(index) = first_mismatch {
10176 tags.truncate(index);
10177 }
10178 }
10179
10180 tags
10181 }
10182
10183 pub fn move_to_enclosing_bracket(
10184 &mut self,
10185 _: &MoveToEnclosingBracket,
10186 window: &mut Window,
10187 cx: &mut Context<Self>,
10188 ) {
10189 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10190 s.move_offsets_with(|snapshot, selection| {
10191 let Some(enclosing_bracket_ranges) =
10192 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10193 else {
10194 return;
10195 };
10196
10197 let mut best_length = usize::MAX;
10198 let mut best_inside = false;
10199 let mut best_in_bracket_range = false;
10200 let mut best_destination = None;
10201 for (open, close) in enclosing_bracket_ranges {
10202 let close = close.to_inclusive();
10203 let length = close.end() - open.start;
10204 let inside = selection.start >= open.end && selection.end <= *close.start();
10205 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10206 || close.contains(&selection.head());
10207
10208 // If best is next to a bracket and current isn't, skip
10209 if !in_bracket_range && best_in_bracket_range {
10210 continue;
10211 }
10212
10213 // Prefer smaller lengths unless best is inside and current isn't
10214 if length > best_length && (best_inside || !inside) {
10215 continue;
10216 }
10217
10218 best_length = length;
10219 best_inside = inside;
10220 best_in_bracket_range = in_bracket_range;
10221 best_destination = Some(
10222 if close.contains(&selection.start) && close.contains(&selection.end) {
10223 if inside {
10224 open.end
10225 } else {
10226 open.start
10227 }
10228 } else if inside {
10229 *close.start()
10230 } else {
10231 *close.end()
10232 },
10233 );
10234 }
10235
10236 if let Some(destination) = best_destination {
10237 selection.collapse_to(destination, SelectionGoal::None);
10238 }
10239 })
10240 });
10241 }
10242
10243 pub fn undo_selection(
10244 &mut self,
10245 _: &UndoSelection,
10246 window: &mut Window,
10247 cx: &mut Context<Self>,
10248 ) {
10249 self.end_selection(window, cx);
10250 self.selection_history.mode = SelectionHistoryMode::Undoing;
10251 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10252 self.change_selections(None, window, cx, |s| {
10253 s.select_anchors(entry.selections.to_vec())
10254 });
10255 self.select_next_state = entry.select_next_state;
10256 self.select_prev_state = entry.select_prev_state;
10257 self.add_selections_state = entry.add_selections_state;
10258 self.request_autoscroll(Autoscroll::newest(), cx);
10259 }
10260 self.selection_history.mode = SelectionHistoryMode::Normal;
10261 }
10262
10263 pub fn redo_selection(
10264 &mut self,
10265 _: &RedoSelection,
10266 window: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) {
10269 self.end_selection(window, cx);
10270 self.selection_history.mode = SelectionHistoryMode::Redoing;
10271 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10272 self.change_selections(None, window, cx, |s| {
10273 s.select_anchors(entry.selections.to_vec())
10274 });
10275 self.select_next_state = entry.select_next_state;
10276 self.select_prev_state = entry.select_prev_state;
10277 self.add_selections_state = entry.add_selections_state;
10278 self.request_autoscroll(Autoscroll::newest(), cx);
10279 }
10280 self.selection_history.mode = SelectionHistoryMode::Normal;
10281 }
10282
10283 pub fn expand_excerpts(
10284 &mut self,
10285 action: &ExpandExcerpts,
10286 _: &mut Window,
10287 cx: &mut Context<Self>,
10288 ) {
10289 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10290 }
10291
10292 pub fn expand_excerpts_down(
10293 &mut self,
10294 action: &ExpandExcerptsDown,
10295 _: &mut Window,
10296 cx: &mut Context<Self>,
10297 ) {
10298 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10299 }
10300
10301 pub fn expand_excerpts_up(
10302 &mut self,
10303 action: &ExpandExcerptsUp,
10304 _: &mut Window,
10305 cx: &mut Context<Self>,
10306 ) {
10307 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10308 }
10309
10310 pub fn expand_excerpts_for_direction(
10311 &mut self,
10312 lines: u32,
10313 direction: ExpandExcerptDirection,
10314
10315 cx: &mut Context<Self>,
10316 ) {
10317 let selections = self.selections.disjoint_anchors();
10318
10319 let lines = if lines == 0 {
10320 EditorSettings::get_global(cx).expand_excerpt_lines
10321 } else {
10322 lines
10323 };
10324
10325 self.buffer.update(cx, |buffer, cx| {
10326 let snapshot = buffer.snapshot(cx);
10327 let mut excerpt_ids = selections
10328 .iter()
10329 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10330 .collect::<Vec<_>>();
10331 excerpt_ids.sort();
10332 excerpt_ids.dedup();
10333 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10334 })
10335 }
10336
10337 pub fn expand_excerpt(
10338 &mut self,
10339 excerpt: ExcerptId,
10340 direction: ExpandExcerptDirection,
10341 cx: &mut Context<Self>,
10342 ) {
10343 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10344 self.buffer.update(cx, |buffer, cx| {
10345 buffer.expand_excerpts([excerpt], lines, direction, cx)
10346 })
10347 }
10348
10349 pub fn go_to_singleton_buffer_point(
10350 &mut self,
10351 point: Point,
10352 window: &mut Window,
10353 cx: &mut Context<Self>,
10354 ) {
10355 self.go_to_singleton_buffer_range(point..point, window, cx);
10356 }
10357
10358 pub fn go_to_singleton_buffer_range(
10359 &mut self,
10360 range: Range<Point>,
10361 window: &mut Window,
10362 cx: &mut Context<Self>,
10363 ) {
10364 let multibuffer = self.buffer().read(cx);
10365 let Some(buffer) = multibuffer.as_singleton() else {
10366 return;
10367 };
10368 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10369 return;
10370 };
10371 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10372 return;
10373 };
10374 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10375 s.select_anchor_ranges([start..end])
10376 });
10377 }
10378
10379 fn go_to_diagnostic(
10380 &mut self,
10381 _: &GoToDiagnostic,
10382 window: &mut Window,
10383 cx: &mut Context<Self>,
10384 ) {
10385 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10386 }
10387
10388 fn go_to_prev_diagnostic(
10389 &mut self,
10390 _: &GoToPrevDiagnostic,
10391 window: &mut Window,
10392 cx: &mut Context<Self>,
10393 ) {
10394 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10395 }
10396
10397 pub fn go_to_diagnostic_impl(
10398 &mut self,
10399 direction: Direction,
10400 window: &mut Window,
10401 cx: &mut Context<Self>,
10402 ) {
10403 let buffer = self.buffer.read(cx).snapshot(cx);
10404 let selection = self.selections.newest::<usize>(cx);
10405
10406 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10407 if direction == Direction::Next {
10408 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10409 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10410 return;
10411 };
10412 self.activate_diagnostics(
10413 buffer_id,
10414 popover.local_diagnostic.diagnostic.group_id,
10415 window,
10416 cx,
10417 );
10418 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10419 let primary_range_start = active_diagnostics.primary_range.start;
10420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10421 let mut new_selection = s.newest_anchor().clone();
10422 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10423 s.select_anchors(vec![new_selection.clone()]);
10424 });
10425 self.refresh_inline_completion(false, true, window, cx);
10426 }
10427 return;
10428 }
10429 }
10430
10431 let active_group_id = self
10432 .active_diagnostics
10433 .as_ref()
10434 .map(|active_group| active_group.group_id);
10435 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10436 active_diagnostics
10437 .primary_range
10438 .to_offset(&buffer)
10439 .to_inclusive()
10440 });
10441 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10442 if active_primary_range.contains(&selection.head()) {
10443 *active_primary_range.start()
10444 } else {
10445 selection.head()
10446 }
10447 } else {
10448 selection.head()
10449 };
10450
10451 let snapshot = self.snapshot(window, cx);
10452 let primary_diagnostics_before = buffer
10453 .diagnostics_in_range::<usize>(0..search_start)
10454 .filter(|entry| entry.diagnostic.is_primary)
10455 .filter(|entry| entry.range.start != entry.range.end)
10456 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10457 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10458 .collect::<Vec<_>>();
10459 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10460 primary_diagnostics_before
10461 .iter()
10462 .position(|entry| entry.diagnostic.group_id == active_group_id)
10463 });
10464
10465 let primary_diagnostics_after = buffer
10466 .diagnostics_in_range::<usize>(search_start..buffer.len())
10467 .filter(|entry| entry.diagnostic.is_primary)
10468 .filter(|entry| entry.range.start != entry.range.end)
10469 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10470 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10471 .collect::<Vec<_>>();
10472 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10473 primary_diagnostics_after
10474 .iter()
10475 .enumerate()
10476 .rev()
10477 .find_map(|(i, entry)| {
10478 if entry.diagnostic.group_id == active_group_id {
10479 Some(i)
10480 } else {
10481 None
10482 }
10483 })
10484 });
10485
10486 let next_primary_diagnostic = match direction {
10487 Direction::Prev => primary_diagnostics_before
10488 .iter()
10489 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10490 .rev()
10491 .next(),
10492 Direction::Next => primary_diagnostics_after
10493 .iter()
10494 .skip(
10495 last_same_group_diagnostic_after
10496 .map(|index| index + 1)
10497 .unwrap_or(0),
10498 )
10499 .next(),
10500 };
10501
10502 // Cycle around to the start of the buffer, potentially moving back to the start of
10503 // the currently active diagnostic.
10504 let cycle_around = || match direction {
10505 Direction::Prev => primary_diagnostics_after
10506 .iter()
10507 .rev()
10508 .chain(primary_diagnostics_before.iter().rev())
10509 .next(),
10510 Direction::Next => primary_diagnostics_before
10511 .iter()
10512 .chain(primary_diagnostics_after.iter())
10513 .next(),
10514 };
10515
10516 if let Some((primary_range, group_id)) = next_primary_diagnostic
10517 .or_else(cycle_around)
10518 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10519 {
10520 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10521 return;
10522 };
10523 self.activate_diagnostics(buffer_id, group_id, window, cx);
10524 if self.active_diagnostics.is_some() {
10525 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10526 s.select(vec![Selection {
10527 id: selection.id,
10528 start: primary_range.start,
10529 end: primary_range.start,
10530 reversed: false,
10531 goal: SelectionGoal::None,
10532 }]);
10533 });
10534 self.refresh_inline_completion(false, true, window, cx);
10535 }
10536 }
10537 }
10538
10539 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10540 let snapshot = self.snapshot(window, cx);
10541 let selection = self.selections.newest::<Point>(cx);
10542 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10543 }
10544
10545 fn go_to_hunk_after_position(
10546 &mut self,
10547 snapshot: &EditorSnapshot,
10548 position: Point,
10549 window: &mut Window,
10550 cx: &mut Context<Editor>,
10551 ) -> Option<MultiBufferDiffHunk> {
10552 let mut hunk = snapshot
10553 .buffer_snapshot
10554 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10555 .find(|hunk| hunk.row_range.start.0 > position.row);
10556 if hunk.is_none() {
10557 hunk = snapshot
10558 .buffer_snapshot
10559 .diff_hunks_in_range(Point::zero()..position)
10560 .find(|hunk| hunk.row_range.end.0 < position.row)
10561 }
10562 if let Some(hunk) = &hunk {
10563 let destination = Point::new(hunk.row_range.start.0, 0);
10564 self.unfold_ranges(&[destination..destination], false, false, cx);
10565 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10566 s.select_ranges(vec![destination..destination]);
10567 });
10568 }
10569
10570 hunk
10571 }
10572
10573 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10574 let snapshot = self.snapshot(window, cx);
10575 let selection = self.selections.newest::<Point>(cx);
10576 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10577 }
10578
10579 fn go_to_hunk_before_position(
10580 &mut self,
10581 snapshot: &EditorSnapshot,
10582 position: Point,
10583 window: &mut Window,
10584 cx: &mut Context<Editor>,
10585 ) -> Option<MultiBufferDiffHunk> {
10586 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10587 if hunk.is_none() {
10588 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10589 }
10590 if let Some(hunk) = &hunk {
10591 let destination = Point::new(hunk.row_range.start.0, 0);
10592 self.unfold_ranges(&[destination..destination], false, false, cx);
10593 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10594 s.select_ranges(vec![destination..destination]);
10595 });
10596 }
10597
10598 hunk
10599 }
10600
10601 pub fn go_to_definition(
10602 &mut self,
10603 _: &GoToDefinition,
10604 window: &mut Window,
10605 cx: &mut Context<Self>,
10606 ) -> Task<Result<Navigated>> {
10607 let definition =
10608 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10609 cx.spawn_in(window, |editor, mut cx| async move {
10610 if definition.await? == Navigated::Yes {
10611 return Ok(Navigated::Yes);
10612 }
10613 match editor.update_in(&mut cx, |editor, window, cx| {
10614 editor.find_all_references(&FindAllReferences, window, cx)
10615 })? {
10616 Some(references) => references.await,
10617 None => Ok(Navigated::No),
10618 }
10619 })
10620 }
10621
10622 pub fn go_to_declaration(
10623 &mut self,
10624 _: &GoToDeclaration,
10625 window: &mut Window,
10626 cx: &mut Context<Self>,
10627 ) -> Task<Result<Navigated>> {
10628 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10629 }
10630
10631 pub fn go_to_declaration_split(
10632 &mut self,
10633 _: &GoToDeclaration,
10634 window: &mut Window,
10635 cx: &mut Context<Self>,
10636 ) -> Task<Result<Navigated>> {
10637 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10638 }
10639
10640 pub fn go_to_implementation(
10641 &mut self,
10642 _: &GoToImplementation,
10643 window: &mut Window,
10644 cx: &mut Context<Self>,
10645 ) -> Task<Result<Navigated>> {
10646 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10647 }
10648
10649 pub fn go_to_implementation_split(
10650 &mut self,
10651 _: &GoToImplementationSplit,
10652 window: &mut Window,
10653 cx: &mut Context<Self>,
10654 ) -> Task<Result<Navigated>> {
10655 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10656 }
10657
10658 pub fn go_to_type_definition(
10659 &mut self,
10660 _: &GoToTypeDefinition,
10661 window: &mut Window,
10662 cx: &mut Context<Self>,
10663 ) -> Task<Result<Navigated>> {
10664 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10665 }
10666
10667 pub fn go_to_definition_split(
10668 &mut self,
10669 _: &GoToDefinitionSplit,
10670 window: &mut Window,
10671 cx: &mut Context<Self>,
10672 ) -> Task<Result<Navigated>> {
10673 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10674 }
10675
10676 pub fn go_to_type_definition_split(
10677 &mut self,
10678 _: &GoToTypeDefinitionSplit,
10679 window: &mut Window,
10680 cx: &mut Context<Self>,
10681 ) -> Task<Result<Navigated>> {
10682 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10683 }
10684
10685 fn go_to_definition_of_kind(
10686 &mut self,
10687 kind: GotoDefinitionKind,
10688 split: bool,
10689 window: &mut Window,
10690 cx: &mut Context<Self>,
10691 ) -> Task<Result<Navigated>> {
10692 let Some(provider) = self.semantics_provider.clone() else {
10693 return Task::ready(Ok(Navigated::No));
10694 };
10695 let head = self.selections.newest::<usize>(cx).head();
10696 let buffer = self.buffer.read(cx);
10697 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10698 text_anchor
10699 } else {
10700 return Task::ready(Ok(Navigated::No));
10701 };
10702
10703 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10704 return Task::ready(Ok(Navigated::No));
10705 };
10706
10707 cx.spawn_in(window, |editor, mut cx| async move {
10708 let definitions = definitions.await?;
10709 let navigated = editor
10710 .update_in(&mut cx, |editor, window, cx| {
10711 editor.navigate_to_hover_links(
10712 Some(kind),
10713 definitions
10714 .into_iter()
10715 .filter(|location| {
10716 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10717 })
10718 .map(HoverLink::Text)
10719 .collect::<Vec<_>>(),
10720 split,
10721 window,
10722 cx,
10723 )
10724 })?
10725 .await?;
10726 anyhow::Ok(navigated)
10727 })
10728 }
10729
10730 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10731 let selection = self.selections.newest_anchor();
10732 let head = selection.head();
10733 let tail = selection.tail();
10734
10735 let Some((buffer, start_position)) =
10736 self.buffer.read(cx).text_anchor_for_position(head, cx)
10737 else {
10738 return;
10739 };
10740
10741 let end_position = if head != tail {
10742 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10743 return;
10744 };
10745 Some(pos)
10746 } else {
10747 None
10748 };
10749
10750 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10751 let url = if let Some(end_pos) = end_position {
10752 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10753 } else {
10754 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10755 };
10756
10757 if let Some(url) = url {
10758 editor.update(&mut cx, |_, cx| {
10759 cx.open_url(&url);
10760 })
10761 } else {
10762 Ok(())
10763 }
10764 });
10765
10766 url_finder.detach();
10767 }
10768
10769 pub fn open_selected_filename(
10770 &mut self,
10771 _: &OpenSelectedFilename,
10772 window: &mut Window,
10773 cx: &mut Context<Self>,
10774 ) {
10775 let Some(workspace) = self.workspace() else {
10776 return;
10777 };
10778
10779 let position = self.selections.newest_anchor().head();
10780
10781 let Some((buffer, buffer_position)) =
10782 self.buffer.read(cx).text_anchor_for_position(position, cx)
10783 else {
10784 return;
10785 };
10786
10787 let project = self.project.clone();
10788
10789 cx.spawn_in(window, |_, mut cx| async move {
10790 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10791
10792 if let Some((_, path)) = result {
10793 workspace
10794 .update_in(&mut cx, |workspace, window, cx| {
10795 workspace.open_resolved_path(path, window, cx)
10796 })?
10797 .await?;
10798 }
10799 anyhow::Ok(())
10800 })
10801 .detach();
10802 }
10803
10804 pub(crate) fn navigate_to_hover_links(
10805 &mut self,
10806 kind: Option<GotoDefinitionKind>,
10807 mut definitions: Vec<HoverLink>,
10808 split: bool,
10809 window: &mut Window,
10810 cx: &mut Context<Editor>,
10811 ) -> Task<Result<Navigated>> {
10812 // If there is one definition, just open it directly
10813 if definitions.len() == 1 {
10814 let definition = definitions.pop().unwrap();
10815
10816 enum TargetTaskResult {
10817 Location(Option<Location>),
10818 AlreadyNavigated,
10819 }
10820
10821 let target_task = match definition {
10822 HoverLink::Text(link) => {
10823 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10824 }
10825 HoverLink::InlayHint(lsp_location, server_id) => {
10826 let computation =
10827 self.compute_target_location(lsp_location, server_id, window, cx);
10828 cx.background_executor().spawn(async move {
10829 let location = computation.await?;
10830 Ok(TargetTaskResult::Location(location))
10831 })
10832 }
10833 HoverLink::Url(url) => {
10834 cx.open_url(&url);
10835 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10836 }
10837 HoverLink::File(path) => {
10838 if let Some(workspace) = self.workspace() {
10839 cx.spawn_in(window, |_, mut cx| async move {
10840 workspace
10841 .update_in(&mut cx, |workspace, window, cx| {
10842 workspace.open_resolved_path(path, window, cx)
10843 })?
10844 .await
10845 .map(|_| TargetTaskResult::AlreadyNavigated)
10846 })
10847 } else {
10848 Task::ready(Ok(TargetTaskResult::Location(None)))
10849 }
10850 }
10851 };
10852 cx.spawn_in(window, |editor, mut cx| async move {
10853 let target = match target_task.await.context("target resolution task")? {
10854 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10855 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10856 TargetTaskResult::Location(Some(target)) => target,
10857 };
10858
10859 editor.update_in(&mut cx, |editor, window, cx| {
10860 let Some(workspace) = editor.workspace() else {
10861 return Navigated::No;
10862 };
10863 let pane = workspace.read(cx).active_pane().clone();
10864
10865 let range = target.range.to_point(target.buffer.read(cx));
10866 let range = editor.range_for_match(&range);
10867 let range = collapse_multiline_range(range);
10868
10869 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10870 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10871 } else {
10872 window.defer(cx, move |window, cx| {
10873 let target_editor: Entity<Self> =
10874 workspace.update(cx, |workspace, cx| {
10875 let pane = if split {
10876 workspace.adjacent_pane(window, cx)
10877 } else {
10878 workspace.active_pane().clone()
10879 };
10880
10881 workspace.open_project_item(
10882 pane,
10883 target.buffer.clone(),
10884 true,
10885 true,
10886 window,
10887 cx,
10888 )
10889 });
10890 target_editor.update(cx, |target_editor, cx| {
10891 // When selecting a definition in a different buffer, disable the nav history
10892 // to avoid creating a history entry at the previous cursor location.
10893 pane.update(cx, |pane, _| pane.disable_history());
10894 target_editor.go_to_singleton_buffer_range(range, window, cx);
10895 pane.update(cx, |pane, _| pane.enable_history());
10896 });
10897 });
10898 }
10899 Navigated::Yes
10900 })
10901 })
10902 } else if !definitions.is_empty() {
10903 cx.spawn_in(window, |editor, mut cx| async move {
10904 let (title, location_tasks, workspace) = editor
10905 .update_in(&mut cx, |editor, window, cx| {
10906 let tab_kind = match kind {
10907 Some(GotoDefinitionKind::Implementation) => "Implementations",
10908 _ => "Definitions",
10909 };
10910 let title = definitions
10911 .iter()
10912 .find_map(|definition| match definition {
10913 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10914 let buffer = origin.buffer.read(cx);
10915 format!(
10916 "{} for {}",
10917 tab_kind,
10918 buffer
10919 .text_for_range(origin.range.clone())
10920 .collect::<String>()
10921 )
10922 }),
10923 HoverLink::InlayHint(_, _) => None,
10924 HoverLink::Url(_) => None,
10925 HoverLink::File(_) => None,
10926 })
10927 .unwrap_or(tab_kind.to_string());
10928 let location_tasks = definitions
10929 .into_iter()
10930 .map(|definition| match definition {
10931 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10932 HoverLink::InlayHint(lsp_location, server_id) => editor
10933 .compute_target_location(lsp_location, server_id, window, cx),
10934 HoverLink::Url(_) => Task::ready(Ok(None)),
10935 HoverLink::File(_) => Task::ready(Ok(None)),
10936 })
10937 .collect::<Vec<_>>();
10938 (title, location_tasks, editor.workspace().clone())
10939 })
10940 .context("location tasks preparation")?;
10941
10942 let locations = future::join_all(location_tasks)
10943 .await
10944 .into_iter()
10945 .filter_map(|location| location.transpose())
10946 .collect::<Result<_>>()
10947 .context("location tasks")?;
10948
10949 let Some(workspace) = workspace else {
10950 return Ok(Navigated::No);
10951 };
10952 let opened = workspace
10953 .update_in(&mut cx, |workspace, window, cx| {
10954 Self::open_locations_in_multibuffer(
10955 workspace,
10956 locations,
10957 title,
10958 split,
10959 MultibufferSelectionMode::First,
10960 window,
10961 cx,
10962 )
10963 })
10964 .ok();
10965
10966 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10967 })
10968 } else {
10969 Task::ready(Ok(Navigated::No))
10970 }
10971 }
10972
10973 fn compute_target_location(
10974 &self,
10975 lsp_location: lsp::Location,
10976 server_id: LanguageServerId,
10977 window: &mut Window,
10978 cx: &mut Context<Self>,
10979 ) -> Task<anyhow::Result<Option<Location>>> {
10980 let Some(project) = self.project.clone() else {
10981 return Task::ready(Ok(None));
10982 };
10983
10984 cx.spawn_in(window, move |editor, mut cx| async move {
10985 let location_task = editor.update(&mut cx, |_, cx| {
10986 project.update(cx, |project, cx| {
10987 let language_server_name = project
10988 .language_server_statuses(cx)
10989 .find(|(id, _)| server_id == *id)
10990 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10991 language_server_name.map(|language_server_name| {
10992 project.open_local_buffer_via_lsp(
10993 lsp_location.uri.clone(),
10994 server_id,
10995 language_server_name,
10996 cx,
10997 )
10998 })
10999 })
11000 })?;
11001 let location = match location_task {
11002 Some(task) => Some({
11003 let target_buffer_handle = task.await.context("open local buffer")?;
11004 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11005 let target_start = target_buffer
11006 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11007 let target_end = target_buffer
11008 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11009 target_buffer.anchor_after(target_start)
11010 ..target_buffer.anchor_before(target_end)
11011 })?;
11012 Location {
11013 buffer: target_buffer_handle,
11014 range,
11015 }
11016 }),
11017 None => None,
11018 };
11019 Ok(location)
11020 })
11021 }
11022
11023 pub fn find_all_references(
11024 &mut self,
11025 _: &FindAllReferences,
11026 window: &mut Window,
11027 cx: &mut Context<Self>,
11028 ) -> Option<Task<Result<Navigated>>> {
11029 let selection = self.selections.newest::<usize>(cx);
11030 let multi_buffer = self.buffer.read(cx);
11031 let head = selection.head();
11032
11033 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11034 let head_anchor = multi_buffer_snapshot.anchor_at(
11035 head,
11036 if head < selection.tail() {
11037 Bias::Right
11038 } else {
11039 Bias::Left
11040 },
11041 );
11042
11043 match self
11044 .find_all_references_task_sources
11045 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11046 {
11047 Ok(_) => {
11048 log::info!(
11049 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11050 );
11051 return None;
11052 }
11053 Err(i) => {
11054 self.find_all_references_task_sources.insert(i, head_anchor);
11055 }
11056 }
11057
11058 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11059 let workspace = self.workspace()?;
11060 let project = workspace.read(cx).project().clone();
11061 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11062 Some(cx.spawn_in(window, |editor, mut cx| async move {
11063 let _cleanup = defer({
11064 let mut cx = cx.clone();
11065 move || {
11066 let _ = editor.update(&mut cx, |editor, _| {
11067 if let Ok(i) =
11068 editor
11069 .find_all_references_task_sources
11070 .binary_search_by(|anchor| {
11071 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11072 })
11073 {
11074 editor.find_all_references_task_sources.remove(i);
11075 }
11076 });
11077 }
11078 });
11079
11080 let locations = references.await?;
11081 if locations.is_empty() {
11082 return anyhow::Ok(Navigated::No);
11083 }
11084
11085 workspace.update_in(&mut cx, |workspace, window, cx| {
11086 let title = locations
11087 .first()
11088 .as_ref()
11089 .map(|location| {
11090 let buffer = location.buffer.read(cx);
11091 format!(
11092 "References to `{}`",
11093 buffer
11094 .text_for_range(location.range.clone())
11095 .collect::<String>()
11096 )
11097 })
11098 .unwrap();
11099 Self::open_locations_in_multibuffer(
11100 workspace,
11101 locations,
11102 title,
11103 false,
11104 MultibufferSelectionMode::First,
11105 window,
11106 cx,
11107 );
11108 Navigated::Yes
11109 })
11110 }))
11111 }
11112
11113 /// Opens a multibuffer with the given project locations in it
11114 pub fn open_locations_in_multibuffer(
11115 workspace: &mut Workspace,
11116 mut locations: Vec<Location>,
11117 title: String,
11118 split: bool,
11119 multibuffer_selection_mode: MultibufferSelectionMode,
11120 window: &mut Window,
11121 cx: &mut Context<Workspace>,
11122 ) {
11123 // If there are multiple definitions, open them in a multibuffer
11124 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11125 let mut locations = locations.into_iter().peekable();
11126 let mut ranges = Vec::new();
11127 let capability = workspace.project().read(cx).capability();
11128
11129 let excerpt_buffer = cx.new(|cx| {
11130 let mut multibuffer = MultiBuffer::new(capability);
11131 while let Some(location) = locations.next() {
11132 let buffer = location.buffer.read(cx);
11133 let mut ranges_for_buffer = Vec::new();
11134 let range = location.range.to_offset(buffer);
11135 ranges_for_buffer.push(range.clone());
11136
11137 while let Some(next_location) = locations.peek() {
11138 if next_location.buffer == location.buffer {
11139 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11140 locations.next();
11141 } else {
11142 break;
11143 }
11144 }
11145
11146 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11147 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11148 location.buffer.clone(),
11149 ranges_for_buffer,
11150 DEFAULT_MULTIBUFFER_CONTEXT,
11151 cx,
11152 ))
11153 }
11154
11155 multibuffer.with_title(title)
11156 });
11157
11158 let editor = cx.new(|cx| {
11159 Editor::for_multibuffer(
11160 excerpt_buffer,
11161 Some(workspace.project().clone()),
11162 true,
11163 window,
11164 cx,
11165 )
11166 });
11167 editor.update(cx, |editor, cx| {
11168 match multibuffer_selection_mode {
11169 MultibufferSelectionMode::First => {
11170 if let Some(first_range) = ranges.first() {
11171 editor.change_selections(None, window, cx, |selections| {
11172 selections.clear_disjoint();
11173 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11174 });
11175 }
11176 editor.highlight_background::<Self>(
11177 &ranges,
11178 |theme| theme.editor_highlighted_line_background,
11179 cx,
11180 );
11181 }
11182 MultibufferSelectionMode::All => {
11183 editor.change_selections(None, window, cx, |selections| {
11184 selections.clear_disjoint();
11185 selections.select_anchor_ranges(ranges);
11186 });
11187 }
11188 }
11189 editor.register_buffers_with_language_servers(cx);
11190 });
11191
11192 let item = Box::new(editor);
11193 let item_id = item.item_id();
11194
11195 if split {
11196 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11197 } else {
11198 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11199 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11200 pane.close_current_preview_item(window, cx)
11201 } else {
11202 None
11203 }
11204 });
11205 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11206 }
11207 workspace.active_pane().update(cx, |pane, cx| {
11208 pane.set_preview_item_id(Some(item_id), cx);
11209 });
11210 }
11211
11212 pub fn rename(
11213 &mut self,
11214 _: &Rename,
11215 window: &mut Window,
11216 cx: &mut Context<Self>,
11217 ) -> Option<Task<Result<()>>> {
11218 use language::ToOffset as _;
11219
11220 let provider = self.semantics_provider.clone()?;
11221 let selection = self.selections.newest_anchor().clone();
11222 let (cursor_buffer, cursor_buffer_position) = self
11223 .buffer
11224 .read(cx)
11225 .text_anchor_for_position(selection.head(), cx)?;
11226 let (tail_buffer, cursor_buffer_position_end) = self
11227 .buffer
11228 .read(cx)
11229 .text_anchor_for_position(selection.tail(), cx)?;
11230 if tail_buffer != cursor_buffer {
11231 return None;
11232 }
11233
11234 let snapshot = cursor_buffer.read(cx).snapshot();
11235 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11236 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11237 let prepare_rename = provider
11238 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11239 .unwrap_or_else(|| Task::ready(Ok(None)));
11240 drop(snapshot);
11241
11242 Some(cx.spawn_in(window, |this, mut cx| async move {
11243 let rename_range = if let Some(range) = prepare_rename.await? {
11244 Some(range)
11245 } else {
11246 this.update(&mut cx, |this, cx| {
11247 let buffer = this.buffer.read(cx).snapshot(cx);
11248 let mut buffer_highlights = this
11249 .document_highlights_for_position(selection.head(), &buffer)
11250 .filter(|highlight| {
11251 highlight.start.excerpt_id == selection.head().excerpt_id
11252 && highlight.end.excerpt_id == selection.head().excerpt_id
11253 });
11254 buffer_highlights
11255 .next()
11256 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11257 })?
11258 };
11259 if let Some(rename_range) = rename_range {
11260 this.update_in(&mut cx, |this, window, cx| {
11261 let snapshot = cursor_buffer.read(cx).snapshot();
11262 let rename_buffer_range = rename_range.to_offset(&snapshot);
11263 let cursor_offset_in_rename_range =
11264 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11265 let cursor_offset_in_rename_range_end =
11266 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11267
11268 this.take_rename(false, window, cx);
11269 let buffer = this.buffer.read(cx).read(cx);
11270 let cursor_offset = selection.head().to_offset(&buffer);
11271 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11272 let rename_end = rename_start + rename_buffer_range.len();
11273 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11274 let mut old_highlight_id = None;
11275 let old_name: Arc<str> = buffer
11276 .chunks(rename_start..rename_end, true)
11277 .map(|chunk| {
11278 if old_highlight_id.is_none() {
11279 old_highlight_id = chunk.syntax_highlight_id;
11280 }
11281 chunk.text
11282 })
11283 .collect::<String>()
11284 .into();
11285
11286 drop(buffer);
11287
11288 // Position the selection in the rename editor so that it matches the current selection.
11289 this.show_local_selections = false;
11290 let rename_editor = cx.new(|cx| {
11291 let mut editor = Editor::single_line(window, cx);
11292 editor.buffer.update(cx, |buffer, cx| {
11293 buffer.edit([(0..0, old_name.clone())], None, cx)
11294 });
11295 let rename_selection_range = match cursor_offset_in_rename_range
11296 .cmp(&cursor_offset_in_rename_range_end)
11297 {
11298 Ordering::Equal => {
11299 editor.select_all(&SelectAll, window, cx);
11300 return editor;
11301 }
11302 Ordering::Less => {
11303 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11304 }
11305 Ordering::Greater => {
11306 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11307 }
11308 };
11309 if rename_selection_range.end > old_name.len() {
11310 editor.select_all(&SelectAll, window, cx);
11311 } else {
11312 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11313 s.select_ranges([rename_selection_range]);
11314 });
11315 }
11316 editor
11317 });
11318 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11319 if e == &EditorEvent::Focused {
11320 cx.emit(EditorEvent::FocusedIn)
11321 }
11322 })
11323 .detach();
11324
11325 let write_highlights =
11326 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11327 let read_highlights =
11328 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11329 let ranges = write_highlights
11330 .iter()
11331 .flat_map(|(_, ranges)| ranges.iter())
11332 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11333 .cloned()
11334 .collect();
11335
11336 this.highlight_text::<Rename>(
11337 ranges,
11338 HighlightStyle {
11339 fade_out: Some(0.6),
11340 ..Default::default()
11341 },
11342 cx,
11343 );
11344 let rename_focus_handle = rename_editor.focus_handle(cx);
11345 window.focus(&rename_focus_handle);
11346 let block_id = this.insert_blocks(
11347 [BlockProperties {
11348 style: BlockStyle::Flex,
11349 placement: BlockPlacement::Below(range.start),
11350 height: 1,
11351 render: Arc::new({
11352 let rename_editor = rename_editor.clone();
11353 move |cx: &mut BlockContext| {
11354 let mut text_style = cx.editor_style.text.clone();
11355 if let Some(highlight_style) = old_highlight_id
11356 .and_then(|h| h.style(&cx.editor_style.syntax))
11357 {
11358 text_style = text_style.highlight(highlight_style);
11359 }
11360 div()
11361 .block_mouse_down()
11362 .pl(cx.anchor_x)
11363 .child(EditorElement::new(
11364 &rename_editor,
11365 EditorStyle {
11366 background: cx.theme().system().transparent,
11367 local_player: cx.editor_style.local_player,
11368 text: text_style,
11369 scrollbar_width: cx.editor_style.scrollbar_width,
11370 syntax: cx.editor_style.syntax.clone(),
11371 status: cx.editor_style.status.clone(),
11372 inlay_hints_style: HighlightStyle {
11373 font_weight: Some(FontWeight::BOLD),
11374 ..make_inlay_hints_style(cx.app)
11375 },
11376 inline_completion_styles: make_suggestion_styles(
11377 cx.app,
11378 ),
11379 ..EditorStyle::default()
11380 },
11381 ))
11382 .into_any_element()
11383 }
11384 }),
11385 priority: 0,
11386 }],
11387 Some(Autoscroll::fit()),
11388 cx,
11389 )[0];
11390 this.pending_rename = Some(RenameState {
11391 range,
11392 old_name,
11393 editor: rename_editor,
11394 block_id,
11395 });
11396 })?;
11397 }
11398
11399 Ok(())
11400 }))
11401 }
11402
11403 pub fn confirm_rename(
11404 &mut self,
11405 _: &ConfirmRename,
11406 window: &mut Window,
11407 cx: &mut Context<Self>,
11408 ) -> Option<Task<Result<()>>> {
11409 let rename = self.take_rename(false, window, cx)?;
11410 let workspace = self.workspace()?.downgrade();
11411 let (buffer, start) = self
11412 .buffer
11413 .read(cx)
11414 .text_anchor_for_position(rename.range.start, cx)?;
11415 let (end_buffer, _) = self
11416 .buffer
11417 .read(cx)
11418 .text_anchor_for_position(rename.range.end, cx)?;
11419 if buffer != end_buffer {
11420 return None;
11421 }
11422
11423 let old_name = rename.old_name;
11424 let new_name = rename.editor.read(cx).text(cx);
11425
11426 let rename = self.semantics_provider.as_ref()?.perform_rename(
11427 &buffer,
11428 start,
11429 new_name.clone(),
11430 cx,
11431 )?;
11432
11433 Some(cx.spawn_in(window, |editor, mut cx| async move {
11434 let project_transaction = rename.await?;
11435 Self::open_project_transaction(
11436 &editor,
11437 workspace,
11438 project_transaction,
11439 format!("Rename: {} → {}", old_name, new_name),
11440 cx.clone(),
11441 )
11442 .await?;
11443
11444 editor.update(&mut cx, |editor, cx| {
11445 editor.refresh_document_highlights(cx);
11446 })?;
11447 Ok(())
11448 }))
11449 }
11450
11451 fn take_rename(
11452 &mut self,
11453 moving_cursor: bool,
11454 window: &mut Window,
11455 cx: &mut Context<Self>,
11456 ) -> Option<RenameState> {
11457 let rename = self.pending_rename.take()?;
11458 if rename.editor.focus_handle(cx).is_focused(window) {
11459 window.focus(&self.focus_handle);
11460 }
11461
11462 self.remove_blocks(
11463 [rename.block_id].into_iter().collect(),
11464 Some(Autoscroll::fit()),
11465 cx,
11466 );
11467 self.clear_highlights::<Rename>(cx);
11468 self.show_local_selections = true;
11469
11470 if moving_cursor {
11471 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11472 editor.selections.newest::<usize>(cx).head()
11473 });
11474
11475 // Update the selection to match the position of the selection inside
11476 // the rename editor.
11477 let snapshot = self.buffer.read(cx).read(cx);
11478 let rename_range = rename.range.to_offset(&snapshot);
11479 let cursor_in_editor = snapshot
11480 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11481 .min(rename_range.end);
11482 drop(snapshot);
11483
11484 self.change_selections(None, window, cx, |s| {
11485 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11486 });
11487 } else {
11488 self.refresh_document_highlights(cx);
11489 }
11490
11491 Some(rename)
11492 }
11493
11494 pub fn pending_rename(&self) -> Option<&RenameState> {
11495 self.pending_rename.as_ref()
11496 }
11497
11498 fn format(
11499 &mut self,
11500 _: &Format,
11501 window: &mut Window,
11502 cx: &mut Context<Self>,
11503 ) -> Option<Task<Result<()>>> {
11504 let project = match &self.project {
11505 Some(project) => project.clone(),
11506 None => return None,
11507 };
11508
11509 Some(self.perform_format(
11510 project,
11511 FormatTrigger::Manual,
11512 FormatTarget::Buffers,
11513 window,
11514 cx,
11515 ))
11516 }
11517
11518 fn format_selections(
11519 &mut self,
11520 _: &FormatSelections,
11521 window: &mut Window,
11522 cx: &mut Context<Self>,
11523 ) -> Option<Task<Result<()>>> {
11524 let project = match &self.project {
11525 Some(project) => project.clone(),
11526 None => return None,
11527 };
11528
11529 let ranges = self
11530 .selections
11531 .all_adjusted(cx)
11532 .into_iter()
11533 .map(|selection| selection.range())
11534 .collect_vec();
11535
11536 Some(self.perform_format(
11537 project,
11538 FormatTrigger::Manual,
11539 FormatTarget::Ranges(ranges),
11540 window,
11541 cx,
11542 ))
11543 }
11544
11545 fn perform_format(
11546 &mut self,
11547 project: Entity<Project>,
11548 trigger: FormatTrigger,
11549 target: FormatTarget,
11550 window: &mut Window,
11551 cx: &mut Context<Self>,
11552 ) -> Task<Result<()>> {
11553 let buffer = self.buffer.clone();
11554 let (buffers, target) = match target {
11555 FormatTarget::Buffers => {
11556 let mut buffers = buffer.read(cx).all_buffers();
11557 if trigger == FormatTrigger::Save {
11558 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11559 }
11560 (buffers, LspFormatTarget::Buffers)
11561 }
11562 FormatTarget::Ranges(selection_ranges) => {
11563 let multi_buffer = buffer.read(cx);
11564 let snapshot = multi_buffer.read(cx);
11565 let mut buffers = HashSet::default();
11566 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11567 BTreeMap::new();
11568 for selection_range in selection_ranges {
11569 for (buffer, buffer_range, _) in
11570 snapshot.range_to_buffer_ranges(selection_range)
11571 {
11572 let buffer_id = buffer.remote_id();
11573 let start = buffer.anchor_before(buffer_range.start);
11574 let end = buffer.anchor_after(buffer_range.end);
11575 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11576 buffer_id_to_ranges
11577 .entry(buffer_id)
11578 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11579 .or_insert_with(|| vec![start..end]);
11580 }
11581 }
11582 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11583 }
11584 };
11585
11586 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11587 let format = project.update(cx, |project, cx| {
11588 project.format(buffers, target, true, trigger, cx)
11589 });
11590
11591 cx.spawn_in(window, |_, mut cx| async move {
11592 let transaction = futures::select_biased! {
11593 () = timeout => {
11594 log::warn!("timed out waiting for formatting");
11595 None
11596 }
11597 transaction = format.log_err().fuse() => transaction,
11598 };
11599
11600 buffer
11601 .update(&mut cx, |buffer, cx| {
11602 if let Some(transaction) = transaction {
11603 if !buffer.is_singleton() {
11604 buffer.push_transaction(&transaction.0, cx);
11605 }
11606 }
11607
11608 cx.notify();
11609 })
11610 .ok();
11611
11612 Ok(())
11613 })
11614 }
11615
11616 fn restart_language_server(
11617 &mut self,
11618 _: &RestartLanguageServer,
11619 _: &mut Window,
11620 cx: &mut Context<Self>,
11621 ) {
11622 if let Some(project) = self.project.clone() {
11623 self.buffer.update(cx, |multi_buffer, cx| {
11624 project.update(cx, |project, cx| {
11625 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11626 });
11627 })
11628 }
11629 }
11630
11631 fn cancel_language_server_work(
11632 workspace: &mut Workspace,
11633 _: &actions::CancelLanguageServerWork,
11634 _: &mut Window,
11635 cx: &mut Context<Workspace>,
11636 ) {
11637 let project = workspace.project();
11638 let buffers = workspace
11639 .active_item(cx)
11640 .and_then(|item| item.act_as::<Editor>(cx))
11641 .map_or(HashSet::default(), |editor| {
11642 editor.read(cx).buffer.read(cx).all_buffers()
11643 });
11644 project.update(cx, |project, cx| {
11645 project.cancel_language_server_work_for_buffers(buffers, cx);
11646 });
11647 }
11648
11649 fn show_character_palette(
11650 &mut self,
11651 _: &ShowCharacterPalette,
11652 window: &mut Window,
11653 _: &mut Context<Self>,
11654 ) {
11655 window.show_character_palette();
11656 }
11657
11658 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11659 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11660 let buffer = self.buffer.read(cx).snapshot(cx);
11661 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11662 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11663 let is_valid = buffer
11664 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11665 .any(|entry| {
11666 entry.diagnostic.is_primary
11667 && !entry.range.is_empty()
11668 && entry.range.start == primary_range_start
11669 && entry.diagnostic.message == active_diagnostics.primary_message
11670 });
11671
11672 if is_valid != active_diagnostics.is_valid {
11673 active_diagnostics.is_valid = is_valid;
11674 let mut new_styles = HashMap::default();
11675 for (block_id, diagnostic) in &active_diagnostics.blocks {
11676 new_styles.insert(
11677 *block_id,
11678 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11679 );
11680 }
11681 self.display_map.update(cx, |display_map, _cx| {
11682 display_map.replace_blocks(new_styles)
11683 });
11684 }
11685 }
11686 }
11687
11688 fn activate_diagnostics(
11689 &mut self,
11690 buffer_id: BufferId,
11691 group_id: usize,
11692 window: &mut Window,
11693 cx: &mut Context<Self>,
11694 ) {
11695 self.dismiss_diagnostics(cx);
11696 let snapshot = self.snapshot(window, cx);
11697 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11698 let buffer = self.buffer.read(cx).snapshot(cx);
11699
11700 let mut primary_range = None;
11701 let mut primary_message = None;
11702 let diagnostic_group = buffer
11703 .diagnostic_group(buffer_id, group_id)
11704 .filter_map(|entry| {
11705 let start = entry.range.start;
11706 let end = entry.range.end;
11707 if snapshot.is_line_folded(MultiBufferRow(start.row))
11708 && (start.row == end.row
11709 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11710 {
11711 return None;
11712 }
11713 if entry.diagnostic.is_primary {
11714 primary_range = Some(entry.range.clone());
11715 primary_message = Some(entry.diagnostic.message.clone());
11716 }
11717 Some(entry)
11718 })
11719 .collect::<Vec<_>>();
11720 let primary_range = primary_range?;
11721 let primary_message = primary_message?;
11722
11723 let blocks = display_map
11724 .insert_blocks(
11725 diagnostic_group.iter().map(|entry| {
11726 let diagnostic = entry.diagnostic.clone();
11727 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11728 BlockProperties {
11729 style: BlockStyle::Fixed,
11730 placement: BlockPlacement::Below(
11731 buffer.anchor_after(entry.range.start),
11732 ),
11733 height: message_height,
11734 render: diagnostic_block_renderer(diagnostic, None, true, true),
11735 priority: 0,
11736 }
11737 }),
11738 cx,
11739 )
11740 .into_iter()
11741 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11742 .collect();
11743
11744 Some(ActiveDiagnosticGroup {
11745 primary_range: buffer.anchor_before(primary_range.start)
11746 ..buffer.anchor_after(primary_range.end),
11747 primary_message,
11748 group_id,
11749 blocks,
11750 is_valid: true,
11751 })
11752 });
11753 }
11754
11755 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11756 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11757 self.display_map.update(cx, |display_map, cx| {
11758 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11759 });
11760 cx.notify();
11761 }
11762 }
11763
11764 pub fn set_selections_from_remote(
11765 &mut self,
11766 selections: Vec<Selection<Anchor>>,
11767 pending_selection: Option<Selection<Anchor>>,
11768 window: &mut Window,
11769 cx: &mut Context<Self>,
11770 ) {
11771 let old_cursor_position = self.selections.newest_anchor().head();
11772 self.selections.change_with(cx, |s| {
11773 s.select_anchors(selections);
11774 if let Some(pending_selection) = pending_selection {
11775 s.set_pending(pending_selection, SelectMode::Character);
11776 } else {
11777 s.clear_pending();
11778 }
11779 });
11780 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11781 }
11782
11783 fn push_to_selection_history(&mut self) {
11784 self.selection_history.push(SelectionHistoryEntry {
11785 selections: self.selections.disjoint_anchors(),
11786 select_next_state: self.select_next_state.clone(),
11787 select_prev_state: self.select_prev_state.clone(),
11788 add_selections_state: self.add_selections_state.clone(),
11789 });
11790 }
11791
11792 pub fn transact(
11793 &mut self,
11794 window: &mut Window,
11795 cx: &mut Context<Self>,
11796 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11797 ) -> Option<TransactionId> {
11798 self.start_transaction_at(Instant::now(), window, cx);
11799 update(self, window, cx);
11800 self.end_transaction_at(Instant::now(), cx)
11801 }
11802
11803 pub fn start_transaction_at(
11804 &mut self,
11805 now: Instant,
11806 window: &mut Window,
11807 cx: &mut Context<Self>,
11808 ) {
11809 self.end_selection(window, cx);
11810 if let Some(tx_id) = self
11811 .buffer
11812 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11813 {
11814 self.selection_history
11815 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11816 cx.emit(EditorEvent::TransactionBegun {
11817 transaction_id: tx_id,
11818 })
11819 }
11820 }
11821
11822 pub fn end_transaction_at(
11823 &mut self,
11824 now: Instant,
11825 cx: &mut Context<Self>,
11826 ) -> Option<TransactionId> {
11827 if let Some(transaction_id) = self
11828 .buffer
11829 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11830 {
11831 if let Some((_, end_selections)) =
11832 self.selection_history.transaction_mut(transaction_id)
11833 {
11834 *end_selections = Some(self.selections.disjoint_anchors());
11835 } else {
11836 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11837 }
11838
11839 cx.emit(EditorEvent::Edited { transaction_id });
11840 Some(transaction_id)
11841 } else {
11842 None
11843 }
11844 }
11845
11846 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11847 if self.selection_mark_mode {
11848 self.change_selections(None, window, cx, |s| {
11849 s.move_with(|_, sel| {
11850 sel.collapse_to(sel.head(), SelectionGoal::None);
11851 });
11852 })
11853 }
11854 self.selection_mark_mode = true;
11855 cx.notify();
11856 }
11857
11858 pub fn swap_selection_ends(
11859 &mut self,
11860 _: &actions::SwapSelectionEnds,
11861 window: &mut Window,
11862 cx: &mut Context<Self>,
11863 ) {
11864 self.change_selections(None, window, cx, |s| {
11865 s.move_with(|_, sel| {
11866 if sel.start != sel.end {
11867 sel.reversed = !sel.reversed
11868 }
11869 });
11870 });
11871 self.request_autoscroll(Autoscroll::newest(), cx);
11872 cx.notify();
11873 }
11874
11875 pub fn toggle_fold(
11876 &mut self,
11877 _: &actions::ToggleFold,
11878 window: &mut Window,
11879 cx: &mut Context<Self>,
11880 ) {
11881 if self.is_singleton(cx) {
11882 let selection = self.selections.newest::<Point>(cx);
11883
11884 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11885 let range = if selection.is_empty() {
11886 let point = selection.head().to_display_point(&display_map);
11887 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11888 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11889 .to_point(&display_map);
11890 start..end
11891 } else {
11892 selection.range()
11893 };
11894 if display_map.folds_in_range(range).next().is_some() {
11895 self.unfold_lines(&Default::default(), window, cx)
11896 } else {
11897 self.fold(&Default::default(), window, cx)
11898 }
11899 } else {
11900 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11901 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11902 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11903 .map(|(snapshot, _, _)| snapshot.remote_id())
11904 .collect();
11905
11906 for buffer_id in buffer_ids {
11907 if self.is_buffer_folded(buffer_id, cx) {
11908 self.unfold_buffer(buffer_id, cx);
11909 } else {
11910 self.fold_buffer(buffer_id, cx);
11911 }
11912 }
11913 }
11914 }
11915
11916 pub fn toggle_fold_recursive(
11917 &mut self,
11918 _: &actions::ToggleFoldRecursive,
11919 window: &mut Window,
11920 cx: &mut Context<Self>,
11921 ) {
11922 let selection = self.selections.newest::<Point>(cx);
11923
11924 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11925 let range = if selection.is_empty() {
11926 let point = selection.head().to_display_point(&display_map);
11927 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11928 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11929 .to_point(&display_map);
11930 start..end
11931 } else {
11932 selection.range()
11933 };
11934 if display_map.folds_in_range(range).next().is_some() {
11935 self.unfold_recursive(&Default::default(), window, cx)
11936 } else {
11937 self.fold_recursive(&Default::default(), window, cx)
11938 }
11939 }
11940
11941 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11942 if self.is_singleton(cx) {
11943 let mut to_fold = Vec::new();
11944 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11945 let selections = self.selections.all_adjusted(cx);
11946
11947 for selection in selections {
11948 let range = selection.range().sorted();
11949 let buffer_start_row = range.start.row;
11950
11951 if range.start.row != range.end.row {
11952 let mut found = false;
11953 let mut row = range.start.row;
11954 while row <= range.end.row {
11955 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11956 {
11957 found = true;
11958 row = crease.range().end.row + 1;
11959 to_fold.push(crease);
11960 } else {
11961 row += 1
11962 }
11963 }
11964 if found {
11965 continue;
11966 }
11967 }
11968
11969 for row in (0..=range.start.row).rev() {
11970 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11971 if crease.range().end.row >= buffer_start_row {
11972 to_fold.push(crease);
11973 if row <= range.start.row {
11974 break;
11975 }
11976 }
11977 }
11978 }
11979 }
11980
11981 self.fold_creases(to_fold, true, window, cx);
11982 } else {
11983 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11984
11985 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11986 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11987 .map(|(snapshot, _, _)| snapshot.remote_id())
11988 .collect();
11989 for buffer_id in buffer_ids {
11990 self.fold_buffer(buffer_id, cx);
11991 }
11992 }
11993 }
11994
11995 fn fold_at_level(
11996 &mut self,
11997 fold_at: &FoldAtLevel,
11998 window: &mut Window,
11999 cx: &mut Context<Self>,
12000 ) {
12001 if !self.buffer.read(cx).is_singleton() {
12002 return;
12003 }
12004
12005 let fold_at_level = fold_at.0;
12006 let snapshot = self.buffer.read(cx).snapshot(cx);
12007 let mut to_fold = Vec::new();
12008 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12009
12010 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12011 while start_row < end_row {
12012 match self
12013 .snapshot(window, cx)
12014 .crease_for_buffer_row(MultiBufferRow(start_row))
12015 {
12016 Some(crease) => {
12017 let nested_start_row = crease.range().start.row + 1;
12018 let nested_end_row = crease.range().end.row;
12019
12020 if current_level < fold_at_level {
12021 stack.push((nested_start_row, nested_end_row, current_level + 1));
12022 } else if current_level == fold_at_level {
12023 to_fold.push(crease);
12024 }
12025
12026 start_row = nested_end_row + 1;
12027 }
12028 None => start_row += 1,
12029 }
12030 }
12031 }
12032
12033 self.fold_creases(to_fold, true, window, cx);
12034 }
12035
12036 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12037 if self.buffer.read(cx).is_singleton() {
12038 let mut fold_ranges = Vec::new();
12039 let snapshot = self.buffer.read(cx).snapshot(cx);
12040
12041 for row in 0..snapshot.max_row().0 {
12042 if let Some(foldable_range) = self
12043 .snapshot(window, cx)
12044 .crease_for_buffer_row(MultiBufferRow(row))
12045 {
12046 fold_ranges.push(foldable_range);
12047 }
12048 }
12049
12050 self.fold_creases(fold_ranges, true, window, cx);
12051 } else {
12052 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12053 editor
12054 .update_in(&mut cx, |editor, _, cx| {
12055 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12056 editor.fold_buffer(buffer_id, cx);
12057 }
12058 })
12059 .ok();
12060 });
12061 }
12062 }
12063
12064 pub fn fold_function_bodies(
12065 &mut self,
12066 _: &actions::FoldFunctionBodies,
12067 window: &mut Window,
12068 cx: &mut Context<Self>,
12069 ) {
12070 let snapshot = self.buffer.read(cx).snapshot(cx);
12071
12072 let ranges = snapshot
12073 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12074 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12075 .collect::<Vec<_>>();
12076
12077 let creases = ranges
12078 .into_iter()
12079 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12080 .collect();
12081
12082 self.fold_creases(creases, true, window, cx);
12083 }
12084
12085 pub fn fold_recursive(
12086 &mut self,
12087 _: &actions::FoldRecursive,
12088 window: &mut Window,
12089 cx: &mut Context<Self>,
12090 ) {
12091 let mut to_fold = Vec::new();
12092 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12093 let selections = self.selections.all_adjusted(cx);
12094
12095 for selection in selections {
12096 let range = selection.range().sorted();
12097 let buffer_start_row = range.start.row;
12098
12099 if range.start.row != range.end.row {
12100 let mut found = false;
12101 for row in range.start.row..=range.end.row {
12102 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12103 found = true;
12104 to_fold.push(crease);
12105 }
12106 }
12107 if found {
12108 continue;
12109 }
12110 }
12111
12112 for row in (0..=range.start.row).rev() {
12113 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12114 if crease.range().end.row >= buffer_start_row {
12115 to_fold.push(crease);
12116 } else {
12117 break;
12118 }
12119 }
12120 }
12121 }
12122
12123 self.fold_creases(to_fold, true, window, cx);
12124 }
12125
12126 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12127 let buffer_row = fold_at.buffer_row;
12128 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12129
12130 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12131 let autoscroll = self
12132 .selections
12133 .all::<Point>(cx)
12134 .iter()
12135 .any(|selection| crease.range().overlaps(&selection.range()));
12136
12137 self.fold_creases(vec![crease], autoscroll, window, cx);
12138 }
12139 }
12140
12141 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12142 if self.is_singleton(cx) {
12143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12144 let buffer = &display_map.buffer_snapshot;
12145 let selections = self.selections.all::<Point>(cx);
12146 let ranges = selections
12147 .iter()
12148 .map(|s| {
12149 let range = s.display_range(&display_map).sorted();
12150 let mut start = range.start.to_point(&display_map);
12151 let mut end = range.end.to_point(&display_map);
12152 start.column = 0;
12153 end.column = buffer.line_len(MultiBufferRow(end.row));
12154 start..end
12155 })
12156 .collect::<Vec<_>>();
12157
12158 self.unfold_ranges(&ranges, true, true, cx);
12159 } else {
12160 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12161 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12162 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12163 .map(|(snapshot, _, _)| snapshot.remote_id())
12164 .collect();
12165 for buffer_id in buffer_ids {
12166 self.unfold_buffer(buffer_id, cx);
12167 }
12168 }
12169 }
12170
12171 pub fn unfold_recursive(
12172 &mut self,
12173 _: &UnfoldRecursive,
12174 _window: &mut Window,
12175 cx: &mut Context<Self>,
12176 ) {
12177 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12178 let selections = self.selections.all::<Point>(cx);
12179 let ranges = selections
12180 .iter()
12181 .map(|s| {
12182 let mut range = s.display_range(&display_map).sorted();
12183 *range.start.column_mut() = 0;
12184 *range.end.column_mut() = display_map.line_len(range.end.row());
12185 let start = range.start.to_point(&display_map);
12186 let end = range.end.to_point(&display_map);
12187 start..end
12188 })
12189 .collect::<Vec<_>>();
12190
12191 self.unfold_ranges(&ranges, true, true, cx);
12192 }
12193
12194 pub fn unfold_at(
12195 &mut self,
12196 unfold_at: &UnfoldAt,
12197 _window: &mut Window,
12198 cx: &mut Context<Self>,
12199 ) {
12200 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12201
12202 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12203 ..Point::new(
12204 unfold_at.buffer_row.0,
12205 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12206 );
12207
12208 let autoscroll = self
12209 .selections
12210 .all::<Point>(cx)
12211 .iter()
12212 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12213
12214 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12215 }
12216
12217 pub fn unfold_all(
12218 &mut self,
12219 _: &actions::UnfoldAll,
12220 _window: &mut Window,
12221 cx: &mut Context<Self>,
12222 ) {
12223 if self.buffer.read(cx).is_singleton() {
12224 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12225 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12226 } else {
12227 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12228 editor
12229 .update(&mut cx, |editor, cx| {
12230 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12231 editor.unfold_buffer(buffer_id, cx);
12232 }
12233 })
12234 .ok();
12235 });
12236 }
12237 }
12238
12239 pub fn fold_selected_ranges(
12240 &mut self,
12241 _: &FoldSelectedRanges,
12242 window: &mut Window,
12243 cx: &mut Context<Self>,
12244 ) {
12245 let selections = self.selections.all::<Point>(cx);
12246 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12247 let line_mode = self.selections.line_mode;
12248 let ranges = selections
12249 .into_iter()
12250 .map(|s| {
12251 if line_mode {
12252 let start = Point::new(s.start.row, 0);
12253 let end = Point::new(
12254 s.end.row,
12255 display_map
12256 .buffer_snapshot
12257 .line_len(MultiBufferRow(s.end.row)),
12258 );
12259 Crease::simple(start..end, display_map.fold_placeholder.clone())
12260 } else {
12261 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12262 }
12263 })
12264 .collect::<Vec<_>>();
12265 self.fold_creases(ranges, true, window, cx);
12266 }
12267
12268 pub fn fold_ranges<T: ToOffset + Clone>(
12269 &mut self,
12270 ranges: Vec<Range<T>>,
12271 auto_scroll: bool,
12272 window: &mut Window,
12273 cx: &mut Context<Self>,
12274 ) {
12275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12276 let ranges = ranges
12277 .into_iter()
12278 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12279 .collect::<Vec<_>>();
12280 self.fold_creases(ranges, auto_scroll, window, cx);
12281 }
12282
12283 pub fn fold_creases<T: ToOffset + Clone>(
12284 &mut self,
12285 creases: Vec<Crease<T>>,
12286 auto_scroll: bool,
12287 window: &mut Window,
12288 cx: &mut Context<Self>,
12289 ) {
12290 if creases.is_empty() {
12291 return;
12292 }
12293
12294 let mut buffers_affected = HashSet::default();
12295 let multi_buffer = self.buffer().read(cx);
12296 for crease in &creases {
12297 if let Some((_, buffer, _)) =
12298 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12299 {
12300 buffers_affected.insert(buffer.read(cx).remote_id());
12301 };
12302 }
12303
12304 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12305
12306 if auto_scroll {
12307 self.request_autoscroll(Autoscroll::fit(), cx);
12308 }
12309
12310 cx.notify();
12311
12312 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12313 // Clear diagnostics block when folding a range that contains it.
12314 let snapshot = self.snapshot(window, cx);
12315 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12316 drop(snapshot);
12317 self.active_diagnostics = Some(active_diagnostics);
12318 self.dismiss_diagnostics(cx);
12319 } else {
12320 self.active_diagnostics = Some(active_diagnostics);
12321 }
12322 }
12323
12324 self.scrollbar_marker_state.dirty = true;
12325 }
12326
12327 /// Removes any folds whose ranges intersect any of the given ranges.
12328 pub fn unfold_ranges<T: ToOffset + Clone>(
12329 &mut self,
12330 ranges: &[Range<T>],
12331 inclusive: bool,
12332 auto_scroll: bool,
12333 cx: &mut Context<Self>,
12334 ) {
12335 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12336 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12337 });
12338 }
12339
12340 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12341 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12342 return;
12343 }
12344 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12345 self.display_map
12346 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12347 cx.emit(EditorEvent::BufferFoldToggled {
12348 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12349 folded: true,
12350 });
12351 cx.notify();
12352 }
12353
12354 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12355 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12356 return;
12357 }
12358 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12359 self.display_map.update(cx, |display_map, cx| {
12360 display_map.unfold_buffer(buffer_id, cx);
12361 });
12362 cx.emit(EditorEvent::BufferFoldToggled {
12363 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12364 folded: false,
12365 });
12366 cx.notify();
12367 }
12368
12369 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12370 self.display_map.read(cx).is_buffer_folded(buffer)
12371 }
12372
12373 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12374 self.display_map.read(cx).folded_buffers()
12375 }
12376
12377 /// Removes any folds with the given ranges.
12378 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12379 &mut self,
12380 ranges: &[Range<T>],
12381 type_id: TypeId,
12382 auto_scroll: bool,
12383 cx: &mut Context<Self>,
12384 ) {
12385 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12386 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12387 });
12388 }
12389
12390 fn remove_folds_with<T: ToOffset + Clone>(
12391 &mut self,
12392 ranges: &[Range<T>],
12393 auto_scroll: bool,
12394 cx: &mut Context<Self>,
12395 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12396 ) {
12397 if ranges.is_empty() {
12398 return;
12399 }
12400
12401 let mut buffers_affected = HashSet::default();
12402 let multi_buffer = self.buffer().read(cx);
12403 for range in ranges {
12404 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12405 buffers_affected.insert(buffer.read(cx).remote_id());
12406 };
12407 }
12408
12409 self.display_map.update(cx, update);
12410
12411 if auto_scroll {
12412 self.request_autoscroll(Autoscroll::fit(), cx);
12413 }
12414
12415 cx.notify();
12416 self.scrollbar_marker_state.dirty = true;
12417 self.active_indent_guides_state.dirty = true;
12418 }
12419
12420 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12421 self.display_map.read(cx).fold_placeholder.clone()
12422 }
12423
12424 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12425 self.buffer.update(cx, |buffer, cx| {
12426 buffer.set_all_diff_hunks_expanded(cx);
12427 });
12428 }
12429
12430 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12431 self.distinguish_unstaged_diff_hunks = true;
12432 }
12433
12434 pub fn expand_all_diff_hunks(
12435 &mut self,
12436 _: &ExpandAllHunkDiffs,
12437 _window: &mut Window,
12438 cx: &mut Context<Self>,
12439 ) {
12440 self.buffer.update(cx, |buffer, cx| {
12441 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12442 });
12443 }
12444
12445 pub fn toggle_selected_diff_hunks(
12446 &mut self,
12447 _: &ToggleSelectedDiffHunks,
12448 _window: &mut Window,
12449 cx: &mut Context<Self>,
12450 ) {
12451 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12452 self.toggle_diff_hunks_in_ranges(ranges, cx);
12453 }
12454
12455 fn diff_hunks_in_ranges<'a>(
12456 &'a self,
12457 ranges: &'a [Range<Anchor>],
12458 buffer: &'a MultiBufferSnapshot,
12459 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12460 ranges.iter().flat_map(move |range| {
12461 let end_excerpt_id = range.end.excerpt_id;
12462 let range = range.to_point(buffer);
12463 let mut peek_end = range.end;
12464 if range.end.row < buffer.max_row().0 {
12465 peek_end = Point::new(range.end.row + 1, 0);
12466 }
12467 buffer
12468 .diff_hunks_in_range(range.start..peek_end)
12469 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12470 })
12471 }
12472
12473 pub fn has_stageable_diff_hunks_in_ranges(
12474 &self,
12475 ranges: &[Range<Anchor>],
12476 snapshot: &MultiBufferSnapshot,
12477 ) -> bool {
12478 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12479 hunks.any(|hunk| {
12480 log::debug!("considering {hunk:?}");
12481 hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12482 })
12483 }
12484
12485 pub fn toggle_staged_selected_diff_hunks(
12486 &mut self,
12487 _: &ToggleStagedSelectedDiffHunks,
12488 _window: &mut Window,
12489 cx: &mut Context<Self>,
12490 ) {
12491 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12492 self.stage_or_unstage_diff_hunks(&ranges, cx);
12493 }
12494
12495 pub fn stage_or_unstage_diff_hunks(
12496 &mut self,
12497 ranges: &[Range<Anchor>],
12498 cx: &mut Context<Self>,
12499 ) {
12500 let Some(project) = &self.project else {
12501 return;
12502 };
12503 let snapshot = self.buffer.read(cx).snapshot(cx);
12504 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12505
12506 let chunk_by = self
12507 .diff_hunks_in_ranges(&ranges, &snapshot)
12508 .chunk_by(|hunk| hunk.buffer_id);
12509 for (buffer_id, hunks) in &chunk_by {
12510 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12511 log::debug!("no buffer for id");
12512 continue;
12513 };
12514 let buffer = buffer.read(cx).snapshot();
12515 let Some((repo, path)) = project
12516 .read(cx)
12517 .repository_and_path_for_buffer_id(buffer_id, cx)
12518 else {
12519 log::debug!("no git repo for buffer id");
12520 continue;
12521 };
12522 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12523 log::debug!("no diff for buffer id");
12524 continue;
12525 };
12526 let Some(secondary_diff) = diff.secondary_diff() else {
12527 log::debug!("no secondary diff for buffer id");
12528 continue;
12529 };
12530
12531 let edits = diff.secondary_edits_for_stage_or_unstage(
12532 stage,
12533 hunks.map(|hunk| {
12534 (
12535 hunk.diff_base_byte_range.clone(),
12536 hunk.secondary_diff_base_byte_range.clone(),
12537 hunk.buffer_range.clone(),
12538 )
12539 }),
12540 &buffer,
12541 );
12542
12543 let index_base = secondary_diff.base_text().map_or_else(
12544 || Rope::from(""),
12545 |snapshot| snapshot.text.as_rope().clone(),
12546 );
12547 let index_buffer = cx.new(|cx| {
12548 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12549 });
12550 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12551 index_buffer.edit(edits, None, cx);
12552 index_buffer.snapshot().as_rope().to_string()
12553 });
12554 let new_index_text = if new_index_text.is_empty()
12555 && (diff.is_single_insertion
12556 || buffer
12557 .file()
12558 .map_or(false, |file| file.disk_state() == DiskState::New))
12559 {
12560 log::debug!("removing from index");
12561 None
12562 } else {
12563 Some(new_index_text)
12564 };
12565
12566 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12567 }
12568 }
12569
12570 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12571 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12572 self.buffer
12573 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12574 }
12575
12576 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12577 self.buffer.update(cx, |buffer, cx| {
12578 let ranges = vec![Anchor::min()..Anchor::max()];
12579 if !buffer.all_diff_hunks_expanded()
12580 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12581 {
12582 buffer.collapse_diff_hunks(ranges, cx);
12583 true
12584 } else {
12585 false
12586 }
12587 })
12588 }
12589
12590 fn toggle_diff_hunks_in_ranges(
12591 &mut self,
12592 ranges: Vec<Range<Anchor>>,
12593 cx: &mut Context<'_, Editor>,
12594 ) {
12595 self.buffer.update(cx, |buffer, cx| {
12596 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12597 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12598 })
12599 }
12600
12601 fn toggle_diff_hunks_in_ranges_narrow(
12602 &mut self,
12603 ranges: Vec<Range<Anchor>>,
12604 cx: &mut Context<'_, Editor>,
12605 ) {
12606 self.buffer.update(cx, |buffer, cx| {
12607 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12608 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12609 })
12610 }
12611
12612 pub(crate) fn apply_all_diff_hunks(
12613 &mut self,
12614 _: &ApplyAllDiffHunks,
12615 window: &mut Window,
12616 cx: &mut Context<Self>,
12617 ) {
12618 let buffers = self.buffer.read(cx).all_buffers();
12619 for branch_buffer in buffers {
12620 branch_buffer.update(cx, |branch_buffer, cx| {
12621 branch_buffer.merge_into_base(Vec::new(), cx);
12622 });
12623 }
12624
12625 if let Some(project) = self.project.clone() {
12626 self.save(true, project, window, cx).detach_and_log_err(cx);
12627 }
12628 }
12629
12630 pub(crate) fn apply_selected_diff_hunks(
12631 &mut self,
12632 _: &ApplyDiffHunk,
12633 window: &mut Window,
12634 cx: &mut Context<Self>,
12635 ) {
12636 let snapshot = self.snapshot(window, cx);
12637 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12638 let mut ranges_by_buffer = HashMap::default();
12639 self.transact(window, cx, |editor, _window, cx| {
12640 for hunk in hunks {
12641 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12642 ranges_by_buffer
12643 .entry(buffer.clone())
12644 .or_insert_with(Vec::new)
12645 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12646 }
12647 }
12648
12649 for (buffer, ranges) in ranges_by_buffer {
12650 buffer.update(cx, |buffer, cx| {
12651 buffer.merge_into_base(ranges, cx);
12652 });
12653 }
12654 });
12655
12656 if let Some(project) = self.project.clone() {
12657 self.save(true, project, window, cx).detach_and_log_err(cx);
12658 }
12659 }
12660
12661 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12662 if hovered != self.gutter_hovered {
12663 self.gutter_hovered = hovered;
12664 cx.notify();
12665 }
12666 }
12667
12668 pub fn insert_blocks(
12669 &mut self,
12670 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12671 autoscroll: Option<Autoscroll>,
12672 cx: &mut Context<Self>,
12673 ) -> Vec<CustomBlockId> {
12674 let blocks = self
12675 .display_map
12676 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12677 if let Some(autoscroll) = autoscroll {
12678 self.request_autoscroll(autoscroll, cx);
12679 }
12680 cx.notify();
12681 blocks
12682 }
12683
12684 pub fn resize_blocks(
12685 &mut self,
12686 heights: HashMap<CustomBlockId, u32>,
12687 autoscroll: Option<Autoscroll>,
12688 cx: &mut Context<Self>,
12689 ) {
12690 self.display_map
12691 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12692 if let Some(autoscroll) = autoscroll {
12693 self.request_autoscroll(autoscroll, cx);
12694 }
12695 cx.notify();
12696 }
12697
12698 pub fn replace_blocks(
12699 &mut self,
12700 renderers: HashMap<CustomBlockId, RenderBlock>,
12701 autoscroll: Option<Autoscroll>,
12702 cx: &mut Context<Self>,
12703 ) {
12704 self.display_map
12705 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12706 if let Some(autoscroll) = autoscroll {
12707 self.request_autoscroll(autoscroll, cx);
12708 }
12709 cx.notify();
12710 }
12711
12712 pub fn remove_blocks(
12713 &mut self,
12714 block_ids: HashSet<CustomBlockId>,
12715 autoscroll: Option<Autoscroll>,
12716 cx: &mut Context<Self>,
12717 ) {
12718 self.display_map.update(cx, |display_map, cx| {
12719 display_map.remove_blocks(block_ids, cx)
12720 });
12721 if let Some(autoscroll) = autoscroll {
12722 self.request_autoscroll(autoscroll, cx);
12723 }
12724 cx.notify();
12725 }
12726
12727 pub fn row_for_block(
12728 &self,
12729 block_id: CustomBlockId,
12730 cx: &mut Context<Self>,
12731 ) -> Option<DisplayRow> {
12732 self.display_map
12733 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12734 }
12735
12736 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12737 self.focused_block = Some(focused_block);
12738 }
12739
12740 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12741 self.focused_block.take()
12742 }
12743
12744 pub fn insert_creases(
12745 &mut self,
12746 creases: impl IntoIterator<Item = Crease<Anchor>>,
12747 cx: &mut Context<Self>,
12748 ) -> Vec<CreaseId> {
12749 self.display_map
12750 .update(cx, |map, cx| map.insert_creases(creases, cx))
12751 }
12752
12753 pub fn remove_creases(
12754 &mut self,
12755 ids: impl IntoIterator<Item = CreaseId>,
12756 cx: &mut Context<Self>,
12757 ) {
12758 self.display_map
12759 .update(cx, |map, cx| map.remove_creases(ids, cx));
12760 }
12761
12762 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12763 self.display_map
12764 .update(cx, |map, cx| map.snapshot(cx))
12765 .longest_row()
12766 }
12767
12768 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12769 self.display_map
12770 .update(cx, |map, cx| map.snapshot(cx))
12771 .max_point()
12772 }
12773
12774 pub fn text(&self, cx: &App) -> String {
12775 self.buffer.read(cx).read(cx).text()
12776 }
12777
12778 pub fn is_empty(&self, cx: &App) -> bool {
12779 self.buffer.read(cx).read(cx).is_empty()
12780 }
12781
12782 pub fn text_option(&self, cx: &App) -> Option<String> {
12783 let text = self.text(cx);
12784 let text = text.trim();
12785
12786 if text.is_empty() {
12787 return None;
12788 }
12789
12790 Some(text.to_string())
12791 }
12792
12793 pub fn set_text(
12794 &mut self,
12795 text: impl Into<Arc<str>>,
12796 window: &mut Window,
12797 cx: &mut Context<Self>,
12798 ) {
12799 self.transact(window, cx, |this, _, cx| {
12800 this.buffer
12801 .read(cx)
12802 .as_singleton()
12803 .expect("you can only call set_text on editors for singleton buffers")
12804 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12805 });
12806 }
12807
12808 pub fn display_text(&self, cx: &mut App) -> String {
12809 self.display_map
12810 .update(cx, |map, cx| map.snapshot(cx))
12811 .text()
12812 }
12813
12814 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12815 let mut wrap_guides = smallvec::smallvec![];
12816
12817 if self.show_wrap_guides == Some(false) {
12818 return wrap_guides;
12819 }
12820
12821 let settings = self.buffer.read(cx).settings_at(0, cx);
12822 if settings.show_wrap_guides {
12823 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12824 wrap_guides.push((soft_wrap as usize, true));
12825 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12826 wrap_guides.push((soft_wrap as usize, true));
12827 }
12828 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12829 }
12830
12831 wrap_guides
12832 }
12833
12834 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12835 let settings = self.buffer.read(cx).settings_at(0, cx);
12836 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12837 match mode {
12838 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12839 SoftWrap::None
12840 }
12841 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12842 language_settings::SoftWrap::PreferredLineLength => {
12843 SoftWrap::Column(settings.preferred_line_length)
12844 }
12845 language_settings::SoftWrap::Bounded => {
12846 SoftWrap::Bounded(settings.preferred_line_length)
12847 }
12848 }
12849 }
12850
12851 pub fn set_soft_wrap_mode(
12852 &mut self,
12853 mode: language_settings::SoftWrap,
12854
12855 cx: &mut Context<Self>,
12856 ) {
12857 self.soft_wrap_mode_override = Some(mode);
12858 cx.notify();
12859 }
12860
12861 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12862 self.text_style_refinement = Some(style);
12863 }
12864
12865 /// called by the Element so we know what style we were most recently rendered with.
12866 pub(crate) fn set_style(
12867 &mut self,
12868 style: EditorStyle,
12869 window: &mut Window,
12870 cx: &mut Context<Self>,
12871 ) {
12872 let rem_size = window.rem_size();
12873 self.display_map.update(cx, |map, cx| {
12874 map.set_font(
12875 style.text.font(),
12876 style.text.font_size.to_pixels(rem_size),
12877 cx,
12878 )
12879 });
12880 self.style = Some(style);
12881 }
12882
12883 pub fn style(&self) -> Option<&EditorStyle> {
12884 self.style.as_ref()
12885 }
12886
12887 // Called by the element. This method is not designed to be called outside of the editor
12888 // element's layout code because it does not notify when rewrapping is computed synchronously.
12889 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12890 self.display_map
12891 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12892 }
12893
12894 pub fn set_soft_wrap(&mut self) {
12895 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12896 }
12897
12898 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12899 if self.soft_wrap_mode_override.is_some() {
12900 self.soft_wrap_mode_override.take();
12901 } else {
12902 let soft_wrap = match self.soft_wrap_mode(cx) {
12903 SoftWrap::GitDiff => return,
12904 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12905 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12906 language_settings::SoftWrap::None
12907 }
12908 };
12909 self.soft_wrap_mode_override = Some(soft_wrap);
12910 }
12911 cx.notify();
12912 }
12913
12914 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12915 let Some(workspace) = self.workspace() else {
12916 return;
12917 };
12918 let fs = workspace.read(cx).app_state().fs.clone();
12919 let current_show = TabBarSettings::get_global(cx).show;
12920 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12921 setting.show = Some(!current_show);
12922 });
12923 }
12924
12925 pub fn toggle_indent_guides(
12926 &mut self,
12927 _: &ToggleIndentGuides,
12928 _: &mut Window,
12929 cx: &mut Context<Self>,
12930 ) {
12931 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12932 self.buffer
12933 .read(cx)
12934 .settings_at(0, cx)
12935 .indent_guides
12936 .enabled
12937 });
12938 self.show_indent_guides = Some(!currently_enabled);
12939 cx.notify();
12940 }
12941
12942 fn should_show_indent_guides(&self) -> Option<bool> {
12943 self.show_indent_guides
12944 }
12945
12946 pub fn toggle_line_numbers(
12947 &mut self,
12948 _: &ToggleLineNumbers,
12949 _: &mut Window,
12950 cx: &mut Context<Self>,
12951 ) {
12952 let mut editor_settings = EditorSettings::get_global(cx).clone();
12953 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12954 EditorSettings::override_global(editor_settings, cx);
12955 }
12956
12957 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12958 self.use_relative_line_numbers
12959 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12960 }
12961
12962 pub fn toggle_relative_line_numbers(
12963 &mut self,
12964 _: &ToggleRelativeLineNumbers,
12965 _: &mut Window,
12966 cx: &mut Context<Self>,
12967 ) {
12968 let is_relative = self.should_use_relative_line_numbers(cx);
12969 self.set_relative_line_number(Some(!is_relative), cx)
12970 }
12971
12972 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12973 self.use_relative_line_numbers = is_relative;
12974 cx.notify();
12975 }
12976
12977 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12978 self.show_gutter = show_gutter;
12979 cx.notify();
12980 }
12981
12982 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12983 self.show_scrollbars = show_scrollbars;
12984 cx.notify();
12985 }
12986
12987 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12988 self.show_line_numbers = Some(show_line_numbers);
12989 cx.notify();
12990 }
12991
12992 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12993 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12994 cx.notify();
12995 }
12996
12997 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12998 self.show_code_actions = Some(show_code_actions);
12999 cx.notify();
13000 }
13001
13002 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13003 self.show_runnables = Some(show_runnables);
13004 cx.notify();
13005 }
13006
13007 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13008 if self.display_map.read(cx).masked != masked {
13009 self.display_map.update(cx, |map, _| map.masked = masked);
13010 }
13011 cx.notify()
13012 }
13013
13014 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13015 self.show_wrap_guides = Some(show_wrap_guides);
13016 cx.notify();
13017 }
13018
13019 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13020 self.show_indent_guides = Some(show_indent_guides);
13021 cx.notify();
13022 }
13023
13024 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13025 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13026 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13027 if let Some(dir) = file.abs_path(cx).parent() {
13028 return Some(dir.to_owned());
13029 }
13030 }
13031
13032 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13033 return Some(project_path.path.to_path_buf());
13034 }
13035 }
13036
13037 None
13038 }
13039
13040 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13041 self.active_excerpt(cx)?
13042 .1
13043 .read(cx)
13044 .file()
13045 .and_then(|f| f.as_local())
13046 }
13047
13048 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13049 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13050 let buffer = buffer.read(cx);
13051 if let Some(project_path) = buffer.project_path(cx) {
13052 let project = self.project.as_ref()?.read(cx);
13053 project.absolute_path(&project_path, cx)
13054 } else {
13055 buffer
13056 .file()
13057 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13058 }
13059 })
13060 }
13061
13062 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13063 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13064 let project_path = buffer.read(cx).project_path(cx)?;
13065 let project = self.project.as_ref()?.read(cx);
13066 let entry = project.entry_for_path(&project_path, cx)?;
13067 let path = entry.path.to_path_buf();
13068 Some(path)
13069 })
13070 }
13071
13072 pub fn reveal_in_finder(
13073 &mut self,
13074 _: &RevealInFileManager,
13075 _window: &mut Window,
13076 cx: &mut Context<Self>,
13077 ) {
13078 if let Some(target) = self.target_file(cx) {
13079 cx.reveal_path(&target.abs_path(cx));
13080 }
13081 }
13082
13083 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13084 if let Some(path) = self.target_file_abs_path(cx) {
13085 if let Some(path) = path.to_str() {
13086 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13087 }
13088 }
13089 }
13090
13091 pub fn copy_relative_path(
13092 &mut self,
13093 _: &CopyRelativePath,
13094 _window: &mut Window,
13095 cx: &mut Context<Self>,
13096 ) {
13097 if let Some(path) = self.target_file_path(cx) {
13098 if let Some(path) = path.to_str() {
13099 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13100 }
13101 }
13102 }
13103
13104 pub fn copy_file_name_without_extension(
13105 &mut self,
13106 _: &CopyFileNameWithoutExtension,
13107 _: &mut Window,
13108 cx: &mut Context<Self>,
13109 ) {
13110 if let Some(file) = self.target_file(cx) {
13111 if let Some(file_stem) = file.path().file_stem() {
13112 if let Some(name) = file_stem.to_str() {
13113 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13114 }
13115 }
13116 }
13117 }
13118
13119 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13120 if let Some(file) = self.target_file(cx) {
13121 if let Some(file_name) = file.path().file_name() {
13122 if let Some(name) = file_name.to_str() {
13123 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13124 }
13125 }
13126 }
13127 }
13128
13129 pub fn toggle_git_blame(
13130 &mut self,
13131 _: &ToggleGitBlame,
13132 window: &mut Window,
13133 cx: &mut Context<Self>,
13134 ) {
13135 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13136
13137 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13138 self.start_git_blame(true, window, cx);
13139 }
13140
13141 cx.notify();
13142 }
13143
13144 pub fn toggle_git_blame_inline(
13145 &mut self,
13146 _: &ToggleGitBlameInline,
13147 window: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) {
13150 self.toggle_git_blame_inline_internal(true, window, cx);
13151 cx.notify();
13152 }
13153
13154 pub fn git_blame_inline_enabled(&self) -> bool {
13155 self.git_blame_inline_enabled
13156 }
13157
13158 pub fn toggle_selection_menu(
13159 &mut self,
13160 _: &ToggleSelectionMenu,
13161 _: &mut Window,
13162 cx: &mut Context<Self>,
13163 ) {
13164 self.show_selection_menu = self
13165 .show_selection_menu
13166 .map(|show_selections_menu| !show_selections_menu)
13167 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13168
13169 cx.notify();
13170 }
13171
13172 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13173 self.show_selection_menu
13174 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13175 }
13176
13177 fn start_git_blame(
13178 &mut self,
13179 user_triggered: bool,
13180 window: &mut Window,
13181 cx: &mut Context<Self>,
13182 ) {
13183 if let Some(project) = self.project.as_ref() {
13184 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13185 return;
13186 };
13187
13188 if buffer.read(cx).file().is_none() {
13189 return;
13190 }
13191
13192 let focused = self.focus_handle(cx).contains_focused(window, cx);
13193
13194 let project = project.clone();
13195 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13196 self.blame_subscription =
13197 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13198 self.blame = Some(blame);
13199 }
13200 }
13201
13202 fn toggle_git_blame_inline_internal(
13203 &mut self,
13204 user_triggered: bool,
13205 window: &mut Window,
13206 cx: &mut Context<Self>,
13207 ) {
13208 if self.git_blame_inline_enabled {
13209 self.git_blame_inline_enabled = false;
13210 self.show_git_blame_inline = false;
13211 self.show_git_blame_inline_delay_task.take();
13212 } else {
13213 self.git_blame_inline_enabled = true;
13214 self.start_git_blame_inline(user_triggered, window, cx);
13215 }
13216
13217 cx.notify();
13218 }
13219
13220 fn start_git_blame_inline(
13221 &mut self,
13222 user_triggered: bool,
13223 window: &mut Window,
13224 cx: &mut Context<Self>,
13225 ) {
13226 self.start_git_blame(user_triggered, window, cx);
13227
13228 if ProjectSettings::get_global(cx)
13229 .git
13230 .inline_blame_delay()
13231 .is_some()
13232 {
13233 self.start_inline_blame_timer(window, cx);
13234 } else {
13235 self.show_git_blame_inline = true
13236 }
13237 }
13238
13239 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13240 self.blame.as_ref()
13241 }
13242
13243 pub fn show_git_blame_gutter(&self) -> bool {
13244 self.show_git_blame_gutter
13245 }
13246
13247 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13248 self.show_git_blame_gutter && self.has_blame_entries(cx)
13249 }
13250
13251 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13252 self.show_git_blame_inline
13253 && self.focus_handle.is_focused(window)
13254 && !self.newest_selection_head_on_empty_line(cx)
13255 && self.has_blame_entries(cx)
13256 }
13257
13258 fn has_blame_entries(&self, cx: &App) -> bool {
13259 self.blame()
13260 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13261 }
13262
13263 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13264 let cursor_anchor = self.selections.newest_anchor().head();
13265
13266 let snapshot = self.buffer.read(cx).snapshot(cx);
13267 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13268
13269 snapshot.line_len(buffer_row) == 0
13270 }
13271
13272 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13273 let buffer_and_selection = maybe!({
13274 let selection = self.selections.newest::<Point>(cx);
13275 let selection_range = selection.range();
13276
13277 let multi_buffer = self.buffer().read(cx);
13278 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13279 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13280
13281 let (buffer, range, _) = if selection.reversed {
13282 buffer_ranges.first()
13283 } else {
13284 buffer_ranges.last()
13285 }?;
13286
13287 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13288 ..text::ToPoint::to_point(&range.end, &buffer).row;
13289 Some((
13290 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13291 selection,
13292 ))
13293 });
13294
13295 let Some((buffer, selection)) = buffer_and_selection else {
13296 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13297 };
13298
13299 let Some(project) = self.project.as_ref() else {
13300 return Task::ready(Err(anyhow!("editor does not have project")));
13301 };
13302
13303 project.update(cx, |project, cx| {
13304 project.get_permalink_to_line(&buffer, selection, cx)
13305 })
13306 }
13307
13308 pub fn copy_permalink_to_line(
13309 &mut self,
13310 _: &CopyPermalinkToLine,
13311 window: &mut Window,
13312 cx: &mut Context<Self>,
13313 ) {
13314 let permalink_task = self.get_permalink_to_line(cx);
13315 let workspace = self.workspace();
13316
13317 cx.spawn_in(window, |_, mut cx| async move {
13318 match permalink_task.await {
13319 Ok(permalink) => {
13320 cx.update(|_, cx| {
13321 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13322 })
13323 .ok();
13324 }
13325 Err(err) => {
13326 let message = format!("Failed to copy permalink: {err}");
13327
13328 Err::<(), anyhow::Error>(err).log_err();
13329
13330 if let Some(workspace) = workspace {
13331 workspace
13332 .update_in(&mut cx, |workspace, _, cx| {
13333 struct CopyPermalinkToLine;
13334
13335 workspace.show_toast(
13336 Toast::new(
13337 NotificationId::unique::<CopyPermalinkToLine>(),
13338 message,
13339 ),
13340 cx,
13341 )
13342 })
13343 .ok();
13344 }
13345 }
13346 }
13347 })
13348 .detach();
13349 }
13350
13351 pub fn copy_file_location(
13352 &mut self,
13353 _: &CopyFileLocation,
13354 _: &mut Window,
13355 cx: &mut Context<Self>,
13356 ) {
13357 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13358 if let Some(file) = self.target_file(cx) {
13359 if let Some(path) = file.path().to_str() {
13360 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13361 }
13362 }
13363 }
13364
13365 pub fn open_permalink_to_line(
13366 &mut self,
13367 _: &OpenPermalinkToLine,
13368 window: &mut Window,
13369 cx: &mut Context<Self>,
13370 ) {
13371 let permalink_task = self.get_permalink_to_line(cx);
13372 let workspace = self.workspace();
13373
13374 cx.spawn_in(window, |_, mut cx| async move {
13375 match permalink_task.await {
13376 Ok(permalink) => {
13377 cx.update(|_, cx| {
13378 cx.open_url(permalink.as_ref());
13379 })
13380 .ok();
13381 }
13382 Err(err) => {
13383 let message = format!("Failed to open permalink: {err}");
13384
13385 Err::<(), anyhow::Error>(err).log_err();
13386
13387 if let Some(workspace) = workspace {
13388 workspace
13389 .update(&mut cx, |workspace, cx| {
13390 struct OpenPermalinkToLine;
13391
13392 workspace.show_toast(
13393 Toast::new(
13394 NotificationId::unique::<OpenPermalinkToLine>(),
13395 message,
13396 ),
13397 cx,
13398 )
13399 })
13400 .ok();
13401 }
13402 }
13403 }
13404 })
13405 .detach();
13406 }
13407
13408 pub fn insert_uuid_v4(
13409 &mut self,
13410 _: &InsertUuidV4,
13411 window: &mut Window,
13412 cx: &mut Context<Self>,
13413 ) {
13414 self.insert_uuid(UuidVersion::V4, window, cx);
13415 }
13416
13417 pub fn insert_uuid_v7(
13418 &mut self,
13419 _: &InsertUuidV7,
13420 window: &mut Window,
13421 cx: &mut Context<Self>,
13422 ) {
13423 self.insert_uuid(UuidVersion::V7, window, cx);
13424 }
13425
13426 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13427 self.transact(window, cx, |this, window, cx| {
13428 let edits = this
13429 .selections
13430 .all::<Point>(cx)
13431 .into_iter()
13432 .map(|selection| {
13433 let uuid = match version {
13434 UuidVersion::V4 => uuid::Uuid::new_v4(),
13435 UuidVersion::V7 => uuid::Uuid::now_v7(),
13436 };
13437
13438 (selection.range(), uuid.to_string())
13439 });
13440 this.edit(edits, cx);
13441 this.refresh_inline_completion(true, false, window, cx);
13442 });
13443 }
13444
13445 pub fn open_selections_in_multibuffer(
13446 &mut self,
13447 _: &OpenSelectionsInMultibuffer,
13448 window: &mut Window,
13449 cx: &mut Context<Self>,
13450 ) {
13451 let multibuffer = self.buffer.read(cx);
13452
13453 let Some(buffer) = multibuffer.as_singleton() else {
13454 return;
13455 };
13456
13457 let Some(workspace) = self.workspace() else {
13458 return;
13459 };
13460
13461 let locations = self
13462 .selections
13463 .disjoint_anchors()
13464 .iter()
13465 .map(|range| Location {
13466 buffer: buffer.clone(),
13467 range: range.start.text_anchor..range.end.text_anchor,
13468 })
13469 .collect::<Vec<_>>();
13470
13471 let title = multibuffer.title(cx).to_string();
13472
13473 cx.spawn_in(window, |_, mut cx| async move {
13474 workspace.update_in(&mut cx, |workspace, window, cx| {
13475 Self::open_locations_in_multibuffer(
13476 workspace,
13477 locations,
13478 format!("Selections for '{title}'"),
13479 false,
13480 MultibufferSelectionMode::All,
13481 window,
13482 cx,
13483 );
13484 })
13485 })
13486 .detach();
13487 }
13488
13489 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13490 /// last highlight added will be used.
13491 ///
13492 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13493 pub fn highlight_rows<T: 'static>(
13494 &mut self,
13495 range: Range<Anchor>,
13496 color: Hsla,
13497 should_autoscroll: bool,
13498 cx: &mut Context<Self>,
13499 ) {
13500 let snapshot = self.buffer().read(cx).snapshot(cx);
13501 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13502 let ix = row_highlights.binary_search_by(|highlight| {
13503 Ordering::Equal
13504 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13505 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13506 });
13507
13508 if let Err(mut ix) = ix {
13509 let index = post_inc(&mut self.highlight_order);
13510
13511 // If this range intersects with the preceding highlight, then merge it with
13512 // the preceding highlight. Otherwise insert a new highlight.
13513 let mut merged = false;
13514 if ix > 0 {
13515 let prev_highlight = &mut row_highlights[ix - 1];
13516 if prev_highlight
13517 .range
13518 .end
13519 .cmp(&range.start, &snapshot)
13520 .is_ge()
13521 {
13522 ix -= 1;
13523 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13524 prev_highlight.range.end = range.end;
13525 }
13526 merged = true;
13527 prev_highlight.index = index;
13528 prev_highlight.color = color;
13529 prev_highlight.should_autoscroll = should_autoscroll;
13530 }
13531 }
13532
13533 if !merged {
13534 row_highlights.insert(
13535 ix,
13536 RowHighlight {
13537 range: range.clone(),
13538 index,
13539 color,
13540 should_autoscroll,
13541 },
13542 );
13543 }
13544
13545 // If any of the following highlights intersect with this one, merge them.
13546 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13547 let highlight = &row_highlights[ix];
13548 if next_highlight
13549 .range
13550 .start
13551 .cmp(&highlight.range.end, &snapshot)
13552 .is_le()
13553 {
13554 if next_highlight
13555 .range
13556 .end
13557 .cmp(&highlight.range.end, &snapshot)
13558 .is_gt()
13559 {
13560 row_highlights[ix].range.end = next_highlight.range.end;
13561 }
13562 row_highlights.remove(ix + 1);
13563 } else {
13564 break;
13565 }
13566 }
13567 }
13568 }
13569
13570 /// Remove any highlighted row ranges of the given type that intersect the
13571 /// given ranges.
13572 pub fn remove_highlighted_rows<T: 'static>(
13573 &mut self,
13574 ranges_to_remove: Vec<Range<Anchor>>,
13575 cx: &mut Context<Self>,
13576 ) {
13577 let snapshot = self.buffer().read(cx).snapshot(cx);
13578 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13579 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13580 row_highlights.retain(|highlight| {
13581 while let Some(range_to_remove) = ranges_to_remove.peek() {
13582 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13583 Ordering::Less | Ordering::Equal => {
13584 ranges_to_remove.next();
13585 }
13586 Ordering::Greater => {
13587 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13588 Ordering::Less | Ordering::Equal => {
13589 return false;
13590 }
13591 Ordering::Greater => break,
13592 }
13593 }
13594 }
13595 }
13596
13597 true
13598 })
13599 }
13600
13601 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13602 pub fn clear_row_highlights<T: 'static>(&mut self) {
13603 self.highlighted_rows.remove(&TypeId::of::<T>());
13604 }
13605
13606 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13607 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13608 self.highlighted_rows
13609 .get(&TypeId::of::<T>())
13610 .map_or(&[] as &[_], |vec| vec.as_slice())
13611 .iter()
13612 .map(|highlight| (highlight.range.clone(), highlight.color))
13613 }
13614
13615 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13616 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13617 /// Allows to ignore certain kinds of highlights.
13618 pub fn highlighted_display_rows(
13619 &self,
13620 window: &mut Window,
13621 cx: &mut App,
13622 ) -> BTreeMap<DisplayRow, Background> {
13623 let snapshot = self.snapshot(window, cx);
13624 let mut used_highlight_orders = HashMap::default();
13625 self.highlighted_rows
13626 .iter()
13627 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13628 .fold(
13629 BTreeMap::<DisplayRow, Background>::new(),
13630 |mut unique_rows, highlight| {
13631 let start = highlight.range.start.to_display_point(&snapshot);
13632 let end = highlight.range.end.to_display_point(&snapshot);
13633 let start_row = start.row().0;
13634 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13635 && end.column() == 0
13636 {
13637 end.row().0.saturating_sub(1)
13638 } else {
13639 end.row().0
13640 };
13641 for row in start_row..=end_row {
13642 let used_index =
13643 used_highlight_orders.entry(row).or_insert(highlight.index);
13644 if highlight.index >= *used_index {
13645 *used_index = highlight.index;
13646 unique_rows.insert(DisplayRow(row), highlight.color.into());
13647 }
13648 }
13649 unique_rows
13650 },
13651 )
13652 }
13653
13654 pub fn highlighted_display_row_for_autoscroll(
13655 &self,
13656 snapshot: &DisplaySnapshot,
13657 ) -> Option<DisplayRow> {
13658 self.highlighted_rows
13659 .values()
13660 .flat_map(|highlighted_rows| highlighted_rows.iter())
13661 .filter_map(|highlight| {
13662 if highlight.should_autoscroll {
13663 Some(highlight.range.start.to_display_point(snapshot).row())
13664 } else {
13665 None
13666 }
13667 })
13668 .min()
13669 }
13670
13671 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13672 self.highlight_background::<SearchWithinRange>(
13673 ranges,
13674 |colors| colors.editor_document_highlight_read_background,
13675 cx,
13676 )
13677 }
13678
13679 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13680 self.breadcrumb_header = Some(new_header);
13681 }
13682
13683 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13684 self.clear_background_highlights::<SearchWithinRange>(cx);
13685 }
13686
13687 pub fn highlight_background<T: 'static>(
13688 &mut self,
13689 ranges: &[Range<Anchor>],
13690 color_fetcher: fn(&ThemeColors) -> Hsla,
13691 cx: &mut Context<Self>,
13692 ) {
13693 self.background_highlights
13694 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13695 self.scrollbar_marker_state.dirty = true;
13696 cx.notify();
13697 }
13698
13699 pub fn clear_background_highlights<T: 'static>(
13700 &mut self,
13701 cx: &mut Context<Self>,
13702 ) -> Option<BackgroundHighlight> {
13703 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13704 if !text_highlights.1.is_empty() {
13705 self.scrollbar_marker_state.dirty = true;
13706 cx.notify();
13707 }
13708 Some(text_highlights)
13709 }
13710
13711 pub fn highlight_gutter<T: 'static>(
13712 &mut self,
13713 ranges: &[Range<Anchor>],
13714 color_fetcher: fn(&App) -> Hsla,
13715 cx: &mut Context<Self>,
13716 ) {
13717 self.gutter_highlights
13718 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13719 cx.notify();
13720 }
13721
13722 pub fn clear_gutter_highlights<T: 'static>(
13723 &mut self,
13724 cx: &mut Context<Self>,
13725 ) -> Option<GutterHighlight> {
13726 cx.notify();
13727 self.gutter_highlights.remove(&TypeId::of::<T>())
13728 }
13729
13730 #[cfg(feature = "test-support")]
13731 pub fn all_text_background_highlights(
13732 &self,
13733 window: &mut Window,
13734 cx: &mut Context<Self>,
13735 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13736 let snapshot = self.snapshot(window, cx);
13737 let buffer = &snapshot.buffer_snapshot;
13738 let start = buffer.anchor_before(0);
13739 let end = buffer.anchor_after(buffer.len());
13740 let theme = cx.theme().colors();
13741 self.background_highlights_in_range(start..end, &snapshot, theme)
13742 }
13743
13744 #[cfg(feature = "test-support")]
13745 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13746 let snapshot = self.buffer().read(cx).snapshot(cx);
13747
13748 let highlights = self
13749 .background_highlights
13750 .get(&TypeId::of::<items::BufferSearchHighlights>());
13751
13752 if let Some((_color, ranges)) = highlights {
13753 ranges
13754 .iter()
13755 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13756 .collect_vec()
13757 } else {
13758 vec![]
13759 }
13760 }
13761
13762 fn document_highlights_for_position<'a>(
13763 &'a self,
13764 position: Anchor,
13765 buffer: &'a MultiBufferSnapshot,
13766 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13767 let read_highlights = self
13768 .background_highlights
13769 .get(&TypeId::of::<DocumentHighlightRead>())
13770 .map(|h| &h.1);
13771 let write_highlights = self
13772 .background_highlights
13773 .get(&TypeId::of::<DocumentHighlightWrite>())
13774 .map(|h| &h.1);
13775 let left_position = position.bias_left(buffer);
13776 let right_position = position.bias_right(buffer);
13777 read_highlights
13778 .into_iter()
13779 .chain(write_highlights)
13780 .flat_map(move |ranges| {
13781 let start_ix = match ranges.binary_search_by(|probe| {
13782 let cmp = probe.end.cmp(&left_position, buffer);
13783 if cmp.is_ge() {
13784 Ordering::Greater
13785 } else {
13786 Ordering::Less
13787 }
13788 }) {
13789 Ok(i) | Err(i) => i,
13790 };
13791
13792 ranges[start_ix..]
13793 .iter()
13794 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13795 })
13796 }
13797
13798 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13799 self.background_highlights
13800 .get(&TypeId::of::<T>())
13801 .map_or(false, |(_, highlights)| !highlights.is_empty())
13802 }
13803
13804 pub fn background_highlights_in_range(
13805 &self,
13806 search_range: Range<Anchor>,
13807 display_snapshot: &DisplaySnapshot,
13808 theme: &ThemeColors,
13809 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13810 let mut results = Vec::new();
13811 for (color_fetcher, ranges) in self.background_highlights.values() {
13812 let color = color_fetcher(theme);
13813 let start_ix = match ranges.binary_search_by(|probe| {
13814 let cmp = probe
13815 .end
13816 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13817 if cmp.is_gt() {
13818 Ordering::Greater
13819 } else {
13820 Ordering::Less
13821 }
13822 }) {
13823 Ok(i) | Err(i) => i,
13824 };
13825 for range in &ranges[start_ix..] {
13826 if range
13827 .start
13828 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13829 .is_ge()
13830 {
13831 break;
13832 }
13833
13834 let start = range.start.to_display_point(display_snapshot);
13835 let end = range.end.to_display_point(display_snapshot);
13836 results.push((start..end, color))
13837 }
13838 }
13839 results
13840 }
13841
13842 pub fn background_highlight_row_ranges<T: 'static>(
13843 &self,
13844 search_range: Range<Anchor>,
13845 display_snapshot: &DisplaySnapshot,
13846 count: usize,
13847 ) -> Vec<RangeInclusive<DisplayPoint>> {
13848 let mut results = Vec::new();
13849 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13850 return vec![];
13851 };
13852
13853 let start_ix = match ranges.binary_search_by(|probe| {
13854 let cmp = probe
13855 .end
13856 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13857 if cmp.is_gt() {
13858 Ordering::Greater
13859 } else {
13860 Ordering::Less
13861 }
13862 }) {
13863 Ok(i) | Err(i) => i,
13864 };
13865 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13866 if let (Some(start_display), Some(end_display)) = (start, end) {
13867 results.push(
13868 start_display.to_display_point(display_snapshot)
13869 ..=end_display.to_display_point(display_snapshot),
13870 );
13871 }
13872 };
13873 let mut start_row: Option<Point> = None;
13874 let mut end_row: Option<Point> = None;
13875 if ranges.len() > count {
13876 return Vec::new();
13877 }
13878 for range in &ranges[start_ix..] {
13879 if range
13880 .start
13881 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13882 .is_ge()
13883 {
13884 break;
13885 }
13886 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13887 if let Some(current_row) = &end_row {
13888 if end.row == current_row.row {
13889 continue;
13890 }
13891 }
13892 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13893 if start_row.is_none() {
13894 assert_eq!(end_row, None);
13895 start_row = Some(start);
13896 end_row = Some(end);
13897 continue;
13898 }
13899 if let Some(current_end) = end_row.as_mut() {
13900 if start.row > current_end.row + 1 {
13901 push_region(start_row, end_row);
13902 start_row = Some(start);
13903 end_row = Some(end);
13904 } else {
13905 // Merge two hunks.
13906 *current_end = end;
13907 }
13908 } else {
13909 unreachable!();
13910 }
13911 }
13912 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13913 push_region(start_row, end_row);
13914 results
13915 }
13916
13917 pub fn gutter_highlights_in_range(
13918 &self,
13919 search_range: Range<Anchor>,
13920 display_snapshot: &DisplaySnapshot,
13921 cx: &App,
13922 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13923 let mut results = Vec::new();
13924 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13925 let color = color_fetcher(cx);
13926 let start_ix = match ranges.binary_search_by(|probe| {
13927 let cmp = probe
13928 .end
13929 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13930 if cmp.is_gt() {
13931 Ordering::Greater
13932 } else {
13933 Ordering::Less
13934 }
13935 }) {
13936 Ok(i) | Err(i) => i,
13937 };
13938 for range in &ranges[start_ix..] {
13939 if range
13940 .start
13941 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13942 .is_ge()
13943 {
13944 break;
13945 }
13946
13947 let start = range.start.to_display_point(display_snapshot);
13948 let end = range.end.to_display_point(display_snapshot);
13949 results.push((start..end, color))
13950 }
13951 }
13952 results
13953 }
13954
13955 /// Get the text ranges corresponding to the redaction query
13956 pub fn redacted_ranges(
13957 &self,
13958 search_range: Range<Anchor>,
13959 display_snapshot: &DisplaySnapshot,
13960 cx: &App,
13961 ) -> Vec<Range<DisplayPoint>> {
13962 display_snapshot
13963 .buffer_snapshot
13964 .redacted_ranges(search_range, |file| {
13965 if let Some(file) = file {
13966 file.is_private()
13967 && EditorSettings::get(
13968 Some(SettingsLocation {
13969 worktree_id: file.worktree_id(cx),
13970 path: file.path().as_ref(),
13971 }),
13972 cx,
13973 )
13974 .redact_private_values
13975 } else {
13976 false
13977 }
13978 })
13979 .map(|range| {
13980 range.start.to_display_point(display_snapshot)
13981 ..range.end.to_display_point(display_snapshot)
13982 })
13983 .collect()
13984 }
13985
13986 pub fn highlight_text<T: 'static>(
13987 &mut self,
13988 ranges: Vec<Range<Anchor>>,
13989 style: HighlightStyle,
13990 cx: &mut Context<Self>,
13991 ) {
13992 self.display_map.update(cx, |map, _| {
13993 map.highlight_text(TypeId::of::<T>(), ranges, style)
13994 });
13995 cx.notify();
13996 }
13997
13998 pub(crate) fn highlight_inlays<T: 'static>(
13999 &mut self,
14000 highlights: Vec<InlayHighlight>,
14001 style: HighlightStyle,
14002 cx: &mut Context<Self>,
14003 ) {
14004 self.display_map.update(cx, |map, _| {
14005 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14006 });
14007 cx.notify();
14008 }
14009
14010 pub fn text_highlights<'a, T: 'static>(
14011 &'a self,
14012 cx: &'a App,
14013 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14014 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14015 }
14016
14017 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14018 let cleared = self
14019 .display_map
14020 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14021 if cleared {
14022 cx.notify();
14023 }
14024 }
14025
14026 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14027 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14028 && self.focus_handle.is_focused(window)
14029 }
14030
14031 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14032 self.show_cursor_when_unfocused = is_enabled;
14033 cx.notify();
14034 }
14035
14036 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14037 self.project
14038 .as_ref()
14039 .map(|project| project.read(cx).lsp_store())
14040 }
14041
14042 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14043 cx.notify();
14044 }
14045
14046 fn on_buffer_event(
14047 &mut self,
14048 multibuffer: &Entity<MultiBuffer>,
14049 event: &multi_buffer::Event,
14050 window: &mut Window,
14051 cx: &mut Context<Self>,
14052 ) {
14053 match event {
14054 multi_buffer::Event::Edited {
14055 singleton_buffer_edited,
14056 edited_buffer: buffer_edited,
14057 } => {
14058 self.scrollbar_marker_state.dirty = true;
14059 self.active_indent_guides_state.dirty = true;
14060 self.refresh_active_diagnostics(cx);
14061 self.refresh_code_actions(window, cx);
14062 if self.has_active_inline_completion() {
14063 self.update_visible_inline_completion(window, cx);
14064 }
14065 if let Some(buffer) = buffer_edited {
14066 let buffer_id = buffer.read(cx).remote_id();
14067 if !self.registered_buffers.contains_key(&buffer_id) {
14068 if let Some(lsp_store) = self.lsp_store(cx) {
14069 lsp_store.update(cx, |lsp_store, cx| {
14070 self.registered_buffers.insert(
14071 buffer_id,
14072 lsp_store.register_buffer_with_language_servers(&buffer, cx),
14073 );
14074 })
14075 }
14076 }
14077 }
14078 cx.emit(EditorEvent::BufferEdited);
14079 cx.emit(SearchEvent::MatchesInvalidated);
14080 if *singleton_buffer_edited {
14081 if let Some(project) = &self.project {
14082 let project = project.read(cx);
14083 #[allow(clippy::mutable_key_type)]
14084 let languages_affected = multibuffer
14085 .read(cx)
14086 .all_buffers()
14087 .into_iter()
14088 .filter_map(|buffer| {
14089 let buffer = buffer.read(cx);
14090 let language = buffer.language()?;
14091 if project.is_local()
14092 && project
14093 .language_servers_for_local_buffer(buffer, cx)
14094 .count()
14095 == 0
14096 {
14097 None
14098 } else {
14099 Some(language)
14100 }
14101 })
14102 .cloned()
14103 .collect::<HashSet<_>>();
14104 if !languages_affected.is_empty() {
14105 self.refresh_inlay_hints(
14106 InlayHintRefreshReason::BufferEdited(languages_affected),
14107 cx,
14108 );
14109 }
14110 }
14111 }
14112
14113 let Some(project) = &self.project else { return };
14114 let (telemetry, is_via_ssh) = {
14115 let project = project.read(cx);
14116 let telemetry = project.client().telemetry().clone();
14117 let is_via_ssh = project.is_via_ssh();
14118 (telemetry, is_via_ssh)
14119 };
14120 refresh_linked_ranges(self, window, cx);
14121 telemetry.log_edit_event("editor", is_via_ssh);
14122 }
14123 multi_buffer::Event::ExcerptsAdded {
14124 buffer,
14125 predecessor,
14126 excerpts,
14127 } => {
14128 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14129 let buffer_id = buffer.read(cx).remote_id();
14130 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14131 if let Some(project) = &self.project {
14132 self.load_diff_task = Some(
14133 get_uncommitted_diff_for_buffer(
14134 project,
14135 [buffer.clone()],
14136 self.buffer.clone(),
14137 cx,
14138 )
14139 .shared(),
14140 );
14141 }
14142 }
14143 cx.emit(EditorEvent::ExcerptsAdded {
14144 buffer: buffer.clone(),
14145 predecessor: *predecessor,
14146 excerpts: excerpts.clone(),
14147 });
14148 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14149 }
14150 multi_buffer::Event::ExcerptsRemoved { ids } => {
14151 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14152 let buffer = self.buffer.read(cx);
14153 self.registered_buffers
14154 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14155 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14156 }
14157 multi_buffer::Event::ExcerptsEdited { ids } => {
14158 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14159 }
14160 multi_buffer::Event::ExcerptsExpanded { ids } => {
14161 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14162 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14163 }
14164 multi_buffer::Event::Reparsed(buffer_id) => {
14165 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14166
14167 cx.emit(EditorEvent::Reparsed(*buffer_id));
14168 }
14169 multi_buffer::Event::DiffHunksToggled => {
14170 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14171 }
14172 multi_buffer::Event::LanguageChanged(buffer_id) => {
14173 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14174 cx.emit(EditorEvent::Reparsed(*buffer_id));
14175 cx.notify();
14176 }
14177 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14178 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14179 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14180 cx.emit(EditorEvent::TitleChanged)
14181 }
14182 // multi_buffer::Event::DiffBaseChanged => {
14183 // self.scrollbar_marker_state.dirty = true;
14184 // cx.emit(EditorEvent::DiffBaseChanged);
14185 // cx.notify();
14186 // }
14187 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14188 multi_buffer::Event::DiagnosticsUpdated => {
14189 self.refresh_active_diagnostics(cx);
14190 self.scrollbar_marker_state.dirty = true;
14191 cx.notify();
14192 }
14193 _ => {}
14194 };
14195 }
14196
14197 fn on_display_map_changed(
14198 &mut self,
14199 _: Entity<DisplayMap>,
14200 _: &mut Window,
14201 cx: &mut Context<Self>,
14202 ) {
14203 cx.notify();
14204 }
14205
14206 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14207 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14208 self.refresh_inline_completion(true, false, window, cx);
14209 self.refresh_inlay_hints(
14210 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14211 self.selections.newest_anchor().head(),
14212 &self.buffer.read(cx).snapshot(cx),
14213 cx,
14214 )),
14215 cx,
14216 );
14217
14218 let old_cursor_shape = self.cursor_shape;
14219
14220 {
14221 let editor_settings = EditorSettings::get_global(cx);
14222 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14223 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14224 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14225 }
14226
14227 if old_cursor_shape != self.cursor_shape {
14228 cx.emit(EditorEvent::CursorShapeChanged);
14229 }
14230
14231 let project_settings = ProjectSettings::get_global(cx);
14232 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14233
14234 if self.mode == EditorMode::Full {
14235 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14236 if self.git_blame_inline_enabled != inline_blame_enabled {
14237 self.toggle_git_blame_inline_internal(false, window, cx);
14238 }
14239 }
14240
14241 cx.notify();
14242 }
14243
14244 pub fn set_searchable(&mut self, searchable: bool) {
14245 self.searchable = searchable;
14246 }
14247
14248 pub fn searchable(&self) -> bool {
14249 self.searchable
14250 }
14251
14252 fn open_proposed_changes_editor(
14253 &mut self,
14254 _: &OpenProposedChangesEditor,
14255 window: &mut Window,
14256 cx: &mut Context<Self>,
14257 ) {
14258 let Some(workspace) = self.workspace() else {
14259 cx.propagate();
14260 return;
14261 };
14262
14263 let selections = self.selections.all::<usize>(cx);
14264 let multi_buffer = self.buffer.read(cx);
14265 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14266 let mut new_selections_by_buffer = HashMap::default();
14267 for selection in selections {
14268 for (buffer, range, _) in
14269 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14270 {
14271 let mut range = range.to_point(buffer);
14272 range.start.column = 0;
14273 range.end.column = buffer.line_len(range.end.row);
14274 new_selections_by_buffer
14275 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14276 .or_insert(Vec::new())
14277 .push(range)
14278 }
14279 }
14280
14281 let proposed_changes_buffers = new_selections_by_buffer
14282 .into_iter()
14283 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14284 .collect::<Vec<_>>();
14285 let proposed_changes_editor = cx.new(|cx| {
14286 ProposedChangesEditor::new(
14287 "Proposed changes",
14288 proposed_changes_buffers,
14289 self.project.clone(),
14290 window,
14291 cx,
14292 )
14293 });
14294
14295 window.defer(cx, move |window, cx| {
14296 workspace.update(cx, |workspace, cx| {
14297 workspace.active_pane().update(cx, |pane, cx| {
14298 pane.add_item(
14299 Box::new(proposed_changes_editor),
14300 true,
14301 true,
14302 None,
14303 window,
14304 cx,
14305 );
14306 });
14307 });
14308 });
14309 }
14310
14311 pub fn open_excerpts_in_split(
14312 &mut self,
14313 _: &OpenExcerptsSplit,
14314 window: &mut Window,
14315 cx: &mut Context<Self>,
14316 ) {
14317 self.open_excerpts_common(None, true, window, cx)
14318 }
14319
14320 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14321 self.open_excerpts_common(None, false, window, cx)
14322 }
14323
14324 fn open_excerpts_common(
14325 &mut self,
14326 jump_data: Option<JumpData>,
14327 split: bool,
14328 window: &mut Window,
14329 cx: &mut Context<Self>,
14330 ) {
14331 let Some(workspace) = self.workspace() else {
14332 cx.propagate();
14333 return;
14334 };
14335
14336 if self.buffer.read(cx).is_singleton() {
14337 cx.propagate();
14338 return;
14339 }
14340
14341 let mut new_selections_by_buffer = HashMap::default();
14342 match &jump_data {
14343 Some(JumpData::MultiBufferPoint {
14344 excerpt_id,
14345 position,
14346 anchor,
14347 line_offset_from_top,
14348 }) => {
14349 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14350 if let Some(buffer) = multi_buffer_snapshot
14351 .buffer_id_for_excerpt(*excerpt_id)
14352 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14353 {
14354 let buffer_snapshot = buffer.read(cx).snapshot();
14355 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14356 language::ToPoint::to_point(anchor, &buffer_snapshot)
14357 } else {
14358 buffer_snapshot.clip_point(*position, Bias::Left)
14359 };
14360 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14361 new_selections_by_buffer.insert(
14362 buffer,
14363 (
14364 vec![jump_to_offset..jump_to_offset],
14365 Some(*line_offset_from_top),
14366 ),
14367 );
14368 }
14369 }
14370 Some(JumpData::MultiBufferRow {
14371 row,
14372 line_offset_from_top,
14373 }) => {
14374 let point = MultiBufferPoint::new(row.0, 0);
14375 if let Some((buffer, buffer_point, _)) =
14376 self.buffer.read(cx).point_to_buffer_point(point, cx)
14377 {
14378 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14379 new_selections_by_buffer
14380 .entry(buffer)
14381 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14382 .0
14383 .push(buffer_offset..buffer_offset)
14384 }
14385 }
14386 None => {
14387 let selections = self.selections.all::<usize>(cx);
14388 let multi_buffer = self.buffer.read(cx);
14389 for selection in selections {
14390 for (buffer, mut range, _) in multi_buffer
14391 .snapshot(cx)
14392 .range_to_buffer_ranges(selection.range())
14393 {
14394 // When editing branch buffers, jump to the corresponding location
14395 // in their base buffer.
14396 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14397 let buffer = buffer_handle.read(cx);
14398 if let Some(base_buffer) = buffer.base_buffer() {
14399 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14400 buffer_handle = base_buffer;
14401 }
14402
14403 if selection.reversed {
14404 mem::swap(&mut range.start, &mut range.end);
14405 }
14406 new_selections_by_buffer
14407 .entry(buffer_handle)
14408 .or_insert((Vec::new(), None))
14409 .0
14410 .push(range)
14411 }
14412 }
14413 }
14414 }
14415
14416 if new_selections_by_buffer.is_empty() {
14417 return;
14418 }
14419
14420 // We defer the pane interaction because we ourselves are a workspace item
14421 // and activating a new item causes the pane to call a method on us reentrantly,
14422 // which panics if we're on the stack.
14423 window.defer(cx, move |window, cx| {
14424 workspace.update(cx, |workspace, cx| {
14425 let pane = if split {
14426 workspace.adjacent_pane(window, cx)
14427 } else {
14428 workspace.active_pane().clone()
14429 };
14430
14431 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14432 let editor = buffer
14433 .read(cx)
14434 .file()
14435 .is_none()
14436 .then(|| {
14437 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14438 // so `workspace.open_project_item` will never find them, always opening a new editor.
14439 // Instead, we try to activate the existing editor in the pane first.
14440 let (editor, pane_item_index) =
14441 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14442 let editor = item.downcast::<Editor>()?;
14443 let singleton_buffer =
14444 editor.read(cx).buffer().read(cx).as_singleton()?;
14445 if singleton_buffer == buffer {
14446 Some((editor, i))
14447 } else {
14448 None
14449 }
14450 })?;
14451 pane.update(cx, |pane, cx| {
14452 pane.activate_item(pane_item_index, true, true, window, cx)
14453 });
14454 Some(editor)
14455 })
14456 .flatten()
14457 .unwrap_or_else(|| {
14458 workspace.open_project_item::<Self>(
14459 pane.clone(),
14460 buffer,
14461 true,
14462 true,
14463 window,
14464 cx,
14465 )
14466 });
14467
14468 editor.update(cx, |editor, cx| {
14469 let autoscroll = match scroll_offset {
14470 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14471 None => Autoscroll::newest(),
14472 };
14473 let nav_history = editor.nav_history.take();
14474 editor.change_selections(Some(autoscroll), window, cx, |s| {
14475 s.select_ranges(ranges);
14476 });
14477 editor.nav_history = nav_history;
14478 });
14479 }
14480 })
14481 });
14482 }
14483
14484 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14485 let snapshot = self.buffer.read(cx).read(cx);
14486 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14487 Some(
14488 ranges
14489 .iter()
14490 .map(move |range| {
14491 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14492 })
14493 .collect(),
14494 )
14495 }
14496
14497 fn selection_replacement_ranges(
14498 &self,
14499 range: Range<OffsetUtf16>,
14500 cx: &mut App,
14501 ) -> Vec<Range<OffsetUtf16>> {
14502 let selections = self.selections.all::<OffsetUtf16>(cx);
14503 let newest_selection = selections
14504 .iter()
14505 .max_by_key(|selection| selection.id)
14506 .unwrap();
14507 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14508 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14509 let snapshot = self.buffer.read(cx).read(cx);
14510 selections
14511 .into_iter()
14512 .map(|mut selection| {
14513 selection.start.0 =
14514 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14515 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14516 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14517 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14518 })
14519 .collect()
14520 }
14521
14522 fn report_editor_event(
14523 &self,
14524 event_type: &'static str,
14525 file_extension: Option<String>,
14526 cx: &App,
14527 ) {
14528 if cfg!(any(test, feature = "test-support")) {
14529 return;
14530 }
14531
14532 let Some(project) = &self.project else { return };
14533
14534 // If None, we are in a file without an extension
14535 let file = self
14536 .buffer
14537 .read(cx)
14538 .as_singleton()
14539 .and_then(|b| b.read(cx).file());
14540 let file_extension = file_extension.or(file
14541 .as_ref()
14542 .and_then(|file| Path::new(file.file_name(cx)).extension())
14543 .and_then(|e| e.to_str())
14544 .map(|a| a.to_string()));
14545
14546 let vim_mode = cx
14547 .global::<SettingsStore>()
14548 .raw_user_settings()
14549 .get("vim_mode")
14550 == Some(&serde_json::Value::Bool(true));
14551
14552 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14553 let copilot_enabled = edit_predictions_provider
14554 == language::language_settings::EditPredictionProvider::Copilot;
14555 let copilot_enabled_for_language = self
14556 .buffer
14557 .read(cx)
14558 .settings_at(0, cx)
14559 .show_edit_predictions;
14560
14561 let project = project.read(cx);
14562 telemetry::event!(
14563 event_type,
14564 file_extension,
14565 vim_mode,
14566 copilot_enabled,
14567 copilot_enabled_for_language,
14568 edit_predictions_provider,
14569 is_via_ssh = project.is_via_ssh(),
14570 );
14571 }
14572
14573 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14574 /// with each line being an array of {text, highlight} objects.
14575 fn copy_highlight_json(
14576 &mut self,
14577 _: &CopyHighlightJson,
14578 window: &mut Window,
14579 cx: &mut Context<Self>,
14580 ) {
14581 #[derive(Serialize)]
14582 struct Chunk<'a> {
14583 text: String,
14584 highlight: Option<&'a str>,
14585 }
14586
14587 let snapshot = self.buffer.read(cx).snapshot(cx);
14588 let range = self
14589 .selected_text_range(false, window, cx)
14590 .and_then(|selection| {
14591 if selection.range.is_empty() {
14592 None
14593 } else {
14594 Some(selection.range)
14595 }
14596 })
14597 .unwrap_or_else(|| 0..snapshot.len());
14598
14599 let chunks = snapshot.chunks(range, true);
14600 let mut lines = Vec::new();
14601 let mut line: VecDeque<Chunk> = VecDeque::new();
14602
14603 let Some(style) = self.style.as_ref() else {
14604 return;
14605 };
14606
14607 for chunk in chunks {
14608 let highlight = chunk
14609 .syntax_highlight_id
14610 .and_then(|id| id.name(&style.syntax));
14611 let mut chunk_lines = chunk.text.split('\n').peekable();
14612 while let Some(text) = chunk_lines.next() {
14613 let mut merged_with_last_token = false;
14614 if let Some(last_token) = line.back_mut() {
14615 if last_token.highlight == highlight {
14616 last_token.text.push_str(text);
14617 merged_with_last_token = true;
14618 }
14619 }
14620
14621 if !merged_with_last_token {
14622 line.push_back(Chunk {
14623 text: text.into(),
14624 highlight,
14625 });
14626 }
14627
14628 if chunk_lines.peek().is_some() {
14629 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14630 line.pop_front();
14631 }
14632 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14633 line.pop_back();
14634 }
14635
14636 lines.push(mem::take(&mut line));
14637 }
14638 }
14639 }
14640
14641 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14642 return;
14643 };
14644 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14645 }
14646
14647 pub fn open_context_menu(
14648 &mut self,
14649 _: &OpenContextMenu,
14650 window: &mut Window,
14651 cx: &mut Context<Self>,
14652 ) {
14653 self.request_autoscroll(Autoscroll::newest(), cx);
14654 let position = self.selections.newest_display(cx).start;
14655 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14656 }
14657
14658 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14659 &self.inlay_hint_cache
14660 }
14661
14662 pub fn replay_insert_event(
14663 &mut self,
14664 text: &str,
14665 relative_utf16_range: Option<Range<isize>>,
14666 window: &mut Window,
14667 cx: &mut Context<Self>,
14668 ) {
14669 if !self.input_enabled {
14670 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14671 return;
14672 }
14673 if let Some(relative_utf16_range) = relative_utf16_range {
14674 let selections = self.selections.all::<OffsetUtf16>(cx);
14675 self.change_selections(None, window, cx, |s| {
14676 let new_ranges = selections.into_iter().map(|range| {
14677 let start = OffsetUtf16(
14678 range
14679 .head()
14680 .0
14681 .saturating_add_signed(relative_utf16_range.start),
14682 );
14683 let end = OffsetUtf16(
14684 range
14685 .head()
14686 .0
14687 .saturating_add_signed(relative_utf16_range.end),
14688 );
14689 start..end
14690 });
14691 s.select_ranges(new_ranges);
14692 });
14693 }
14694
14695 self.handle_input(text, window, cx);
14696 }
14697
14698 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14699 let Some(provider) = self.semantics_provider.as_ref() else {
14700 return false;
14701 };
14702
14703 let mut supports = false;
14704 self.buffer().read(cx).for_each_buffer(|buffer| {
14705 supports |= provider.supports_inlay_hints(buffer, cx);
14706 });
14707 supports
14708 }
14709
14710 pub fn is_focused(&self, window: &Window) -> bool {
14711 self.focus_handle.is_focused(window)
14712 }
14713
14714 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14715 cx.emit(EditorEvent::Focused);
14716
14717 if let Some(descendant) = self
14718 .last_focused_descendant
14719 .take()
14720 .and_then(|descendant| descendant.upgrade())
14721 {
14722 window.focus(&descendant);
14723 } else {
14724 if let Some(blame) = self.blame.as_ref() {
14725 blame.update(cx, GitBlame::focus)
14726 }
14727
14728 self.blink_manager.update(cx, BlinkManager::enable);
14729 self.show_cursor_names(window, cx);
14730 self.buffer.update(cx, |buffer, cx| {
14731 buffer.finalize_last_transaction(cx);
14732 if self.leader_peer_id.is_none() {
14733 buffer.set_active_selections(
14734 &self.selections.disjoint_anchors(),
14735 self.selections.line_mode,
14736 self.cursor_shape,
14737 cx,
14738 );
14739 }
14740 });
14741 }
14742 }
14743
14744 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14745 cx.emit(EditorEvent::FocusedIn)
14746 }
14747
14748 fn handle_focus_out(
14749 &mut self,
14750 event: FocusOutEvent,
14751 _window: &mut Window,
14752 _cx: &mut Context<Self>,
14753 ) {
14754 if event.blurred != self.focus_handle {
14755 self.last_focused_descendant = Some(event.blurred);
14756 }
14757 }
14758
14759 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14760 self.blink_manager.update(cx, BlinkManager::disable);
14761 self.buffer
14762 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14763
14764 if let Some(blame) = self.blame.as_ref() {
14765 blame.update(cx, GitBlame::blur)
14766 }
14767 if !self.hover_state.focused(window, cx) {
14768 hide_hover(self, cx);
14769 }
14770
14771 self.hide_context_menu(window, cx);
14772 self.discard_inline_completion(false, cx);
14773 cx.emit(EditorEvent::Blurred);
14774 cx.notify();
14775 }
14776
14777 pub fn register_action<A: Action>(
14778 &mut self,
14779 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14780 ) -> Subscription {
14781 let id = self.next_editor_action_id.post_inc();
14782 let listener = Arc::new(listener);
14783 self.editor_actions.borrow_mut().insert(
14784 id,
14785 Box::new(move |window, _| {
14786 let listener = listener.clone();
14787 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14788 let action = action.downcast_ref().unwrap();
14789 if phase == DispatchPhase::Bubble {
14790 listener(action, window, cx)
14791 }
14792 })
14793 }),
14794 );
14795
14796 let editor_actions = self.editor_actions.clone();
14797 Subscription::new(move || {
14798 editor_actions.borrow_mut().remove(&id);
14799 })
14800 }
14801
14802 pub fn file_header_size(&self) -> u32 {
14803 FILE_HEADER_HEIGHT
14804 }
14805
14806 pub fn revert(
14807 &mut self,
14808 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14809 window: &mut Window,
14810 cx: &mut Context<Self>,
14811 ) {
14812 self.buffer().update(cx, |multi_buffer, cx| {
14813 for (buffer_id, changes) in revert_changes {
14814 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14815 buffer.update(cx, |buffer, cx| {
14816 buffer.edit(
14817 changes.into_iter().map(|(range, text)| {
14818 (range, text.to_string().map(Arc::<str>::from))
14819 }),
14820 None,
14821 cx,
14822 );
14823 });
14824 }
14825 }
14826 });
14827 self.change_selections(None, window, cx, |selections| selections.refresh());
14828 }
14829
14830 pub fn to_pixel_point(
14831 &self,
14832 source: multi_buffer::Anchor,
14833 editor_snapshot: &EditorSnapshot,
14834 window: &mut Window,
14835 ) -> Option<gpui::Point<Pixels>> {
14836 let source_point = source.to_display_point(editor_snapshot);
14837 self.display_to_pixel_point(source_point, editor_snapshot, window)
14838 }
14839
14840 pub fn display_to_pixel_point(
14841 &self,
14842 source: DisplayPoint,
14843 editor_snapshot: &EditorSnapshot,
14844 window: &mut Window,
14845 ) -> Option<gpui::Point<Pixels>> {
14846 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14847 let text_layout_details = self.text_layout_details(window);
14848 let scroll_top = text_layout_details
14849 .scroll_anchor
14850 .scroll_position(editor_snapshot)
14851 .y;
14852
14853 if source.row().as_f32() < scroll_top.floor() {
14854 return None;
14855 }
14856 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14857 let source_y = line_height * (source.row().as_f32() - scroll_top);
14858 Some(gpui::Point::new(source_x, source_y))
14859 }
14860
14861 pub fn has_visible_completions_menu(&self) -> bool {
14862 !self.edit_prediction_preview_is_active()
14863 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14864 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14865 })
14866 }
14867
14868 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14869 self.addons
14870 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14871 }
14872
14873 pub fn unregister_addon<T: Addon>(&mut self) {
14874 self.addons.remove(&std::any::TypeId::of::<T>());
14875 }
14876
14877 pub fn addon<T: Addon>(&self) -> Option<&T> {
14878 let type_id = std::any::TypeId::of::<T>();
14879 self.addons
14880 .get(&type_id)
14881 .and_then(|item| item.to_any().downcast_ref::<T>())
14882 }
14883
14884 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14885 let text_layout_details = self.text_layout_details(window);
14886 let style = &text_layout_details.editor_style;
14887 let font_id = window.text_system().resolve_font(&style.text.font());
14888 let font_size = style.text.font_size.to_pixels(window.rem_size());
14889 let line_height = style.text.line_height_in_pixels(window.rem_size());
14890 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14891
14892 gpui::Size::new(em_width, line_height)
14893 }
14894
14895 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
14896 self.load_diff_task.clone()
14897 }
14898}
14899
14900fn get_uncommitted_diff_for_buffer(
14901 project: &Entity<Project>,
14902 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14903 buffer: Entity<MultiBuffer>,
14904 cx: &mut App,
14905) -> Task<()> {
14906 let mut tasks = Vec::new();
14907 project.update(cx, |project, cx| {
14908 for buffer in buffers {
14909 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14910 }
14911 });
14912 cx.spawn(|mut cx| async move {
14913 let diffs = futures::future::join_all(tasks).await;
14914 buffer
14915 .update(&mut cx, |buffer, cx| {
14916 for diff in diffs.into_iter().flatten() {
14917 buffer.add_diff(diff, cx);
14918 }
14919 })
14920 .ok();
14921 })
14922}
14923
14924fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14925 let tab_size = tab_size.get() as usize;
14926 let mut width = offset;
14927
14928 for ch in text.chars() {
14929 width += if ch == '\t' {
14930 tab_size - (width % tab_size)
14931 } else {
14932 1
14933 };
14934 }
14935
14936 width - offset
14937}
14938
14939#[cfg(test)]
14940mod tests {
14941 use super::*;
14942
14943 #[test]
14944 fn test_string_size_with_expanded_tabs() {
14945 let nz = |val| NonZeroU32::new(val).unwrap();
14946 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14947 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14948 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14949 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14950 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14951 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14952 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14953 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14954 }
14955}
14956
14957/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14958struct WordBreakingTokenizer<'a> {
14959 input: &'a str,
14960}
14961
14962impl<'a> WordBreakingTokenizer<'a> {
14963 fn new(input: &'a str) -> Self {
14964 Self { input }
14965 }
14966}
14967
14968fn is_char_ideographic(ch: char) -> bool {
14969 use unicode_script::Script::*;
14970 use unicode_script::UnicodeScript;
14971 matches!(ch.script(), Han | Tangut | Yi)
14972}
14973
14974fn is_grapheme_ideographic(text: &str) -> bool {
14975 text.chars().any(is_char_ideographic)
14976}
14977
14978fn is_grapheme_whitespace(text: &str) -> bool {
14979 text.chars().any(|x| x.is_whitespace())
14980}
14981
14982fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14983 text.chars().next().map_or(false, |ch| {
14984 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14985 })
14986}
14987
14988#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14989struct WordBreakToken<'a> {
14990 token: &'a str,
14991 grapheme_len: usize,
14992 is_whitespace: bool,
14993}
14994
14995impl<'a> Iterator for WordBreakingTokenizer<'a> {
14996 /// Yields a span, the count of graphemes in the token, and whether it was
14997 /// whitespace. Note that it also breaks at word boundaries.
14998 type Item = WordBreakToken<'a>;
14999
15000 fn next(&mut self) -> Option<Self::Item> {
15001 use unicode_segmentation::UnicodeSegmentation;
15002 if self.input.is_empty() {
15003 return None;
15004 }
15005
15006 let mut iter = self.input.graphemes(true).peekable();
15007 let mut offset = 0;
15008 let mut graphemes = 0;
15009 if let Some(first_grapheme) = iter.next() {
15010 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15011 offset += first_grapheme.len();
15012 graphemes += 1;
15013 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15014 if let Some(grapheme) = iter.peek().copied() {
15015 if should_stay_with_preceding_ideograph(grapheme) {
15016 offset += grapheme.len();
15017 graphemes += 1;
15018 }
15019 }
15020 } else {
15021 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15022 let mut next_word_bound = words.peek().copied();
15023 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15024 next_word_bound = words.next();
15025 }
15026 while let Some(grapheme) = iter.peek().copied() {
15027 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15028 break;
15029 };
15030 if is_grapheme_whitespace(grapheme) != is_whitespace {
15031 break;
15032 };
15033 offset += grapheme.len();
15034 graphemes += 1;
15035 iter.next();
15036 }
15037 }
15038 let token = &self.input[..offset];
15039 self.input = &self.input[offset..];
15040 if is_whitespace {
15041 Some(WordBreakToken {
15042 token: " ",
15043 grapheme_len: 1,
15044 is_whitespace: true,
15045 })
15046 } else {
15047 Some(WordBreakToken {
15048 token,
15049 grapheme_len: graphemes,
15050 is_whitespace: false,
15051 })
15052 }
15053 } else {
15054 None
15055 }
15056 }
15057}
15058
15059#[test]
15060fn test_word_breaking_tokenizer() {
15061 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15062 ("", &[]),
15063 (" ", &[(" ", 1, true)]),
15064 ("Ʒ", &[("Ʒ", 1, false)]),
15065 ("Ǽ", &[("Ǽ", 1, false)]),
15066 ("⋑", &[("⋑", 1, false)]),
15067 ("⋑⋑", &[("⋑⋑", 2, false)]),
15068 (
15069 "原理,进而",
15070 &[
15071 ("原", 1, false),
15072 ("理,", 2, false),
15073 ("进", 1, false),
15074 ("而", 1, false),
15075 ],
15076 ),
15077 (
15078 "hello world",
15079 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15080 ),
15081 (
15082 "hello, world",
15083 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15084 ),
15085 (
15086 " hello world",
15087 &[
15088 (" ", 1, true),
15089 ("hello", 5, false),
15090 (" ", 1, true),
15091 ("world", 5, false),
15092 ],
15093 ),
15094 (
15095 "这是什么 \n 钢笔",
15096 &[
15097 ("这", 1, false),
15098 ("是", 1, false),
15099 ("什", 1, false),
15100 ("么", 1, false),
15101 (" ", 1, true),
15102 ("钢", 1, false),
15103 ("笔", 1, false),
15104 ],
15105 ),
15106 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15107 ];
15108
15109 for (input, result) in tests {
15110 assert_eq!(
15111 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15112 result
15113 .iter()
15114 .copied()
15115 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15116 token,
15117 grapheme_len,
15118 is_whitespace,
15119 })
15120 .collect::<Vec<_>>()
15121 );
15122 }
15123}
15124
15125fn wrap_with_prefix(
15126 line_prefix: String,
15127 unwrapped_text: String,
15128 wrap_column: usize,
15129 tab_size: NonZeroU32,
15130) -> String {
15131 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15132 let mut wrapped_text = String::new();
15133 let mut current_line = line_prefix.clone();
15134
15135 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15136 let mut current_line_len = line_prefix_len;
15137 for WordBreakToken {
15138 token,
15139 grapheme_len,
15140 is_whitespace,
15141 } in tokenizer
15142 {
15143 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15144 wrapped_text.push_str(current_line.trim_end());
15145 wrapped_text.push('\n');
15146 current_line.truncate(line_prefix.len());
15147 current_line_len = line_prefix_len;
15148 if !is_whitespace {
15149 current_line.push_str(token);
15150 current_line_len += grapheme_len;
15151 }
15152 } else if !is_whitespace {
15153 current_line.push_str(token);
15154 current_line_len += grapheme_len;
15155 } else if current_line_len != line_prefix_len {
15156 current_line.push(' ');
15157 current_line_len += 1;
15158 }
15159 }
15160
15161 if !current_line.is_empty() {
15162 wrapped_text.push_str(¤t_line);
15163 }
15164 wrapped_text
15165}
15166
15167#[test]
15168fn test_wrap_with_prefix() {
15169 assert_eq!(
15170 wrap_with_prefix(
15171 "# ".to_string(),
15172 "abcdefg".to_string(),
15173 4,
15174 NonZeroU32::new(4).unwrap()
15175 ),
15176 "# abcdefg"
15177 );
15178 assert_eq!(
15179 wrap_with_prefix(
15180 "".to_string(),
15181 "\thello world".to_string(),
15182 8,
15183 NonZeroU32::new(4).unwrap()
15184 ),
15185 "hello\nworld"
15186 );
15187 assert_eq!(
15188 wrap_with_prefix(
15189 "// ".to_string(),
15190 "xx \nyy zz aa bb cc".to_string(),
15191 12,
15192 NonZeroU32::new(4).unwrap()
15193 ),
15194 "// xx yy zz\n// aa bb cc"
15195 );
15196 assert_eq!(
15197 wrap_with_prefix(
15198 String::new(),
15199 "这是什么 \n 钢笔".to_string(),
15200 3,
15201 NonZeroU32::new(4).unwrap()
15202 ),
15203 "这是什\n么 钢\n笔"
15204 );
15205}
15206
15207pub trait CollaborationHub {
15208 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15209 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15210 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15211}
15212
15213impl CollaborationHub for Entity<Project> {
15214 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15215 self.read(cx).collaborators()
15216 }
15217
15218 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15219 self.read(cx).user_store().read(cx).participant_indices()
15220 }
15221
15222 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15223 let this = self.read(cx);
15224 let user_ids = this.collaborators().values().map(|c| c.user_id);
15225 this.user_store().read_with(cx, |user_store, cx| {
15226 user_store.participant_names(user_ids, cx)
15227 })
15228 }
15229}
15230
15231pub trait SemanticsProvider {
15232 fn hover(
15233 &self,
15234 buffer: &Entity<Buffer>,
15235 position: text::Anchor,
15236 cx: &mut App,
15237 ) -> Option<Task<Vec<project::Hover>>>;
15238
15239 fn inlay_hints(
15240 &self,
15241 buffer_handle: Entity<Buffer>,
15242 range: Range<text::Anchor>,
15243 cx: &mut App,
15244 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15245
15246 fn resolve_inlay_hint(
15247 &self,
15248 hint: InlayHint,
15249 buffer_handle: Entity<Buffer>,
15250 server_id: LanguageServerId,
15251 cx: &mut App,
15252 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15253
15254 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15255
15256 fn document_highlights(
15257 &self,
15258 buffer: &Entity<Buffer>,
15259 position: text::Anchor,
15260 cx: &mut App,
15261 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15262
15263 fn definitions(
15264 &self,
15265 buffer: &Entity<Buffer>,
15266 position: text::Anchor,
15267 kind: GotoDefinitionKind,
15268 cx: &mut App,
15269 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15270
15271 fn range_for_rename(
15272 &self,
15273 buffer: &Entity<Buffer>,
15274 position: text::Anchor,
15275 cx: &mut App,
15276 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15277
15278 fn perform_rename(
15279 &self,
15280 buffer: &Entity<Buffer>,
15281 position: text::Anchor,
15282 new_name: String,
15283 cx: &mut App,
15284 ) -> Option<Task<Result<ProjectTransaction>>>;
15285}
15286
15287pub trait CompletionProvider {
15288 fn completions(
15289 &self,
15290 buffer: &Entity<Buffer>,
15291 buffer_position: text::Anchor,
15292 trigger: CompletionContext,
15293 window: &mut Window,
15294 cx: &mut Context<Editor>,
15295 ) -> Task<Result<Vec<Completion>>>;
15296
15297 fn resolve_completions(
15298 &self,
15299 buffer: Entity<Buffer>,
15300 completion_indices: Vec<usize>,
15301 completions: Rc<RefCell<Box<[Completion]>>>,
15302 cx: &mut Context<Editor>,
15303 ) -> Task<Result<bool>>;
15304
15305 fn apply_additional_edits_for_completion(
15306 &self,
15307 _buffer: Entity<Buffer>,
15308 _completions: Rc<RefCell<Box<[Completion]>>>,
15309 _completion_index: usize,
15310 _push_to_history: bool,
15311 _cx: &mut Context<Editor>,
15312 ) -> Task<Result<Option<language::Transaction>>> {
15313 Task::ready(Ok(None))
15314 }
15315
15316 fn is_completion_trigger(
15317 &self,
15318 buffer: &Entity<Buffer>,
15319 position: language::Anchor,
15320 text: &str,
15321 trigger_in_words: bool,
15322 cx: &mut Context<Editor>,
15323 ) -> bool;
15324
15325 fn sort_completions(&self) -> bool {
15326 true
15327 }
15328}
15329
15330pub trait CodeActionProvider {
15331 fn id(&self) -> Arc<str>;
15332
15333 fn code_actions(
15334 &self,
15335 buffer: &Entity<Buffer>,
15336 range: Range<text::Anchor>,
15337 window: &mut Window,
15338 cx: &mut App,
15339 ) -> Task<Result<Vec<CodeAction>>>;
15340
15341 fn apply_code_action(
15342 &self,
15343 buffer_handle: Entity<Buffer>,
15344 action: CodeAction,
15345 excerpt_id: ExcerptId,
15346 push_to_history: bool,
15347 window: &mut Window,
15348 cx: &mut App,
15349 ) -> Task<Result<ProjectTransaction>>;
15350}
15351
15352impl CodeActionProvider for Entity<Project> {
15353 fn id(&self) -> Arc<str> {
15354 "project".into()
15355 }
15356
15357 fn code_actions(
15358 &self,
15359 buffer: &Entity<Buffer>,
15360 range: Range<text::Anchor>,
15361 _window: &mut Window,
15362 cx: &mut App,
15363 ) -> Task<Result<Vec<CodeAction>>> {
15364 self.update(cx, |project, cx| {
15365 project.code_actions(buffer, range, None, cx)
15366 })
15367 }
15368
15369 fn apply_code_action(
15370 &self,
15371 buffer_handle: Entity<Buffer>,
15372 action: CodeAction,
15373 _excerpt_id: ExcerptId,
15374 push_to_history: bool,
15375 _window: &mut Window,
15376 cx: &mut App,
15377 ) -> Task<Result<ProjectTransaction>> {
15378 self.update(cx, |project, cx| {
15379 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15380 })
15381 }
15382}
15383
15384fn snippet_completions(
15385 project: &Project,
15386 buffer: &Entity<Buffer>,
15387 buffer_position: text::Anchor,
15388 cx: &mut App,
15389) -> Task<Result<Vec<Completion>>> {
15390 let language = buffer.read(cx).language_at(buffer_position);
15391 let language_name = language.as_ref().map(|language| language.lsp_id());
15392 let snippet_store = project.snippets().read(cx);
15393 let snippets = snippet_store.snippets_for(language_name, cx);
15394
15395 if snippets.is_empty() {
15396 return Task::ready(Ok(vec![]));
15397 }
15398 let snapshot = buffer.read(cx).text_snapshot();
15399 let chars: String = snapshot
15400 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15401 .collect();
15402
15403 let scope = language.map(|language| language.default_scope());
15404 let executor = cx.background_executor().clone();
15405
15406 cx.background_executor().spawn(async move {
15407 let classifier = CharClassifier::new(scope).for_completion(true);
15408 let mut last_word = chars
15409 .chars()
15410 .take_while(|c| classifier.is_word(*c))
15411 .collect::<String>();
15412 last_word = last_word.chars().rev().collect();
15413
15414 if last_word.is_empty() {
15415 return Ok(vec![]);
15416 }
15417
15418 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15419 let to_lsp = |point: &text::Anchor| {
15420 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15421 point_to_lsp(end)
15422 };
15423 let lsp_end = to_lsp(&buffer_position);
15424
15425 let candidates = snippets
15426 .iter()
15427 .enumerate()
15428 .flat_map(|(ix, snippet)| {
15429 snippet
15430 .prefix
15431 .iter()
15432 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15433 })
15434 .collect::<Vec<StringMatchCandidate>>();
15435
15436 let mut matches = fuzzy::match_strings(
15437 &candidates,
15438 &last_word,
15439 last_word.chars().any(|c| c.is_uppercase()),
15440 100,
15441 &Default::default(),
15442 executor,
15443 )
15444 .await;
15445
15446 // Remove all candidates where the query's start does not match the start of any word in the candidate
15447 if let Some(query_start) = last_word.chars().next() {
15448 matches.retain(|string_match| {
15449 split_words(&string_match.string).any(|word| {
15450 // Check that the first codepoint of the word as lowercase matches the first
15451 // codepoint of the query as lowercase
15452 word.chars()
15453 .flat_map(|codepoint| codepoint.to_lowercase())
15454 .zip(query_start.to_lowercase())
15455 .all(|(word_cp, query_cp)| word_cp == query_cp)
15456 })
15457 });
15458 }
15459
15460 let matched_strings = matches
15461 .into_iter()
15462 .map(|m| m.string)
15463 .collect::<HashSet<_>>();
15464
15465 let result: Vec<Completion> = snippets
15466 .into_iter()
15467 .filter_map(|snippet| {
15468 let matching_prefix = snippet
15469 .prefix
15470 .iter()
15471 .find(|prefix| matched_strings.contains(*prefix))?;
15472 let start = as_offset - last_word.len();
15473 let start = snapshot.anchor_before(start);
15474 let range = start..buffer_position;
15475 let lsp_start = to_lsp(&start);
15476 let lsp_range = lsp::Range {
15477 start: lsp_start,
15478 end: lsp_end,
15479 };
15480 Some(Completion {
15481 old_range: range,
15482 new_text: snippet.body.clone(),
15483 resolved: false,
15484 label: CodeLabel {
15485 text: matching_prefix.clone(),
15486 runs: vec![],
15487 filter_range: 0..matching_prefix.len(),
15488 },
15489 server_id: LanguageServerId(usize::MAX),
15490 documentation: snippet
15491 .description
15492 .clone()
15493 .map(CompletionDocumentation::SingleLine),
15494 lsp_completion: lsp::CompletionItem {
15495 label: snippet.prefix.first().unwrap().clone(),
15496 kind: Some(CompletionItemKind::SNIPPET),
15497 label_details: snippet.description.as_ref().map(|description| {
15498 lsp::CompletionItemLabelDetails {
15499 detail: Some(description.clone()),
15500 description: None,
15501 }
15502 }),
15503 insert_text_format: Some(InsertTextFormat::SNIPPET),
15504 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15505 lsp::InsertReplaceEdit {
15506 new_text: snippet.body.clone(),
15507 insert: lsp_range,
15508 replace: lsp_range,
15509 },
15510 )),
15511 filter_text: Some(snippet.body.clone()),
15512 sort_text: Some(char::MAX.to_string()),
15513 ..Default::default()
15514 },
15515 confirm: None,
15516 })
15517 })
15518 .collect();
15519
15520 Ok(result)
15521 })
15522}
15523
15524impl CompletionProvider for Entity<Project> {
15525 fn completions(
15526 &self,
15527 buffer: &Entity<Buffer>,
15528 buffer_position: text::Anchor,
15529 options: CompletionContext,
15530 _window: &mut Window,
15531 cx: &mut Context<Editor>,
15532 ) -> Task<Result<Vec<Completion>>> {
15533 self.update(cx, |project, cx| {
15534 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15535 let project_completions = project.completions(buffer, buffer_position, options, cx);
15536 cx.background_executor().spawn(async move {
15537 let mut completions = project_completions.await?;
15538 let snippets_completions = snippets.await?;
15539 completions.extend(snippets_completions);
15540 Ok(completions)
15541 })
15542 })
15543 }
15544
15545 fn resolve_completions(
15546 &self,
15547 buffer: Entity<Buffer>,
15548 completion_indices: Vec<usize>,
15549 completions: Rc<RefCell<Box<[Completion]>>>,
15550 cx: &mut Context<Editor>,
15551 ) -> Task<Result<bool>> {
15552 self.update(cx, |project, cx| {
15553 project.lsp_store().update(cx, |lsp_store, cx| {
15554 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15555 })
15556 })
15557 }
15558
15559 fn apply_additional_edits_for_completion(
15560 &self,
15561 buffer: Entity<Buffer>,
15562 completions: Rc<RefCell<Box<[Completion]>>>,
15563 completion_index: usize,
15564 push_to_history: bool,
15565 cx: &mut Context<Editor>,
15566 ) -> Task<Result<Option<language::Transaction>>> {
15567 self.update(cx, |project, cx| {
15568 project.lsp_store().update(cx, |lsp_store, cx| {
15569 lsp_store.apply_additional_edits_for_completion(
15570 buffer,
15571 completions,
15572 completion_index,
15573 push_to_history,
15574 cx,
15575 )
15576 })
15577 })
15578 }
15579
15580 fn is_completion_trigger(
15581 &self,
15582 buffer: &Entity<Buffer>,
15583 position: language::Anchor,
15584 text: &str,
15585 trigger_in_words: bool,
15586 cx: &mut Context<Editor>,
15587 ) -> bool {
15588 let mut chars = text.chars();
15589 let char = if let Some(char) = chars.next() {
15590 char
15591 } else {
15592 return false;
15593 };
15594 if chars.next().is_some() {
15595 return false;
15596 }
15597
15598 let buffer = buffer.read(cx);
15599 let snapshot = buffer.snapshot();
15600 if !snapshot.settings_at(position, cx).show_completions_on_input {
15601 return false;
15602 }
15603 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15604 if trigger_in_words && classifier.is_word(char) {
15605 return true;
15606 }
15607
15608 buffer.completion_triggers().contains(text)
15609 }
15610}
15611
15612impl SemanticsProvider for Entity<Project> {
15613 fn hover(
15614 &self,
15615 buffer: &Entity<Buffer>,
15616 position: text::Anchor,
15617 cx: &mut App,
15618 ) -> Option<Task<Vec<project::Hover>>> {
15619 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15620 }
15621
15622 fn document_highlights(
15623 &self,
15624 buffer: &Entity<Buffer>,
15625 position: text::Anchor,
15626 cx: &mut App,
15627 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15628 Some(self.update(cx, |project, cx| {
15629 project.document_highlights(buffer, position, cx)
15630 }))
15631 }
15632
15633 fn definitions(
15634 &self,
15635 buffer: &Entity<Buffer>,
15636 position: text::Anchor,
15637 kind: GotoDefinitionKind,
15638 cx: &mut App,
15639 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15640 Some(self.update(cx, |project, cx| match kind {
15641 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15642 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15643 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15644 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15645 }))
15646 }
15647
15648 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15649 // TODO: make this work for remote projects
15650 self.read(cx)
15651 .language_servers_for_local_buffer(buffer.read(cx), cx)
15652 .any(
15653 |(_, server)| match server.capabilities().inlay_hint_provider {
15654 Some(lsp::OneOf::Left(enabled)) => enabled,
15655 Some(lsp::OneOf::Right(_)) => true,
15656 None => false,
15657 },
15658 )
15659 }
15660
15661 fn inlay_hints(
15662 &self,
15663 buffer_handle: Entity<Buffer>,
15664 range: Range<text::Anchor>,
15665 cx: &mut App,
15666 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15667 Some(self.update(cx, |project, cx| {
15668 project.inlay_hints(buffer_handle, range, cx)
15669 }))
15670 }
15671
15672 fn resolve_inlay_hint(
15673 &self,
15674 hint: InlayHint,
15675 buffer_handle: Entity<Buffer>,
15676 server_id: LanguageServerId,
15677 cx: &mut App,
15678 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15679 Some(self.update(cx, |project, cx| {
15680 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15681 }))
15682 }
15683
15684 fn range_for_rename(
15685 &self,
15686 buffer: &Entity<Buffer>,
15687 position: text::Anchor,
15688 cx: &mut App,
15689 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15690 Some(self.update(cx, |project, cx| {
15691 let buffer = buffer.clone();
15692 let task = project.prepare_rename(buffer.clone(), position, cx);
15693 cx.spawn(|_, mut cx| async move {
15694 Ok(match task.await? {
15695 PrepareRenameResponse::Success(range) => Some(range),
15696 PrepareRenameResponse::InvalidPosition => None,
15697 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15698 // Fallback on using TreeSitter info to determine identifier range
15699 buffer.update(&mut cx, |buffer, _| {
15700 let snapshot = buffer.snapshot();
15701 let (range, kind) = snapshot.surrounding_word(position);
15702 if kind != Some(CharKind::Word) {
15703 return None;
15704 }
15705 Some(
15706 snapshot.anchor_before(range.start)
15707 ..snapshot.anchor_after(range.end),
15708 )
15709 })?
15710 }
15711 })
15712 })
15713 }))
15714 }
15715
15716 fn perform_rename(
15717 &self,
15718 buffer: &Entity<Buffer>,
15719 position: text::Anchor,
15720 new_name: String,
15721 cx: &mut App,
15722 ) -> Option<Task<Result<ProjectTransaction>>> {
15723 Some(self.update(cx, |project, cx| {
15724 project.perform_rename(buffer.clone(), position, new_name, cx)
15725 }))
15726 }
15727}
15728
15729fn inlay_hint_settings(
15730 location: Anchor,
15731 snapshot: &MultiBufferSnapshot,
15732 cx: &mut Context<Editor>,
15733) -> InlayHintSettings {
15734 let file = snapshot.file_at(location);
15735 let language = snapshot.language_at(location).map(|l| l.name());
15736 language_settings(language, file, cx).inlay_hints
15737}
15738
15739fn consume_contiguous_rows(
15740 contiguous_row_selections: &mut Vec<Selection<Point>>,
15741 selection: &Selection<Point>,
15742 display_map: &DisplaySnapshot,
15743 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15744) -> (MultiBufferRow, MultiBufferRow) {
15745 contiguous_row_selections.push(selection.clone());
15746 let start_row = MultiBufferRow(selection.start.row);
15747 let mut end_row = ending_row(selection, display_map);
15748
15749 while let Some(next_selection) = selections.peek() {
15750 if next_selection.start.row <= end_row.0 {
15751 end_row = ending_row(next_selection, display_map);
15752 contiguous_row_selections.push(selections.next().unwrap().clone());
15753 } else {
15754 break;
15755 }
15756 }
15757 (start_row, end_row)
15758}
15759
15760fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15761 if next_selection.end.column > 0 || next_selection.is_empty() {
15762 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15763 } else {
15764 MultiBufferRow(next_selection.end.row)
15765 }
15766}
15767
15768impl EditorSnapshot {
15769 pub fn remote_selections_in_range<'a>(
15770 &'a self,
15771 range: &'a Range<Anchor>,
15772 collaboration_hub: &dyn CollaborationHub,
15773 cx: &'a App,
15774 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15775 let participant_names = collaboration_hub.user_names(cx);
15776 let participant_indices = collaboration_hub.user_participant_indices(cx);
15777 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15778 let collaborators_by_replica_id = collaborators_by_peer_id
15779 .iter()
15780 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15781 .collect::<HashMap<_, _>>();
15782 self.buffer_snapshot
15783 .selections_in_range(range, false)
15784 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15785 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15786 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15787 let user_name = participant_names.get(&collaborator.user_id).cloned();
15788 Some(RemoteSelection {
15789 replica_id,
15790 selection,
15791 cursor_shape,
15792 line_mode,
15793 participant_index,
15794 peer_id: collaborator.peer_id,
15795 user_name,
15796 })
15797 })
15798 }
15799
15800 pub fn hunks_for_ranges(
15801 &self,
15802 ranges: impl Iterator<Item = Range<Point>>,
15803 ) -> Vec<MultiBufferDiffHunk> {
15804 let mut hunks = Vec::new();
15805 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15806 HashMap::default();
15807 for query_range in ranges {
15808 let query_rows =
15809 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15810 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15811 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15812 ) {
15813 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15814 // when the caret is just above or just below the deleted hunk.
15815 let allow_adjacent = hunk.status().is_removed();
15816 let related_to_selection = if allow_adjacent {
15817 hunk.row_range.overlaps(&query_rows)
15818 || hunk.row_range.start == query_rows.end
15819 || hunk.row_range.end == query_rows.start
15820 } else {
15821 hunk.row_range.overlaps(&query_rows)
15822 };
15823 if related_to_selection {
15824 if !processed_buffer_rows
15825 .entry(hunk.buffer_id)
15826 .or_default()
15827 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15828 {
15829 continue;
15830 }
15831 hunks.push(hunk);
15832 }
15833 }
15834 }
15835
15836 hunks
15837 }
15838
15839 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15840 self.display_snapshot.buffer_snapshot.language_at(position)
15841 }
15842
15843 pub fn is_focused(&self) -> bool {
15844 self.is_focused
15845 }
15846
15847 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15848 self.placeholder_text.as_ref()
15849 }
15850
15851 pub fn scroll_position(&self) -> gpui::Point<f32> {
15852 self.scroll_anchor.scroll_position(&self.display_snapshot)
15853 }
15854
15855 fn gutter_dimensions(
15856 &self,
15857 font_id: FontId,
15858 font_size: Pixels,
15859 max_line_number_width: Pixels,
15860 cx: &App,
15861 ) -> Option<GutterDimensions> {
15862 if !self.show_gutter {
15863 return None;
15864 }
15865
15866 let descent = cx.text_system().descent(font_id, font_size);
15867 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15868 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15869
15870 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15871 matches!(
15872 ProjectSettings::get_global(cx).git.git_gutter,
15873 Some(GitGutterSetting::TrackedFiles)
15874 )
15875 });
15876 let gutter_settings = EditorSettings::get_global(cx).gutter;
15877 let show_line_numbers = self
15878 .show_line_numbers
15879 .unwrap_or(gutter_settings.line_numbers);
15880 let line_gutter_width = if show_line_numbers {
15881 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15882 let min_width_for_number_on_gutter = em_advance * 4.0;
15883 max_line_number_width.max(min_width_for_number_on_gutter)
15884 } else {
15885 0.0.into()
15886 };
15887
15888 let show_code_actions = self
15889 .show_code_actions
15890 .unwrap_or(gutter_settings.code_actions);
15891
15892 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15893
15894 let git_blame_entries_width =
15895 self.git_blame_gutter_max_author_length
15896 .map(|max_author_length| {
15897 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15898
15899 /// The number of characters to dedicate to gaps and margins.
15900 const SPACING_WIDTH: usize = 4;
15901
15902 let max_char_count = max_author_length
15903 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15904 + ::git::SHORT_SHA_LENGTH
15905 + MAX_RELATIVE_TIMESTAMP.len()
15906 + SPACING_WIDTH;
15907
15908 em_advance * max_char_count
15909 });
15910
15911 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15912 left_padding += if show_code_actions || show_runnables {
15913 em_width * 3.0
15914 } else if show_git_gutter && show_line_numbers {
15915 em_width * 2.0
15916 } else if show_git_gutter || show_line_numbers {
15917 em_width
15918 } else {
15919 px(0.)
15920 };
15921
15922 let right_padding = if gutter_settings.folds && show_line_numbers {
15923 em_width * 4.0
15924 } else if gutter_settings.folds {
15925 em_width * 3.0
15926 } else if show_line_numbers {
15927 em_width
15928 } else {
15929 px(0.)
15930 };
15931
15932 Some(GutterDimensions {
15933 left_padding,
15934 right_padding,
15935 width: line_gutter_width + left_padding + right_padding,
15936 margin: -descent,
15937 git_blame_entries_width,
15938 })
15939 }
15940
15941 pub fn render_crease_toggle(
15942 &self,
15943 buffer_row: MultiBufferRow,
15944 row_contains_cursor: bool,
15945 editor: Entity<Editor>,
15946 window: &mut Window,
15947 cx: &mut App,
15948 ) -> Option<AnyElement> {
15949 let folded = self.is_line_folded(buffer_row);
15950 let mut is_foldable = false;
15951
15952 if let Some(crease) = self
15953 .crease_snapshot
15954 .query_row(buffer_row, &self.buffer_snapshot)
15955 {
15956 is_foldable = true;
15957 match crease {
15958 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15959 if let Some(render_toggle) = render_toggle {
15960 let toggle_callback =
15961 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15962 if folded {
15963 editor.update(cx, |editor, cx| {
15964 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15965 });
15966 } else {
15967 editor.update(cx, |editor, cx| {
15968 editor.unfold_at(
15969 &crate::UnfoldAt { buffer_row },
15970 window,
15971 cx,
15972 )
15973 });
15974 }
15975 });
15976 return Some((render_toggle)(
15977 buffer_row,
15978 folded,
15979 toggle_callback,
15980 window,
15981 cx,
15982 ));
15983 }
15984 }
15985 }
15986 }
15987
15988 is_foldable |= self.starts_indent(buffer_row);
15989
15990 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15991 Some(
15992 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15993 .toggle_state(folded)
15994 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15995 if folded {
15996 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15997 } else {
15998 this.fold_at(&FoldAt { buffer_row }, window, cx);
15999 }
16000 }))
16001 .into_any_element(),
16002 )
16003 } else {
16004 None
16005 }
16006 }
16007
16008 pub fn render_crease_trailer(
16009 &self,
16010 buffer_row: MultiBufferRow,
16011 window: &mut Window,
16012 cx: &mut App,
16013 ) -> Option<AnyElement> {
16014 let folded = self.is_line_folded(buffer_row);
16015 if let Crease::Inline { render_trailer, .. } = self
16016 .crease_snapshot
16017 .query_row(buffer_row, &self.buffer_snapshot)?
16018 {
16019 let render_trailer = render_trailer.as_ref()?;
16020 Some(render_trailer(buffer_row, folded, window, cx))
16021 } else {
16022 None
16023 }
16024 }
16025}
16026
16027impl Deref for EditorSnapshot {
16028 type Target = DisplaySnapshot;
16029
16030 fn deref(&self) -> &Self::Target {
16031 &self.display_snapshot
16032 }
16033}
16034
16035#[derive(Clone, Debug, PartialEq, Eq)]
16036pub enum EditorEvent {
16037 InputIgnored {
16038 text: Arc<str>,
16039 },
16040 InputHandled {
16041 utf16_range_to_replace: Option<Range<isize>>,
16042 text: Arc<str>,
16043 },
16044 ExcerptsAdded {
16045 buffer: Entity<Buffer>,
16046 predecessor: ExcerptId,
16047 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16048 },
16049 ExcerptsRemoved {
16050 ids: Vec<ExcerptId>,
16051 },
16052 BufferFoldToggled {
16053 ids: Vec<ExcerptId>,
16054 folded: bool,
16055 },
16056 ExcerptsEdited {
16057 ids: Vec<ExcerptId>,
16058 },
16059 ExcerptsExpanded {
16060 ids: Vec<ExcerptId>,
16061 },
16062 BufferEdited,
16063 Edited {
16064 transaction_id: clock::Lamport,
16065 },
16066 Reparsed(BufferId),
16067 Focused,
16068 FocusedIn,
16069 Blurred,
16070 DirtyChanged,
16071 Saved,
16072 TitleChanged,
16073 DiffBaseChanged,
16074 SelectionsChanged {
16075 local: bool,
16076 },
16077 ScrollPositionChanged {
16078 local: bool,
16079 autoscroll: bool,
16080 },
16081 Closed,
16082 TransactionUndone {
16083 transaction_id: clock::Lamport,
16084 },
16085 TransactionBegun {
16086 transaction_id: clock::Lamport,
16087 },
16088 Reloaded,
16089 CursorShapeChanged,
16090}
16091
16092impl EventEmitter<EditorEvent> for Editor {}
16093
16094impl Focusable for Editor {
16095 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16096 self.focus_handle.clone()
16097 }
16098}
16099
16100impl Render for Editor {
16101 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16102 let settings = ThemeSettings::get_global(cx);
16103
16104 let mut text_style = match self.mode {
16105 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16106 color: cx.theme().colors().editor_foreground,
16107 font_family: settings.ui_font.family.clone(),
16108 font_features: settings.ui_font.features.clone(),
16109 font_fallbacks: settings.ui_font.fallbacks.clone(),
16110 font_size: rems(0.875).into(),
16111 font_weight: settings.ui_font.weight,
16112 line_height: relative(settings.buffer_line_height.value()),
16113 ..Default::default()
16114 },
16115 EditorMode::Full => TextStyle {
16116 color: cx.theme().colors().editor_foreground,
16117 font_family: settings.buffer_font.family.clone(),
16118 font_features: settings.buffer_font.features.clone(),
16119 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16120 font_size: settings.buffer_font_size().into(),
16121 font_weight: settings.buffer_font.weight,
16122 line_height: relative(settings.buffer_line_height.value()),
16123 ..Default::default()
16124 },
16125 };
16126 if let Some(text_style_refinement) = &self.text_style_refinement {
16127 text_style.refine(text_style_refinement)
16128 }
16129
16130 let background = match self.mode {
16131 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16132 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16133 EditorMode::Full => cx.theme().colors().editor_background,
16134 };
16135
16136 EditorElement::new(
16137 &cx.entity(),
16138 EditorStyle {
16139 background,
16140 local_player: cx.theme().players().local(),
16141 text: text_style,
16142 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16143 syntax: cx.theme().syntax().clone(),
16144 status: cx.theme().status().clone(),
16145 inlay_hints_style: make_inlay_hints_style(cx),
16146 inline_completion_styles: make_suggestion_styles(cx),
16147 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16148 },
16149 )
16150 }
16151}
16152
16153impl EntityInputHandler for Editor {
16154 fn text_for_range(
16155 &mut self,
16156 range_utf16: Range<usize>,
16157 adjusted_range: &mut Option<Range<usize>>,
16158 _: &mut Window,
16159 cx: &mut Context<Self>,
16160 ) -> Option<String> {
16161 let snapshot = self.buffer.read(cx).read(cx);
16162 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16163 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16164 if (start.0..end.0) != range_utf16 {
16165 adjusted_range.replace(start.0..end.0);
16166 }
16167 Some(snapshot.text_for_range(start..end).collect())
16168 }
16169
16170 fn selected_text_range(
16171 &mut self,
16172 ignore_disabled_input: bool,
16173 _: &mut Window,
16174 cx: &mut Context<Self>,
16175 ) -> Option<UTF16Selection> {
16176 // Prevent the IME menu from appearing when holding down an alphabetic key
16177 // while input is disabled.
16178 if !ignore_disabled_input && !self.input_enabled {
16179 return None;
16180 }
16181
16182 let selection = self.selections.newest::<OffsetUtf16>(cx);
16183 let range = selection.range();
16184
16185 Some(UTF16Selection {
16186 range: range.start.0..range.end.0,
16187 reversed: selection.reversed,
16188 })
16189 }
16190
16191 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16192 let snapshot = self.buffer.read(cx).read(cx);
16193 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16194 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16195 }
16196
16197 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16198 self.clear_highlights::<InputComposition>(cx);
16199 self.ime_transaction.take();
16200 }
16201
16202 fn replace_text_in_range(
16203 &mut self,
16204 range_utf16: Option<Range<usize>>,
16205 text: &str,
16206 window: &mut Window,
16207 cx: &mut Context<Self>,
16208 ) {
16209 if !self.input_enabled {
16210 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16211 return;
16212 }
16213
16214 self.transact(window, cx, |this, window, cx| {
16215 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16216 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16217 Some(this.selection_replacement_ranges(range_utf16, cx))
16218 } else {
16219 this.marked_text_ranges(cx)
16220 };
16221
16222 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16223 let newest_selection_id = this.selections.newest_anchor().id;
16224 this.selections
16225 .all::<OffsetUtf16>(cx)
16226 .iter()
16227 .zip(ranges_to_replace.iter())
16228 .find_map(|(selection, range)| {
16229 if selection.id == newest_selection_id {
16230 Some(
16231 (range.start.0 as isize - selection.head().0 as isize)
16232 ..(range.end.0 as isize - selection.head().0 as isize),
16233 )
16234 } else {
16235 None
16236 }
16237 })
16238 });
16239
16240 cx.emit(EditorEvent::InputHandled {
16241 utf16_range_to_replace: range_to_replace,
16242 text: text.into(),
16243 });
16244
16245 if let Some(new_selected_ranges) = new_selected_ranges {
16246 this.change_selections(None, window, cx, |selections| {
16247 selections.select_ranges(new_selected_ranges)
16248 });
16249 this.backspace(&Default::default(), window, cx);
16250 }
16251
16252 this.handle_input(text, window, cx);
16253 });
16254
16255 if let Some(transaction) = self.ime_transaction {
16256 self.buffer.update(cx, |buffer, cx| {
16257 buffer.group_until_transaction(transaction, cx);
16258 });
16259 }
16260
16261 self.unmark_text(window, cx);
16262 }
16263
16264 fn replace_and_mark_text_in_range(
16265 &mut self,
16266 range_utf16: Option<Range<usize>>,
16267 text: &str,
16268 new_selected_range_utf16: Option<Range<usize>>,
16269 window: &mut Window,
16270 cx: &mut Context<Self>,
16271 ) {
16272 if !self.input_enabled {
16273 return;
16274 }
16275
16276 let transaction = self.transact(window, cx, |this, window, cx| {
16277 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16278 let snapshot = this.buffer.read(cx).read(cx);
16279 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16280 for marked_range in &mut marked_ranges {
16281 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16282 marked_range.start.0 += relative_range_utf16.start;
16283 marked_range.start =
16284 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16285 marked_range.end =
16286 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16287 }
16288 }
16289 Some(marked_ranges)
16290 } else if let Some(range_utf16) = range_utf16 {
16291 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16292 Some(this.selection_replacement_ranges(range_utf16, cx))
16293 } else {
16294 None
16295 };
16296
16297 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16298 let newest_selection_id = this.selections.newest_anchor().id;
16299 this.selections
16300 .all::<OffsetUtf16>(cx)
16301 .iter()
16302 .zip(ranges_to_replace.iter())
16303 .find_map(|(selection, range)| {
16304 if selection.id == newest_selection_id {
16305 Some(
16306 (range.start.0 as isize - selection.head().0 as isize)
16307 ..(range.end.0 as isize - selection.head().0 as isize),
16308 )
16309 } else {
16310 None
16311 }
16312 })
16313 });
16314
16315 cx.emit(EditorEvent::InputHandled {
16316 utf16_range_to_replace: range_to_replace,
16317 text: text.into(),
16318 });
16319
16320 if let Some(ranges) = ranges_to_replace {
16321 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16322 }
16323
16324 let marked_ranges = {
16325 let snapshot = this.buffer.read(cx).read(cx);
16326 this.selections
16327 .disjoint_anchors()
16328 .iter()
16329 .map(|selection| {
16330 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16331 })
16332 .collect::<Vec<_>>()
16333 };
16334
16335 if text.is_empty() {
16336 this.unmark_text(window, cx);
16337 } else {
16338 this.highlight_text::<InputComposition>(
16339 marked_ranges.clone(),
16340 HighlightStyle {
16341 underline: Some(UnderlineStyle {
16342 thickness: px(1.),
16343 color: None,
16344 wavy: false,
16345 }),
16346 ..Default::default()
16347 },
16348 cx,
16349 );
16350 }
16351
16352 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16353 let use_autoclose = this.use_autoclose;
16354 let use_auto_surround = this.use_auto_surround;
16355 this.set_use_autoclose(false);
16356 this.set_use_auto_surround(false);
16357 this.handle_input(text, window, cx);
16358 this.set_use_autoclose(use_autoclose);
16359 this.set_use_auto_surround(use_auto_surround);
16360
16361 if let Some(new_selected_range) = new_selected_range_utf16 {
16362 let snapshot = this.buffer.read(cx).read(cx);
16363 let new_selected_ranges = marked_ranges
16364 .into_iter()
16365 .map(|marked_range| {
16366 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16367 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16368 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16369 snapshot.clip_offset_utf16(new_start, Bias::Left)
16370 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16371 })
16372 .collect::<Vec<_>>();
16373
16374 drop(snapshot);
16375 this.change_selections(None, window, cx, |selections| {
16376 selections.select_ranges(new_selected_ranges)
16377 });
16378 }
16379 });
16380
16381 self.ime_transaction = self.ime_transaction.or(transaction);
16382 if let Some(transaction) = self.ime_transaction {
16383 self.buffer.update(cx, |buffer, cx| {
16384 buffer.group_until_transaction(transaction, cx);
16385 });
16386 }
16387
16388 if self.text_highlights::<InputComposition>(cx).is_none() {
16389 self.ime_transaction.take();
16390 }
16391 }
16392
16393 fn bounds_for_range(
16394 &mut self,
16395 range_utf16: Range<usize>,
16396 element_bounds: gpui::Bounds<Pixels>,
16397 window: &mut Window,
16398 cx: &mut Context<Self>,
16399 ) -> Option<gpui::Bounds<Pixels>> {
16400 let text_layout_details = self.text_layout_details(window);
16401 let gpui::Size {
16402 width: em_width,
16403 height: line_height,
16404 } = self.character_size(window);
16405
16406 let snapshot = self.snapshot(window, cx);
16407 let scroll_position = snapshot.scroll_position();
16408 let scroll_left = scroll_position.x * em_width;
16409
16410 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16411 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16412 + self.gutter_dimensions.width
16413 + self.gutter_dimensions.margin;
16414 let y = line_height * (start.row().as_f32() - scroll_position.y);
16415
16416 Some(Bounds {
16417 origin: element_bounds.origin + point(x, y),
16418 size: size(em_width, line_height),
16419 })
16420 }
16421
16422 fn character_index_for_point(
16423 &mut self,
16424 point: gpui::Point<Pixels>,
16425 _window: &mut Window,
16426 _cx: &mut Context<Self>,
16427 ) -> Option<usize> {
16428 let position_map = self.last_position_map.as_ref()?;
16429 if !position_map.text_hitbox.contains(&point) {
16430 return None;
16431 }
16432 let display_point = position_map.point_for_position(point).previous_valid;
16433 let anchor = position_map
16434 .snapshot
16435 .display_point_to_anchor(display_point, Bias::Left);
16436 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16437 Some(utf16_offset.0)
16438 }
16439}
16440
16441trait SelectionExt {
16442 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16443 fn spanned_rows(
16444 &self,
16445 include_end_if_at_line_start: bool,
16446 map: &DisplaySnapshot,
16447 ) -> Range<MultiBufferRow>;
16448}
16449
16450impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16451 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16452 let start = self
16453 .start
16454 .to_point(&map.buffer_snapshot)
16455 .to_display_point(map);
16456 let end = self
16457 .end
16458 .to_point(&map.buffer_snapshot)
16459 .to_display_point(map);
16460 if self.reversed {
16461 end..start
16462 } else {
16463 start..end
16464 }
16465 }
16466
16467 fn spanned_rows(
16468 &self,
16469 include_end_if_at_line_start: bool,
16470 map: &DisplaySnapshot,
16471 ) -> Range<MultiBufferRow> {
16472 let start = self.start.to_point(&map.buffer_snapshot);
16473 let mut end = self.end.to_point(&map.buffer_snapshot);
16474 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16475 end.row -= 1;
16476 }
16477
16478 let buffer_start = map.prev_line_boundary(start).0;
16479 let buffer_end = map.next_line_boundary(end).0;
16480 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16481 }
16482}
16483
16484impl<T: InvalidationRegion> InvalidationStack<T> {
16485 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16486 where
16487 S: Clone + ToOffset,
16488 {
16489 while let Some(region) = self.last() {
16490 let all_selections_inside_invalidation_ranges =
16491 if selections.len() == region.ranges().len() {
16492 selections
16493 .iter()
16494 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16495 .all(|(selection, invalidation_range)| {
16496 let head = selection.head().to_offset(buffer);
16497 invalidation_range.start <= head && invalidation_range.end >= head
16498 })
16499 } else {
16500 false
16501 };
16502
16503 if all_selections_inside_invalidation_ranges {
16504 break;
16505 } else {
16506 self.pop();
16507 }
16508 }
16509 }
16510}
16511
16512impl<T> Default for InvalidationStack<T> {
16513 fn default() -> Self {
16514 Self(Default::default())
16515 }
16516}
16517
16518impl<T> Deref for InvalidationStack<T> {
16519 type Target = Vec<T>;
16520
16521 fn deref(&self) -> &Self::Target {
16522 &self.0
16523 }
16524}
16525
16526impl<T> DerefMut for InvalidationStack<T> {
16527 fn deref_mut(&mut self) -> &mut Self::Target {
16528 &mut self.0
16529 }
16530}
16531
16532impl InvalidationRegion for SnippetState {
16533 fn ranges(&self) -> &[Range<Anchor>] {
16534 &self.ranges[self.active_index]
16535 }
16536}
16537
16538pub fn diagnostic_block_renderer(
16539 diagnostic: Diagnostic,
16540 max_message_rows: Option<u8>,
16541 allow_closing: bool,
16542 _is_valid: bool,
16543) -> RenderBlock {
16544 let (text_without_backticks, code_ranges) =
16545 highlight_diagnostic_message(&diagnostic, max_message_rows);
16546
16547 Arc::new(move |cx: &mut BlockContext| {
16548 let group_id: SharedString = cx.block_id.to_string().into();
16549
16550 let mut text_style = cx.window.text_style().clone();
16551 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16552 let theme_settings = ThemeSettings::get_global(cx);
16553 text_style.font_family = theme_settings.buffer_font.family.clone();
16554 text_style.font_style = theme_settings.buffer_font.style;
16555 text_style.font_features = theme_settings.buffer_font.features.clone();
16556 text_style.font_weight = theme_settings.buffer_font.weight;
16557
16558 let multi_line_diagnostic = diagnostic.message.contains('\n');
16559
16560 let buttons = |diagnostic: &Diagnostic| {
16561 if multi_line_diagnostic {
16562 v_flex()
16563 } else {
16564 h_flex()
16565 }
16566 .when(allow_closing, |div| {
16567 div.children(diagnostic.is_primary.then(|| {
16568 IconButton::new("close-block", IconName::XCircle)
16569 .icon_color(Color::Muted)
16570 .size(ButtonSize::Compact)
16571 .style(ButtonStyle::Transparent)
16572 .visible_on_hover(group_id.clone())
16573 .on_click(move |_click, window, cx| {
16574 window.dispatch_action(Box::new(Cancel), cx)
16575 })
16576 .tooltip(|window, cx| {
16577 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16578 })
16579 }))
16580 })
16581 .child(
16582 IconButton::new("copy-block", IconName::Copy)
16583 .icon_color(Color::Muted)
16584 .size(ButtonSize::Compact)
16585 .style(ButtonStyle::Transparent)
16586 .visible_on_hover(group_id.clone())
16587 .on_click({
16588 let message = diagnostic.message.clone();
16589 move |_click, _, cx| {
16590 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16591 }
16592 })
16593 .tooltip(Tooltip::text("Copy diagnostic message")),
16594 )
16595 };
16596
16597 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16598 AvailableSpace::min_size(),
16599 cx.window,
16600 cx.app,
16601 );
16602
16603 h_flex()
16604 .id(cx.block_id)
16605 .group(group_id.clone())
16606 .relative()
16607 .size_full()
16608 .block_mouse_down()
16609 .pl(cx.gutter_dimensions.width)
16610 .w(cx.max_width - cx.gutter_dimensions.full_width())
16611 .child(
16612 div()
16613 .flex()
16614 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16615 .flex_shrink(),
16616 )
16617 .child(buttons(&diagnostic))
16618 .child(div().flex().flex_shrink_0().child(
16619 StyledText::new(text_without_backticks.clone()).with_highlights(
16620 &text_style,
16621 code_ranges.iter().map(|range| {
16622 (
16623 range.clone(),
16624 HighlightStyle {
16625 font_weight: Some(FontWeight::BOLD),
16626 ..Default::default()
16627 },
16628 )
16629 }),
16630 ),
16631 ))
16632 .into_any_element()
16633 })
16634}
16635
16636fn inline_completion_edit_text(
16637 current_snapshot: &BufferSnapshot,
16638 edits: &[(Range<Anchor>, String)],
16639 edit_preview: &EditPreview,
16640 include_deletions: bool,
16641 cx: &App,
16642) -> HighlightedText {
16643 let edits = edits
16644 .iter()
16645 .map(|(anchor, text)| {
16646 (
16647 anchor.start.text_anchor..anchor.end.text_anchor,
16648 text.clone(),
16649 )
16650 })
16651 .collect::<Vec<_>>();
16652
16653 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16654}
16655
16656pub fn highlight_diagnostic_message(
16657 diagnostic: &Diagnostic,
16658 mut max_message_rows: Option<u8>,
16659) -> (SharedString, Vec<Range<usize>>) {
16660 let mut text_without_backticks = String::new();
16661 let mut code_ranges = Vec::new();
16662
16663 if let Some(source) = &diagnostic.source {
16664 text_without_backticks.push_str(source);
16665 code_ranges.push(0..source.len());
16666 text_without_backticks.push_str(": ");
16667 }
16668
16669 let mut prev_offset = 0;
16670 let mut in_code_block = false;
16671 let has_row_limit = max_message_rows.is_some();
16672 let mut newline_indices = diagnostic
16673 .message
16674 .match_indices('\n')
16675 .filter(|_| has_row_limit)
16676 .map(|(ix, _)| ix)
16677 .fuse()
16678 .peekable();
16679
16680 for (quote_ix, _) in diagnostic
16681 .message
16682 .match_indices('`')
16683 .chain([(diagnostic.message.len(), "")])
16684 {
16685 let mut first_newline_ix = None;
16686 let mut last_newline_ix = None;
16687 while let Some(newline_ix) = newline_indices.peek() {
16688 if *newline_ix < quote_ix {
16689 if first_newline_ix.is_none() {
16690 first_newline_ix = Some(*newline_ix);
16691 }
16692 last_newline_ix = Some(*newline_ix);
16693
16694 if let Some(rows_left) = &mut max_message_rows {
16695 if *rows_left == 0 {
16696 break;
16697 } else {
16698 *rows_left -= 1;
16699 }
16700 }
16701 let _ = newline_indices.next();
16702 } else {
16703 break;
16704 }
16705 }
16706 let prev_len = text_without_backticks.len();
16707 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16708 text_without_backticks.push_str(new_text);
16709 if in_code_block {
16710 code_ranges.push(prev_len..text_without_backticks.len());
16711 }
16712 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16713 in_code_block = !in_code_block;
16714 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16715 text_without_backticks.push_str("...");
16716 break;
16717 }
16718 }
16719
16720 (text_without_backticks.into(), code_ranges)
16721}
16722
16723fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16724 match severity {
16725 DiagnosticSeverity::ERROR => colors.error,
16726 DiagnosticSeverity::WARNING => colors.warning,
16727 DiagnosticSeverity::INFORMATION => colors.info,
16728 DiagnosticSeverity::HINT => colors.info,
16729 _ => colors.ignored,
16730 }
16731}
16732
16733pub fn styled_runs_for_code_label<'a>(
16734 label: &'a CodeLabel,
16735 syntax_theme: &'a theme::SyntaxTheme,
16736) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16737 let fade_out = HighlightStyle {
16738 fade_out: Some(0.35),
16739 ..Default::default()
16740 };
16741
16742 let mut prev_end = label.filter_range.end;
16743 label
16744 .runs
16745 .iter()
16746 .enumerate()
16747 .flat_map(move |(ix, (range, highlight_id))| {
16748 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16749 style
16750 } else {
16751 return Default::default();
16752 };
16753 let mut muted_style = style;
16754 muted_style.highlight(fade_out);
16755
16756 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16757 if range.start >= label.filter_range.end {
16758 if range.start > prev_end {
16759 runs.push((prev_end..range.start, fade_out));
16760 }
16761 runs.push((range.clone(), muted_style));
16762 } else if range.end <= label.filter_range.end {
16763 runs.push((range.clone(), style));
16764 } else {
16765 runs.push((range.start..label.filter_range.end, style));
16766 runs.push((label.filter_range.end..range.end, muted_style));
16767 }
16768 prev_end = cmp::max(prev_end, range.end);
16769
16770 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16771 runs.push((prev_end..label.text.len(), fade_out));
16772 }
16773
16774 runs
16775 })
16776}
16777
16778pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16779 let mut prev_index = 0;
16780 let mut prev_codepoint: Option<char> = None;
16781 text.char_indices()
16782 .chain([(text.len(), '\0')])
16783 .filter_map(move |(index, codepoint)| {
16784 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16785 let is_boundary = index == text.len()
16786 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16787 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16788 if is_boundary {
16789 let chunk = &text[prev_index..index];
16790 prev_index = index;
16791 Some(chunk)
16792 } else {
16793 None
16794 }
16795 })
16796}
16797
16798pub trait RangeToAnchorExt: Sized {
16799 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16800
16801 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16802 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16803 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16804 }
16805}
16806
16807impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16808 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16809 let start_offset = self.start.to_offset(snapshot);
16810 let end_offset = self.end.to_offset(snapshot);
16811 if start_offset == end_offset {
16812 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16813 } else {
16814 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16815 }
16816 }
16817}
16818
16819pub trait RowExt {
16820 fn as_f32(&self) -> f32;
16821
16822 fn next_row(&self) -> Self;
16823
16824 fn previous_row(&self) -> Self;
16825
16826 fn minus(&self, other: Self) -> u32;
16827}
16828
16829impl RowExt for DisplayRow {
16830 fn as_f32(&self) -> f32 {
16831 self.0 as f32
16832 }
16833
16834 fn next_row(&self) -> Self {
16835 Self(self.0 + 1)
16836 }
16837
16838 fn previous_row(&self) -> Self {
16839 Self(self.0.saturating_sub(1))
16840 }
16841
16842 fn minus(&self, other: Self) -> u32 {
16843 self.0 - other.0
16844 }
16845}
16846
16847impl RowExt for MultiBufferRow {
16848 fn as_f32(&self) -> f32 {
16849 self.0 as f32
16850 }
16851
16852 fn next_row(&self) -> Self {
16853 Self(self.0 + 1)
16854 }
16855
16856 fn previous_row(&self) -> Self {
16857 Self(self.0.saturating_sub(1))
16858 }
16859
16860 fn minus(&self, other: Self) -> u32 {
16861 self.0 - other.0
16862 }
16863}
16864
16865trait RowRangeExt {
16866 type Row;
16867
16868 fn len(&self) -> usize;
16869
16870 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16871}
16872
16873impl RowRangeExt for Range<MultiBufferRow> {
16874 type Row = MultiBufferRow;
16875
16876 fn len(&self) -> usize {
16877 (self.end.0 - self.start.0) as usize
16878 }
16879
16880 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16881 (self.start.0..self.end.0).map(MultiBufferRow)
16882 }
16883}
16884
16885impl RowRangeExt for Range<DisplayRow> {
16886 type Row = DisplayRow;
16887
16888 fn len(&self) -> usize {
16889 (self.end.0 - self.start.0) as usize
16890 }
16891
16892 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16893 (self.start.0..self.end.0).map(DisplayRow)
16894 }
16895}
16896
16897/// If select range has more than one line, we
16898/// just point the cursor to range.start.
16899fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16900 if range.start.row == range.end.row {
16901 range
16902 } else {
16903 range.start..range.start
16904 }
16905}
16906pub struct KillRing(ClipboardItem);
16907impl Global for KillRing {}
16908
16909const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16910
16911fn all_edits_insertions_or_deletions(
16912 edits: &Vec<(Range<Anchor>, String)>,
16913 snapshot: &MultiBufferSnapshot,
16914) -> bool {
16915 let mut all_insertions = true;
16916 let mut all_deletions = true;
16917
16918 for (range, new_text) in edits.iter() {
16919 let range_is_empty = range.to_offset(&snapshot).is_empty();
16920 let text_is_empty = new_text.is_empty();
16921
16922 if range_is_empty != text_is_empty {
16923 if range_is_empty {
16924 all_deletions = false;
16925 } else {
16926 all_insertions = false;
16927 }
16928 } else {
16929 return false;
16930 }
16931
16932 if !all_insertions && !all_deletions {
16933 return false;
16934 }
16935 }
16936 all_insertions || all_deletions
16937}