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 blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
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 client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use display_map::*;
60pub use display_map::{DisplayPoint, FoldPlaceholder};
61pub use editor_settings::{
62 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
63};
64pub use editor_settings_controls::*;
65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use futures::{future, FutureExt};
70use fuzzy::StringMatchCandidate;
71
72use code_context_menus::{
73 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
74 CompletionsMenu, ContextMenuOrigin,
75};
76use git::blame::GitBlame;
77use gpui::{
78 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
79 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
80 ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
81 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
82 HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
83 PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
84 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
85 WeakEntity, WeakFocusHandle, Window,
86};
87use highlight_matching_bracket::refresh_matching_bracket_highlights;
88use hover_popover::{hide_hover, HoverState};
89use indent_guides::ActiveIndentGuidesState;
90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
91pub use inline_completion::Direction;
92use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
93pub use items::MAX_TAB_TITLE_LEN;
94use itertools::Itertools;
95use language::{
96 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
97 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
98 CompletionDocumentation, CursorShape, Diagnostic, EditPredictionsMode, EditPreview,
99 HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
100 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
101};
102use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
103use linked_editing_ranges::refresh_linked_ranges;
104use mouse_context_menu::MouseContextMenu;
105pub use proposed_changes_editor::{
106 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
107};
108use similar::{ChangeTag, TextDiff};
109use std::iter::Peekable;
110use task::{ResolvedTask, TaskTemplate, TaskVariables};
111
112use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
113pub use lsp::CompletionContext;
114use lsp::{
115 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
116 LanguageServerId, LanguageServerName,
117};
118
119use language::BufferSnapshot;
120use movement::TextLayoutDetails;
121pub use multi_buffer::{
122 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
123 ToOffset, ToPoint,
124};
125use multi_buffer::{
126 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
127 ToOffsetUtf16,
128};
129use project::{
130 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
131 project_settings::{GitGutterSetting, ProjectSettings},
132 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
133 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
134};
135use rand::prelude::*;
136use rpc::{proto::*, ErrorExt};
137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
138use selections_collection::{
139 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
140};
141use serde::{Deserialize, Serialize};
142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
143use smallvec::SmallVec;
144use snippet::Snippet;
145use std::{
146 any::TypeId,
147 borrow::Cow,
148 cell::RefCell,
149 cmp::{self, Ordering, Reverse},
150 mem,
151 num::NonZeroU32,
152 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
153 path::{Path, PathBuf},
154 rc::Rc,
155 sync::Arc,
156 time::{Duration, Instant},
157};
158pub use sum_tree::Bias;
159use sum_tree::TreeMap;
160use text::{BufferId, OffsetUtf16, Rope};
161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::{find_url, find_url_from_range};
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188
189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
191
192pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
193pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
194 "edit_prediction_requires_modifier";
195
196pub fn render_parsed_markdown(
197 element_id: impl Into<ElementId>,
198 parsed: &language::ParsedMarkdown,
199 editor_style: &EditorStyle,
200 workspace: Option<WeakEntity<Workspace>>,
201 cx: &mut App,
202) -> InteractiveText {
203 let code_span_background_color = cx
204 .theme()
205 .colors()
206 .editor_document_highlight_read_background;
207
208 let highlights = gpui::combine_highlights(
209 parsed.highlights.iter().filter_map(|(range, highlight)| {
210 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
211 Some((range.clone(), highlight))
212 }),
213 parsed
214 .regions
215 .iter()
216 .zip(&parsed.region_ranges)
217 .filter_map(|(region, range)| {
218 if region.code {
219 Some((
220 range.clone(),
221 HighlightStyle {
222 background_color: Some(code_span_background_color),
223 ..Default::default()
224 },
225 ))
226 } else {
227 None
228 }
229 }),
230 );
231
232 let mut links = Vec::new();
233 let mut link_ranges = Vec::new();
234 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
235 if let Some(link) = region.link.clone() {
236 links.push(link);
237 link_ranges.push(range.clone());
238 }
239 }
240
241 InteractiveText::new(
242 element_id,
243 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
244 )
245 .on_click(
246 link_ranges,
247 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace
253 .open_abs_path(path.clone(), false, window, cx)
254 .detach();
255 });
256 }
257 }
258 },
259 )
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
263pub enum InlayId {
264 InlineCompletion(usize),
265 Hint(usize),
266}
267
268impl InlayId {
269 fn id(&self) -> usize {
270 match self {
271 Self::InlineCompletion(id) => *id,
272 Self::Hint(id) => *id,
273 }
274 }
275}
276
277enum DocumentHighlightRead {}
278enum DocumentHighlightWrite {}
279enum InputComposition {}
280
281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
282pub enum Navigated {
283 Yes,
284 No,
285}
286
287impl Navigated {
288 pub fn from_bool(yes: bool) -> Navigated {
289 if yes {
290 Navigated::Yes
291 } else {
292 Navigated::No
293 }
294 }
295}
296
297pub fn init_settings(cx: &mut App) {
298 EditorSettings::register(cx);
299}
300
301pub fn init(cx: &mut App) {
302 init_settings(cx);
303
304 workspace::register_project_item::<Editor>(cx);
305 workspace::FollowableViewRegistry::register::<Editor>(cx);
306 workspace::register_serializable_item::<Editor>(cx);
307
308 cx.observe_new(
309 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
310 workspace.register_action(Editor::new_file);
311 workspace.register_action(Editor::new_file_vertical);
312 workspace.register_action(Editor::new_file_horizontal);
313 workspace.register_action(Editor::cancel_language_server_work);
314 },
315 )
316 .detach();
317
318 cx.on_action(move |_: &workspace::NewFile, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(
322 Default::default(),
323 app_state,
324 cx,
325 |workspace, window, cx| {
326 Editor::new_file(workspace, &Default::default(), window, cx)
327 },
328 )
329 .detach();
330 }
331 });
332 cx.on_action(move |_: &workspace::NewWindow, cx| {
333 let app_state = workspace::AppState::global(cx);
334 if let Some(app_state) = app_state.upgrade() {
335 workspace::open_new(
336 Default::default(),
337 app_state,
338 cx,
339 |workspace, window, cx| {
340 cx.activate(true);
341 Editor::new_file(workspace, &Default::default(), window, cx)
342 },
343 )
344 .detach();
345 }
346 });
347}
348
349pub struct SearchWithinRange;
350
351trait InvalidationRegion {
352 fn ranges(&self) -> &[Range<Anchor>];
353}
354
355#[derive(Clone, Debug, PartialEq)]
356pub enum SelectPhase {
357 Begin {
358 position: DisplayPoint,
359 add: bool,
360 click_count: usize,
361 },
362 BeginColumnar {
363 position: DisplayPoint,
364 reset: bool,
365 goal_column: u32,
366 },
367 Extend {
368 position: DisplayPoint,
369 click_count: usize,
370 },
371 Update {
372 position: DisplayPoint,
373 goal_column: u32,
374 scroll_delta: gpui::Point<f32>,
375 },
376 End,
377}
378
379#[derive(Clone, Debug)]
380pub enum SelectMode {
381 Character,
382 Word(Range<Anchor>),
383 Line(Range<Anchor>),
384 All,
385}
386
387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
388pub enum EditorMode {
389 SingleLine { auto_width: bool },
390 AutoHeight { max_lines: usize },
391 Full,
392}
393
394#[derive(Copy, Clone, Debug)]
395pub enum SoftWrap {
396 /// Prefer not to wrap at all.
397 ///
398 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
399 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
400 GitDiff,
401 /// Prefer a single line generally, unless an overly long line is encountered.
402 None,
403 /// Soft wrap lines that exceed the editor width.
404 EditorWidth,
405 /// Soft wrap lines at the preferred line length.
406 Column(u32),
407 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
408 Bounded(u32),
409}
410
411#[derive(Clone)]
412pub struct EditorStyle {
413 pub background: Hsla,
414 pub local_player: PlayerColor,
415 pub text: TextStyle,
416 pub scrollbar_width: Pixels,
417 pub syntax: Arc<SyntaxTheme>,
418 pub status: StatusColors,
419 pub inlay_hints_style: HighlightStyle,
420 pub inline_completion_styles: InlineCompletionStyles,
421 pub unnecessary_code_fade: f32,
422}
423
424impl Default for EditorStyle {
425 fn default() -> Self {
426 Self {
427 background: Hsla::default(),
428 local_player: PlayerColor::default(),
429 text: TextStyle::default(),
430 scrollbar_width: Pixels::default(),
431 syntax: Default::default(),
432 // HACK: Status colors don't have a real default.
433 // We should look into removing the status colors from the editor
434 // style and retrieve them directly from the theme.
435 status: StatusColors::dark(),
436 inlay_hints_style: HighlightStyle::default(),
437 inline_completion_styles: InlineCompletionStyles {
438 insertion: HighlightStyle::default(),
439 whitespace: HighlightStyle::default(),
440 },
441 unnecessary_code_fade: Default::default(),
442 }
443 }
444}
445
446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
447 let show_background = language_settings::language_settings(None, None, cx)
448 .inlay_hints
449 .show_background;
450
451 HighlightStyle {
452 color: Some(cx.theme().status().hint),
453 background_color: show_background.then(|| cx.theme().status().hint_background),
454 ..HighlightStyle::default()
455 }
456}
457
458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
459 InlineCompletionStyles {
460 insertion: HighlightStyle {
461 color: Some(cx.theme().status().predictive),
462 ..HighlightStyle::default()
463 },
464 whitespace: HighlightStyle {
465 background_color: Some(cx.theme().status().created_background),
466 ..HighlightStyle::default()
467 },
468 }
469}
470
471type CompletionId = usize;
472
473pub(crate) enum EditDisplayMode {
474 TabAccept,
475 DiffPopover,
476 Inline,
477}
478
479enum InlineCompletion {
480 Edit {
481 edits: Vec<(Range<Anchor>, String)>,
482 edit_preview: Option<EditPreview>,
483 display_mode: EditDisplayMode,
484 snapshot: BufferSnapshot,
485 },
486 Move {
487 target: Anchor,
488 snapshot: BufferSnapshot,
489 },
490}
491
492struct InlineCompletionState {
493 inlay_ids: Vec<InlayId>,
494 completion: InlineCompletion,
495 completion_id: Option<SharedString>,
496 invalidation_range: Range<Anchor>,
497}
498
499enum EditPredictionSettings {
500 Disabled,
501 Enabled {
502 show_in_menu: bool,
503 preview_requires_modifier: bool,
504 },
505}
506
507impl EditPredictionSettings {
508 pub fn is_enabled(&self) -> bool {
509 match self {
510 EditPredictionSettings::Disabled => false,
511 EditPredictionSettings::Enabled { .. } => true,
512 }
513 }
514}
515
516enum InlineCompletionHighlight {}
517
518pub enum MenuInlineCompletionsPolicy {
519 Never,
520 ByProvider,
521}
522
523pub enum EditPredictionPreview {
524 /// Modifier is not pressed
525 Inactive,
526 /// Modifier pressed
527 Active {
528 previous_scroll_position: Option<ScrollAnchor>,
529 },
530}
531
532#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
533struct EditorActionId(usize);
534
535impl EditorActionId {
536 pub fn post_inc(&mut self) -> Self {
537 let answer = self.0;
538
539 *self = Self(answer + 1);
540
541 Self(answer)
542 }
543}
544
545// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
546// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
547
548type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
549type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
550
551#[derive(Default)]
552struct ScrollbarMarkerState {
553 scrollbar_size: Size<Pixels>,
554 dirty: bool,
555 markers: Arc<[PaintQuad]>,
556 pending_refresh: Option<Task<Result<()>>>,
557}
558
559impl ScrollbarMarkerState {
560 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
561 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
562 }
563}
564
565#[derive(Clone, Debug)]
566struct RunnableTasks {
567 templates: Vec<(TaskSourceKind, TaskTemplate)>,
568 offset: MultiBufferOffset,
569 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
570 column: u32,
571 // Values of all named captures, including those starting with '_'
572 extra_variables: HashMap<String, String>,
573 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
574 context_range: Range<BufferOffset>,
575}
576
577impl RunnableTasks {
578 fn resolve<'a>(
579 &'a self,
580 cx: &'a task::TaskContext,
581 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
582 self.templates.iter().filter_map(|(kind, template)| {
583 template
584 .resolve_task(&kind.to_id_base(), cx)
585 .map(|task| (kind.clone(), task))
586 })
587 }
588}
589
590#[derive(Clone)]
591struct ResolvedTasks {
592 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
593 position: Anchor,
594}
595#[derive(Copy, Clone, Debug)]
596struct MultiBufferOffset(usize);
597#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
598struct BufferOffset(usize);
599
600// Addons allow storing per-editor state in other crates (e.g. Vim)
601pub trait Addon: 'static {
602 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
603
604 fn render_buffer_header_controls(
605 &self,
606 _: &ExcerptInfo,
607 _: &Window,
608 _: &App,
609 ) -> Option<AnyElement> {
610 None
611 }
612
613 fn to_any(&self) -> &dyn std::any::Any;
614}
615
616#[derive(Debug, Copy, Clone, PartialEq, Eq)]
617pub enum IsVimMode {
618 Yes,
619 No,
620}
621
622/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
623///
624/// See the [module level documentation](self) for more information.
625pub struct Editor {
626 focus_handle: FocusHandle,
627 last_focused_descendant: Option<WeakFocusHandle>,
628 /// The text buffer being edited
629 buffer: Entity<MultiBuffer>,
630 /// Map of how text in the buffer should be displayed.
631 /// Handles soft wraps, folds, fake inlay text insertions, etc.
632 pub display_map: Entity<DisplayMap>,
633 pub selections: SelectionsCollection,
634 pub scroll_manager: ScrollManager,
635 /// When inline assist editors are linked, they all render cursors because
636 /// typing enters text into each of them, even the ones that aren't focused.
637 pub(crate) show_cursor_when_unfocused: bool,
638 columnar_selection_tail: Option<Anchor>,
639 add_selections_state: Option<AddSelectionsState>,
640 select_next_state: Option<SelectNextState>,
641 select_prev_state: Option<SelectNextState>,
642 selection_history: SelectionHistory,
643 autoclose_regions: Vec<AutocloseRegion>,
644 snippet_stack: InvalidationStack<SnippetState>,
645 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
646 ime_transaction: Option<TransactionId>,
647 active_diagnostics: Option<ActiveDiagnosticGroup>,
648 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
649
650 // TODO: make this a access method
651 pub project: Option<Entity<Project>>,
652 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
653 completion_provider: Option<Box<dyn CompletionProvider>>,
654 collaboration_hub: Option<Box<dyn CollaborationHub>>,
655 blink_manager: Entity<BlinkManager>,
656 show_cursor_names: bool,
657 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
658 pub show_local_selections: bool,
659 mode: EditorMode,
660 show_breadcrumbs: bool,
661 show_gutter: bool,
662 show_scrollbars: bool,
663 show_line_numbers: Option<bool>,
664 use_relative_line_numbers: Option<bool>,
665 show_git_diff_gutter: Option<bool>,
666 show_code_actions: Option<bool>,
667 show_runnables: Option<bool>,
668 show_wrap_guides: Option<bool>,
669 show_indent_guides: Option<bool>,
670 placeholder_text: Option<Arc<str>>,
671 highlight_order: usize,
672 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
673 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
674 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
675 scrollbar_marker_state: ScrollbarMarkerState,
676 active_indent_guides_state: ActiveIndentGuidesState,
677 nav_history: Option<ItemNavHistory>,
678 context_menu: RefCell<Option<CodeContextMenu>>,
679 mouse_context_menu: Option<MouseContextMenu>,
680 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
681 signature_help_state: SignatureHelpState,
682 auto_signature_help: Option<bool>,
683 find_all_references_task_sources: Vec<Anchor>,
684 next_completion_id: CompletionId,
685 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
686 code_actions_task: Option<Task<Result<()>>>,
687 document_highlights_task: Option<Task<()>>,
688 linked_editing_range_task: Option<Task<Option<()>>>,
689 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
690 pending_rename: Option<RenameState>,
691 searchable: bool,
692 cursor_shape: CursorShape,
693 current_line_highlight: Option<CurrentLineHighlight>,
694 collapse_matches: bool,
695 autoindent_mode: Option<AutoindentMode>,
696 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
697 input_enabled: bool,
698 use_modal_editing: bool,
699 read_only: bool,
700 leader_peer_id: Option<PeerId>,
701 remote_id: Option<ViewId>,
702 hover_state: HoverState,
703 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
704 gutter_hovered: bool,
705 hovered_link_state: Option<HoveredLinkState>,
706 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
707 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
708 active_inline_completion: Option<InlineCompletionState>,
709 /// Used to prevent flickering as the user types while the menu is open
710 stale_inline_completion_in_menu: Option<InlineCompletionState>,
711 edit_prediction_settings: EditPredictionSettings,
712 inline_completions_hidden_for_vim_mode: bool,
713 show_inline_completions_override: Option<bool>,
714 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
715 edit_prediction_preview: EditPredictionPreview,
716 inlay_hint_cache: InlayHintCache,
717 next_inlay_id: usize,
718 _subscriptions: Vec<Subscription>,
719 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
720 gutter_dimensions: GutterDimensions,
721 style: Option<EditorStyle>,
722 text_style_refinement: Option<TextStyleRefinement>,
723 next_editor_action_id: EditorActionId,
724 editor_actions:
725 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
726 use_autoclose: bool,
727 use_auto_surround: bool,
728 auto_replace_emoji_shortcode: bool,
729 show_git_blame_gutter: bool,
730 show_git_blame_inline: bool,
731 show_git_blame_inline_delay_task: Option<Task<()>>,
732 distinguish_unstaged_diff_hunks: bool,
733 git_blame_inline_enabled: bool,
734 serialize_dirty_buffers: bool,
735 show_selection_menu: Option<bool>,
736 blame: Option<Entity<GitBlame>>,
737 blame_subscription: Option<Subscription>,
738 custom_context_menu: Option<
739 Box<
740 dyn 'static
741 + Fn(
742 &mut Self,
743 DisplayPoint,
744 &mut Window,
745 &mut Context<Self>,
746 ) -> Option<Entity<ui::ContextMenu>>,
747 >,
748 >,
749 last_bounds: Option<Bounds<Pixels>>,
750 last_position_map: Option<Rc<PositionMap>>,
751 expect_bounds_change: Option<Bounds<Pixels>>,
752 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
753 tasks_update_task: Option<Task<()>>,
754 in_project_search: bool,
755 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
756 breadcrumb_header: Option<String>,
757 focused_block: Option<FocusedBlock>,
758 next_scroll_position: NextScrollCursorCenterTopBottom,
759 addons: HashMap<TypeId, Box<dyn Addon>>,
760 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
761 selection_mark_mode: bool,
762 toggle_fold_multiple_buffers: Task<()>,
763 _scroll_cursor_center_top_bottom_task: Task<()>,
764}
765
766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
767enum NextScrollCursorCenterTopBottom {
768 #[default]
769 Center,
770 Top,
771 Bottom,
772}
773
774impl NextScrollCursorCenterTopBottom {
775 fn next(&self) -> Self {
776 match self {
777 Self::Center => Self::Top,
778 Self::Top => Self::Bottom,
779 Self::Bottom => Self::Center,
780 }
781 }
782}
783
784#[derive(Clone)]
785pub struct EditorSnapshot {
786 pub mode: EditorMode,
787 show_gutter: bool,
788 show_line_numbers: Option<bool>,
789 show_git_diff_gutter: Option<bool>,
790 show_code_actions: Option<bool>,
791 show_runnables: Option<bool>,
792 git_blame_gutter_max_author_length: Option<usize>,
793 pub display_snapshot: DisplaySnapshot,
794 pub placeholder_text: Option<Arc<str>>,
795 is_focused: bool,
796 scroll_anchor: ScrollAnchor,
797 ongoing_scroll: OngoingScroll,
798 current_line_highlight: CurrentLineHighlight,
799 gutter_hovered: bool,
800}
801
802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
803
804#[derive(Default, Debug, Clone, Copy)]
805pub struct GutterDimensions {
806 pub left_padding: Pixels,
807 pub right_padding: Pixels,
808 pub width: Pixels,
809 pub margin: Pixels,
810 pub git_blame_entries_width: Option<Pixels>,
811}
812
813impl GutterDimensions {
814 /// The full width of the space taken up by the gutter.
815 pub fn full_width(&self) -> Pixels {
816 self.margin + self.width
817 }
818
819 /// The width of the space reserved for the fold indicators,
820 /// use alongside 'justify_end' and `gutter_width` to
821 /// right align content with the line numbers
822 pub fn fold_area_width(&self) -> Pixels {
823 self.margin + self.right_padding
824 }
825}
826
827#[derive(Debug)]
828pub struct RemoteSelection {
829 pub replica_id: ReplicaId,
830 pub selection: Selection<Anchor>,
831 pub cursor_shape: CursorShape,
832 pub peer_id: PeerId,
833 pub line_mode: bool,
834 pub participant_index: Option<ParticipantIndex>,
835 pub user_name: Option<SharedString>,
836}
837
838#[derive(Clone, Debug)]
839struct SelectionHistoryEntry {
840 selections: Arc<[Selection<Anchor>]>,
841 select_next_state: Option<SelectNextState>,
842 select_prev_state: Option<SelectNextState>,
843 add_selections_state: Option<AddSelectionsState>,
844}
845
846enum SelectionHistoryMode {
847 Normal,
848 Undoing,
849 Redoing,
850}
851
852#[derive(Clone, PartialEq, Eq, Hash)]
853struct HoveredCursor {
854 replica_id: u16,
855 selection_id: usize,
856}
857
858impl Default for SelectionHistoryMode {
859 fn default() -> Self {
860 Self::Normal
861 }
862}
863
864#[derive(Default)]
865struct SelectionHistory {
866 #[allow(clippy::type_complexity)]
867 selections_by_transaction:
868 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
869 mode: SelectionHistoryMode,
870 undo_stack: VecDeque<SelectionHistoryEntry>,
871 redo_stack: VecDeque<SelectionHistoryEntry>,
872}
873
874impl SelectionHistory {
875 fn insert_transaction(
876 &mut self,
877 transaction_id: TransactionId,
878 selections: Arc<[Selection<Anchor>]>,
879 ) {
880 self.selections_by_transaction
881 .insert(transaction_id, (selections, None));
882 }
883
884 #[allow(clippy::type_complexity)]
885 fn transaction(
886 &self,
887 transaction_id: TransactionId,
888 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
889 self.selections_by_transaction.get(&transaction_id)
890 }
891
892 #[allow(clippy::type_complexity)]
893 fn transaction_mut(
894 &mut self,
895 transaction_id: TransactionId,
896 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
897 self.selections_by_transaction.get_mut(&transaction_id)
898 }
899
900 fn push(&mut self, entry: SelectionHistoryEntry) {
901 if !entry.selections.is_empty() {
902 match self.mode {
903 SelectionHistoryMode::Normal => {
904 self.push_undo(entry);
905 self.redo_stack.clear();
906 }
907 SelectionHistoryMode::Undoing => self.push_redo(entry),
908 SelectionHistoryMode::Redoing => self.push_undo(entry),
909 }
910 }
911 }
912
913 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
914 if self
915 .undo_stack
916 .back()
917 .map_or(true, |e| e.selections != entry.selections)
918 {
919 self.undo_stack.push_back(entry);
920 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
921 self.undo_stack.pop_front();
922 }
923 }
924 }
925
926 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
927 if self
928 .redo_stack
929 .back()
930 .map_or(true, |e| e.selections != entry.selections)
931 {
932 self.redo_stack.push_back(entry);
933 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
934 self.redo_stack.pop_front();
935 }
936 }
937 }
938}
939
940struct RowHighlight {
941 index: usize,
942 range: Range<Anchor>,
943 color: Hsla,
944 should_autoscroll: bool,
945}
946
947#[derive(Clone, Debug)]
948struct AddSelectionsState {
949 above: bool,
950 stack: Vec<usize>,
951}
952
953#[derive(Clone)]
954struct SelectNextState {
955 query: AhoCorasick,
956 wordwise: bool,
957 done: bool,
958}
959
960impl std::fmt::Debug for SelectNextState {
961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962 f.debug_struct(std::any::type_name::<Self>())
963 .field("wordwise", &self.wordwise)
964 .field("done", &self.done)
965 .finish()
966 }
967}
968
969#[derive(Debug)]
970struct AutocloseRegion {
971 selection_id: usize,
972 range: Range<Anchor>,
973 pair: BracketPair,
974}
975
976#[derive(Debug)]
977struct SnippetState {
978 ranges: Vec<Vec<Range<Anchor>>>,
979 active_index: usize,
980 choices: Vec<Option<Vec<String>>>,
981}
982
983#[doc(hidden)]
984pub struct RenameState {
985 pub range: Range<Anchor>,
986 pub old_name: Arc<str>,
987 pub editor: Entity<Editor>,
988 block_id: CustomBlockId,
989}
990
991struct InvalidationStack<T>(Vec<T>);
992
993struct RegisteredInlineCompletionProvider {
994 provider: Arc<dyn InlineCompletionProviderHandle>,
995 _subscription: Subscription,
996}
997
998#[derive(Debug)]
999struct ActiveDiagnosticGroup {
1000 primary_range: Range<Anchor>,
1001 primary_message: String,
1002 group_id: usize,
1003 blocks: HashMap<CustomBlockId, Diagnostic>,
1004 is_valid: bool,
1005}
1006
1007#[derive(Serialize, Deserialize, Clone, Debug)]
1008pub struct ClipboardSelection {
1009 pub len: usize,
1010 pub is_entire_line: bool,
1011 pub first_line_indent: u32,
1012}
1013
1014#[derive(Debug)]
1015pub(crate) struct NavigationData {
1016 cursor_anchor: Anchor,
1017 cursor_position: Point,
1018 scroll_anchor: ScrollAnchor,
1019 scroll_top_row: u32,
1020}
1021
1022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1023pub enum GotoDefinitionKind {
1024 Symbol,
1025 Declaration,
1026 Type,
1027 Implementation,
1028}
1029
1030#[derive(Debug, Clone)]
1031enum InlayHintRefreshReason {
1032 Toggle(bool),
1033 SettingsChange(InlayHintSettings),
1034 NewLinesShown,
1035 BufferEdited(HashSet<Arc<Language>>),
1036 RefreshRequested,
1037 ExcerptsRemoved(Vec<ExcerptId>),
1038}
1039
1040impl InlayHintRefreshReason {
1041 fn description(&self) -> &'static str {
1042 match self {
1043 Self::Toggle(_) => "toggle",
1044 Self::SettingsChange(_) => "settings change",
1045 Self::NewLinesShown => "new lines shown",
1046 Self::BufferEdited(_) => "buffer edited",
1047 Self::RefreshRequested => "refresh requested",
1048 Self::ExcerptsRemoved(_) => "excerpts removed",
1049 }
1050 }
1051}
1052
1053pub enum FormatTarget {
1054 Buffers,
1055 Ranges(Vec<Range<MultiBufferPoint>>),
1056}
1057
1058pub(crate) struct FocusedBlock {
1059 id: BlockId,
1060 focus_handle: WeakFocusHandle,
1061}
1062
1063#[derive(Clone)]
1064enum JumpData {
1065 MultiBufferRow {
1066 row: MultiBufferRow,
1067 line_offset_from_top: u32,
1068 },
1069 MultiBufferPoint {
1070 excerpt_id: ExcerptId,
1071 position: Point,
1072 anchor: text::Anchor,
1073 line_offset_from_top: u32,
1074 },
1075}
1076
1077pub enum MultibufferSelectionMode {
1078 First,
1079 All,
1080}
1081
1082impl Editor {
1083 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1084 let buffer = cx.new(|cx| Buffer::local("", cx));
1085 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1086 Self::new(
1087 EditorMode::SingleLine { auto_width: false },
1088 buffer,
1089 None,
1090 false,
1091 window,
1092 cx,
1093 )
1094 }
1095
1096 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1097 let buffer = cx.new(|cx| Buffer::local("", cx));
1098 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1099 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1100 }
1101
1102 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1103 let buffer = cx.new(|cx| Buffer::local("", cx));
1104 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1105 Self::new(
1106 EditorMode::SingleLine { auto_width: true },
1107 buffer,
1108 None,
1109 false,
1110 window,
1111 cx,
1112 )
1113 }
1114
1115 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1116 let buffer = cx.new(|cx| Buffer::local("", cx));
1117 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1118 Self::new(
1119 EditorMode::AutoHeight { max_lines },
1120 buffer,
1121 None,
1122 false,
1123 window,
1124 cx,
1125 )
1126 }
1127
1128 pub fn for_buffer(
1129 buffer: Entity<Buffer>,
1130 project: Option<Entity<Project>>,
1131 window: &mut Window,
1132 cx: &mut Context<Self>,
1133 ) -> Self {
1134 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1135 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1136 }
1137
1138 pub fn for_multibuffer(
1139 buffer: Entity<MultiBuffer>,
1140 project: Option<Entity<Project>>,
1141 show_excerpt_controls: bool,
1142 window: &mut Window,
1143 cx: &mut Context<Self>,
1144 ) -> Self {
1145 Self::new(
1146 EditorMode::Full,
1147 buffer,
1148 project,
1149 show_excerpt_controls,
1150 window,
1151 cx,
1152 )
1153 }
1154
1155 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1156 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1157 let mut clone = Self::new(
1158 self.mode,
1159 self.buffer.clone(),
1160 self.project.clone(),
1161 show_excerpt_controls,
1162 window,
1163 cx,
1164 );
1165 self.display_map.update(cx, |display_map, cx| {
1166 let snapshot = display_map.snapshot(cx);
1167 clone.display_map.update(cx, |display_map, cx| {
1168 display_map.set_state(&snapshot, cx);
1169 });
1170 });
1171 clone.selections.clone_state(&self.selections);
1172 clone.scroll_manager.clone_state(&self.scroll_manager);
1173 clone.searchable = self.searchable;
1174 clone
1175 }
1176
1177 pub fn new(
1178 mode: EditorMode,
1179 buffer: Entity<MultiBuffer>,
1180 project: Option<Entity<Project>>,
1181 show_excerpt_controls: bool,
1182 window: &mut Window,
1183 cx: &mut Context<Self>,
1184 ) -> Self {
1185 let style = window.text_style();
1186 let font_size = style.font_size.to_pixels(window.rem_size());
1187 let editor = cx.entity().downgrade();
1188 let fold_placeholder = FoldPlaceholder {
1189 constrain_width: true,
1190 render: Arc::new(move |fold_id, fold_range, _, cx| {
1191 let editor = editor.clone();
1192 div()
1193 .id(fold_id)
1194 .bg(cx.theme().colors().ghost_element_background)
1195 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1196 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1197 .rounded_sm()
1198 .size_full()
1199 .cursor_pointer()
1200 .child("⋯")
1201 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1202 .on_click(move |_, _window, cx| {
1203 editor
1204 .update(cx, |editor, cx| {
1205 editor.unfold_ranges(
1206 &[fold_range.start..fold_range.end],
1207 true,
1208 false,
1209 cx,
1210 );
1211 cx.stop_propagation();
1212 })
1213 .ok();
1214 })
1215 .into_any()
1216 }),
1217 merge_adjacent: true,
1218 ..Default::default()
1219 };
1220 let display_map = cx.new(|cx| {
1221 DisplayMap::new(
1222 buffer.clone(),
1223 style.font(),
1224 font_size,
1225 None,
1226 show_excerpt_controls,
1227 FILE_HEADER_HEIGHT,
1228 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1229 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1230 fold_placeholder,
1231 cx,
1232 )
1233 });
1234
1235 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1236
1237 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1238
1239 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1240 .then(|| language_settings::SoftWrap::None);
1241
1242 let mut project_subscriptions = Vec::new();
1243 if mode == EditorMode::Full {
1244 if let Some(project) = project.as_ref() {
1245 if buffer.read(cx).is_singleton() {
1246 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1247 cx.emit(EditorEvent::TitleChanged);
1248 }));
1249 }
1250 project_subscriptions.push(cx.subscribe_in(
1251 project,
1252 window,
1253 |editor, _, event, window, cx| {
1254 if let project::Event::RefreshInlayHints = event {
1255 editor
1256 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1257 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1258 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1259 let focus_handle = editor.focus_handle(cx);
1260 if focus_handle.is_focused(window) {
1261 let snapshot = buffer.read(cx).snapshot();
1262 for (range, snippet) in snippet_edits {
1263 let editor_range =
1264 language::range_from_lsp(*range).to_offset(&snapshot);
1265 editor
1266 .insert_snippet(
1267 &[editor_range],
1268 snippet.clone(),
1269 window,
1270 cx,
1271 )
1272 .ok();
1273 }
1274 }
1275 }
1276 }
1277 },
1278 ));
1279 if let Some(task_inventory) = project
1280 .read(cx)
1281 .task_store()
1282 .read(cx)
1283 .task_inventory()
1284 .cloned()
1285 {
1286 project_subscriptions.push(cx.observe_in(
1287 &task_inventory,
1288 window,
1289 |editor, _, window, cx| {
1290 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1291 },
1292 ));
1293 }
1294 }
1295 }
1296
1297 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1298
1299 let inlay_hint_settings =
1300 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1301 let focus_handle = cx.focus_handle();
1302 cx.on_focus(&focus_handle, window, Self::handle_focus)
1303 .detach();
1304 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1305 .detach();
1306 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1307 .detach();
1308 cx.on_blur(&focus_handle, window, Self::handle_blur)
1309 .detach();
1310
1311 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1312 Some(false)
1313 } else {
1314 None
1315 };
1316
1317 let mut code_action_providers = Vec::new();
1318 if let Some(project) = project.clone() {
1319 get_uncommitted_diff_for_buffer(
1320 &project,
1321 buffer.read(cx).all_buffers(),
1322 buffer.clone(),
1323 cx,
1324 );
1325 code_action_providers.push(Rc::new(project) as Rc<_>);
1326 }
1327
1328 let mut this = Self {
1329 focus_handle,
1330 show_cursor_when_unfocused: false,
1331 last_focused_descendant: None,
1332 buffer: buffer.clone(),
1333 display_map: display_map.clone(),
1334 selections,
1335 scroll_manager: ScrollManager::new(cx),
1336 columnar_selection_tail: None,
1337 add_selections_state: None,
1338 select_next_state: None,
1339 select_prev_state: None,
1340 selection_history: Default::default(),
1341 autoclose_regions: Default::default(),
1342 snippet_stack: Default::default(),
1343 select_larger_syntax_node_stack: Vec::new(),
1344 ime_transaction: Default::default(),
1345 active_diagnostics: None,
1346 soft_wrap_mode_override,
1347 completion_provider: project.clone().map(|project| Box::new(project) as _),
1348 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1349 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1350 project,
1351 blink_manager: blink_manager.clone(),
1352 show_local_selections: true,
1353 show_scrollbars: true,
1354 mode,
1355 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1356 show_gutter: mode == EditorMode::Full,
1357 show_line_numbers: None,
1358 use_relative_line_numbers: None,
1359 show_git_diff_gutter: None,
1360 show_code_actions: None,
1361 show_runnables: None,
1362 show_wrap_guides: None,
1363 show_indent_guides,
1364 placeholder_text: None,
1365 highlight_order: 0,
1366 highlighted_rows: HashMap::default(),
1367 background_highlights: Default::default(),
1368 gutter_highlights: TreeMap::default(),
1369 scrollbar_marker_state: ScrollbarMarkerState::default(),
1370 active_indent_guides_state: ActiveIndentGuidesState::default(),
1371 nav_history: None,
1372 context_menu: RefCell::new(None),
1373 mouse_context_menu: None,
1374 completion_tasks: Default::default(),
1375 signature_help_state: SignatureHelpState::default(),
1376 auto_signature_help: None,
1377 find_all_references_task_sources: Vec::new(),
1378 next_completion_id: 0,
1379 next_inlay_id: 0,
1380 code_action_providers,
1381 available_code_actions: Default::default(),
1382 code_actions_task: Default::default(),
1383 document_highlights_task: Default::default(),
1384 linked_editing_range_task: Default::default(),
1385 pending_rename: Default::default(),
1386 searchable: true,
1387 cursor_shape: EditorSettings::get_global(cx)
1388 .cursor_shape
1389 .unwrap_or_default(),
1390 current_line_highlight: None,
1391 autoindent_mode: Some(AutoindentMode::EachLine),
1392 collapse_matches: false,
1393 workspace: None,
1394 input_enabled: true,
1395 use_modal_editing: mode == EditorMode::Full,
1396 read_only: false,
1397 use_autoclose: true,
1398 use_auto_surround: true,
1399 auto_replace_emoji_shortcode: false,
1400 leader_peer_id: None,
1401 remote_id: None,
1402 hover_state: Default::default(),
1403 pending_mouse_down: None,
1404 hovered_link_state: Default::default(),
1405 edit_prediction_provider: None,
1406 active_inline_completion: None,
1407 stale_inline_completion_in_menu: None,
1408 edit_prediction_preview: EditPredictionPreview::Inactive,
1409 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1410
1411 gutter_hovered: false,
1412 pixel_position_of_newest_cursor: None,
1413 last_bounds: None,
1414 last_position_map: None,
1415 expect_bounds_change: None,
1416 gutter_dimensions: GutterDimensions::default(),
1417 style: None,
1418 show_cursor_names: false,
1419 hovered_cursors: Default::default(),
1420 next_editor_action_id: EditorActionId::default(),
1421 editor_actions: Rc::default(),
1422 inline_completions_hidden_for_vim_mode: false,
1423 show_inline_completions_override: None,
1424 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1425 edit_prediction_settings: EditPredictionSettings::Disabled,
1426 custom_context_menu: None,
1427 show_git_blame_gutter: false,
1428 show_git_blame_inline: false,
1429 distinguish_unstaged_diff_hunks: false,
1430 show_selection_menu: None,
1431 show_git_blame_inline_delay_task: None,
1432 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1433 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1434 .session
1435 .restore_unsaved_buffers,
1436 blame: None,
1437 blame_subscription: None,
1438 tasks: Default::default(),
1439 _subscriptions: vec![
1440 cx.observe(&buffer, Self::on_buffer_changed),
1441 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1442 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1443 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1444 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1445 cx.observe_window_activation(window, |editor, window, cx| {
1446 let active = window.is_window_active();
1447 editor.blink_manager.update(cx, |blink_manager, cx| {
1448 if active {
1449 blink_manager.enable(cx);
1450 } else {
1451 blink_manager.disable(cx);
1452 }
1453 });
1454 }),
1455 ],
1456 tasks_update_task: None,
1457 linked_edit_ranges: Default::default(),
1458 in_project_search: false,
1459 previous_search_ranges: None,
1460 breadcrumb_header: None,
1461 focused_block: None,
1462 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1463 addons: HashMap::default(),
1464 registered_buffers: HashMap::default(),
1465 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1466 selection_mark_mode: false,
1467 toggle_fold_multiple_buffers: Task::ready(()),
1468 text_style_refinement: None,
1469 };
1470 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1471 this._subscriptions.extend(project_subscriptions);
1472
1473 this.end_selection(window, cx);
1474 this.scroll_manager.show_scrollbar(window, cx);
1475
1476 if mode == EditorMode::Full {
1477 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1478 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1479
1480 if this.git_blame_inline_enabled {
1481 this.git_blame_inline_enabled = true;
1482 this.start_git_blame_inline(false, window, cx);
1483 }
1484
1485 if let Some(buffer) = buffer.read(cx).as_singleton() {
1486 if let Some(project) = this.project.as_ref() {
1487 let lsp_store = project.read(cx).lsp_store();
1488 let handle = lsp_store.update(cx, |lsp_store, cx| {
1489 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1490 });
1491 this.registered_buffers
1492 .insert(buffer.read(cx).remote_id(), handle);
1493 }
1494 }
1495 }
1496
1497 this.report_editor_event("Editor Opened", None, cx);
1498 this
1499 }
1500
1501 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1502 self.mouse_context_menu
1503 .as_ref()
1504 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1505 }
1506
1507 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1508 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1509 }
1510
1511 fn key_context_internal(
1512 &self,
1513 has_active_edit_prediction: bool,
1514 window: &Window,
1515 cx: &App,
1516 ) -> KeyContext {
1517 let mut key_context = KeyContext::new_with_defaults();
1518 key_context.add("Editor");
1519 let mode = match self.mode {
1520 EditorMode::SingleLine { .. } => "single_line",
1521 EditorMode::AutoHeight { .. } => "auto_height",
1522 EditorMode::Full => "full",
1523 };
1524
1525 if EditorSettings::jupyter_enabled(cx) {
1526 key_context.add("jupyter");
1527 }
1528
1529 key_context.set("mode", mode);
1530 if self.pending_rename.is_some() {
1531 key_context.add("renaming");
1532 }
1533
1534 let mut showing_completions = false;
1535
1536 match self.context_menu.borrow().as_ref() {
1537 Some(CodeContextMenu::Completions(_)) => {
1538 key_context.add("menu");
1539 key_context.add("showing_completions");
1540 showing_completions = true;
1541 }
1542 Some(CodeContextMenu::CodeActions(_)) => {
1543 key_context.add("menu");
1544 key_context.add("showing_code_actions")
1545 }
1546 None => {}
1547 }
1548
1549 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1550 if !self.focus_handle(cx).contains_focused(window, cx)
1551 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1552 {
1553 for addon in self.addons.values() {
1554 addon.extend_key_context(&mut key_context, cx)
1555 }
1556 }
1557
1558 if let Some(extension) = self
1559 .buffer
1560 .read(cx)
1561 .as_singleton()
1562 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1563 {
1564 key_context.set("extension", extension.to_string());
1565 }
1566
1567 if has_active_edit_prediction {
1568 key_context.add("copilot_suggestion");
1569 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1570
1571 if showing_completions || self.edit_prediction_requires_modifier() {
1572 key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
1573 }
1574 }
1575
1576 if self.selection_mark_mode {
1577 key_context.add("selection_mode");
1578 }
1579
1580 key_context
1581 }
1582
1583 pub fn accept_edit_prediction_keybind(
1584 &self,
1585 window: &Window,
1586 cx: &App,
1587 ) -> AcceptEditPredictionBinding {
1588 let key_context = self.key_context_internal(true, window, cx);
1589 AcceptEditPredictionBinding(
1590 window
1591 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1592 .into_iter()
1593 .rev()
1594 .next(),
1595 )
1596 }
1597
1598 pub fn new_file(
1599 workspace: &mut Workspace,
1600 _: &workspace::NewFile,
1601 window: &mut Window,
1602 cx: &mut Context<Workspace>,
1603 ) {
1604 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1605 "Failed to create buffer",
1606 window,
1607 cx,
1608 |e, _, _| match e.error_code() {
1609 ErrorCode::RemoteUpgradeRequired => Some(format!(
1610 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1611 e.error_tag("required").unwrap_or("the latest version")
1612 )),
1613 _ => None,
1614 },
1615 );
1616 }
1617
1618 pub fn new_in_workspace(
1619 workspace: &mut Workspace,
1620 window: &mut Window,
1621 cx: &mut Context<Workspace>,
1622 ) -> Task<Result<Entity<Editor>>> {
1623 let project = workspace.project().clone();
1624 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1625
1626 cx.spawn_in(window, |workspace, mut cx| async move {
1627 let buffer = create.await?;
1628 workspace.update_in(&mut cx, |workspace, window, cx| {
1629 let editor =
1630 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1631 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1632 editor
1633 })
1634 })
1635 }
1636
1637 fn new_file_vertical(
1638 workspace: &mut Workspace,
1639 _: &workspace::NewFileSplitVertical,
1640 window: &mut Window,
1641 cx: &mut Context<Workspace>,
1642 ) {
1643 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1644 }
1645
1646 fn new_file_horizontal(
1647 workspace: &mut Workspace,
1648 _: &workspace::NewFileSplitHorizontal,
1649 window: &mut Window,
1650 cx: &mut Context<Workspace>,
1651 ) {
1652 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1653 }
1654
1655 fn new_file_in_direction(
1656 workspace: &mut Workspace,
1657 direction: SplitDirection,
1658 window: &mut Window,
1659 cx: &mut Context<Workspace>,
1660 ) {
1661 let project = workspace.project().clone();
1662 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1663
1664 cx.spawn_in(window, |workspace, mut cx| async move {
1665 let buffer = create.await?;
1666 workspace.update_in(&mut cx, move |workspace, window, cx| {
1667 workspace.split_item(
1668 direction,
1669 Box::new(
1670 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1671 ),
1672 window,
1673 cx,
1674 )
1675 })?;
1676 anyhow::Ok(())
1677 })
1678 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1679 match e.error_code() {
1680 ErrorCode::RemoteUpgradeRequired => Some(format!(
1681 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1682 e.error_tag("required").unwrap_or("the latest version")
1683 )),
1684 _ => None,
1685 }
1686 });
1687 }
1688
1689 pub fn leader_peer_id(&self) -> Option<PeerId> {
1690 self.leader_peer_id
1691 }
1692
1693 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1694 &self.buffer
1695 }
1696
1697 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1698 self.workspace.as_ref()?.0.upgrade()
1699 }
1700
1701 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1702 self.buffer().read(cx).title(cx)
1703 }
1704
1705 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1706 let git_blame_gutter_max_author_length = self
1707 .render_git_blame_gutter(cx)
1708 .then(|| {
1709 if let Some(blame) = self.blame.as_ref() {
1710 let max_author_length =
1711 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1712 Some(max_author_length)
1713 } else {
1714 None
1715 }
1716 })
1717 .flatten();
1718
1719 EditorSnapshot {
1720 mode: self.mode,
1721 show_gutter: self.show_gutter,
1722 show_line_numbers: self.show_line_numbers,
1723 show_git_diff_gutter: self.show_git_diff_gutter,
1724 show_code_actions: self.show_code_actions,
1725 show_runnables: self.show_runnables,
1726 git_blame_gutter_max_author_length,
1727 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1728 scroll_anchor: self.scroll_manager.anchor(),
1729 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1730 placeholder_text: self.placeholder_text.clone(),
1731 is_focused: self.focus_handle.is_focused(window),
1732 current_line_highlight: self
1733 .current_line_highlight
1734 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1735 gutter_hovered: self.gutter_hovered,
1736 }
1737 }
1738
1739 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1740 self.buffer.read(cx).language_at(point, cx)
1741 }
1742
1743 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1744 self.buffer.read(cx).read(cx).file_at(point).cloned()
1745 }
1746
1747 pub fn active_excerpt(
1748 &self,
1749 cx: &App,
1750 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1751 self.buffer
1752 .read(cx)
1753 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1754 }
1755
1756 pub fn mode(&self) -> EditorMode {
1757 self.mode
1758 }
1759
1760 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1761 self.collaboration_hub.as_deref()
1762 }
1763
1764 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1765 self.collaboration_hub = Some(hub);
1766 }
1767
1768 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1769 self.in_project_search = in_project_search;
1770 }
1771
1772 pub fn set_custom_context_menu(
1773 &mut self,
1774 f: impl 'static
1775 + Fn(
1776 &mut Self,
1777 DisplayPoint,
1778 &mut Window,
1779 &mut Context<Self>,
1780 ) -> Option<Entity<ui::ContextMenu>>,
1781 ) {
1782 self.custom_context_menu = Some(Box::new(f))
1783 }
1784
1785 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1786 self.completion_provider = provider;
1787 }
1788
1789 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1790 self.semantics_provider.clone()
1791 }
1792
1793 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1794 self.semantics_provider = provider;
1795 }
1796
1797 pub fn set_edit_prediction_provider<T>(
1798 &mut self,
1799 provider: Option<Entity<T>>,
1800 window: &mut Window,
1801 cx: &mut Context<Self>,
1802 ) where
1803 T: EditPredictionProvider,
1804 {
1805 self.edit_prediction_provider =
1806 provider.map(|provider| RegisteredInlineCompletionProvider {
1807 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1808 if this.focus_handle.is_focused(window) {
1809 this.update_visible_inline_completion(window, cx);
1810 }
1811 }),
1812 provider: Arc::new(provider),
1813 });
1814 self.refresh_inline_completion(false, false, window, cx);
1815 }
1816
1817 pub fn placeholder_text(&self) -> Option<&str> {
1818 self.placeholder_text.as_deref()
1819 }
1820
1821 pub fn set_placeholder_text(
1822 &mut self,
1823 placeholder_text: impl Into<Arc<str>>,
1824 cx: &mut Context<Self>,
1825 ) {
1826 let placeholder_text = Some(placeholder_text.into());
1827 if self.placeholder_text != placeholder_text {
1828 self.placeholder_text = placeholder_text;
1829 cx.notify();
1830 }
1831 }
1832
1833 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1834 self.cursor_shape = cursor_shape;
1835
1836 // Disrupt blink for immediate user feedback that the cursor shape has changed
1837 self.blink_manager.update(cx, BlinkManager::show_cursor);
1838
1839 cx.notify();
1840 }
1841
1842 pub fn set_current_line_highlight(
1843 &mut self,
1844 current_line_highlight: Option<CurrentLineHighlight>,
1845 ) {
1846 self.current_line_highlight = current_line_highlight;
1847 }
1848
1849 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1850 self.collapse_matches = collapse_matches;
1851 }
1852
1853 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1854 let buffers = self.buffer.read(cx).all_buffers();
1855 let Some(lsp_store) = self.lsp_store(cx) else {
1856 return;
1857 };
1858 lsp_store.update(cx, |lsp_store, cx| {
1859 for buffer in buffers {
1860 self.registered_buffers
1861 .entry(buffer.read(cx).remote_id())
1862 .or_insert_with(|| {
1863 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1864 });
1865 }
1866 })
1867 }
1868
1869 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1870 if self.collapse_matches {
1871 return range.start..range.start;
1872 }
1873 range.clone()
1874 }
1875
1876 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1877 if self.display_map.read(cx).clip_at_line_ends != clip {
1878 self.display_map
1879 .update(cx, |map, _| map.clip_at_line_ends = clip);
1880 }
1881 }
1882
1883 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1884 self.input_enabled = input_enabled;
1885 }
1886
1887 pub fn set_inline_completions_hidden_for_vim_mode(
1888 &mut self,
1889 hidden: bool,
1890 window: &mut Window,
1891 cx: &mut Context<Self>,
1892 ) {
1893 if hidden != self.inline_completions_hidden_for_vim_mode {
1894 self.inline_completions_hidden_for_vim_mode = hidden;
1895 if hidden {
1896 self.update_visible_inline_completion(window, cx);
1897 } else {
1898 self.refresh_inline_completion(true, false, window, cx);
1899 }
1900 }
1901 }
1902
1903 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1904 self.menu_inline_completions_policy = value;
1905 }
1906
1907 pub fn set_autoindent(&mut self, autoindent: bool) {
1908 if autoindent {
1909 self.autoindent_mode = Some(AutoindentMode::EachLine);
1910 } else {
1911 self.autoindent_mode = None;
1912 }
1913 }
1914
1915 pub fn read_only(&self, cx: &App) -> bool {
1916 self.read_only || self.buffer.read(cx).read_only()
1917 }
1918
1919 pub fn set_read_only(&mut self, read_only: bool) {
1920 self.read_only = read_only;
1921 }
1922
1923 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1924 self.use_autoclose = autoclose;
1925 }
1926
1927 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1928 self.use_auto_surround = auto_surround;
1929 }
1930
1931 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1932 self.auto_replace_emoji_shortcode = auto_replace;
1933 }
1934
1935 pub fn toggle_inline_completions(
1936 &mut self,
1937 _: &ToggleEditPrediction,
1938 window: &mut Window,
1939 cx: &mut Context<Self>,
1940 ) {
1941 if self.show_inline_completions_override.is_some() {
1942 self.set_show_edit_predictions(None, window, cx);
1943 } else {
1944 let show_edit_predictions = !self.edit_predictions_enabled();
1945 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1946 }
1947 }
1948
1949 pub fn set_show_edit_predictions(
1950 &mut self,
1951 show_edit_predictions: Option<bool>,
1952 window: &mut Window,
1953 cx: &mut Context<Self>,
1954 ) {
1955 self.show_inline_completions_override = show_edit_predictions;
1956 self.refresh_inline_completion(false, true, window, cx);
1957 }
1958
1959 fn inline_completions_disabled_in_scope(
1960 &self,
1961 buffer: &Entity<Buffer>,
1962 buffer_position: language::Anchor,
1963 cx: &App,
1964 ) -> bool {
1965 let snapshot = buffer.read(cx).snapshot();
1966 let settings = snapshot.settings_at(buffer_position, cx);
1967
1968 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1969 return false;
1970 };
1971
1972 scope.override_name().map_or(false, |scope_name| {
1973 settings
1974 .edit_predictions_disabled_in
1975 .iter()
1976 .any(|s| s == scope_name)
1977 })
1978 }
1979
1980 pub fn set_use_modal_editing(&mut self, to: bool) {
1981 self.use_modal_editing = to;
1982 }
1983
1984 pub fn use_modal_editing(&self) -> bool {
1985 self.use_modal_editing
1986 }
1987
1988 fn selections_did_change(
1989 &mut self,
1990 local: bool,
1991 old_cursor_position: &Anchor,
1992 show_completions: bool,
1993 window: &mut Window,
1994 cx: &mut Context<Self>,
1995 ) {
1996 window.invalidate_character_coordinates();
1997
1998 // Copy selections to primary selection buffer
1999 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2000 if local {
2001 let selections = self.selections.all::<usize>(cx);
2002 let buffer_handle = self.buffer.read(cx).read(cx);
2003
2004 let mut text = String::new();
2005 for (index, selection) in selections.iter().enumerate() {
2006 let text_for_selection = buffer_handle
2007 .text_for_range(selection.start..selection.end)
2008 .collect::<String>();
2009
2010 text.push_str(&text_for_selection);
2011 if index != selections.len() - 1 {
2012 text.push('\n');
2013 }
2014 }
2015
2016 if !text.is_empty() {
2017 cx.write_to_primary(ClipboardItem::new_string(text));
2018 }
2019 }
2020
2021 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2022 self.buffer.update(cx, |buffer, cx| {
2023 buffer.set_active_selections(
2024 &self.selections.disjoint_anchors(),
2025 self.selections.line_mode,
2026 self.cursor_shape,
2027 cx,
2028 )
2029 });
2030 }
2031 let display_map = self
2032 .display_map
2033 .update(cx, |display_map, cx| display_map.snapshot(cx));
2034 let buffer = &display_map.buffer_snapshot;
2035 self.add_selections_state = None;
2036 self.select_next_state = None;
2037 self.select_prev_state = None;
2038 self.select_larger_syntax_node_stack.clear();
2039 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2040 self.snippet_stack
2041 .invalidate(&self.selections.disjoint_anchors(), buffer);
2042 self.take_rename(false, window, cx);
2043
2044 let new_cursor_position = self.selections.newest_anchor().head();
2045
2046 self.push_to_nav_history(
2047 *old_cursor_position,
2048 Some(new_cursor_position.to_point(buffer)),
2049 cx,
2050 );
2051
2052 if local {
2053 let new_cursor_position = self.selections.newest_anchor().head();
2054 let mut context_menu = self.context_menu.borrow_mut();
2055 let completion_menu = match context_menu.as_ref() {
2056 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2057 _ => {
2058 *context_menu = None;
2059 None
2060 }
2061 };
2062 if let Some(buffer_id) = new_cursor_position.buffer_id {
2063 if !self.registered_buffers.contains_key(&buffer_id) {
2064 if let Some(lsp_store) = self.lsp_store(cx) {
2065 lsp_store.update(cx, |lsp_store, cx| {
2066 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2067 return;
2068 };
2069 self.registered_buffers.insert(
2070 buffer_id,
2071 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2072 );
2073 })
2074 }
2075 }
2076 }
2077
2078 if let Some(completion_menu) = completion_menu {
2079 let cursor_position = new_cursor_position.to_offset(buffer);
2080 let (word_range, kind) =
2081 buffer.surrounding_word(completion_menu.initial_position, true);
2082 if kind == Some(CharKind::Word)
2083 && word_range.to_inclusive().contains(&cursor_position)
2084 {
2085 let mut completion_menu = completion_menu.clone();
2086 drop(context_menu);
2087
2088 let query = Self::completion_query(buffer, cursor_position);
2089 cx.spawn(move |this, mut cx| async move {
2090 completion_menu
2091 .filter(query.as_deref(), cx.background_executor().clone())
2092 .await;
2093
2094 this.update(&mut cx, |this, cx| {
2095 let mut context_menu = this.context_menu.borrow_mut();
2096 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2097 else {
2098 return;
2099 };
2100
2101 if menu.id > completion_menu.id {
2102 return;
2103 }
2104
2105 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2106 drop(context_menu);
2107 cx.notify();
2108 })
2109 })
2110 .detach();
2111
2112 if show_completions {
2113 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2114 }
2115 } else {
2116 drop(context_menu);
2117 self.hide_context_menu(window, cx);
2118 }
2119 } else {
2120 drop(context_menu);
2121 }
2122
2123 hide_hover(self, cx);
2124
2125 if old_cursor_position.to_display_point(&display_map).row()
2126 != new_cursor_position.to_display_point(&display_map).row()
2127 {
2128 self.available_code_actions.take();
2129 }
2130 self.refresh_code_actions(window, cx);
2131 self.refresh_document_highlights(cx);
2132 refresh_matching_bracket_highlights(self, window, cx);
2133 self.update_visible_inline_completion(window, cx);
2134 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2135 if self.git_blame_inline_enabled {
2136 self.start_inline_blame_timer(window, cx);
2137 }
2138 }
2139
2140 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2141 cx.emit(EditorEvent::SelectionsChanged { local });
2142
2143 if self.selections.disjoint_anchors().len() == 1 {
2144 cx.emit(SearchEvent::ActiveMatchChanged)
2145 }
2146 cx.notify();
2147 }
2148
2149 pub fn change_selections<R>(
2150 &mut self,
2151 autoscroll: Option<Autoscroll>,
2152 window: &mut Window,
2153 cx: &mut Context<Self>,
2154 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2155 ) -> R {
2156 self.change_selections_inner(autoscroll, true, window, cx, change)
2157 }
2158
2159 pub fn change_selections_inner<R>(
2160 &mut self,
2161 autoscroll: Option<Autoscroll>,
2162 request_completions: bool,
2163 window: &mut Window,
2164 cx: &mut Context<Self>,
2165 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2166 ) -> R {
2167 let old_cursor_position = self.selections.newest_anchor().head();
2168 self.push_to_selection_history();
2169
2170 let (changed, result) = self.selections.change_with(cx, change);
2171
2172 if changed {
2173 if let Some(autoscroll) = autoscroll {
2174 self.request_autoscroll(autoscroll, cx);
2175 }
2176 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2177
2178 if self.should_open_signature_help_automatically(
2179 &old_cursor_position,
2180 self.signature_help_state.backspace_pressed(),
2181 cx,
2182 ) {
2183 self.show_signature_help(&ShowSignatureHelp, window, cx);
2184 }
2185 self.signature_help_state.set_backspace_pressed(false);
2186 }
2187
2188 result
2189 }
2190
2191 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2192 where
2193 I: IntoIterator<Item = (Range<S>, T)>,
2194 S: ToOffset,
2195 T: Into<Arc<str>>,
2196 {
2197 if self.read_only(cx) {
2198 return;
2199 }
2200
2201 self.buffer
2202 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2203 }
2204
2205 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2206 where
2207 I: IntoIterator<Item = (Range<S>, T)>,
2208 S: ToOffset,
2209 T: Into<Arc<str>>,
2210 {
2211 if self.read_only(cx) {
2212 return;
2213 }
2214
2215 self.buffer.update(cx, |buffer, cx| {
2216 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2217 });
2218 }
2219
2220 pub fn edit_with_block_indent<I, S, T>(
2221 &mut self,
2222 edits: I,
2223 original_indent_columns: Vec<u32>,
2224 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(
2236 edits,
2237 Some(AutoindentMode::Block {
2238 original_indent_columns,
2239 }),
2240 cx,
2241 )
2242 });
2243 }
2244
2245 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2246 self.hide_context_menu(window, cx);
2247
2248 match phase {
2249 SelectPhase::Begin {
2250 position,
2251 add,
2252 click_count,
2253 } => self.begin_selection(position, add, click_count, window, cx),
2254 SelectPhase::BeginColumnar {
2255 position,
2256 goal_column,
2257 reset,
2258 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2259 SelectPhase::Extend {
2260 position,
2261 click_count,
2262 } => self.extend_selection(position, click_count, window, cx),
2263 SelectPhase::Update {
2264 position,
2265 goal_column,
2266 scroll_delta,
2267 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2268 SelectPhase::End => self.end_selection(window, cx),
2269 }
2270 }
2271
2272 fn extend_selection(
2273 &mut self,
2274 position: DisplayPoint,
2275 click_count: usize,
2276 window: &mut Window,
2277 cx: &mut Context<Self>,
2278 ) {
2279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2280 let tail = self.selections.newest::<usize>(cx).tail();
2281 self.begin_selection(position, false, click_count, window, cx);
2282
2283 let position = position.to_offset(&display_map, Bias::Left);
2284 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2285
2286 let mut pending_selection = self
2287 .selections
2288 .pending_anchor()
2289 .expect("extend_selection not called with pending selection");
2290 if position >= tail {
2291 pending_selection.start = tail_anchor;
2292 } else {
2293 pending_selection.end = tail_anchor;
2294 pending_selection.reversed = true;
2295 }
2296
2297 let mut pending_mode = self.selections.pending_mode().unwrap();
2298 match &mut pending_mode {
2299 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2300 _ => {}
2301 }
2302
2303 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2304 s.set_pending(pending_selection, pending_mode)
2305 });
2306 }
2307
2308 fn begin_selection(
2309 &mut self,
2310 position: DisplayPoint,
2311 add: bool,
2312 click_count: usize,
2313 window: &mut Window,
2314 cx: &mut Context<Self>,
2315 ) {
2316 if !self.focus_handle.is_focused(window) {
2317 self.last_focused_descendant = None;
2318 window.focus(&self.focus_handle);
2319 }
2320
2321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2322 let buffer = &display_map.buffer_snapshot;
2323 let newest_selection = self.selections.newest_anchor().clone();
2324 let position = display_map.clip_point(position, Bias::Left);
2325
2326 let start;
2327 let end;
2328 let mode;
2329 let mut auto_scroll;
2330 match click_count {
2331 1 => {
2332 start = buffer.anchor_before(position.to_point(&display_map));
2333 end = start;
2334 mode = SelectMode::Character;
2335 auto_scroll = true;
2336 }
2337 2 => {
2338 let range = movement::surrounding_word(&display_map, position);
2339 start = buffer.anchor_before(range.start.to_point(&display_map));
2340 end = buffer.anchor_before(range.end.to_point(&display_map));
2341 mode = SelectMode::Word(start..end);
2342 auto_scroll = true;
2343 }
2344 3 => {
2345 let position = display_map
2346 .clip_point(position, Bias::Left)
2347 .to_point(&display_map);
2348 let line_start = display_map.prev_line_boundary(position).0;
2349 let next_line_start = buffer.clip_point(
2350 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2351 Bias::Left,
2352 );
2353 start = buffer.anchor_before(line_start);
2354 end = buffer.anchor_before(next_line_start);
2355 mode = SelectMode::Line(start..end);
2356 auto_scroll = true;
2357 }
2358 _ => {
2359 start = buffer.anchor_before(0);
2360 end = buffer.anchor_before(buffer.len());
2361 mode = SelectMode::All;
2362 auto_scroll = false;
2363 }
2364 }
2365 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2366
2367 let point_to_delete: Option<usize> = {
2368 let selected_points: Vec<Selection<Point>> =
2369 self.selections.disjoint_in_range(start..end, cx);
2370
2371 if !add || click_count > 1 {
2372 None
2373 } else if !selected_points.is_empty() {
2374 Some(selected_points[0].id)
2375 } else {
2376 let clicked_point_already_selected =
2377 self.selections.disjoint.iter().find(|selection| {
2378 selection.start.to_point(buffer) == start.to_point(buffer)
2379 || selection.end.to_point(buffer) == end.to_point(buffer)
2380 });
2381
2382 clicked_point_already_selected.map(|selection| selection.id)
2383 }
2384 };
2385
2386 let selections_count = self.selections.count();
2387
2388 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2389 if let Some(point_to_delete) = point_to_delete {
2390 s.delete(point_to_delete);
2391
2392 if selections_count == 1 {
2393 s.set_pending_anchor_range(start..end, mode);
2394 }
2395 } else {
2396 if !add {
2397 s.clear_disjoint();
2398 } else if click_count > 1 {
2399 s.delete(newest_selection.id)
2400 }
2401
2402 s.set_pending_anchor_range(start..end, mode);
2403 }
2404 });
2405 }
2406
2407 fn begin_columnar_selection(
2408 &mut self,
2409 position: DisplayPoint,
2410 goal_column: u32,
2411 reset: bool,
2412 window: &mut Window,
2413 cx: &mut Context<Self>,
2414 ) {
2415 if !self.focus_handle.is_focused(window) {
2416 self.last_focused_descendant = None;
2417 window.focus(&self.focus_handle);
2418 }
2419
2420 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2421
2422 if reset {
2423 let pointer_position = display_map
2424 .buffer_snapshot
2425 .anchor_before(position.to_point(&display_map));
2426
2427 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2428 s.clear_disjoint();
2429 s.set_pending_anchor_range(
2430 pointer_position..pointer_position,
2431 SelectMode::Character,
2432 );
2433 });
2434 }
2435
2436 let tail = self.selections.newest::<Point>(cx).tail();
2437 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2438
2439 if !reset {
2440 self.select_columns(
2441 tail.to_display_point(&display_map),
2442 position,
2443 goal_column,
2444 &display_map,
2445 window,
2446 cx,
2447 );
2448 }
2449 }
2450
2451 fn update_selection(
2452 &mut self,
2453 position: DisplayPoint,
2454 goal_column: u32,
2455 scroll_delta: gpui::Point<f32>,
2456 window: &mut Window,
2457 cx: &mut Context<Self>,
2458 ) {
2459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2460
2461 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2462 let tail = tail.to_display_point(&display_map);
2463 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2464 } else if let Some(mut pending) = self.selections.pending_anchor() {
2465 let buffer = self.buffer.read(cx).snapshot(cx);
2466 let head;
2467 let tail;
2468 let mode = self.selections.pending_mode().unwrap();
2469 match &mode {
2470 SelectMode::Character => {
2471 head = position.to_point(&display_map);
2472 tail = pending.tail().to_point(&buffer);
2473 }
2474 SelectMode::Word(original_range) => {
2475 let original_display_range = original_range.start.to_display_point(&display_map)
2476 ..original_range.end.to_display_point(&display_map);
2477 let original_buffer_range = original_display_range.start.to_point(&display_map)
2478 ..original_display_range.end.to_point(&display_map);
2479 if movement::is_inside_word(&display_map, position)
2480 || original_display_range.contains(&position)
2481 {
2482 let word_range = movement::surrounding_word(&display_map, position);
2483 if word_range.start < original_display_range.start {
2484 head = word_range.start.to_point(&display_map);
2485 } else {
2486 head = word_range.end.to_point(&display_map);
2487 }
2488 } else {
2489 head = position.to_point(&display_map);
2490 }
2491
2492 if head <= original_buffer_range.start {
2493 tail = original_buffer_range.end;
2494 } else {
2495 tail = original_buffer_range.start;
2496 }
2497 }
2498 SelectMode::Line(original_range) => {
2499 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2500
2501 let position = display_map
2502 .clip_point(position, Bias::Left)
2503 .to_point(&display_map);
2504 let line_start = display_map.prev_line_boundary(position).0;
2505 let next_line_start = buffer.clip_point(
2506 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2507 Bias::Left,
2508 );
2509
2510 if line_start < original_range.start {
2511 head = line_start
2512 } else {
2513 head = next_line_start
2514 }
2515
2516 if head <= original_range.start {
2517 tail = original_range.end;
2518 } else {
2519 tail = original_range.start;
2520 }
2521 }
2522 SelectMode::All => {
2523 return;
2524 }
2525 };
2526
2527 if head < tail {
2528 pending.start = buffer.anchor_before(head);
2529 pending.end = buffer.anchor_before(tail);
2530 pending.reversed = true;
2531 } else {
2532 pending.start = buffer.anchor_before(tail);
2533 pending.end = buffer.anchor_before(head);
2534 pending.reversed = false;
2535 }
2536
2537 self.change_selections(None, window, cx, |s| {
2538 s.set_pending(pending, mode);
2539 });
2540 } else {
2541 log::error!("update_selection dispatched with no pending selection");
2542 return;
2543 }
2544
2545 self.apply_scroll_delta(scroll_delta, window, cx);
2546 cx.notify();
2547 }
2548
2549 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2550 self.columnar_selection_tail.take();
2551 if self.selections.pending_anchor().is_some() {
2552 let selections = self.selections.all::<usize>(cx);
2553 self.change_selections(None, window, cx, |s| {
2554 s.select(selections);
2555 s.clear_pending();
2556 });
2557 }
2558 }
2559
2560 fn select_columns(
2561 &mut self,
2562 tail: DisplayPoint,
2563 head: DisplayPoint,
2564 goal_column: u32,
2565 display_map: &DisplaySnapshot,
2566 window: &mut Window,
2567 cx: &mut Context<Self>,
2568 ) {
2569 let start_row = cmp::min(tail.row(), head.row());
2570 let end_row = cmp::max(tail.row(), head.row());
2571 let start_column = cmp::min(tail.column(), goal_column);
2572 let end_column = cmp::max(tail.column(), goal_column);
2573 let reversed = start_column < tail.column();
2574
2575 let selection_ranges = (start_row.0..=end_row.0)
2576 .map(DisplayRow)
2577 .filter_map(|row| {
2578 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2579 let start = display_map
2580 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2581 .to_point(display_map);
2582 let end = display_map
2583 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2584 .to_point(display_map);
2585 if reversed {
2586 Some(end..start)
2587 } else {
2588 Some(start..end)
2589 }
2590 } else {
2591 None
2592 }
2593 })
2594 .collect::<Vec<_>>();
2595
2596 self.change_selections(None, window, cx, |s| {
2597 s.select_ranges(selection_ranges);
2598 });
2599 cx.notify();
2600 }
2601
2602 pub fn has_pending_nonempty_selection(&self) -> bool {
2603 let pending_nonempty_selection = match self.selections.pending_anchor() {
2604 Some(Selection { start, end, .. }) => start != end,
2605 None => false,
2606 };
2607
2608 pending_nonempty_selection
2609 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2610 }
2611
2612 pub fn has_pending_selection(&self) -> bool {
2613 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2614 }
2615
2616 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2617 self.selection_mark_mode = false;
2618
2619 if self.clear_expanded_diff_hunks(cx) {
2620 cx.notify();
2621 return;
2622 }
2623 if self.dismiss_menus_and_popups(true, window, cx) {
2624 return;
2625 }
2626
2627 if self.mode == EditorMode::Full
2628 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2629 {
2630 return;
2631 }
2632
2633 cx.propagate();
2634 }
2635
2636 pub fn dismiss_menus_and_popups(
2637 &mut self,
2638 is_user_requested: bool,
2639 window: &mut Window,
2640 cx: &mut Context<Self>,
2641 ) -> bool {
2642 if self.take_rename(false, window, cx).is_some() {
2643 return true;
2644 }
2645
2646 if hide_hover(self, cx) {
2647 return true;
2648 }
2649
2650 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2651 return true;
2652 }
2653
2654 if self.hide_context_menu(window, cx).is_some() {
2655 return true;
2656 }
2657
2658 if self.mouse_context_menu.take().is_some() {
2659 return true;
2660 }
2661
2662 if is_user_requested && self.discard_inline_completion(true, cx) {
2663 return true;
2664 }
2665
2666 if self.snippet_stack.pop().is_some() {
2667 return true;
2668 }
2669
2670 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2671 self.dismiss_diagnostics(cx);
2672 return true;
2673 }
2674
2675 false
2676 }
2677
2678 fn linked_editing_ranges_for(
2679 &self,
2680 selection: Range<text::Anchor>,
2681 cx: &App,
2682 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2683 if self.linked_edit_ranges.is_empty() {
2684 return None;
2685 }
2686 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2687 selection.end.buffer_id.and_then(|end_buffer_id| {
2688 if selection.start.buffer_id != Some(end_buffer_id) {
2689 return None;
2690 }
2691 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2692 let snapshot = buffer.read(cx).snapshot();
2693 self.linked_edit_ranges
2694 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2695 .map(|ranges| (ranges, snapshot, buffer))
2696 })?;
2697 use text::ToOffset as TO;
2698 // find offset from the start of current range to current cursor position
2699 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2700
2701 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2702 let start_difference = start_offset - start_byte_offset;
2703 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2704 let end_difference = end_offset - start_byte_offset;
2705 // Current range has associated linked ranges.
2706 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2707 for range in linked_ranges.iter() {
2708 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2709 let end_offset = start_offset + end_difference;
2710 let start_offset = start_offset + start_difference;
2711 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2712 continue;
2713 }
2714 if self.selections.disjoint_anchor_ranges().any(|s| {
2715 if s.start.buffer_id != selection.start.buffer_id
2716 || s.end.buffer_id != selection.end.buffer_id
2717 {
2718 return false;
2719 }
2720 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2721 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2722 }) {
2723 continue;
2724 }
2725 let start = buffer_snapshot.anchor_after(start_offset);
2726 let end = buffer_snapshot.anchor_after(end_offset);
2727 linked_edits
2728 .entry(buffer.clone())
2729 .or_default()
2730 .push(start..end);
2731 }
2732 Some(linked_edits)
2733 }
2734
2735 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2736 let text: Arc<str> = text.into();
2737
2738 if self.read_only(cx) {
2739 return;
2740 }
2741
2742 let selections = self.selections.all_adjusted(cx);
2743 let mut bracket_inserted = false;
2744 let mut edits = Vec::new();
2745 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2746 let mut new_selections = Vec::with_capacity(selections.len());
2747 let mut new_autoclose_regions = Vec::new();
2748 let snapshot = self.buffer.read(cx).read(cx);
2749
2750 for (selection, autoclose_region) in
2751 self.selections_with_autoclose_regions(selections, &snapshot)
2752 {
2753 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2754 // Determine if the inserted text matches the opening or closing
2755 // bracket of any of this language's bracket pairs.
2756 let mut bracket_pair = None;
2757 let mut is_bracket_pair_start = false;
2758 let mut is_bracket_pair_end = false;
2759 if !text.is_empty() {
2760 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2761 // and they are removing the character that triggered IME popup.
2762 for (pair, enabled) in scope.brackets() {
2763 if !pair.close && !pair.surround {
2764 continue;
2765 }
2766
2767 if enabled && pair.start.ends_with(text.as_ref()) {
2768 let prefix_len = pair.start.len() - text.len();
2769 let preceding_text_matches_prefix = prefix_len == 0
2770 || (selection.start.column >= (prefix_len as u32)
2771 && snapshot.contains_str_at(
2772 Point::new(
2773 selection.start.row,
2774 selection.start.column - (prefix_len as u32),
2775 ),
2776 &pair.start[..prefix_len],
2777 ));
2778 if preceding_text_matches_prefix {
2779 bracket_pair = Some(pair.clone());
2780 is_bracket_pair_start = true;
2781 break;
2782 }
2783 }
2784 if pair.end.as_str() == text.as_ref() {
2785 bracket_pair = Some(pair.clone());
2786 is_bracket_pair_end = true;
2787 break;
2788 }
2789 }
2790 }
2791
2792 if let Some(bracket_pair) = bracket_pair {
2793 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2794 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2795 let auto_surround =
2796 self.use_auto_surround && snapshot_settings.use_auto_surround;
2797 if selection.is_empty() {
2798 if is_bracket_pair_start {
2799 // If the inserted text is a suffix of an opening bracket and the
2800 // selection is preceded by the rest of the opening bracket, then
2801 // insert the closing bracket.
2802 let following_text_allows_autoclose = snapshot
2803 .chars_at(selection.start)
2804 .next()
2805 .map_or(true, |c| scope.should_autoclose_before(c));
2806
2807 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2808 && bracket_pair.start.len() == 1
2809 {
2810 let target = bracket_pair.start.chars().next().unwrap();
2811 let current_line_count = snapshot
2812 .reversed_chars_at(selection.start)
2813 .take_while(|&c| c != '\n')
2814 .filter(|&c| c == target)
2815 .count();
2816 current_line_count % 2 == 1
2817 } else {
2818 false
2819 };
2820
2821 if autoclose
2822 && bracket_pair.close
2823 && following_text_allows_autoclose
2824 && !is_closing_quote
2825 {
2826 let anchor = snapshot.anchor_before(selection.end);
2827 new_selections.push((selection.map(|_| anchor), text.len()));
2828 new_autoclose_regions.push((
2829 anchor,
2830 text.len(),
2831 selection.id,
2832 bracket_pair.clone(),
2833 ));
2834 edits.push((
2835 selection.range(),
2836 format!("{}{}", text, bracket_pair.end).into(),
2837 ));
2838 bracket_inserted = true;
2839 continue;
2840 }
2841 }
2842
2843 if let Some(region) = autoclose_region {
2844 // If the selection is followed by an auto-inserted closing bracket,
2845 // then don't insert that closing bracket again; just move the selection
2846 // past the closing bracket.
2847 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2848 && text.as_ref() == region.pair.end.as_str();
2849 if should_skip {
2850 let anchor = snapshot.anchor_after(selection.end);
2851 new_selections
2852 .push((selection.map(|_| anchor), region.pair.end.len()));
2853 continue;
2854 }
2855 }
2856
2857 let always_treat_brackets_as_autoclosed = snapshot
2858 .settings_at(selection.start, cx)
2859 .always_treat_brackets_as_autoclosed;
2860 if always_treat_brackets_as_autoclosed
2861 && is_bracket_pair_end
2862 && snapshot.contains_str_at(selection.end, text.as_ref())
2863 {
2864 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2865 // and the inserted text is a closing bracket and the selection is followed
2866 // by the closing bracket then move the selection past the closing bracket.
2867 let anchor = snapshot.anchor_after(selection.end);
2868 new_selections.push((selection.map(|_| anchor), text.len()));
2869 continue;
2870 }
2871 }
2872 // If an opening bracket is 1 character long and is typed while
2873 // text is selected, then surround that text with the bracket pair.
2874 else if auto_surround
2875 && bracket_pair.surround
2876 && is_bracket_pair_start
2877 && bracket_pair.start.chars().count() == 1
2878 {
2879 edits.push((selection.start..selection.start, text.clone()));
2880 edits.push((
2881 selection.end..selection.end,
2882 bracket_pair.end.as_str().into(),
2883 ));
2884 bracket_inserted = true;
2885 new_selections.push((
2886 Selection {
2887 id: selection.id,
2888 start: snapshot.anchor_after(selection.start),
2889 end: snapshot.anchor_before(selection.end),
2890 reversed: selection.reversed,
2891 goal: selection.goal,
2892 },
2893 0,
2894 ));
2895 continue;
2896 }
2897 }
2898 }
2899
2900 if self.auto_replace_emoji_shortcode
2901 && selection.is_empty()
2902 && text.as_ref().ends_with(':')
2903 {
2904 if let Some(possible_emoji_short_code) =
2905 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2906 {
2907 if !possible_emoji_short_code.is_empty() {
2908 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2909 let emoji_shortcode_start = Point::new(
2910 selection.start.row,
2911 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2912 );
2913
2914 // Remove shortcode from buffer
2915 edits.push((
2916 emoji_shortcode_start..selection.start,
2917 "".to_string().into(),
2918 ));
2919 new_selections.push((
2920 Selection {
2921 id: selection.id,
2922 start: snapshot.anchor_after(emoji_shortcode_start),
2923 end: snapshot.anchor_before(selection.start),
2924 reversed: selection.reversed,
2925 goal: selection.goal,
2926 },
2927 0,
2928 ));
2929
2930 // Insert emoji
2931 let selection_start_anchor = snapshot.anchor_after(selection.start);
2932 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2933 edits.push((selection.start..selection.end, emoji.to_string().into()));
2934
2935 continue;
2936 }
2937 }
2938 }
2939 }
2940
2941 // If not handling any auto-close operation, then just replace the selected
2942 // text with the given input and move the selection to the end of the
2943 // newly inserted text.
2944 let anchor = snapshot.anchor_after(selection.end);
2945 if !self.linked_edit_ranges.is_empty() {
2946 let start_anchor = snapshot.anchor_before(selection.start);
2947
2948 let is_word_char = text.chars().next().map_or(true, |char| {
2949 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2950 classifier.is_word(char)
2951 });
2952
2953 if is_word_char {
2954 if let Some(ranges) = self
2955 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2956 {
2957 for (buffer, edits) in ranges {
2958 linked_edits
2959 .entry(buffer.clone())
2960 .or_default()
2961 .extend(edits.into_iter().map(|range| (range, text.clone())));
2962 }
2963 }
2964 }
2965 }
2966
2967 new_selections.push((selection.map(|_| anchor), 0));
2968 edits.push((selection.start..selection.end, text.clone()));
2969 }
2970
2971 drop(snapshot);
2972
2973 self.transact(window, cx, |this, window, cx| {
2974 this.buffer.update(cx, |buffer, cx| {
2975 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2976 });
2977 for (buffer, edits) in linked_edits {
2978 buffer.update(cx, |buffer, cx| {
2979 let snapshot = buffer.snapshot();
2980 let edits = edits
2981 .into_iter()
2982 .map(|(range, text)| {
2983 use text::ToPoint as TP;
2984 let end_point = TP::to_point(&range.end, &snapshot);
2985 let start_point = TP::to_point(&range.start, &snapshot);
2986 (start_point..end_point, text)
2987 })
2988 .sorted_by_key(|(range, _)| range.start)
2989 .collect::<Vec<_>>();
2990 buffer.edit(edits, None, cx);
2991 })
2992 }
2993 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2994 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2995 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2996 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2997 .zip(new_selection_deltas)
2998 .map(|(selection, delta)| Selection {
2999 id: selection.id,
3000 start: selection.start + delta,
3001 end: selection.end + delta,
3002 reversed: selection.reversed,
3003 goal: SelectionGoal::None,
3004 })
3005 .collect::<Vec<_>>();
3006
3007 let mut i = 0;
3008 for (position, delta, selection_id, pair) in new_autoclose_regions {
3009 let position = position.to_offset(&map.buffer_snapshot) + delta;
3010 let start = map.buffer_snapshot.anchor_before(position);
3011 let end = map.buffer_snapshot.anchor_after(position);
3012 while let Some(existing_state) = this.autoclose_regions.get(i) {
3013 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3014 Ordering::Less => i += 1,
3015 Ordering::Greater => break,
3016 Ordering::Equal => {
3017 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3018 Ordering::Less => i += 1,
3019 Ordering::Equal => break,
3020 Ordering::Greater => break,
3021 }
3022 }
3023 }
3024 }
3025 this.autoclose_regions.insert(
3026 i,
3027 AutocloseRegion {
3028 selection_id,
3029 range: start..end,
3030 pair,
3031 },
3032 );
3033 }
3034
3035 let had_active_inline_completion = this.has_active_inline_completion();
3036 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3037 s.select(new_selections)
3038 });
3039
3040 if !bracket_inserted {
3041 if let Some(on_type_format_task) =
3042 this.trigger_on_type_formatting(text.to_string(), window, cx)
3043 {
3044 on_type_format_task.detach_and_log_err(cx);
3045 }
3046 }
3047
3048 let editor_settings = EditorSettings::get_global(cx);
3049 if bracket_inserted
3050 && (editor_settings.auto_signature_help
3051 || editor_settings.show_signature_help_after_edits)
3052 {
3053 this.show_signature_help(&ShowSignatureHelp, window, cx);
3054 }
3055
3056 let trigger_in_words =
3057 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3058 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3059 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3060 this.refresh_inline_completion(true, false, window, cx);
3061 });
3062 }
3063
3064 fn find_possible_emoji_shortcode_at_position(
3065 snapshot: &MultiBufferSnapshot,
3066 position: Point,
3067 ) -> Option<String> {
3068 let mut chars = Vec::new();
3069 let mut found_colon = false;
3070 for char in snapshot.reversed_chars_at(position).take(100) {
3071 // Found a possible emoji shortcode in the middle of the buffer
3072 if found_colon {
3073 if char.is_whitespace() {
3074 chars.reverse();
3075 return Some(chars.iter().collect());
3076 }
3077 // If the previous character is not a whitespace, we are in the middle of a word
3078 // and we only want to complete the shortcode if the word is made up of other emojis
3079 let mut containing_word = String::new();
3080 for ch in snapshot
3081 .reversed_chars_at(position)
3082 .skip(chars.len() + 1)
3083 .take(100)
3084 {
3085 if ch.is_whitespace() {
3086 break;
3087 }
3088 containing_word.push(ch);
3089 }
3090 let containing_word = containing_word.chars().rev().collect::<String>();
3091 if util::word_consists_of_emojis(containing_word.as_str()) {
3092 chars.reverse();
3093 return Some(chars.iter().collect());
3094 }
3095 }
3096
3097 if char.is_whitespace() || !char.is_ascii() {
3098 return None;
3099 }
3100 if char == ':' {
3101 found_colon = true;
3102 } else {
3103 chars.push(char);
3104 }
3105 }
3106 // Found a possible emoji shortcode at the beginning of the buffer
3107 chars.reverse();
3108 Some(chars.iter().collect())
3109 }
3110
3111 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3112 self.transact(window, cx, |this, window, cx| {
3113 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3114 let selections = this.selections.all::<usize>(cx);
3115 let multi_buffer = this.buffer.read(cx);
3116 let buffer = multi_buffer.snapshot(cx);
3117 selections
3118 .iter()
3119 .map(|selection| {
3120 let start_point = selection.start.to_point(&buffer);
3121 let mut indent =
3122 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3123 indent.len = cmp::min(indent.len, start_point.column);
3124 let start = selection.start;
3125 let end = selection.end;
3126 let selection_is_empty = start == end;
3127 let language_scope = buffer.language_scope_at(start);
3128 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3129 &language_scope
3130 {
3131 let leading_whitespace_len = buffer
3132 .reversed_chars_at(start)
3133 .take_while(|c| c.is_whitespace() && *c != '\n')
3134 .map(|c| c.len_utf8())
3135 .sum::<usize>();
3136
3137 let trailing_whitespace_len = buffer
3138 .chars_at(end)
3139 .take_while(|c| c.is_whitespace() && *c != '\n')
3140 .map(|c| c.len_utf8())
3141 .sum::<usize>();
3142
3143 let insert_extra_newline =
3144 language.brackets().any(|(pair, enabled)| {
3145 let pair_start = pair.start.trim_end();
3146 let pair_end = pair.end.trim_start();
3147
3148 enabled
3149 && pair.newline
3150 && buffer.contains_str_at(
3151 end + trailing_whitespace_len,
3152 pair_end,
3153 )
3154 && buffer.contains_str_at(
3155 (start - leading_whitespace_len)
3156 .saturating_sub(pair_start.len()),
3157 pair_start,
3158 )
3159 });
3160
3161 // Comment extension on newline is allowed only for cursor selections
3162 let comment_delimiter = maybe!({
3163 if !selection_is_empty {
3164 return None;
3165 }
3166
3167 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3168 return None;
3169 }
3170
3171 let delimiters = language.line_comment_prefixes();
3172 let max_len_of_delimiter =
3173 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3174 let (snapshot, range) =
3175 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3176
3177 let mut index_of_first_non_whitespace = 0;
3178 let comment_candidate = snapshot
3179 .chars_for_range(range)
3180 .skip_while(|c| {
3181 let should_skip = c.is_whitespace();
3182 if should_skip {
3183 index_of_first_non_whitespace += 1;
3184 }
3185 should_skip
3186 })
3187 .take(max_len_of_delimiter)
3188 .collect::<String>();
3189 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3190 comment_candidate.starts_with(comment_prefix.as_ref())
3191 })?;
3192 let cursor_is_placed_after_comment_marker =
3193 index_of_first_non_whitespace + comment_prefix.len()
3194 <= start_point.column as usize;
3195 if cursor_is_placed_after_comment_marker {
3196 Some(comment_prefix.clone())
3197 } else {
3198 None
3199 }
3200 });
3201 (comment_delimiter, insert_extra_newline)
3202 } else {
3203 (None, false)
3204 };
3205
3206 let capacity_for_delimiter = comment_delimiter
3207 .as_deref()
3208 .map(str::len)
3209 .unwrap_or_default();
3210 let mut new_text =
3211 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3212 new_text.push('\n');
3213 new_text.extend(indent.chars());
3214 if let Some(delimiter) = &comment_delimiter {
3215 new_text.push_str(delimiter);
3216 }
3217 if insert_extra_newline {
3218 new_text = new_text.repeat(2);
3219 }
3220
3221 let anchor = buffer.anchor_after(end);
3222 let new_selection = selection.map(|_| anchor);
3223 (
3224 (start..end, new_text),
3225 (insert_extra_newline, new_selection),
3226 )
3227 })
3228 .unzip()
3229 };
3230
3231 this.edit_with_autoindent(edits, cx);
3232 let buffer = this.buffer.read(cx).snapshot(cx);
3233 let new_selections = selection_fixup_info
3234 .into_iter()
3235 .map(|(extra_newline_inserted, new_selection)| {
3236 let mut cursor = new_selection.end.to_point(&buffer);
3237 if extra_newline_inserted {
3238 cursor.row -= 1;
3239 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3240 }
3241 new_selection.map(|_| cursor)
3242 })
3243 .collect();
3244
3245 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3246 s.select(new_selections)
3247 });
3248 this.refresh_inline_completion(true, false, window, cx);
3249 });
3250 }
3251
3252 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3253 let buffer = self.buffer.read(cx);
3254 let snapshot = buffer.snapshot(cx);
3255
3256 let mut edits = Vec::new();
3257 let mut rows = Vec::new();
3258
3259 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3260 let cursor = selection.head();
3261 let row = cursor.row;
3262
3263 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3264
3265 let newline = "\n".to_string();
3266 edits.push((start_of_line..start_of_line, newline));
3267
3268 rows.push(row + rows_inserted as u32);
3269 }
3270
3271 self.transact(window, cx, |editor, window, cx| {
3272 editor.edit(edits, cx);
3273
3274 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3275 let mut index = 0;
3276 s.move_cursors_with(|map, _, _| {
3277 let row = rows[index];
3278 index += 1;
3279
3280 let point = Point::new(row, 0);
3281 let boundary = map.next_line_boundary(point).1;
3282 let clipped = map.clip_point(boundary, Bias::Left);
3283
3284 (clipped, SelectionGoal::None)
3285 });
3286 });
3287
3288 let mut indent_edits = Vec::new();
3289 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3290 for row in rows {
3291 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3292 for (row, indent) in indents {
3293 if indent.len == 0 {
3294 continue;
3295 }
3296
3297 let text = match indent.kind {
3298 IndentKind::Space => " ".repeat(indent.len as usize),
3299 IndentKind::Tab => "\t".repeat(indent.len as usize),
3300 };
3301 let point = Point::new(row.0, 0);
3302 indent_edits.push((point..point, text));
3303 }
3304 }
3305 editor.edit(indent_edits, cx);
3306 });
3307 }
3308
3309 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3310 let buffer = self.buffer.read(cx);
3311 let snapshot = buffer.snapshot(cx);
3312
3313 let mut edits = Vec::new();
3314 let mut rows = Vec::new();
3315 let mut rows_inserted = 0;
3316
3317 for selection in self.selections.all_adjusted(cx) {
3318 let cursor = selection.head();
3319 let row = cursor.row;
3320
3321 let point = Point::new(row + 1, 0);
3322 let start_of_line = snapshot.clip_point(point, Bias::Left);
3323
3324 let newline = "\n".to_string();
3325 edits.push((start_of_line..start_of_line, newline));
3326
3327 rows_inserted += 1;
3328 rows.push(row + rows_inserted);
3329 }
3330
3331 self.transact(window, cx, |editor, window, cx| {
3332 editor.edit(edits, cx);
3333
3334 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3335 let mut index = 0;
3336 s.move_cursors_with(|map, _, _| {
3337 let row = rows[index];
3338 index += 1;
3339
3340 let point = Point::new(row, 0);
3341 let boundary = map.next_line_boundary(point).1;
3342 let clipped = map.clip_point(boundary, Bias::Left);
3343
3344 (clipped, SelectionGoal::None)
3345 });
3346 });
3347
3348 let mut indent_edits = Vec::new();
3349 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3350 for row in rows {
3351 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3352 for (row, indent) in indents {
3353 if indent.len == 0 {
3354 continue;
3355 }
3356
3357 let text = match indent.kind {
3358 IndentKind::Space => " ".repeat(indent.len as usize),
3359 IndentKind::Tab => "\t".repeat(indent.len as usize),
3360 };
3361 let point = Point::new(row.0, 0);
3362 indent_edits.push((point..point, text));
3363 }
3364 }
3365 editor.edit(indent_edits, cx);
3366 });
3367 }
3368
3369 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3370 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3371 original_indent_columns: Vec::new(),
3372 });
3373 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3374 }
3375
3376 fn insert_with_autoindent_mode(
3377 &mut self,
3378 text: &str,
3379 autoindent_mode: Option<AutoindentMode>,
3380 window: &mut Window,
3381 cx: &mut Context<Self>,
3382 ) {
3383 if self.read_only(cx) {
3384 return;
3385 }
3386
3387 let text: Arc<str> = text.into();
3388 self.transact(window, cx, |this, window, cx| {
3389 let old_selections = this.selections.all_adjusted(cx);
3390 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3391 let anchors = {
3392 let snapshot = buffer.read(cx);
3393 old_selections
3394 .iter()
3395 .map(|s| {
3396 let anchor = snapshot.anchor_after(s.head());
3397 s.map(|_| anchor)
3398 })
3399 .collect::<Vec<_>>()
3400 };
3401 buffer.edit(
3402 old_selections
3403 .iter()
3404 .map(|s| (s.start..s.end, text.clone())),
3405 autoindent_mode,
3406 cx,
3407 );
3408 anchors
3409 });
3410
3411 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3412 s.select_anchors(selection_anchors);
3413 });
3414
3415 cx.notify();
3416 });
3417 }
3418
3419 fn trigger_completion_on_input(
3420 &mut self,
3421 text: &str,
3422 trigger_in_words: bool,
3423 window: &mut Window,
3424 cx: &mut Context<Self>,
3425 ) {
3426 if self.is_completion_trigger(text, trigger_in_words, cx) {
3427 self.show_completions(
3428 &ShowCompletions {
3429 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3430 },
3431 window,
3432 cx,
3433 );
3434 } else {
3435 self.hide_context_menu(window, cx);
3436 }
3437 }
3438
3439 fn is_completion_trigger(
3440 &self,
3441 text: &str,
3442 trigger_in_words: bool,
3443 cx: &mut Context<Self>,
3444 ) -> bool {
3445 let position = self.selections.newest_anchor().head();
3446 let multibuffer = self.buffer.read(cx);
3447 let Some(buffer) = position
3448 .buffer_id
3449 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3450 else {
3451 return false;
3452 };
3453
3454 if let Some(completion_provider) = &self.completion_provider {
3455 completion_provider.is_completion_trigger(
3456 &buffer,
3457 position.text_anchor,
3458 text,
3459 trigger_in_words,
3460 cx,
3461 )
3462 } else {
3463 false
3464 }
3465 }
3466
3467 /// If any empty selections is touching the start of its innermost containing autoclose
3468 /// region, expand it to select the brackets.
3469 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3470 let selections = self.selections.all::<usize>(cx);
3471 let buffer = self.buffer.read(cx).read(cx);
3472 let new_selections = self
3473 .selections_with_autoclose_regions(selections, &buffer)
3474 .map(|(mut selection, region)| {
3475 if !selection.is_empty() {
3476 return selection;
3477 }
3478
3479 if let Some(region) = region {
3480 let mut range = region.range.to_offset(&buffer);
3481 if selection.start == range.start && range.start >= region.pair.start.len() {
3482 range.start -= region.pair.start.len();
3483 if buffer.contains_str_at(range.start, ®ion.pair.start)
3484 && buffer.contains_str_at(range.end, ®ion.pair.end)
3485 {
3486 range.end += region.pair.end.len();
3487 selection.start = range.start;
3488 selection.end = range.end;
3489
3490 return selection;
3491 }
3492 }
3493 }
3494
3495 let always_treat_brackets_as_autoclosed = buffer
3496 .settings_at(selection.start, cx)
3497 .always_treat_brackets_as_autoclosed;
3498
3499 if !always_treat_brackets_as_autoclosed {
3500 return selection;
3501 }
3502
3503 if let Some(scope) = buffer.language_scope_at(selection.start) {
3504 for (pair, enabled) in scope.brackets() {
3505 if !enabled || !pair.close {
3506 continue;
3507 }
3508
3509 if buffer.contains_str_at(selection.start, &pair.end) {
3510 let pair_start_len = pair.start.len();
3511 if buffer.contains_str_at(
3512 selection.start.saturating_sub(pair_start_len),
3513 &pair.start,
3514 ) {
3515 selection.start -= pair_start_len;
3516 selection.end += pair.end.len();
3517
3518 return selection;
3519 }
3520 }
3521 }
3522 }
3523
3524 selection
3525 })
3526 .collect();
3527
3528 drop(buffer);
3529 self.change_selections(None, window, cx, |selections| {
3530 selections.select(new_selections)
3531 });
3532 }
3533
3534 /// Iterate the given selections, and for each one, find the smallest surrounding
3535 /// autoclose region. This uses the ordering of the selections and the autoclose
3536 /// regions to avoid repeated comparisons.
3537 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3538 &'a self,
3539 selections: impl IntoIterator<Item = Selection<D>>,
3540 buffer: &'a MultiBufferSnapshot,
3541 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3542 let mut i = 0;
3543 let mut regions = self.autoclose_regions.as_slice();
3544 selections.into_iter().map(move |selection| {
3545 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3546
3547 let mut enclosing = None;
3548 while let Some(pair_state) = regions.get(i) {
3549 if pair_state.range.end.to_offset(buffer) < range.start {
3550 regions = ®ions[i + 1..];
3551 i = 0;
3552 } else if pair_state.range.start.to_offset(buffer) > range.end {
3553 break;
3554 } else {
3555 if pair_state.selection_id == selection.id {
3556 enclosing = Some(pair_state);
3557 }
3558 i += 1;
3559 }
3560 }
3561
3562 (selection, enclosing)
3563 })
3564 }
3565
3566 /// Remove any autoclose regions that no longer contain their selection.
3567 fn invalidate_autoclose_regions(
3568 &mut self,
3569 mut selections: &[Selection<Anchor>],
3570 buffer: &MultiBufferSnapshot,
3571 ) {
3572 self.autoclose_regions.retain(|state| {
3573 let mut i = 0;
3574 while let Some(selection) = selections.get(i) {
3575 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3576 selections = &selections[1..];
3577 continue;
3578 }
3579 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3580 break;
3581 }
3582 if selection.id == state.selection_id {
3583 return true;
3584 } else {
3585 i += 1;
3586 }
3587 }
3588 false
3589 });
3590 }
3591
3592 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3593 let offset = position.to_offset(buffer);
3594 let (word_range, kind) = buffer.surrounding_word(offset, true);
3595 if offset > word_range.start && kind == Some(CharKind::Word) {
3596 Some(
3597 buffer
3598 .text_for_range(word_range.start..offset)
3599 .collect::<String>(),
3600 )
3601 } else {
3602 None
3603 }
3604 }
3605
3606 pub fn toggle_inlay_hints(
3607 &mut self,
3608 _: &ToggleInlayHints,
3609 _: &mut Window,
3610 cx: &mut Context<Self>,
3611 ) {
3612 self.refresh_inlay_hints(
3613 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3614 cx,
3615 );
3616 }
3617
3618 pub fn inlay_hints_enabled(&self) -> bool {
3619 self.inlay_hint_cache.enabled
3620 }
3621
3622 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3623 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3624 return;
3625 }
3626
3627 let reason_description = reason.description();
3628 let ignore_debounce = matches!(
3629 reason,
3630 InlayHintRefreshReason::SettingsChange(_)
3631 | InlayHintRefreshReason::Toggle(_)
3632 | InlayHintRefreshReason::ExcerptsRemoved(_)
3633 );
3634 let (invalidate_cache, required_languages) = match reason {
3635 InlayHintRefreshReason::Toggle(enabled) => {
3636 self.inlay_hint_cache.enabled = enabled;
3637 if enabled {
3638 (InvalidationStrategy::RefreshRequested, None)
3639 } else {
3640 self.inlay_hint_cache.clear();
3641 self.splice_inlays(
3642 &self
3643 .visible_inlay_hints(cx)
3644 .iter()
3645 .map(|inlay| inlay.id)
3646 .collect::<Vec<InlayId>>(),
3647 Vec::new(),
3648 cx,
3649 );
3650 return;
3651 }
3652 }
3653 InlayHintRefreshReason::SettingsChange(new_settings) => {
3654 match self.inlay_hint_cache.update_settings(
3655 &self.buffer,
3656 new_settings,
3657 self.visible_inlay_hints(cx),
3658 cx,
3659 ) {
3660 ControlFlow::Break(Some(InlaySplice {
3661 to_remove,
3662 to_insert,
3663 })) => {
3664 self.splice_inlays(&to_remove, to_insert, cx);
3665 return;
3666 }
3667 ControlFlow::Break(None) => return,
3668 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3669 }
3670 }
3671 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3672 if let Some(InlaySplice {
3673 to_remove,
3674 to_insert,
3675 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3676 {
3677 self.splice_inlays(&to_remove, to_insert, cx);
3678 }
3679 return;
3680 }
3681 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3682 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3683 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3684 }
3685 InlayHintRefreshReason::RefreshRequested => {
3686 (InvalidationStrategy::RefreshRequested, None)
3687 }
3688 };
3689
3690 if let Some(InlaySplice {
3691 to_remove,
3692 to_insert,
3693 }) = self.inlay_hint_cache.spawn_hint_refresh(
3694 reason_description,
3695 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3696 invalidate_cache,
3697 ignore_debounce,
3698 cx,
3699 ) {
3700 self.splice_inlays(&to_remove, to_insert, cx);
3701 }
3702 }
3703
3704 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3705 self.display_map
3706 .read(cx)
3707 .current_inlays()
3708 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3709 .cloned()
3710 .collect()
3711 }
3712
3713 pub fn excerpts_for_inlay_hints_query(
3714 &self,
3715 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3716 cx: &mut Context<Editor>,
3717 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3718 let Some(project) = self.project.as_ref() else {
3719 return HashMap::default();
3720 };
3721 let project = project.read(cx);
3722 let multi_buffer = self.buffer().read(cx);
3723 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3724 let multi_buffer_visible_start = self
3725 .scroll_manager
3726 .anchor()
3727 .anchor
3728 .to_point(&multi_buffer_snapshot);
3729 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3730 multi_buffer_visible_start
3731 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3732 Bias::Left,
3733 );
3734 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3735 multi_buffer_snapshot
3736 .range_to_buffer_ranges(multi_buffer_visible_range)
3737 .into_iter()
3738 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3739 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3740 let buffer_file = project::File::from_dyn(buffer.file())?;
3741 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3742 let worktree_entry = buffer_worktree
3743 .read(cx)
3744 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3745 if worktree_entry.is_ignored {
3746 return None;
3747 }
3748
3749 let language = buffer.language()?;
3750 if let Some(restrict_to_languages) = restrict_to_languages {
3751 if !restrict_to_languages.contains(language) {
3752 return None;
3753 }
3754 }
3755 Some((
3756 excerpt_id,
3757 (
3758 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3759 buffer.version().clone(),
3760 excerpt_visible_range,
3761 ),
3762 ))
3763 })
3764 .collect()
3765 }
3766
3767 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3768 TextLayoutDetails {
3769 text_system: window.text_system().clone(),
3770 editor_style: self.style.clone().unwrap(),
3771 rem_size: window.rem_size(),
3772 scroll_anchor: self.scroll_manager.anchor(),
3773 visible_rows: self.visible_line_count(),
3774 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3775 }
3776 }
3777
3778 pub fn splice_inlays(
3779 &self,
3780 to_remove: &[InlayId],
3781 to_insert: Vec<Inlay>,
3782 cx: &mut Context<Self>,
3783 ) {
3784 self.display_map.update(cx, |display_map, cx| {
3785 display_map.splice_inlays(to_remove, to_insert, cx)
3786 });
3787 cx.notify();
3788 }
3789
3790 fn trigger_on_type_formatting(
3791 &self,
3792 input: String,
3793 window: &mut Window,
3794 cx: &mut Context<Self>,
3795 ) -> Option<Task<Result<()>>> {
3796 if input.len() != 1 {
3797 return None;
3798 }
3799
3800 let project = self.project.as_ref()?;
3801 let position = self.selections.newest_anchor().head();
3802 let (buffer, buffer_position) = self
3803 .buffer
3804 .read(cx)
3805 .text_anchor_for_position(position, cx)?;
3806
3807 let settings = language_settings::language_settings(
3808 buffer
3809 .read(cx)
3810 .language_at(buffer_position)
3811 .map(|l| l.name()),
3812 buffer.read(cx).file(),
3813 cx,
3814 );
3815 if !settings.use_on_type_format {
3816 return None;
3817 }
3818
3819 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3820 // hence we do LSP request & edit on host side only — add formats to host's history.
3821 let push_to_lsp_host_history = true;
3822 // If this is not the host, append its history with new edits.
3823 let push_to_client_history = project.read(cx).is_via_collab();
3824
3825 let on_type_formatting = project.update(cx, |project, cx| {
3826 project.on_type_format(
3827 buffer.clone(),
3828 buffer_position,
3829 input,
3830 push_to_lsp_host_history,
3831 cx,
3832 )
3833 });
3834 Some(cx.spawn_in(window, |editor, mut cx| async move {
3835 if let Some(transaction) = on_type_formatting.await? {
3836 if push_to_client_history {
3837 buffer
3838 .update(&mut cx, |buffer, _| {
3839 buffer.push_transaction(transaction, Instant::now());
3840 })
3841 .ok();
3842 }
3843 editor.update(&mut cx, |editor, cx| {
3844 editor.refresh_document_highlights(cx);
3845 })?;
3846 }
3847 Ok(())
3848 }))
3849 }
3850
3851 pub fn show_completions(
3852 &mut self,
3853 options: &ShowCompletions,
3854 window: &mut Window,
3855 cx: &mut Context<Self>,
3856 ) {
3857 if self.pending_rename.is_some() {
3858 return;
3859 }
3860
3861 let Some(provider) = self.completion_provider.as_ref() else {
3862 return;
3863 };
3864
3865 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3866 return;
3867 }
3868
3869 let position = self.selections.newest_anchor().head();
3870 if position.diff_base_anchor.is_some() {
3871 return;
3872 }
3873 let (buffer, buffer_position) =
3874 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3875 output
3876 } else {
3877 return;
3878 };
3879 let show_completion_documentation = buffer
3880 .read(cx)
3881 .snapshot()
3882 .settings_at(buffer_position, cx)
3883 .show_completion_documentation;
3884
3885 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3886
3887 let trigger_kind = match &options.trigger {
3888 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3889 CompletionTriggerKind::TRIGGER_CHARACTER
3890 }
3891 _ => CompletionTriggerKind::INVOKED,
3892 };
3893 let completion_context = CompletionContext {
3894 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3895 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3896 Some(String::from(trigger))
3897 } else {
3898 None
3899 }
3900 }),
3901 trigger_kind,
3902 };
3903 let completions =
3904 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3905 let sort_completions = provider.sort_completions();
3906
3907 let id = post_inc(&mut self.next_completion_id);
3908 let task = cx.spawn_in(window, |editor, mut cx| {
3909 async move {
3910 editor.update(&mut cx, |this, _| {
3911 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3912 })?;
3913 let completions = completions.await.log_err();
3914 let menu = if let Some(completions) = completions {
3915 let mut menu = CompletionsMenu::new(
3916 id,
3917 sort_completions,
3918 show_completion_documentation,
3919 position,
3920 buffer.clone(),
3921 completions.into(),
3922 );
3923
3924 menu.filter(query.as_deref(), cx.background_executor().clone())
3925 .await;
3926
3927 menu.visible().then_some(menu)
3928 } else {
3929 None
3930 };
3931
3932 editor.update_in(&mut cx, |editor, window, cx| {
3933 match editor.context_menu.borrow().as_ref() {
3934 None => {}
3935 Some(CodeContextMenu::Completions(prev_menu)) => {
3936 if prev_menu.id > id {
3937 return;
3938 }
3939 }
3940 _ => return,
3941 }
3942
3943 if editor.focus_handle.is_focused(window) && menu.is_some() {
3944 let mut menu = menu.unwrap();
3945 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3946
3947 *editor.context_menu.borrow_mut() =
3948 Some(CodeContextMenu::Completions(menu));
3949
3950 if editor.show_edit_predictions_in_menu() {
3951 editor.update_visible_inline_completion(window, cx);
3952 } else {
3953 editor.discard_inline_completion(false, cx);
3954 }
3955
3956 cx.notify();
3957 } else if editor.completion_tasks.len() <= 1 {
3958 // If there are no more completion tasks and the last menu was
3959 // empty, we should hide it.
3960 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3961 // If it was already hidden and we don't show inline
3962 // completions in the menu, we should also show the
3963 // inline-completion when available.
3964 if was_hidden && editor.show_edit_predictions_in_menu() {
3965 editor.update_visible_inline_completion(window, cx);
3966 }
3967 }
3968 })?;
3969
3970 Ok::<_, anyhow::Error>(())
3971 }
3972 .log_err()
3973 });
3974
3975 self.completion_tasks.push((id, task));
3976 }
3977
3978 pub fn confirm_completion(
3979 &mut self,
3980 action: &ConfirmCompletion,
3981 window: &mut Window,
3982 cx: &mut Context<Self>,
3983 ) -> Option<Task<Result<()>>> {
3984 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3985 }
3986
3987 pub fn compose_completion(
3988 &mut self,
3989 action: &ComposeCompletion,
3990 window: &mut Window,
3991 cx: &mut Context<Self>,
3992 ) -> Option<Task<Result<()>>> {
3993 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3994 }
3995
3996 fn do_completion(
3997 &mut self,
3998 item_ix: Option<usize>,
3999 intent: CompletionIntent,
4000 window: &mut Window,
4001 cx: &mut Context<Editor>,
4002 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4003 use language::ToOffset as _;
4004
4005 let completions_menu =
4006 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4007 menu
4008 } else {
4009 return None;
4010 };
4011
4012 let entries = completions_menu.entries.borrow();
4013 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4014 if self.show_edit_predictions_in_menu() {
4015 self.discard_inline_completion(true, cx);
4016 }
4017 let candidate_id = mat.candidate_id;
4018 drop(entries);
4019
4020 let buffer_handle = completions_menu.buffer;
4021 let completion = completions_menu
4022 .completions
4023 .borrow()
4024 .get(candidate_id)?
4025 .clone();
4026 cx.stop_propagation();
4027
4028 let snippet;
4029 let text;
4030
4031 if completion.is_snippet() {
4032 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4033 text = snippet.as_ref().unwrap().text.clone();
4034 } else {
4035 snippet = None;
4036 text = completion.new_text.clone();
4037 };
4038 let selections = self.selections.all::<usize>(cx);
4039 let buffer = buffer_handle.read(cx);
4040 let old_range = completion.old_range.to_offset(buffer);
4041 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4042
4043 let newest_selection = self.selections.newest_anchor();
4044 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4045 return None;
4046 }
4047
4048 let lookbehind = newest_selection
4049 .start
4050 .text_anchor
4051 .to_offset(buffer)
4052 .saturating_sub(old_range.start);
4053 let lookahead = old_range
4054 .end
4055 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4056 let mut common_prefix_len = old_text
4057 .bytes()
4058 .zip(text.bytes())
4059 .take_while(|(a, b)| a == b)
4060 .count();
4061
4062 let snapshot = self.buffer.read(cx).snapshot(cx);
4063 let mut range_to_replace: Option<Range<isize>> = None;
4064 let mut ranges = Vec::new();
4065 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4066 for selection in &selections {
4067 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4068 let start = selection.start.saturating_sub(lookbehind);
4069 let end = selection.end + lookahead;
4070 if selection.id == newest_selection.id {
4071 range_to_replace = Some(
4072 ((start + common_prefix_len) as isize - selection.start as isize)
4073 ..(end as isize - selection.start as isize),
4074 );
4075 }
4076 ranges.push(start + common_prefix_len..end);
4077 } else {
4078 common_prefix_len = 0;
4079 ranges.clear();
4080 ranges.extend(selections.iter().map(|s| {
4081 if s.id == newest_selection.id {
4082 range_to_replace = Some(
4083 old_range.start.to_offset_utf16(&snapshot).0 as isize
4084 - selection.start as isize
4085 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4086 - selection.start as isize,
4087 );
4088 old_range.clone()
4089 } else {
4090 s.start..s.end
4091 }
4092 }));
4093 break;
4094 }
4095 if !self.linked_edit_ranges.is_empty() {
4096 let start_anchor = snapshot.anchor_before(selection.head());
4097 let end_anchor = snapshot.anchor_after(selection.tail());
4098 if let Some(ranges) = self
4099 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4100 {
4101 for (buffer, edits) in ranges {
4102 linked_edits.entry(buffer.clone()).or_default().extend(
4103 edits
4104 .into_iter()
4105 .map(|range| (range, text[common_prefix_len..].to_owned())),
4106 );
4107 }
4108 }
4109 }
4110 }
4111 let text = &text[common_prefix_len..];
4112
4113 cx.emit(EditorEvent::InputHandled {
4114 utf16_range_to_replace: range_to_replace,
4115 text: text.into(),
4116 });
4117
4118 self.transact(window, cx, |this, window, cx| {
4119 if let Some(mut snippet) = snippet {
4120 snippet.text = text.to_string();
4121 for tabstop in snippet
4122 .tabstops
4123 .iter_mut()
4124 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4125 {
4126 tabstop.start -= common_prefix_len as isize;
4127 tabstop.end -= common_prefix_len as isize;
4128 }
4129
4130 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4131 } else {
4132 this.buffer.update(cx, |buffer, cx| {
4133 buffer.edit(
4134 ranges.iter().map(|range| (range.clone(), text)),
4135 this.autoindent_mode.clone(),
4136 cx,
4137 );
4138 });
4139 }
4140 for (buffer, edits) in linked_edits {
4141 buffer.update(cx, |buffer, cx| {
4142 let snapshot = buffer.snapshot();
4143 let edits = edits
4144 .into_iter()
4145 .map(|(range, text)| {
4146 use text::ToPoint as TP;
4147 let end_point = TP::to_point(&range.end, &snapshot);
4148 let start_point = TP::to_point(&range.start, &snapshot);
4149 (start_point..end_point, text)
4150 })
4151 .sorted_by_key(|(range, _)| range.start)
4152 .collect::<Vec<_>>();
4153 buffer.edit(edits, None, cx);
4154 })
4155 }
4156
4157 this.refresh_inline_completion(true, false, window, cx);
4158 });
4159
4160 let show_new_completions_on_confirm = completion
4161 .confirm
4162 .as_ref()
4163 .map_or(false, |confirm| confirm(intent, window, cx));
4164 if show_new_completions_on_confirm {
4165 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4166 }
4167
4168 let provider = self.completion_provider.as_ref()?;
4169 drop(completion);
4170 let apply_edits = provider.apply_additional_edits_for_completion(
4171 buffer_handle,
4172 completions_menu.completions.clone(),
4173 candidate_id,
4174 true,
4175 cx,
4176 );
4177
4178 let editor_settings = EditorSettings::get_global(cx);
4179 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4180 // After the code completion is finished, users often want to know what signatures are needed.
4181 // so we should automatically call signature_help
4182 self.show_signature_help(&ShowSignatureHelp, window, cx);
4183 }
4184
4185 Some(cx.foreground_executor().spawn(async move {
4186 apply_edits.await?;
4187 Ok(())
4188 }))
4189 }
4190
4191 pub fn toggle_code_actions(
4192 &mut self,
4193 action: &ToggleCodeActions,
4194 window: &mut Window,
4195 cx: &mut Context<Self>,
4196 ) {
4197 let mut context_menu = self.context_menu.borrow_mut();
4198 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4199 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4200 // Toggle if we're selecting the same one
4201 *context_menu = None;
4202 cx.notify();
4203 return;
4204 } else {
4205 // Otherwise, clear it and start a new one
4206 *context_menu = None;
4207 cx.notify();
4208 }
4209 }
4210 drop(context_menu);
4211 let snapshot = self.snapshot(window, cx);
4212 let deployed_from_indicator = action.deployed_from_indicator;
4213 let mut task = self.code_actions_task.take();
4214 let action = action.clone();
4215 cx.spawn_in(window, |editor, mut cx| async move {
4216 while let Some(prev_task) = task {
4217 prev_task.await.log_err();
4218 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4219 }
4220
4221 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4222 if editor.focus_handle.is_focused(window) {
4223 let multibuffer_point = action
4224 .deployed_from_indicator
4225 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4226 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4227 let (buffer, buffer_row) = snapshot
4228 .buffer_snapshot
4229 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4230 .and_then(|(buffer_snapshot, range)| {
4231 editor
4232 .buffer
4233 .read(cx)
4234 .buffer(buffer_snapshot.remote_id())
4235 .map(|buffer| (buffer, range.start.row))
4236 })?;
4237 let (_, code_actions) = editor
4238 .available_code_actions
4239 .clone()
4240 .and_then(|(location, code_actions)| {
4241 let snapshot = location.buffer.read(cx).snapshot();
4242 let point_range = location.range.to_point(&snapshot);
4243 let point_range = point_range.start.row..=point_range.end.row;
4244 if point_range.contains(&buffer_row) {
4245 Some((location, code_actions))
4246 } else {
4247 None
4248 }
4249 })
4250 .unzip();
4251 let buffer_id = buffer.read(cx).remote_id();
4252 let tasks = editor
4253 .tasks
4254 .get(&(buffer_id, buffer_row))
4255 .map(|t| Arc::new(t.to_owned()));
4256 if tasks.is_none() && code_actions.is_none() {
4257 return None;
4258 }
4259
4260 editor.completion_tasks.clear();
4261 editor.discard_inline_completion(false, cx);
4262 let task_context =
4263 tasks
4264 .as_ref()
4265 .zip(editor.project.clone())
4266 .map(|(tasks, project)| {
4267 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4268 });
4269
4270 Some(cx.spawn_in(window, |editor, mut cx| async move {
4271 let task_context = match task_context {
4272 Some(task_context) => task_context.await,
4273 None => None,
4274 };
4275 let resolved_tasks =
4276 tasks.zip(task_context).map(|(tasks, task_context)| {
4277 Rc::new(ResolvedTasks {
4278 templates: tasks.resolve(&task_context).collect(),
4279 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4280 multibuffer_point.row,
4281 tasks.column,
4282 )),
4283 })
4284 });
4285 let spawn_straight_away = resolved_tasks
4286 .as_ref()
4287 .map_or(false, |tasks| tasks.templates.len() == 1)
4288 && code_actions
4289 .as_ref()
4290 .map_or(true, |actions| actions.is_empty());
4291 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4292 *editor.context_menu.borrow_mut() =
4293 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4294 buffer,
4295 actions: CodeActionContents {
4296 tasks: resolved_tasks,
4297 actions: code_actions,
4298 },
4299 selected_item: Default::default(),
4300 scroll_handle: UniformListScrollHandle::default(),
4301 deployed_from_indicator,
4302 }));
4303 if spawn_straight_away {
4304 if let Some(task) = editor.confirm_code_action(
4305 &ConfirmCodeAction { item_ix: Some(0) },
4306 window,
4307 cx,
4308 ) {
4309 cx.notify();
4310 return task;
4311 }
4312 }
4313 cx.notify();
4314 Task::ready(Ok(()))
4315 }) {
4316 task.await
4317 } else {
4318 Ok(())
4319 }
4320 }))
4321 } else {
4322 Some(Task::ready(Ok(())))
4323 }
4324 })?;
4325 if let Some(task) = spawned_test_task {
4326 task.await?;
4327 }
4328
4329 Ok::<_, anyhow::Error>(())
4330 })
4331 .detach_and_log_err(cx);
4332 }
4333
4334 pub fn confirm_code_action(
4335 &mut self,
4336 action: &ConfirmCodeAction,
4337 window: &mut Window,
4338 cx: &mut Context<Self>,
4339 ) -> Option<Task<Result<()>>> {
4340 let actions_menu =
4341 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4342 menu
4343 } else {
4344 return None;
4345 };
4346 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4347 let action = actions_menu.actions.get(action_ix)?;
4348 let title = action.label();
4349 let buffer = actions_menu.buffer;
4350 let workspace = self.workspace()?;
4351
4352 match action {
4353 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4354 workspace.update(cx, |workspace, cx| {
4355 workspace::tasks::schedule_resolved_task(
4356 workspace,
4357 task_source_kind,
4358 resolved_task,
4359 false,
4360 cx,
4361 );
4362
4363 Some(Task::ready(Ok(())))
4364 })
4365 }
4366 CodeActionsItem::CodeAction {
4367 excerpt_id,
4368 action,
4369 provider,
4370 } => {
4371 let apply_code_action =
4372 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4373 let workspace = workspace.downgrade();
4374 Some(cx.spawn_in(window, |editor, cx| async move {
4375 let project_transaction = apply_code_action.await?;
4376 Self::open_project_transaction(
4377 &editor,
4378 workspace,
4379 project_transaction,
4380 title,
4381 cx,
4382 )
4383 .await
4384 }))
4385 }
4386 }
4387 }
4388
4389 pub async fn open_project_transaction(
4390 this: &WeakEntity<Editor>,
4391 workspace: WeakEntity<Workspace>,
4392 transaction: ProjectTransaction,
4393 title: String,
4394 mut cx: AsyncWindowContext,
4395 ) -> Result<()> {
4396 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4397 cx.update(|_, cx| {
4398 entries.sort_unstable_by_key(|(buffer, _)| {
4399 buffer.read(cx).file().map(|f| f.path().clone())
4400 });
4401 })?;
4402
4403 // If the project transaction's edits are all contained within this editor, then
4404 // avoid opening a new editor to display them.
4405
4406 if let Some((buffer, transaction)) = entries.first() {
4407 if entries.len() == 1 {
4408 let excerpt = this.update(&mut cx, |editor, cx| {
4409 editor
4410 .buffer()
4411 .read(cx)
4412 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4413 })?;
4414 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4415 if excerpted_buffer == *buffer {
4416 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4417 let excerpt_range = excerpt_range.to_offset(buffer);
4418 buffer
4419 .edited_ranges_for_transaction::<usize>(transaction)
4420 .all(|range| {
4421 excerpt_range.start <= range.start
4422 && excerpt_range.end >= range.end
4423 })
4424 })?;
4425
4426 if all_edits_within_excerpt {
4427 return Ok(());
4428 }
4429 }
4430 }
4431 }
4432 } else {
4433 return Ok(());
4434 }
4435
4436 let mut ranges_to_highlight = Vec::new();
4437 let excerpt_buffer = cx.new(|cx| {
4438 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4439 for (buffer_handle, transaction) in &entries {
4440 let buffer = buffer_handle.read(cx);
4441 ranges_to_highlight.extend(
4442 multibuffer.push_excerpts_with_context_lines(
4443 buffer_handle.clone(),
4444 buffer
4445 .edited_ranges_for_transaction::<usize>(transaction)
4446 .collect(),
4447 DEFAULT_MULTIBUFFER_CONTEXT,
4448 cx,
4449 ),
4450 );
4451 }
4452 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4453 multibuffer
4454 })?;
4455
4456 workspace.update_in(&mut cx, |workspace, window, cx| {
4457 let project = workspace.project().clone();
4458 let editor = cx
4459 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4460 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4461 editor.update(cx, |editor, cx| {
4462 editor.highlight_background::<Self>(
4463 &ranges_to_highlight,
4464 |theme| theme.editor_highlighted_line_background,
4465 cx,
4466 );
4467 });
4468 })?;
4469
4470 Ok(())
4471 }
4472
4473 pub fn clear_code_action_providers(&mut self) {
4474 self.code_action_providers.clear();
4475 self.available_code_actions.take();
4476 }
4477
4478 pub fn add_code_action_provider(
4479 &mut self,
4480 provider: Rc<dyn CodeActionProvider>,
4481 window: &mut Window,
4482 cx: &mut Context<Self>,
4483 ) {
4484 if self
4485 .code_action_providers
4486 .iter()
4487 .any(|existing_provider| existing_provider.id() == provider.id())
4488 {
4489 return;
4490 }
4491
4492 self.code_action_providers.push(provider);
4493 self.refresh_code_actions(window, cx);
4494 }
4495
4496 pub fn remove_code_action_provider(
4497 &mut self,
4498 id: Arc<str>,
4499 window: &mut Window,
4500 cx: &mut Context<Self>,
4501 ) {
4502 self.code_action_providers
4503 .retain(|provider| provider.id() != id);
4504 self.refresh_code_actions(window, cx);
4505 }
4506
4507 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4508 let buffer = self.buffer.read(cx);
4509 let newest_selection = self.selections.newest_anchor().clone();
4510 if newest_selection.head().diff_base_anchor.is_some() {
4511 return None;
4512 }
4513 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4514 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4515 if start_buffer != end_buffer {
4516 return None;
4517 }
4518
4519 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4520 cx.background_executor()
4521 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4522 .await;
4523
4524 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4525 let providers = this.code_action_providers.clone();
4526 let tasks = this
4527 .code_action_providers
4528 .iter()
4529 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4530 .collect::<Vec<_>>();
4531 (providers, tasks)
4532 })?;
4533
4534 let mut actions = Vec::new();
4535 for (provider, provider_actions) in
4536 providers.into_iter().zip(future::join_all(tasks).await)
4537 {
4538 if let Some(provider_actions) = provider_actions.log_err() {
4539 actions.extend(provider_actions.into_iter().map(|action| {
4540 AvailableCodeAction {
4541 excerpt_id: newest_selection.start.excerpt_id,
4542 action,
4543 provider: provider.clone(),
4544 }
4545 }));
4546 }
4547 }
4548
4549 this.update(&mut cx, |this, cx| {
4550 this.available_code_actions = if actions.is_empty() {
4551 None
4552 } else {
4553 Some((
4554 Location {
4555 buffer: start_buffer,
4556 range: start..end,
4557 },
4558 actions.into(),
4559 ))
4560 };
4561 cx.notify();
4562 })
4563 }));
4564 None
4565 }
4566
4567 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4568 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4569 self.show_git_blame_inline = false;
4570
4571 self.show_git_blame_inline_delay_task =
4572 Some(cx.spawn_in(window, |this, mut cx| async move {
4573 cx.background_executor().timer(delay).await;
4574
4575 this.update(&mut cx, |this, cx| {
4576 this.show_git_blame_inline = true;
4577 cx.notify();
4578 })
4579 .log_err();
4580 }));
4581 }
4582 }
4583
4584 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4585 if self.pending_rename.is_some() {
4586 return None;
4587 }
4588
4589 let provider = self.semantics_provider.clone()?;
4590 let buffer = self.buffer.read(cx);
4591 let newest_selection = self.selections.newest_anchor().clone();
4592 let cursor_position = newest_selection.head();
4593 let (cursor_buffer, cursor_buffer_position) =
4594 buffer.text_anchor_for_position(cursor_position, cx)?;
4595 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4596 if cursor_buffer != tail_buffer {
4597 return None;
4598 }
4599 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4600 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4601 cx.background_executor()
4602 .timer(Duration::from_millis(debounce))
4603 .await;
4604
4605 let highlights = if let Some(highlights) = cx
4606 .update(|cx| {
4607 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4608 })
4609 .ok()
4610 .flatten()
4611 {
4612 highlights.await.log_err()
4613 } else {
4614 None
4615 };
4616
4617 if let Some(highlights) = highlights {
4618 this.update(&mut cx, |this, cx| {
4619 if this.pending_rename.is_some() {
4620 return;
4621 }
4622
4623 let buffer_id = cursor_position.buffer_id;
4624 let buffer = this.buffer.read(cx);
4625 if !buffer
4626 .text_anchor_for_position(cursor_position, cx)
4627 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4628 {
4629 return;
4630 }
4631
4632 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4633 let mut write_ranges = Vec::new();
4634 let mut read_ranges = Vec::new();
4635 for highlight in highlights {
4636 for (excerpt_id, excerpt_range) in
4637 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4638 {
4639 let start = highlight
4640 .range
4641 .start
4642 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4643 let end = highlight
4644 .range
4645 .end
4646 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4647 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4648 continue;
4649 }
4650
4651 let range = Anchor {
4652 buffer_id,
4653 excerpt_id,
4654 text_anchor: start,
4655 diff_base_anchor: None,
4656 }..Anchor {
4657 buffer_id,
4658 excerpt_id,
4659 text_anchor: end,
4660 diff_base_anchor: None,
4661 };
4662 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4663 write_ranges.push(range);
4664 } else {
4665 read_ranges.push(range);
4666 }
4667 }
4668 }
4669
4670 this.highlight_background::<DocumentHighlightRead>(
4671 &read_ranges,
4672 |theme| theme.editor_document_highlight_read_background,
4673 cx,
4674 );
4675 this.highlight_background::<DocumentHighlightWrite>(
4676 &write_ranges,
4677 |theme| theme.editor_document_highlight_write_background,
4678 cx,
4679 );
4680 cx.notify();
4681 })
4682 .log_err();
4683 }
4684 }));
4685 None
4686 }
4687
4688 pub fn refresh_inline_completion(
4689 &mut self,
4690 debounce: bool,
4691 user_requested: bool,
4692 window: &mut Window,
4693 cx: &mut Context<Self>,
4694 ) -> Option<()> {
4695 let provider = self.edit_prediction_provider()?;
4696 let cursor = self.selections.newest_anchor().head();
4697 let (buffer, cursor_buffer_position) =
4698 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4699
4700 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4701 self.discard_inline_completion(false, cx);
4702 return None;
4703 }
4704
4705 if !user_requested
4706 && (!self.should_show_edit_predictions()
4707 || !self.is_focused(window)
4708 || buffer.read(cx).is_empty())
4709 {
4710 self.discard_inline_completion(false, cx);
4711 return None;
4712 }
4713
4714 self.update_visible_inline_completion(window, cx);
4715 provider.refresh(
4716 self.project.clone(),
4717 buffer,
4718 cursor_buffer_position,
4719 debounce,
4720 cx,
4721 );
4722 Some(())
4723 }
4724
4725 fn show_edit_predictions_in_menu(&self) -> bool {
4726 match self.edit_prediction_settings {
4727 EditPredictionSettings::Disabled => false,
4728 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4729 }
4730 }
4731
4732 pub fn edit_predictions_enabled(&self) -> bool {
4733 match self.edit_prediction_settings {
4734 EditPredictionSettings::Disabled => false,
4735 EditPredictionSettings::Enabled { .. } => true,
4736 }
4737 }
4738
4739 fn edit_prediction_requires_modifier(&self) -> bool {
4740 match self.edit_prediction_settings {
4741 EditPredictionSettings::Disabled => false,
4742 EditPredictionSettings::Enabled {
4743 preview_requires_modifier,
4744 ..
4745 } => preview_requires_modifier,
4746 }
4747 }
4748
4749 fn edit_prediction_settings_at_position(
4750 &self,
4751 buffer: &Entity<Buffer>,
4752 buffer_position: language::Anchor,
4753 cx: &App,
4754 ) -> EditPredictionSettings {
4755 if self.mode != EditorMode::Full
4756 || !self.show_inline_completions_override.unwrap_or(true)
4757 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4758 {
4759 return EditPredictionSettings::Disabled;
4760 }
4761
4762 let buffer = buffer.read(cx);
4763
4764 let file = buffer.file();
4765
4766 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4767 return EditPredictionSettings::Disabled;
4768 };
4769
4770 let by_provider = matches!(
4771 self.menu_inline_completions_policy,
4772 MenuInlineCompletionsPolicy::ByProvider
4773 );
4774
4775 let show_in_menu = by_provider
4776 && self
4777 .edit_prediction_provider
4778 .as_ref()
4779 .map_or(false, |provider| {
4780 provider.provider.show_completions_in_menu()
4781 });
4782
4783 let preview_requires_modifier =
4784 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4785
4786 EditPredictionSettings::Enabled {
4787 show_in_menu,
4788 preview_requires_modifier,
4789 }
4790 }
4791
4792 fn should_show_edit_predictions(&self) -> bool {
4793 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4794 }
4795
4796 pub fn edit_prediction_preview_is_active(&self) -> bool {
4797 matches!(
4798 self.edit_prediction_preview,
4799 EditPredictionPreview::Active { .. }
4800 )
4801 }
4802
4803 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4804 let cursor = self.selections.newest_anchor().head();
4805 if let Some((buffer, cursor_position)) =
4806 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4807 {
4808 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4809 } else {
4810 false
4811 }
4812 }
4813
4814 fn inline_completions_enabled_in_buffer(
4815 &self,
4816 buffer: &Entity<Buffer>,
4817 buffer_position: language::Anchor,
4818 cx: &App,
4819 ) -> bool {
4820 maybe!({
4821 let provider = self.edit_prediction_provider()?;
4822 if !provider.is_enabled(&buffer, buffer_position, cx) {
4823 return Some(false);
4824 }
4825 let buffer = buffer.read(cx);
4826 let Some(file) = buffer.file() else {
4827 return Some(true);
4828 };
4829 let settings = all_language_settings(Some(file), cx);
4830 Some(settings.inline_completions_enabled_for_path(file.path()))
4831 })
4832 .unwrap_or(false)
4833 }
4834
4835 fn cycle_inline_completion(
4836 &mut self,
4837 direction: Direction,
4838 window: &mut Window,
4839 cx: &mut Context<Self>,
4840 ) -> Option<()> {
4841 let provider = self.edit_prediction_provider()?;
4842 let cursor = self.selections.newest_anchor().head();
4843 let (buffer, cursor_buffer_position) =
4844 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4845 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4846 return None;
4847 }
4848
4849 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4850 self.update_visible_inline_completion(window, cx);
4851
4852 Some(())
4853 }
4854
4855 pub fn show_inline_completion(
4856 &mut self,
4857 _: &ShowEditPrediction,
4858 window: &mut Window,
4859 cx: &mut Context<Self>,
4860 ) {
4861 if !self.has_active_inline_completion() {
4862 self.refresh_inline_completion(false, true, window, cx);
4863 return;
4864 }
4865
4866 self.update_visible_inline_completion(window, cx);
4867 }
4868
4869 pub fn display_cursor_names(
4870 &mut self,
4871 _: &DisplayCursorNames,
4872 window: &mut Window,
4873 cx: &mut Context<Self>,
4874 ) {
4875 self.show_cursor_names(window, cx);
4876 }
4877
4878 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4879 self.show_cursor_names = true;
4880 cx.notify();
4881 cx.spawn_in(window, |this, mut cx| async move {
4882 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4883 this.update(&mut cx, |this, cx| {
4884 this.show_cursor_names = false;
4885 cx.notify()
4886 })
4887 .ok()
4888 })
4889 .detach();
4890 }
4891
4892 pub fn next_edit_prediction(
4893 &mut self,
4894 _: &NextEditPrediction,
4895 window: &mut Window,
4896 cx: &mut Context<Self>,
4897 ) {
4898 if self.has_active_inline_completion() {
4899 self.cycle_inline_completion(Direction::Next, window, cx);
4900 } else {
4901 let is_copilot_disabled = self
4902 .refresh_inline_completion(false, true, window, cx)
4903 .is_none();
4904 if is_copilot_disabled {
4905 cx.propagate();
4906 }
4907 }
4908 }
4909
4910 pub fn previous_edit_prediction(
4911 &mut self,
4912 _: &PreviousEditPrediction,
4913 window: &mut Window,
4914 cx: &mut Context<Self>,
4915 ) {
4916 if self.has_active_inline_completion() {
4917 self.cycle_inline_completion(Direction::Prev, window, cx);
4918 } else {
4919 let is_copilot_disabled = self
4920 .refresh_inline_completion(false, true, window, cx)
4921 .is_none();
4922 if is_copilot_disabled {
4923 cx.propagate();
4924 }
4925 }
4926 }
4927
4928 pub fn accept_edit_prediction(
4929 &mut self,
4930 _: &AcceptEditPrediction,
4931 window: &mut Window,
4932 cx: &mut Context<Self>,
4933 ) {
4934 let buffer = self.buffer.read(cx);
4935 let snapshot = buffer.snapshot(cx);
4936 let selection = self.selections.newest_adjusted(cx);
4937 let cursor = selection.head();
4938 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4939 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4940 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4941 {
4942 if cursor.column < suggested_indent.len
4943 && cursor.column <= current_indent.len
4944 && current_indent.len <= suggested_indent.len
4945 {
4946 self.tab(&Default::default(), window, cx);
4947 return;
4948 }
4949 }
4950
4951 if self.show_edit_predictions_in_menu() {
4952 self.hide_context_menu(window, cx);
4953 }
4954
4955 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4956 return;
4957 };
4958
4959 self.report_inline_completion_event(
4960 active_inline_completion.completion_id.clone(),
4961 true,
4962 cx,
4963 );
4964
4965 match &active_inline_completion.completion {
4966 InlineCompletion::Move { target, .. } => {
4967 let target = *target;
4968
4969 if let Some(position_map) = &self.last_position_map {
4970 if position_map
4971 .visible_row_range
4972 .contains(&target.to_display_point(&position_map.snapshot).row())
4973 || !self.edit_prediction_requires_modifier()
4974 {
4975 // Note that this is also done in vim's handler of the Tab action.
4976 self.change_selections(
4977 Some(Autoscroll::newest()),
4978 window,
4979 cx,
4980 |selections| {
4981 selections.select_anchor_ranges([target..target]);
4982 },
4983 );
4984 self.clear_row_highlights::<EditPredictionPreview>();
4985
4986 self.edit_prediction_preview = EditPredictionPreview::Active {
4987 previous_scroll_position: None,
4988 };
4989 } else {
4990 self.edit_prediction_preview = EditPredictionPreview::Active {
4991 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
4992 };
4993 self.highlight_rows::<EditPredictionPreview>(
4994 target..target,
4995 cx.theme().colors().editor_highlighted_line_background,
4996 true,
4997 cx,
4998 );
4999 self.request_autoscroll(Autoscroll::fit(), cx);
5000 }
5001 }
5002 }
5003 InlineCompletion::Edit { edits, .. } => {
5004 if let Some(provider) = self.edit_prediction_provider() {
5005 provider.accept(cx);
5006 }
5007
5008 let snapshot = self.buffer.read(cx).snapshot(cx);
5009 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5010
5011 self.buffer.update(cx, |buffer, cx| {
5012 buffer.edit(edits.iter().cloned(), None, cx)
5013 });
5014
5015 self.change_selections(None, window, cx, |s| {
5016 s.select_anchor_ranges([last_edit_end..last_edit_end])
5017 });
5018
5019 self.update_visible_inline_completion(window, cx);
5020 if self.active_inline_completion.is_none() {
5021 self.refresh_inline_completion(true, true, window, cx);
5022 }
5023
5024 cx.notify();
5025 }
5026 }
5027 }
5028
5029 pub fn accept_partial_inline_completion(
5030 &mut self,
5031 _: &AcceptPartialEditPrediction,
5032 window: &mut Window,
5033 cx: &mut Context<Self>,
5034 ) {
5035 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5036 return;
5037 };
5038 if self.selections.count() != 1 {
5039 return;
5040 }
5041
5042 self.report_inline_completion_event(
5043 active_inline_completion.completion_id.clone(),
5044 true,
5045 cx,
5046 );
5047
5048 match &active_inline_completion.completion {
5049 InlineCompletion::Move { target, .. } => {
5050 let target = *target;
5051 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5052 selections.select_anchor_ranges([target..target]);
5053 });
5054 }
5055 InlineCompletion::Edit { edits, .. } => {
5056 // Find an insertion that starts at the cursor position.
5057 let snapshot = self.buffer.read(cx).snapshot(cx);
5058 let cursor_offset = self.selections.newest::<usize>(cx).head();
5059 let insertion = edits.iter().find_map(|(range, text)| {
5060 let range = range.to_offset(&snapshot);
5061 if range.is_empty() && range.start == cursor_offset {
5062 Some(text)
5063 } else {
5064 None
5065 }
5066 });
5067
5068 if let Some(text) = insertion {
5069 let mut partial_completion = text
5070 .chars()
5071 .by_ref()
5072 .take_while(|c| c.is_alphabetic())
5073 .collect::<String>();
5074 if partial_completion.is_empty() {
5075 partial_completion = text
5076 .chars()
5077 .by_ref()
5078 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5079 .collect::<String>();
5080 }
5081
5082 cx.emit(EditorEvent::InputHandled {
5083 utf16_range_to_replace: None,
5084 text: partial_completion.clone().into(),
5085 });
5086
5087 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5088
5089 self.refresh_inline_completion(true, true, window, cx);
5090 cx.notify();
5091 } else {
5092 self.accept_edit_prediction(&Default::default(), window, cx);
5093 }
5094 }
5095 }
5096 }
5097
5098 fn discard_inline_completion(
5099 &mut self,
5100 should_report_inline_completion_event: bool,
5101 cx: &mut Context<Self>,
5102 ) -> bool {
5103 if should_report_inline_completion_event {
5104 let completion_id = self
5105 .active_inline_completion
5106 .as_ref()
5107 .and_then(|active_completion| active_completion.completion_id.clone());
5108
5109 self.report_inline_completion_event(completion_id, false, cx);
5110 }
5111
5112 if let Some(provider) = self.edit_prediction_provider() {
5113 provider.discard(cx);
5114 }
5115
5116 self.take_active_inline_completion(cx)
5117 }
5118
5119 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5120 let Some(provider) = self.edit_prediction_provider() else {
5121 return;
5122 };
5123
5124 let Some((_, buffer, _)) = self
5125 .buffer
5126 .read(cx)
5127 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5128 else {
5129 return;
5130 };
5131
5132 let extension = buffer
5133 .read(cx)
5134 .file()
5135 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5136
5137 let event_type = match accepted {
5138 true => "Edit Prediction Accepted",
5139 false => "Edit Prediction Discarded",
5140 };
5141 telemetry::event!(
5142 event_type,
5143 provider = provider.name(),
5144 prediction_id = id,
5145 suggestion_accepted = accepted,
5146 file_extension = extension,
5147 );
5148 }
5149
5150 pub fn has_active_inline_completion(&self) -> bool {
5151 self.active_inline_completion.is_some()
5152 }
5153
5154 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5155 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5156 return false;
5157 };
5158
5159 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5160 self.clear_highlights::<InlineCompletionHighlight>(cx);
5161 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5162 true
5163 }
5164
5165 /// Returns true when we're displaying the edit prediction popover below the cursor
5166 /// like we are not previewing and the LSP autocomplete menu is visible
5167 /// or we are in `when_holding_modifier` mode.
5168 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5169 if self.edit_prediction_preview_is_active()
5170 || !self.show_edit_predictions_in_menu()
5171 || !self.edit_predictions_enabled()
5172 {
5173 return false;
5174 }
5175
5176 if self.has_visible_completions_menu() {
5177 return true;
5178 }
5179
5180 has_completion && self.edit_prediction_requires_modifier()
5181 }
5182
5183 fn handle_modifiers_changed(
5184 &mut self,
5185 modifiers: Modifiers,
5186 position_map: &PositionMap,
5187 window: &mut Window,
5188 cx: &mut Context<Self>,
5189 ) {
5190 if self.show_edit_predictions_in_menu() {
5191 self.update_edit_prediction_preview(&modifiers, window, cx);
5192 }
5193
5194 let mouse_position = window.mouse_position();
5195 if !position_map.text_hitbox.is_hovered(window) {
5196 return;
5197 }
5198
5199 self.update_hovered_link(
5200 position_map.point_for_position(mouse_position),
5201 &position_map.snapshot,
5202 modifiers,
5203 window,
5204 cx,
5205 )
5206 }
5207
5208 fn update_edit_prediction_preview(
5209 &mut self,
5210 modifiers: &Modifiers,
5211 window: &mut Window,
5212 cx: &mut Context<Self>,
5213 ) {
5214 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5215 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5216 return;
5217 };
5218
5219 if &accept_keystroke.modifiers == modifiers {
5220 if matches!(
5221 self.edit_prediction_preview,
5222 EditPredictionPreview::Inactive
5223 ) {
5224 self.edit_prediction_preview = EditPredictionPreview::Active {
5225 previous_scroll_position: None,
5226 };
5227
5228 self.update_visible_inline_completion(window, cx);
5229 cx.notify();
5230 }
5231 } else if let EditPredictionPreview::Active {
5232 previous_scroll_position,
5233 } = self.edit_prediction_preview
5234 {
5235 if let (Some(previous_scroll_position), Some(position_map)) =
5236 (previous_scroll_position, self.last_position_map.as_ref())
5237 {
5238 self.set_scroll_position(
5239 previous_scroll_position
5240 .scroll_position(&position_map.snapshot.display_snapshot),
5241 window,
5242 cx,
5243 );
5244 }
5245
5246 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5247 self.clear_row_highlights::<EditPredictionPreview>();
5248 self.update_visible_inline_completion(window, cx);
5249 cx.notify();
5250 }
5251 }
5252
5253 fn update_visible_inline_completion(
5254 &mut self,
5255 _window: &mut Window,
5256 cx: &mut Context<Self>,
5257 ) -> Option<()> {
5258 let selection = self.selections.newest_anchor();
5259 let cursor = selection.head();
5260 let multibuffer = self.buffer.read(cx).snapshot(cx);
5261 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5262 let excerpt_id = cursor.excerpt_id;
5263
5264 let show_in_menu = self.show_edit_predictions_in_menu();
5265 let completions_menu_has_precedence = !show_in_menu
5266 && (self.context_menu.borrow().is_some()
5267 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5268
5269 if completions_menu_has_precedence
5270 || !offset_selection.is_empty()
5271 || self
5272 .active_inline_completion
5273 .as_ref()
5274 .map_or(false, |completion| {
5275 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5276 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5277 !invalidation_range.contains(&offset_selection.head())
5278 })
5279 {
5280 self.discard_inline_completion(false, cx);
5281 return None;
5282 }
5283
5284 self.take_active_inline_completion(cx);
5285 let Some(provider) = self.edit_prediction_provider() else {
5286 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5287 return None;
5288 };
5289
5290 let (buffer, cursor_buffer_position) =
5291 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5292
5293 self.edit_prediction_settings =
5294 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5295
5296 if !self.edit_prediction_settings.is_enabled() {
5297 self.discard_inline_completion(false, cx);
5298 return None;
5299 }
5300
5301 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5302 let edits = inline_completion
5303 .edits
5304 .into_iter()
5305 .flat_map(|(range, new_text)| {
5306 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5307 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5308 Some((start..end, new_text))
5309 })
5310 .collect::<Vec<_>>();
5311 if edits.is_empty() {
5312 return None;
5313 }
5314
5315 let first_edit_start = edits.first().unwrap().0.start;
5316 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5317 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5318
5319 let last_edit_end = edits.last().unwrap().0.end;
5320 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5321 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5322
5323 let cursor_row = cursor.to_point(&multibuffer).row;
5324
5325 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5326
5327 let mut inlay_ids = Vec::new();
5328 let invalidation_row_range;
5329 let move_invalidation_row_range = if cursor_row < edit_start_row {
5330 Some(cursor_row..edit_end_row)
5331 } else if cursor_row > edit_end_row {
5332 Some(edit_start_row..cursor_row)
5333 } else {
5334 None
5335 };
5336 let is_move =
5337 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5338 let completion = if is_move {
5339 invalidation_row_range =
5340 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5341 let target = first_edit_start;
5342 InlineCompletion::Move { target, snapshot }
5343 } else {
5344 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5345 && !self.inline_completions_hidden_for_vim_mode;
5346
5347 if show_completions_in_buffer {
5348 if edits
5349 .iter()
5350 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5351 {
5352 let mut inlays = Vec::new();
5353 for (range, new_text) in &edits {
5354 let inlay = Inlay::inline_completion(
5355 post_inc(&mut self.next_inlay_id),
5356 range.start,
5357 new_text.as_str(),
5358 );
5359 inlay_ids.push(inlay.id);
5360 inlays.push(inlay);
5361 }
5362
5363 self.splice_inlays(&[], inlays, cx);
5364 } else {
5365 let background_color = cx.theme().status().deleted_background;
5366 self.highlight_text::<InlineCompletionHighlight>(
5367 edits.iter().map(|(range, _)| range.clone()).collect(),
5368 HighlightStyle {
5369 background_color: Some(background_color),
5370 ..Default::default()
5371 },
5372 cx,
5373 );
5374 }
5375 }
5376
5377 invalidation_row_range = edit_start_row..edit_end_row;
5378
5379 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5380 if provider.show_tab_accept_marker() {
5381 EditDisplayMode::TabAccept
5382 } else {
5383 EditDisplayMode::Inline
5384 }
5385 } else {
5386 EditDisplayMode::DiffPopover
5387 };
5388
5389 InlineCompletion::Edit {
5390 edits,
5391 edit_preview: inline_completion.edit_preview,
5392 display_mode,
5393 snapshot,
5394 }
5395 };
5396
5397 let invalidation_range = multibuffer
5398 .anchor_before(Point::new(invalidation_row_range.start, 0))
5399 ..multibuffer.anchor_after(Point::new(
5400 invalidation_row_range.end,
5401 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5402 ));
5403
5404 self.stale_inline_completion_in_menu = None;
5405 self.active_inline_completion = Some(InlineCompletionState {
5406 inlay_ids,
5407 completion,
5408 completion_id: inline_completion.id,
5409 invalidation_range,
5410 });
5411
5412 cx.notify();
5413
5414 Some(())
5415 }
5416
5417 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5418 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5419 }
5420
5421 fn render_code_actions_indicator(
5422 &self,
5423 _style: &EditorStyle,
5424 row: DisplayRow,
5425 is_active: bool,
5426 cx: &mut Context<Self>,
5427 ) -> Option<IconButton> {
5428 if self.available_code_actions.is_some() {
5429 Some(
5430 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5431 .shape(ui::IconButtonShape::Square)
5432 .icon_size(IconSize::XSmall)
5433 .icon_color(Color::Muted)
5434 .toggle_state(is_active)
5435 .tooltip({
5436 let focus_handle = self.focus_handle.clone();
5437 move |window, cx| {
5438 Tooltip::for_action_in(
5439 "Toggle Code Actions",
5440 &ToggleCodeActions {
5441 deployed_from_indicator: None,
5442 },
5443 &focus_handle,
5444 window,
5445 cx,
5446 )
5447 }
5448 })
5449 .on_click(cx.listener(move |editor, _e, window, cx| {
5450 window.focus(&editor.focus_handle(cx));
5451 editor.toggle_code_actions(
5452 &ToggleCodeActions {
5453 deployed_from_indicator: Some(row),
5454 },
5455 window,
5456 cx,
5457 );
5458 })),
5459 )
5460 } else {
5461 None
5462 }
5463 }
5464
5465 fn clear_tasks(&mut self) {
5466 self.tasks.clear()
5467 }
5468
5469 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5470 if self.tasks.insert(key, value).is_some() {
5471 // This case should hopefully be rare, but just in case...
5472 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5473 }
5474 }
5475
5476 fn build_tasks_context(
5477 project: &Entity<Project>,
5478 buffer: &Entity<Buffer>,
5479 buffer_row: u32,
5480 tasks: &Arc<RunnableTasks>,
5481 cx: &mut Context<Self>,
5482 ) -> Task<Option<task::TaskContext>> {
5483 let position = Point::new(buffer_row, tasks.column);
5484 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5485 let location = Location {
5486 buffer: buffer.clone(),
5487 range: range_start..range_start,
5488 };
5489 // Fill in the environmental variables from the tree-sitter captures
5490 let mut captured_task_variables = TaskVariables::default();
5491 for (capture_name, value) in tasks.extra_variables.clone() {
5492 captured_task_variables.insert(
5493 task::VariableName::Custom(capture_name.into()),
5494 value.clone(),
5495 );
5496 }
5497 project.update(cx, |project, cx| {
5498 project.task_store().update(cx, |task_store, cx| {
5499 task_store.task_context_for_location(captured_task_variables, location, cx)
5500 })
5501 })
5502 }
5503
5504 pub fn spawn_nearest_task(
5505 &mut self,
5506 action: &SpawnNearestTask,
5507 window: &mut Window,
5508 cx: &mut Context<Self>,
5509 ) {
5510 let Some((workspace, _)) = self.workspace.clone() else {
5511 return;
5512 };
5513 let Some(project) = self.project.clone() else {
5514 return;
5515 };
5516
5517 // Try to find a closest, enclosing node using tree-sitter that has a
5518 // task
5519 let Some((buffer, buffer_row, tasks)) = self
5520 .find_enclosing_node_task(cx)
5521 // Or find the task that's closest in row-distance.
5522 .or_else(|| self.find_closest_task(cx))
5523 else {
5524 return;
5525 };
5526
5527 let reveal_strategy = action.reveal;
5528 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5529 cx.spawn_in(window, |_, mut cx| async move {
5530 let context = task_context.await?;
5531 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5532
5533 let resolved = resolved_task.resolved.as_mut()?;
5534 resolved.reveal = reveal_strategy;
5535
5536 workspace
5537 .update(&mut cx, |workspace, cx| {
5538 workspace::tasks::schedule_resolved_task(
5539 workspace,
5540 task_source_kind,
5541 resolved_task,
5542 false,
5543 cx,
5544 );
5545 })
5546 .ok()
5547 })
5548 .detach();
5549 }
5550
5551 fn find_closest_task(
5552 &mut self,
5553 cx: &mut Context<Self>,
5554 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5555 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5556
5557 let ((buffer_id, row), tasks) = self
5558 .tasks
5559 .iter()
5560 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5561
5562 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5563 let tasks = Arc::new(tasks.to_owned());
5564 Some((buffer, *row, tasks))
5565 }
5566
5567 fn find_enclosing_node_task(
5568 &mut self,
5569 cx: &mut Context<Self>,
5570 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5571 let snapshot = self.buffer.read(cx).snapshot(cx);
5572 let offset = self.selections.newest::<usize>(cx).head();
5573 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5574 let buffer_id = excerpt.buffer().remote_id();
5575
5576 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5577 let mut cursor = layer.node().walk();
5578
5579 while cursor.goto_first_child_for_byte(offset).is_some() {
5580 if cursor.node().end_byte() == offset {
5581 cursor.goto_next_sibling();
5582 }
5583 }
5584
5585 // Ascend to the smallest ancestor that contains the range and has a task.
5586 loop {
5587 let node = cursor.node();
5588 let node_range = node.byte_range();
5589 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5590
5591 // Check if this node contains our offset
5592 if node_range.start <= offset && node_range.end >= offset {
5593 // If it contains offset, check for task
5594 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5595 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5596 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5597 }
5598 }
5599
5600 if !cursor.goto_parent() {
5601 break;
5602 }
5603 }
5604 None
5605 }
5606
5607 fn render_run_indicator(
5608 &self,
5609 _style: &EditorStyle,
5610 is_active: bool,
5611 row: DisplayRow,
5612 cx: &mut Context<Self>,
5613 ) -> IconButton {
5614 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5615 .shape(ui::IconButtonShape::Square)
5616 .icon_size(IconSize::XSmall)
5617 .icon_color(Color::Muted)
5618 .toggle_state(is_active)
5619 .on_click(cx.listener(move |editor, _e, window, cx| {
5620 window.focus(&editor.focus_handle(cx));
5621 editor.toggle_code_actions(
5622 &ToggleCodeActions {
5623 deployed_from_indicator: Some(row),
5624 },
5625 window,
5626 cx,
5627 );
5628 }))
5629 }
5630
5631 pub fn context_menu_visible(&self) -> bool {
5632 !self.edit_prediction_preview_is_active()
5633 && self
5634 .context_menu
5635 .borrow()
5636 .as_ref()
5637 .map_or(false, |menu| menu.visible())
5638 }
5639
5640 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5641 self.context_menu
5642 .borrow()
5643 .as_ref()
5644 .map(|menu| menu.origin())
5645 }
5646
5647 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5648 px(30.)
5649 }
5650
5651 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5652 if self.read_only(cx) {
5653 cx.theme().players().read_only()
5654 } else {
5655 self.style.as_ref().unwrap().local_player
5656 }
5657 }
5658
5659 #[allow(clippy::too_many_arguments)]
5660 fn render_edit_prediction_cursor_popover(
5661 &self,
5662 min_width: Pixels,
5663 max_width: Pixels,
5664 cursor_point: Point,
5665 style: &EditorStyle,
5666 accept_keystroke: &gpui::Keystroke,
5667 _window: &Window,
5668 cx: &mut Context<Editor>,
5669 ) -> Option<AnyElement> {
5670 let provider = self.edit_prediction_provider.as_ref()?;
5671
5672 if provider.provider.needs_terms_acceptance(cx) {
5673 return Some(
5674 h_flex()
5675 .min_w(min_width)
5676 .flex_1()
5677 .px_2()
5678 .py_1()
5679 .gap_3()
5680 .elevation_2(cx)
5681 .hover(|style| style.bg(cx.theme().colors().element_hover))
5682 .id("accept-terms")
5683 .cursor_pointer()
5684 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5685 .on_click(cx.listener(|this, _event, window, cx| {
5686 cx.stop_propagation();
5687 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5688 window.dispatch_action(
5689 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5690 cx,
5691 );
5692 }))
5693 .child(
5694 h_flex()
5695 .flex_1()
5696 .gap_2()
5697 .child(Icon::new(IconName::ZedPredict))
5698 .child(Label::new("Accept Terms of Service"))
5699 .child(div().w_full())
5700 .child(
5701 Icon::new(IconName::ArrowUpRight)
5702 .color(Color::Muted)
5703 .size(IconSize::Small),
5704 )
5705 .into_any_element(),
5706 )
5707 .into_any(),
5708 );
5709 }
5710
5711 let is_refreshing = provider.provider.is_refreshing(cx);
5712
5713 fn pending_completion_container() -> Div {
5714 h_flex()
5715 .h_full()
5716 .flex_1()
5717 .gap_2()
5718 .child(Icon::new(IconName::ZedPredict))
5719 }
5720
5721 let completion = match &self.active_inline_completion {
5722 Some(completion) => match &completion.completion {
5723 InlineCompletion::Move {
5724 target, snapshot, ..
5725 } if !self.has_visible_completions_menu() => {
5726 use text::ToPoint as _;
5727
5728 return Some(
5729 h_flex()
5730 .px_2()
5731 .py_1()
5732 .elevation_2(cx)
5733 .border_color(cx.theme().colors().border)
5734 .rounded_tl(px(0.))
5735 .gap_2()
5736 .child(
5737 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5738 Icon::new(IconName::ZedPredictDown)
5739 } else {
5740 Icon::new(IconName::ZedPredictUp)
5741 },
5742 )
5743 .child(Label::new("Hold").size(LabelSize::Small))
5744 .children(ui::render_modifiers(
5745 &accept_keystroke.modifiers,
5746 PlatformStyle::platform(),
5747 Some(Color::Default),
5748 Some(IconSize::Small.rems().into()),
5749 true,
5750 ))
5751 .into_any(),
5752 );
5753 }
5754 _ => self.render_edit_prediction_cursor_popover_preview(
5755 completion,
5756 cursor_point,
5757 style,
5758 cx,
5759 )?,
5760 },
5761
5762 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5763 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5764 stale_completion,
5765 cursor_point,
5766 style,
5767 cx,
5768 )?,
5769
5770 None => {
5771 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5772 }
5773 },
5774
5775 None => pending_completion_container().child(Label::new("No Prediction")),
5776 };
5777
5778 let completion = if is_refreshing {
5779 completion
5780 .with_animation(
5781 "loading-completion",
5782 Animation::new(Duration::from_secs(2))
5783 .repeat()
5784 .with_easing(pulsating_between(0.4, 0.8)),
5785 |label, delta| label.opacity(delta),
5786 )
5787 .into_any_element()
5788 } else {
5789 completion.into_any_element()
5790 };
5791
5792 let has_completion = self.active_inline_completion.is_some();
5793
5794 Some(
5795 h_flex()
5796 .min_w(min_width)
5797 .max_w(max_width)
5798 .flex_1()
5799 .px_2()
5800 .elevation_2(cx)
5801 .border_color(cx.theme().colors().border)
5802 .child(div().py_1().overflow_hidden().child(completion))
5803 .child(
5804 h_flex()
5805 .h_full()
5806 .border_l_1()
5807 .border_color(cx.theme().colors().border)
5808 .gap_1()
5809 .py_1()
5810 .pl_2()
5811 .child(
5812 h_flex()
5813 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5814 .gap_1()
5815 .children(ui::render_modifiers(
5816 &accept_keystroke.modifiers,
5817 PlatformStyle::platform(),
5818 Some(if !has_completion {
5819 Color::Muted
5820 } else {
5821 Color::Default
5822 }),
5823 None,
5824 true,
5825 )),
5826 )
5827 .child(Label::new("Preview").into_any_element())
5828 .opacity(if has_completion { 1.0 } else { 0.4 }),
5829 )
5830 .into_any(),
5831 )
5832 }
5833
5834 fn render_edit_prediction_cursor_popover_preview(
5835 &self,
5836 completion: &InlineCompletionState,
5837 cursor_point: Point,
5838 style: &EditorStyle,
5839 cx: &mut Context<Editor>,
5840 ) -> Option<Div> {
5841 use text::ToPoint as _;
5842
5843 fn render_relative_row_jump(
5844 prefix: impl Into<String>,
5845 current_row: u32,
5846 target_row: u32,
5847 ) -> Div {
5848 let (row_diff, arrow) = if target_row < current_row {
5849 (current_row - target_row, IconName::ArrowUp)
5850 } else {
5851 (target_row - current_row, IconName::ArrowDown)
5852 };
5853
5854 h_flex()
5855 .child(
5856 Label::new(format!("{}{}", prefix.into(), row_diff))
5857 .color(Color::Muted)
5858 .size(LabelSize::Small),
5859 )
5860 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5861 }
5862
5863 match &completion.completion {
5864 InlineCompletion::Move {
5865 target, snapshot, ..
5866 } => Some(
5867 h_flex()
5868 .px_2()
5869 .gap_2()
5870 .flex_1()
5871 .child(
5872 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5873 Icon::new(IconName::ZedPredictDown)
5874 } else {
5875 Icon::new(IconName::ZedPredictUp)
5876 },
5877 )
5878 .child(Label::new("Jump to Edit")),
5879 ),
5880
5881 InlineCompletion::Edit {
5882 edits,
5883 edit_preview,
5884 snapshot,
5885 display_mode: _,
5886 } => {
5887 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5888
5889 let highlighted_edits = crate::inline_completion_edit_text(
5890 &snapshot,
5891 &edits,
5892 edit_preview.as_ref()?,
5893 true,
5894 cx,
5895 );
5896
5897 let len_total = highlighted_edits.text.len();
5898 let first_line = &highlighted_edits.text
5899 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5900 let first_line_len = first_line.len();
5901
5902 let first_highlight_start = highlighted_edits
5903 .highlights
5904 .first()
5905 .map_or(0, |(range, _)| range.start);
5906 let drop_prefix_len = first_line
5907 .char_indices()
5908 .find(|(_, c)| !c.is_whitespace())
5909 .map_or(first_highlight_start, |(ix, _)| {
5910 ix.min(first_highlight_start)
5911 });
5912
5913 let preview_text = &first_line[drop_prefix_len..];
5914 let preview_len = preview_text.len();
5915 let highlights = highlighted_edits
5916 .highlights
5917 .into_iter()
5918 .take_until(|(range, _)| range.start > first_line_len)
5919 .map(|(range, style)| {
5920 (
5921 range.start - drop_prefix_len
5922 ..(range.end - drop_prefix_len).min(preview_len),
5923 style,
5924 )
5925 });
5926
5927 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5928 .with_highlights(&style.text, highlights);
5929
5930 let preview = h_flex()
5931 .gap_1()
5932 .min_w_16()
5933 .child(styled_text)
5934 .when(len_total > first_line_len, |parent| parent.child("…"));
5935
5936 let left = if first_edit_row != cursor_point.row {
5937 render_relative_row_jump("", cursor_point.row, first_edit_row)
5938 .into_any_element()
5939 } else {
5940 Icon::new(IconName::ZedPredict).into_any_element()
5941 };
5942
5943 Some(
5944 h_flex()
5945 .h_full()
5946 .flex_1()
5947 .gap_2()
5948 .pr_1()
5949 .overflow_x_hidden()
5950 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5951 .child(left)
5952 .child(preview),
5953 )
5954 }
5955 }
5956 }
5957
5958 fn render_context_menu(
5959 &self,
5960 style: &EditorStyle,
5961 max_height_in_lines: u32,
5962 y_flipped: bool,
5963 window: &mut Window,
5964 cx: &mut Context<Editor>,
5965 ) -> Option<AnyElement> {
5966 let menu = self.context_menu.borrow();
5967 let menu = menu.as_ref()?;
5968 if !menu.visible() {
5969 return None;
5970 };
5971 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5972 }
5973
5974 fn render_context_menu_aside(
5975 &self,
5976 style: &EditorStyle,
5977 max_size: Size<Pixels>,
5978 cx: &mut Context<Editor>,
5979 ) -> Option<AnyElement> {
5980 self.context_menu.borrow().as_ref().and_then(|menu| {
5981 if menu.visible() {
5982 menu.render_aside(
5983 style,
5984 max_size,
5985 self.workspace.as_ref().map(|(w, _)| w.clone()),
5986 cx,
5987 )
5988 } else {
5989 None
5990 }
5991 })
5992 }
5993
5994 fn hide_context_menu(
5995 &mut self,
5996 window: &mut Window,
5997 cx: &mut Context<Self>,
5998 ) -> Option<CodeContextMenu> {
5999 cx.notify();
6000 self.completion_tasks.clear();
6001 let context_menu = self.context_menu.borrow_mut().take();
6002 self.stale_inline_completion_in_menu.take();
6003 self.update_visible_inline_completion(window, cx);
6004 context_menu
6005 }
6006
6007 fn show_snippet_choices(
6008 &mut self,
6009 choices: &Vec<String>,
6010 selection: Range<Anchor>,
6011 cx: &mut Context<Self>,
6012 ) {
6013 if selection.start.buffer_id.is_none() {
6014 return;
6015 }
6016 let buffer_id = selection.start.buffer_id.unwrap();
6017 let buffer = self.buffer().read(cx).buffer(buffer_id);
6018 let id = post_inc(&mut self.next_completion_id);
6019
6020 if let Some(buffer) = buffer {
6021 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6022 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6023 ));
6024 }
6025 }
6026
6027 pub fn insert_snippet(
6028 &mut self,
6029 insertion_ranges: &[Range<usize>],
6030 snippet: Snippet,
6031 window: &mut Window,
6032 cx: &mut Context<Self>,
6033 ) -> Result<()> {
6034 struct Tabstop<T> {
6035 is_end_tabstop: bool,
6036 ranges: Vec<Range<T>>,
6037 choices: Option<Vec<String>>,
6038 }
6039
6040 let tabstops = self.buffer.update(cx, |buffer, cx| {
6041 let snippet_text: Arc<str> = snippet.text.clone().into();
6042 buffer.edit(
6043 insertion_ranges
6044 .iter()
6045 .cloned()
6046 .map(|range| (range, snippet_text.clone())),
6047 Some(AutoindentMode::EachLine),
6048 cx,
6049 );
6050
6051 let snapshot = &*buffer.read(cx);
6052 let snippet = &snippet;
6053 snippet
6054 .tabstops
6055 .iter()
6056 .map(|tabstop| {
6057 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6058 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6059 });
6060 let mut tabstop_ranges = tabstop
6061 .ranges
6062 .iter()
6063 .flat_map(|tabstop_range| {
6064 let mut delta = 0_isize;
6065 insertion_ranges.iter().map(move |insertion_range| {
6066 let insertion_start = insertion_range.start as isize + delta;
6067 delta +=
6068 snippet.text.len() as isize - insertion_range.len() as isize;
6069
6070 let start = ((insertion_start + tabstop_range.start) as usize)
6071 .min(snapshot.len());
6072 let end = ((insertion_start + tabstop_range.end) as usize)
6073 .min(snapshot.len());
6074 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6075 })
6076 })
6077 .collect::<Vec<_>>();
6078 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6079
6080 Tabstop {
6081 is_end_tabstop,
6082 ranges: tabstop_ranges,
6083 choices: tabstop.choices.clone(),
6084 }
6085 })
6086 .collect::<Vec<_>>()
6087 });
6088 if let Some(tabstop) = tabstops.first() {
6089 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6090 s.select_ranges(tabstop.ranges.iter().cloned());
6091 });
6092
6093 if let Some(choices) = &tabstop.choices {
6094 if let Some(selection) = tabstop.ranges.first() {
6095 self.show_snippet_choices(choices, selection.clone(), cx)
6096 }
6097 }
6098
6099 // If we're already at the last tabstop and it's at the end of the snippet,
6100 // we're done, we don't need to keep the state around.
6101 if !tabstop.is_end_tabstop {
6102 let choices = tabstops
6103 .iter()
6104 .map(|tabstop| tabstop.choices.clone())
6105 .collect();
6106
6107 let ranges = tabstops
6108 .into_iter()
6109 .map(|tabstop| tabstop.ranges)
6110 .collect::<Vec<_>>();
6111
6112 self.snippet_stack.push(SnippetState {
6113 active_index: 0,
6114 ranges,
6115 choices,
6116 });
6117 }
6118
6119 // Check whether the just-entered snippet ends with an auto-closable bracket.
6120 if self.autoclose_regions.is_empty() {
6121 let snapshot = self.buffer.read(cx).snapshot(cx);
6122 for selection in &mut self.selections.all::<Point>(cx) {
6123 let selection_head = selection.head();
6124 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6125 continue;
6126 };
6127
6128 let mut bracket_pair = None;
6129 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6130 let prev_chars = snapshot
6131 .reversed_chars_at(selection_head)
6132 .collect::<String>();
6133 for (pair, enabled) in scope.brackets() {
6134 if enabled
6135 && pair.close
6136 && prev_chars.starts_with(pair.start.as_str())
6137 && next_chars.starts_with(pair.end.as_str())
6138 {
6139 bracket_pair = Some(pair.clone());
6140 break;
6141 }
6142 }
6143 if let Some(pair) = bracket_pair {
6144 let start = snapshot.anchor_after(selection_head);
6145 let end = snapshot.anchor_after(selection_head);
6146 self.autoclose_regions.push(AutocloseRegion {
6147 selection_id: selection.id,
6148 range: start..end,
6149 pair,
6150 });
6151 }
6152 }
6153 }
6154 }
6155 Ok(())
6156 }
6157
6158 pub fn move_to_next_snippet_tabstop(
6159 &mut self,
6160 window: &mut Window,
6161 cx: &mut Context<Self>,
6162 ) -> bool {
6163 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6164 }
6165
6166 pub fn move_to_prev_snippet_tabstop(
6167 &mut self,
6168 window: &mut Window,
6169 cx: &mut Context<Self>,
6170 ) -> bool {
6171 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6172 }
6173
6174 pub fn move_to_snippet_tabstop(
6175 &mut self,
6176 bias: Bias,
6177 window: &mut Window,
6178 cx: &mut Context<Self>,
6179 ) -> bool {
6180 if let Some(mut snippet) = self.snippet_stack.pop() {
6181 match bias {
6182 Bias::Left => {
6183 if snippet.active_index > 0 {
6184 snippet.active_index -= 1;
6185 } else {
6186 self.snippet_stack.push(snippet);
6187 return false;
6188 }
6189 }
6190 Bias::Right => {
6191 if snippet.active_index + 1 < snippet.ranges.len() {
6192 snippet.active_index += 1;
6193 } else {
6194 self.snippet_stack.push(snippet);
6195 return false;
6196 }
6197 }
6198 }
6199 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6200 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6201 s.select_anchor_ranges(current_ranges.iter().cloned())
6202 });
6203
6204 if let Some(choices) = &snippet.choices[snippet.active_index] {
6205 if let Some(selection) = current_ranges.first() {
6206 self.show_snippet_choices(&choices, selection.clone(), cx);
6207 }
6208 }
6209
6210 // If snippet state is not at the last tabstop, push it back on the stack
6211 if snippet.active_index + 1 < snippet.ranges.len() {
6212 self.snippet_stack.push(snippet);
6213 }
6214 return true;
6215 }
6216 }
6217
6218 false
6219 }
6220
6221 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6222 self.transact(window, cx, |this, window, cx| {
6223 this.select_all(&SelectAll, window, cx);
6224 this.insert("", window, cx);
6225 });
6226 }
6227
6228 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6229 self.transact(window, cx, |this, window, cx| {
6230 this.select_autoclose_pair(window, cx);
6231 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6232 if !this.linked_edit_ranges.is_empty() {
6233 let selections = this.selections.all::<MultiBufferPoint>(cx);
6234 let snapshot = this.buffer.read(cx).snapshot(cx);
6235
6236 for selection in selections.iter() {
6237 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6238 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6239 if selection_start.buffer_id != selection_end.buffer_id {
6240 continue;
6241 }
6242 if let Some(ranges) =
6243 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6244 {
6245 for (buffer, entries) in ranges {
6246 linked_ranges.entry(buffer).or_default().extend(entries);
6247 }
6248 }
6249 }
6250 }
6251
6252 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6253 if !this.selections.line_mode {
6254 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6255 for selection in &mut selections {
6256 if selection.is_empty() {
6257 let old_head = selection.head();
6258 let mut new_head =
6259 movement::left(&display_map, old_head.to_display_point(&display_map))
6260 .to_point(&display_map);
6261 if let Some((buffer, line_buffer_range)) = display_map
6262 .buffer_snapshot
6263 .buffer_line_for_row(MultiBufferRow(old_head.row))
6264 {
6265 let indent_size =
6266 buffer.indent_size_for_line(line_buffer_range.start.row);
6267 let indent_len = match indent_size.kind {
6268 IndentKind::Space => {
6269 buffer.settings_at(line_buffer_range.start, cx).tab_size
6270 }
6271 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6272 };
6273 if old_head.column <= indent_size.len && old_head.column > 0 {
6274 let indent_len = indent_len.get();
6275 new_head = cmp::min(
6276 new_head,
6277 MultiBufferPoint::new(
6278 old_head.row,
6279 ((old_head.column - 1) / indent_len) * indent_len,
6280 ),
6281 );
6282 }
6283 }
6284
6285 selection.set_head(new_head, SelectionGoal::None);
6286 }
6287 }
6288 }
6289
6290 this.signature_help_state.set_backspace_pressed(true);
6291 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6292 s.select(selections)
6293 });
6294 this.insert("", window, cx);
6295 let empty_str: Arc<str> = Arc::from("");
6296 for (buffer, edits) in linked_ranges {
6297 let snapshot = buffer.read(cx).snapshot();
6298 use text::ToPoint as TP;
6299
6300 let edits = edits
6301 .into_iter()
6302 .map(|range| {
6303 let end_point = TP::to_point(&range.end, &snapshot);
6304 let mut start_point = TP::to_point(&range.start, &snapshot);
6305
6306 if end_point == start_point {
6307 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6308 .saturating_sub(1);
6309 start_point =
6310 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6311 };
6312
6313 (start_point..end_point, empty_str.clone())
6314 })
6315 .sorted_by_key(|(range, _)| range.start)
6316 .collect::<Vec<_>>();
6317 buffer.update(cx, |this, cx| {
6318 this.edit(edits, None, cx);
6319 })
6320 }
6321 this.refresh_inline_completion(true, false, window, cx);
6322 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6323 });
6324 }
6325
6326 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6327 self.transact(window, cx, |this, window, cx| {
6328 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6329 let line_mode = s.line_mode;
6330 s.move_with(|map, selection| {
6331 if selection.is_empty() && !line_mode {
6332 let cursor = movement::right(map, selection.head());
6333 selection.end = cursor;
6334 selection.reversed = true;
6335 selection.goal = SelectionGoal::None;
6336 }
6337 })
6338 });
6339 this.insert("", window, cx);
6340 this.refresh_inline_completion(true, false, window, cx);
6341 });
6342 }
6343
6344 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6345 if self.move_to_prev_snippet_tabstop(window, cx) {
6346 return;
6347 }
6348
6349 self.outdent(&Outdent, window, cx);
6350 }
6351
6352 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6353 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6354 return;
6355 }
6356
6357 let mut selections = self.selections.all_adjusted(cx);
6358 let buffer = self.buffer.read(cx);
6359 let snapshot = buffer.snapshot(cx);
6360 let rows_iter = selections.iter().map(|s| s.head().row);
6361 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6362
6363 let mut edits = Vec::new();
6364 let mut prev_edited_row = 0;
6365 let mut row_delta = 0;
6366 for selection in &mut selections {
6367 if selection.start.row != prev_edited_row {
6368 row_delta = 0;
6369 }
6370 prev_edited_row = selection.end.row;
6371
6372 // If the selection is non-empty, then increase the indentation of the selected lines.
6373 if !selection.is_empty() {
6374 row_delta =
6375 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6376 continue;
6377 }
6378
6379 // If the selection is empty and the cursor is in the leading whitespace before the
6380 // suggested indentation, then auto-indent the line.
6381 let cursor = selection.head();
6382 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6383 if let Some(suggested_indent) =
6384 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6385 {
6386 if cursor.column < suggested_indent.len
6387 && cursor.column <= current_indent.len
6388 && current_indent.len <= suggested_indent.len
6389 {
6390 selection.start = Point::new(cursor.row, suggested_indent.len);
6391 selection.end = selection.start;
6392 if row_delta == 0 {
6393 edits.extend(Buffer::edit_for_indent_size_adjustment(
6394 cursor.row,
6395 current_indent,
6396 suggested_indent,
6397 ));
6398 row_delta = suggested_indent.len - current_indent.len;
6399 }
6400 continue;
6401 }
6402 }
6403
6404 // Otherwise, insert a hard or soft tab.
6405 let settings = buffer.settings_at(cursor, cx);
6406 let tab_size = if settings.hard_tabs {
6407 IndentSize::tab()
6408 } else {
6409 let tab_size = settings.tab_size.get();
6410 let char_column = snapshot
6411 .text_for_range(Point::new(cursor.row, 0)..cursor)
6412 .flat_map(str::chars)
6413 .count()
6414 + row_delta as usize;
6415 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6416 IndentSize::spaces(chars_to_next_tab_stop)
6417 };
6418 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6419 selection.end = selection.start;
6420 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6421 row_delta += tab_size.len;
6422 }
6423
6424 self.transact(window, cx, |this, window, cx| {
6425 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6426 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6427 s.select(selections)
6428 });
6429 this.refresh_inline_completion(true, false, window, cx);
6430 });
6431 }
6432
6433 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6434 if self.read_only(cx) {
6435 return;
6436 }
6437 let mut selections = self.selections.all::<Point>(cx);
6438 let mut prev_edited_row = 0;
6439 let mut row_delta = 0;
6440 let mut edits = Vec::new();
6441 let buffer = self.buffer.read(cx);
6442 let snapshot = buffer.snapshot(cx);
6443 for selection in &mut selections {
6444 if selection.start.row != prev_edited_row {
6445 row_delta = 0;
6446 }
6447 prev_edited_row = selection.end.row;
6448
6449 row_delta =
6450 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6451 }
6452
6453 self.transact(window, cx, |this, window, cx| {
6454 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6455 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6456 s.select(selections)
6457 });
6458 });
6459 }
6460
6461 fn indent_selection(
6462 buffer: &MultiBuffer,
6463 snapshot: &MultiBufferSnapshot,
6464 selection: &mut Selection<Point>,
6465 edits: &mut Vec<(Range<Point>, String)>,
6466 delta_for_start_row: u32,
6467 cx: &App,
6468 ) -> u32 {
6469 let settings = buffer.settings_at(selection.start, cx);
6470 let tab_size = settings.tab_size.get();
6471 let indent_kind = if settings.hard_tabs {
6472 IndentKind::Tab
6473 } else {
6474 IndentKind::Space
6475 };
6476 let mut start_row = selection.start.row;
6477 let mut end_row = selection.end.row + 1;
6478
6479 // If a selection ends at the beginning of a line, don't indent
6480 // that last line.
6481 if selection.end.column == 0 && selection.end.row > selection.start.row {
6482 end_row -= 1;
6483 }
6484
6485 // Avoid re-indenting a row that has already been indented by a
6486 // previous selection, but still update this selection's column
6487 // to reflect that indentation.
6488 if delta_for_start_row > 0 {
6489 start_row += 1;
6490 selection.start.column += delta_for_start_row;
6491 if selection.end.row == selection.start.row {
6492 selection.end.column += delta_for_start_row;
6493 }
6494 }
6495
6496 let mut delta_for_end_row = 0;
6497 let has_multiple_rows = start_row + 1 != end_row;
6498 for row in start_row..end_row {
6499 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6500 let indent_delta = match (current_indent.kind, indent_kind) {
6501 (IndentKind::Space, IndentKind::Space) => {
6502 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6503 IndentSize::spaces(columns_to_next_tab_stop)
6504 }
6505 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6506 (_, IndentKind::Tab) => IndentSize::tab(),
6507 };
6508
6509 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6510 0
6511 } else {
6512 selection.start.column
6513 };
6514 let row_start = Point::new(row, start);
6515 edits.push((
6516 row_start..row_start,
6517 indent_delta.chars().collect::<String>(),
6518 ));
6519
6520 // Update this selection's endpoints to reflect the indentation.
6521 if row == selection.start.row {
6522 selection.start.column += indent_delta.len;
6523 }
6524 if row == selection.end.row {
6525 selection.end.column += indent_delta.len;
6526 delta_for_end_row = indent_delta.len;
6527 }
6528 }
6529
6530 if selection.start.row == selection.end.row {
6531 delta_for_start_row + delta_for_end_row
6532 } else {
6533 delta_for_end_row
6534 }
6535 }
6536
6537 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6538 if self.read_only(cx) {
6539 return;
6540 }
6541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6542 let selections = self.selections.all::<Point>(cx);
6543 let mut deletion_ranges = Vec::new();
6544 let mut last_outdent = None;
6545 {
6546 let buffer = self.buffer.read(cx);
6547 let snapshot = buffer.snapshot(cx);
6548 for selection in &selections {
6549 let settings = buffer.settings_at(selection.start, cx);
6550 let tab_size = settings.tab_size.get();
6551 let mut rows = selection.spanned_rows(false, &display_map);
6552
6553 // Avoid re-outdenting a row that has already been outdented by a
6554 // previous selection.
6555 if let Some(last_row) = last_outdent {
6556 if last_row == rows.start {
6557 rows.start = rows.start.next_row();
6558 }
6559 }
6560 let has_multiple_rows = rows.len() > 1;
6561 for row in rows.iter_rows() {
6562 let indent_size = snapshot.indent_size_for_line(row);
6563 if indent_size.len > 0 {
6564 let deletion_len = match indent_size.kind {
6565 IndentKind::Space => {
6566 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6567 if columns_to_prev_tab_stop == 0 {
6568 tab_size
6569 } else {
6570 columns_to_prev_tab_stop
6571 }
6572 }
6573 IndentKind::Tab => 1,
6574 };
6575 let start = if has_multiple_rows
6576 || deletion_len > selection.start.column
6577 || indent_size.len < selection.start.column
6578 {
6579 0
6580 } else {
6581 selection.start.column - deletion_len
6582 };
6583 deletion_ranges.push(
6584 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6585 );
6586 last_outdent = Some(row);
6587 }
6588 }
6589 }
6590 }
6591
6592 self.transact(window, cx, |this, window, cx| {
6593 this.buffer.update(cx, |buffer, cx| {
6594 let empty_str: Arc<str> = Arc::default();
6595 buffer.edit(
6596 deletion_ranges
6597 .into_iter()
6598 .map(|range| (range, empty_str.clone())),
6599 None,
6600 cx,
6601 );
6602 });
6603 let selections = this.selections.all::<usize>(cx);
6604 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6605 s.select(selections)
6606 });
6607 });
6608 }
6609
6610 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6611 if self.read_only(cx) {
6612 return;
6613 }
6614 let selections = self
6615 .selections
6616 .all::<usize>(cx)
6617 .into_iter()
6618 .map(|s| s.range());
6619
6620 self.transact(window, cx, |this, window, cx| {
6621 this.buffer.update(cx, |buffer, cx| {
6622 buffer.autoindent_ranges(selections, cx);
6623 });
6624 let selections = this.selections.all::<usize>(cx);
6625 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6626 s.select(selections)
6627 });
6628 });
6629 }
6630
6631 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6632 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6633 let selections = self.selections.all::<Point>(cx);
6634
6635 let mut new_cursors = Vec::new();
6636 let mut edit_ranges = Vec::new();
6637 let mut selections = selections.iter().peekable();
6638 while let Some(selection) = selections.next() {
6639 let mut rows = selection.spanned_rows(false, &display_map);
6640 let goal_display_column = selection.head().to_display_point(&display_map).column();
6641
6642 // Accumulate contiguous regions of rows that we want to delete.
6643 while let Some(next_selection) = selections.peek() {
6644 let next_rows = next_selection.spanned_rows(false, &display_map);
6645 if next_rows.start <= rows.end {
6646 rows.end = next_rows.end;
6647 selections.next().unwrap();
6648 } else {
6649 break;
6650 }
6651 }
6652
6653 let buffer = &display_map.buffer_snapshot;
6654 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6655 let edit_end;
6656 let cursor_buffer_row;
6657 if buffer.max_point().row >= rows.end.0 {
6658 // If there's a line after the range, delete the \n from the end of the row range
6659 // and position the cursor on the next line.
6660 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6661 cursor_buffer_row = rows.end;
6662 } else {
6663 // If there isn't a line after the range, delete the \n from the line before the
6664 // start of the row range and position the cursor there.
6665 edit_start = edit_start.saturating_sub(1);
6666 edit_end = buffer.len();
6667 cursor_buffer_row = rows.start.previous_row();
6668 }
6669
6670 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6671 *cursor.column_mut() =
6672 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6673
6674 new_cursors.push((
6675 selection.id,
6676 buffer.anchor_after(cursor.to_point(&display_map)),
6677 ));
6678 edit_ranges.push(edit_start..edit_end);
6679 }
6680
6681 self.transact(window, cx, |this, window, cx| {
6682 let buffer = this.buffer.update(cx, |buffer, cx| {
6683 let empty_str: Arc<str> = Arc::default();
6684 buffer.edit(
6685 edit_ranges
6686 .into_iter()
6687 .map(|range| (range, empty_str.clone())),
6688 None,
6689 cx,
6690 );
6691 buffer.snapshot(cx)
6692 });
6693 let new_selections = new_cursors
6694 .into_iter()
6695 .map(|(id, cursor)| {
6696 let cursor = cursor.to_point(&buffer);
6697 Selection {
6698 id,
6699 start: cursor,
6700 end: cursor,
6701 reversed: false,
6702 goal: SelectionGoal::None,
6703 }
6704 })
6705 .collect();
6706
6707 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6708 s.select(new_selections);
6709 });
6710 });
6711 }
6712
6713 pub fn join_lines_impl(
6714 &mut self,
6715 insert_whitespace: bool,
6716 window: &mut Window,
6717 cx: &mut Context<Self>,
6718 ) {
6719 if self.read_only(cx) {
6720 return;
6721 }
6722 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6723 for selection in self.selections.all::<Point>(cx) {
6724 let start = MultiBufferRow(selection.start.row);
6725 // Treat single line selections as if they include the next line. Otherwise this action
6726 // would do nothing for single line selections individual cursors.
6727 let end = if selection.start.row == selection.end.row {
6728 MultiBufferRow(selection.start.row + 1)
6729 } else {
6730 MultiBufferRow(selection.end.row)
6731 };
6732
6733 if let Some(last_row_range) = row_ranges.last_mut() {
6734 if start <= last_row_range.end {
6735 last_row_range.end = end;
6736 continue;
6737 }
6738 }
6739 row_ranges.push(start..end);
6740 }
6741
6742 let snapshot = self.buffer.read(cx).snapshot(cx);
6743 let mut cursor_positions = Vec::new();
6744 for row_range in &row_ranges {
6745 let anchor = snapshot.anchor_before(Point::new(
6746 row_range.end.previous_row().0,
6747 snapshot.line_len(row_range.end.previous_row()),
6748 ));
6749 cursor_positions.push(anchor..anchor);
6750 }
6751
6752 self.transact(window, cx, |this, window, cx| {
6753 for row_range in row_ranges.into_iter().rev() {
6754 for row in row_range.iter_rows().rev() {
6755 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6756 let next_line_row = row.next_row();
6757 let indent = snapshot.indent_size_for_line(next_line_row);
6758 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6759
6760 let replace =
6761 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6762 " "
6763 } else {
6764 ""
6765 };
6766
6767 this.buffer.update(cx, |buffer, cx| {
6768 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6769 });
6770 }
6771 }
6772
6773 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6774 s.select_anchor_ranges(cursor_positions)
6775 });
6776 });
6777 }
6778
6779 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6780 self.join_lines_impl(true, window, cx);
6781 }
6782
6783 pub fn sort_lines_case_sensitive(
6784 &mut self,
6785 _: &SortLinesCaseSensitive,
6786 window: &mut Window,
6787 cx: &mut Context<Self>,
6788 ) {
6789 self.manipulate_lines(window, cx, |lines| lines.sort())
6790 }
6791
6792 pub fn sort_lines_case_insensitive(
6793 &mut self,
6794 _: &SortLinesCaseInsensitive,
6795 window: &mut Window,
6796 cx: &mut Context<Self>,
6797 ) {
6798 self.manipulate_lines(window, cx, |lines| {
6799 lines.sort_by_key(|line| line.to_lowercase())
6800 })
6801 }
6802
6803 pub fn unique_lines_case_insensitive(
6804 &mut self,
6805 _: &UniqueLinesCaseInsensitive,
6806 window: &mut Window,
6807 cx: &mut Context<Self>,
6808 ) {
6809 self.manipulate_lines(window, cx, |lines| {
6810 let mut seen = HashSet::default();
6811 lines.retain(|line| seen.insert(line.to_lowercase()));
6812 })
6813 }
6814
6815 pub fn unique_lines_case_sensitive(
6816 &mut self,
6817 _: &UniqueLinesCaseSensitive,
6818 window: &mut Window,
6819 cx: &mut Context<Self>,
6820 ) {
6821 self.manipulate_lines(window, cx, |lines| {
6822 let mut seen = HashSet::default();
6823 lines.retain(|line| seen.insert(*line));
6824 })
6825 }
6826
6827 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6828 let mut revert_changes = HashMap::default();
6829 let snapshot = self.snapshot(window, cx);
6830 for hunk in snapshot
6831 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6832 {
6833 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6834 }
6835 if !revert_changes.is_empty() {
6836 self.transact(window, cx, |editor, window, cx| {
6837 editor.revert(revert_changes, window, cx);
6838 });
6839 }
6840 }
6841
6842 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6843 let Some(project) = self.project.clone() else {
6844 return;
6845 };
6846 self.reload(project, window, cx)
6847 .detach_and_notify_err(window, cx);
6848 }
6849
6850 pub fn revert_selected_hunks(
6851 &mut self,
6852 _: &RevertSelectedHunks,
6853 window: &mut Window,
6854 cx: &mut Context<Self>,
6855 ) {
6856 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6857 self.revert_hunks_in_ranges(selections, window, cx);
6858 }
6859
6860 fn revert_hunks_in_ranges(
6861 &mut self,
6862 ranges: impl Iterator<Item = Range<Point>>,
6863 window: &mut Window,
6864 cx: &mut Context<Editor>,
6865 ) {
6866 let mut revert_changes = HashMap::default();
6867 let snapshot = self.snapshot(window, cx);
6868 for hunk in &snapshot.hunks_for_ranges(ranges) {
6869 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6870 }
6871 if !revert_changes.is_empty() {
6872 self.transact(window, cx, |editor, window, cx| {
6873 editor.revert(revert_changes, window, cx);
6874 });
6875 }
6876 }
6877
6878 pub fn open_active_item_in_terminal(
6879 &mut self,
6880 _: &OpenInTerminal,
6881 window: &mut Window,
6882 cx: &mut Context<Self>,
6883 ) {
6884 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6885 let project_path = buffer.read(cx).project_path(cx)?;
6886 let project = self.project.as_ref()?.read(cx);
6887 let entry = project.entry_for_path(&project_path, cx)?;
6888 let parent = match &entry.canonical_path {
6889 Some(canonical_path) => canonical_path.to_path_buf(),
6890 None => project.absolute_path(&project_path, cx)?,
6891 }
6892 .parent()?
6893 .to_path_buf();
6894 Some(parent)
6895 }) {
6896 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6897 }
6898 }
6899
6900 pub fn prepare_revert_change(
6901 &self,
6902 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6903 hunk: &MultiBufferDiffHunk,
6904 cx: &mut App,
6905 ) -> Option<()> {
6906 let buffer = self.buffer.read(cx);
6907 let diff = buffer.diff_for(hunk.buffer_id)?;
6908 let buffer = buffer.buffer(hunk.buffer_id)?;
6909 let buffer = buffer.read(cx);
6910 let original_text = diff
6911 .read(cx)
6912 .base_text()
6913 .as_ref()?
6914 .as_rope()
6915 .slice(hunk.diff_base_byte_range.clone());
6916 let buffer_snapshot = buffer.snapshot();
6917 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6918 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6919 probe
6920 .0
6921 .start
6922 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6923 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6924 }) {
6925 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6926 Some(())
6927 } else {
6928 None
6929 }
6930 }
6931
6932 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6933 self.manipulate_lines(window, cx, |lines| lines.reverse())
6934 }
6935
6936 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6937 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6938 }
6939
6940 fn manipulate_lines<Fn>(
6941 &mut self,
6942 window: &mut Window,
6943 cx: &mut Context<Self>,
6944 mut callback: Fn,
6945 ) where
6946 Fn: FnMut(&mut Vec<&str>),
6947 {
6948 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6949 let buffer = self.buffer.read(cx).snapshot(cx);
6950
6951 let mut edits = Vec::new();
6952
6953 let selections = self.selections.all::<Point>(cx);
6954 let mut selections = selections.iter().peekable();
6955 let mut contiguous_row_selections = Vec::new();
6956 let mut new_selections = Vec::new();
6957 let mut added_lines = 0;
6958 let mut removed_lines = 0;
6959
6960 while let Some(selection) = selections.next() {
6961 let (start_row, end_row) = consume_contiguous_rows(
6962 &mut contiguous_row_selections,
6963 selection,
6964 &display_map,
6965 &mut selections,
6966 );
6967
6968 let start_point = Point::new(start_row.0, 0);
6969 let end_point = Point::new(
6970 end_row.previous_row().0,
6971 buffer.line_len(end_row.previous_row()),
6972 );
6973 let text = buffer
6974 .text_for_range(start_point..end_point)
6975 .collect::<String>();
6976
6977 let mut lines = text.split('\n').collect_vec();
6978
6979 let lines_before = lines.len();
6980 callback(&mut lines);
6981 let lines_after = lines.len();
6982
6983 edits.push((start_point..end_point, lines.join("\n")));
6984
6985 // Selections must change based on added and removed line count
6986 let start_row =
6987 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6988 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6989 new_selections.push(Selection {
6990 id: selection.id,
6991 start: start_row,
6992 end: end_row,
6993 goal: SelectionGoal::None,
6994 reversed: selection.reversed,
6995 });
6996
6997 if lines_after > lines_before {
6998 added_lines += lines_after - lines_before;
6999 } else if lines_before > lines_after {
7000 removed_lines += lines_before - lines_after;
7001 }
7002 }
7003
7004 self.transact(window, cx, |this, window, cx| {
7005 let buffer = this.buffer.update(cx, |buffer, cx| {
7006 buffer.edit(edits, None, cx);
7007 buffer.snapshot(cx)
7008 });
7009
7010 // Recalculate offsets on newly edited buffer
7011 let new_selections = new_selections
7012 .iter()
7013 .map(|s| {
7014 let start_point = Point::new(s.start.0, 0);
7015 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7016 Selection {
7017 id: s.id,
7018 start: buffer.point_to_offset(start_point),
7019 end: buffer.point_to_offset(end_point),
7020 goal: s.goal,
7021 reversed: s.reversed,
7022 }
7023 })
7024 .collect();
7025
7026 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7027 s.select(new_selections);
7028 });
7029
7030 this.request_autoscroll(Autoscroll::fit(), cx);
7031 });
7032 }
7033
7034 pub fn convert_to_upper_case(
7035 &mut self,
7036 _: &ConvertToUpperCase,
7037 window: &mut Window,
7038 cx: &mut Context<Self>,
7039 ) {
7040 self.manipulate_text(window, cx, |text| text.to_uppercase())
7041 }
7042
7043 pub fn convert_to_lower_case(
7044 &mut self,
7045 _: &ConvertToLowerCase,
7046 window: &mut Window,
7047 cx: &mut Context<Self>,
7048 ) {
7049 self.manipulate_text(window, cx, |text| text.to_lowercase())
7050 }
7051
7052 pub fn convert_to_title_case(
7053 &mut self,
7054 _: &ConvertToTitleCase,
7055 window: &mut Window,
7056 cx: &mut Context<Self>,
7057 ) {
7058 self.manipulate_text(window, cx, |text| {
7059 text.split('\n')
7060 .map(|line| line.to_case(Case::Title))
7061 .join("\n")
7062 })
7063 }
7064
7065 pub fn convert_to_snake_case(
7066 &mut self,
7067 _: &ConvertToSnakeCase,
7068 window: &mut Window,
7069 cx: &mut Context<Self>,
7070 ) {
7071 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7072 }
7073
7074 pub fn convert_to_kebab_case(
7075 &mut self,
7076 _: &ConvertToKebabCase,
7077 window: &mut Window,
7078 cx: &mut Context<Self>,
7079 ) {
7080 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7081 }
7082
7083 pub fn convert_to_upper_camel_case(
7084 &mut self,
7085 _: &ConvertToUpperCamelCase,
7086 window: &mut Window,
7087 cx: &mut Context<Self>,
7088 ) {
7089 self.manipulate_text(window, cx, |text| {
7090 text.split('\n')
7091 .map(|line| line.to_case(Case::UpperCamel))
7092 .join("\n")
7093 })
7094 }
7095
7096 pub fn convert_to_lower_camel_case(
7097 &mut self,
7098 _: &ConvertToLowerCamelCase,
7099 window: &mut Window,
7100 cx: &mut Context<Self>,
7101 ) {
7102 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7103 }
7104
7105 pub fn convert_to_opposite_case(
7106 &mut self,
7107 _: &ConvertToOppositeCase,
7108 window: &mut Window,
7109 cx: &mut Context<Self>,
7110 ) {
7111 self.manipulate_text(window, cx, |text| {
7112 text.chars()
7113 .fold(String::with_capacity(text.len()), |mut t, c| {
7114 if c.is_uppercase() {
7115 t.extend(c.to_lowercase());
7116 } else {
7117 t.extend(c.to_uppercase());
7118 }
7119 t
7120 })
7121 })
7122 }
7123
7124 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7125 where
7126 Fn: FnMut(&str) -> String,
7127 {
7128 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7129 let buffer = self.buffer.read(cx).snapshot(cx);
7130
7131 let mut new_selections = Vec::new();
7132 let mut edits = Vec::new();
7133 let mut selection_adjustment = 0i32;
7134
7135 for selection in self.selections.all::<usize>(cx) {
7136 let selection_is_empty = selection.is_empty();
7137
7138 let (start, end) = if selection_is_empty {
7139 let word_range = movement::surrounding_word(
7140 &display_map,
7141 selection.start.to_display_point(&display_map),
7142 );
7143 let start = word_range.start.to_offset(&display_map, Bias::Left);
7144 let end = word_range.end.to_offset(&display_map, Bias::Left);
7145 (start, end)
7146 } else {
7147 (selection.start, selection.end)
7148 };
7149
7150 let text = buffer.text_for_range(start..end).collect::<String>();
7151 let old_length = text.len() as i32;
7152 let text = callback(&text);
7153
7154 new_selections.push(Selection {
7155 start: (start as i32 - selection_adjustment) as usize,
7156 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7157 goal: SelectionGoal::None,
7158 ..selection
7159 });
7160
7161 selection_adjustment += old_length - text.len() as i32;
7162
7163 edits.push((start..end, text));
7164 }
7165
7166 self.transact(window, cx, |this, window, cx| {
7167 this.buffer.update(cx, |buffer, cx| {
7168 buffer.edit(edits, None, cx);
7169 });
7170
7171 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7172 s.select(new_selections);
7173 });
7174
7175 this.request_autoscroll(Autoscroll::fit(), cx);
7176 });
7177 }
7178
7179 pub fn duplicate(
7180 &mut self,
7181 upwards: bool,
7182 whole_lines: bool,
7183 window: &mut Window,
7184 cx: &mut Context<Self>,
7185 ) {
7186 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7187 let buffer = &display_map.buffer_snapshot;
7188 let selections = self.selections.all::<Point>(cx);
7189
7190 let mut edits = Vec::new();
7191 let mut selections_iter = selections.iter().peekable();
7192 while let Some(selection) = selections_iter.next() {
7193 let mut rows = selection.spanned_rows(false, &display_map);
7194 // duplicate line-wise
7195 if whole_lines || selection.start == selection.end {
7196 // Avoid duplicating the same lines twice.
7197 while let Some(next_selection) = selections_iter.peek() {
7198 let next_rows = next_selection.spanned_rows(false, &display_map);
7199 if next_rows.start < rows.end {
7200 rows.end = next_rows.end;
7201 selections_iter.next().unwrap();
7202 } else {
7203 break;
7204 }
7205 }
7206
7207 // Copy the text from the selected row region and splice it either at the start
7208 // or end of the region.
7209 let start = Point::new(rows.start.0, 0);
7210 let end = Point::new(
7211 rows.end.previous_row().0,
7212 buffer.line_len(rows.end.previous_row()),
7213 );
7214 let text = buffer
7215 .text_for_range(start..end)
7216 .chain(Some("\n"))
7217 .collect::<String>();
7218 let insert_location = if upwards {
7219 Point::new(rows.end.0, 0)
7220 } else {
7221 start
7222 };
7223 edits.push((insert_location..insert_location, text));
7224 } else {
7225 // duplicate character-wise
7226 let start = selection.start;
7227 let end = selection.end;
7228 let text = buffer.text_for_range(start..end).collect::<String>();
7229 edits.push((selection.end..selection.end, text));
7230 }
7231 }
7232
7233 self.transact(window, cx, |this, _, cx| {
7234 this.buffer.update(cx, |buffer, cx| {
7235 buffer.edit(edits, None, cx);
7236 });
7237
7238 this.request_autoscroll(Autoscroll::fit(), cx);
7239 });
7240 }
7241
7242 pub fn duplicate_line_up(
7243 &mut self,
7244 _: &DuplicateLineUp,
7245 window: &mut Window,
7246 cx: &mut Context<Self>,
7247 ) {
7248 self.duplicate(true, true, window, cx);
7249 }
7250
7251 pub fn duplicate_line_down(
7252 &mut self,
7253 _: &DuplicateLineDown,
7254 window: &mut Window,
7255 cx: &mut Context<Self>,
7256 ) {
7257 self.duplicate(false, true, window, cx);
7258 }
7259
7260 pub fn duplicate_selection(
7261 &mut self,
7262 _: &DuplicateSelection,
7263 window: &mut Window,
7264 cx: &mut Context<Self>,
7265 ) {
7266 self.duplicate(false, false, window, cx);
7267 }
7268
7269 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7270 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7271 let buffer = self.buffer.read(cx).snapshot(cx);
7272
7273 let mut edits = Vec::new();
7274 let mut unfold_ranges = Vec::new();
7275 let mut refold_creases = Vec::new();
7276
7277 let selections = self.selections.all::<Point>(cx);
7278 let mut selections = selections.iter().peekable();
7279 let mut contiguous_row_selections = Vec::new();
7280 let mut new_selections = Vec::new();
7281
7282 while let Some(selection) = selections.next() {
7283 // Find all the selections that span a contiguous row range
7284 let (start_row, end_row) = consume_contiguous_rows(
7285 &mut contiguous_row_selections,
7286 selection,
7287 &display_map,
7288 &mut selections,
7289 );
7290
7291 // Move the text spanned by the row range to be before the line preceding the row range
7292 if start_row.0 > 0 {
7293 let range_to_move = Point::new(
7294 start_row.previous_row().0,
7295 buffer.line_len(start_row.previous_row()),
7296 )
7297 ..Point::new(
7298 end_row.previous_row().0,
7299 buffer.line_len(end_row.previous_row()),
7300 );
7301 let insertion_point = display_map
7302 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7303 .0;
7304
7305 // Don't move lines across excerpts
7306 if buffer
7307 .excerpt_containing(insertion_point..range_to_move.end)
7308 .is_some()
7309 {
7310 let text = buffer
7311 .text_for_range(range_to_move.clone())
7312 .flat_map(|s| s.chars())
7313 .skip(1)
7314 .chain(['\n'])
7315 .collect::<String>();
7316
7317 edits.push((
7318 buffer.anchor_after(range_to_move.start)
7319 ..buffer.anchor_before(range_to_move.end),
7320 String::new(),
7321 ));
7322 let insertion_anchor = buffer.anchor_after(insertion_point);
7323 edits.push((insertion_anchor..insertion_anchor, text));
7324
7325 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7326
7327 // Move selections up
7328 new_selections.extend(contiguous_row_selections.drain(..).map(
7329 |mut selection| {
7330 selection.start.row -= row_delta;
7331 selection.end.row -= row_delta;
7332 selection
7333 },
7334 ));
7335
7336 // Move folds up
7337 unfold_ranges.push(range_to_move.clone());
7338 for fold in display_map.folds_in_range(
7339 buffer.anchor_before(range_to_move.start)
7340 ..buffer.anchor_after(range_to_move.end),
7341 ) {
7342 let mut start = fold.range.start.to_point(&buffer);
7343 let mut end = fold.range.end.to_point(&buffer);
7344 start.row -= row_delta;
7345 end.row -= row_delta;
7346 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7347 }
7348 }
7349 }
7350
7351 // If we didn't move line(s), preserve the existing selections
7352 new_selections.append(&mut contiguous_row_selections);
7353 }
7354
7355 self.transact(window, cx, |this, window, cx| {
7356 this.unfold_ranges(&unfold_ranges, true, true, cx);
7357 this.buffer.update(cx, |buffer, cx| {
7358 for (range, text) in edits {
7359 buffer.edit([(range, text)], None, cx);
7360 }
7361 });
7362 this.fold_creases(refold_creases, true, window, cx);
7363 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7364 s.select(new_selections);
7365 })
7366 });
7367 }
7368
7369 pub fn move_line_down(
7370 &mut self,
7371 _: &MoveLineDown,
7372 window: &mut Window,
7373 cx: &mut Context<Self>,
7374 ) {
7375 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7376 let buffer = self.buffer.read(cx).snapshot(cx);
7377
7378 let mut edits = Vec::new();
7379 let mut unfold_ranges = Vec::new();
7380 let mut refold_creases = Vec::new();
7381
7382 let selections = self.selections.all::<Point>(cx);
7383 let mut selections = selections.iter().peekable();
7384 let mut contiguous_row_selections = Vec::new();
7385 let mut new_selections = Vec::new();
7386
7387 while let Some(selection) = selections.next() {
7388 // Find all the selections that span a contiguous row range
7389 let (start_row, end_row) = consume_contiguous_rows(
7390 &mut contiguous_row_selections,
7391 selection,
7392 &display_map,
7393 &mut selections,
7394 );
7395
7396 // Move the text spanned by the row range to be after the last line of the row range
7397 if end_row.0 <= buffer.max_point().row {
7398 let range_to_move =
7399 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7400 let insertion_point = display_map
7401 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7402 .0;
7403
7404 // Don't move lines across excerpt boundaries
7405 if buffer
7406 .excerpt_containing(range_to_move.start..insertion_point)
7407 .is_some()
7408 {
7409 let mut text = String::from("\n");
7410 text.extend(buffer.text_for_range(range_to_move.clone()));
7411 text.pop(); // Drop trailing newline
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 = insertion_point.row - range_to_move.end.row + 1;
7421
7422 // Move selections down
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 down
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 transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7465 let text_layout_details = &self.text_layout_details(window);
7466 self.transact(window, cx, |this, window, cx| {
7467 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7468 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7469 let line_mode = s.line_mode;
7470 s.move_with(|display_map, selection| {
7471 if !selection.is_empty() || line_mode {
7472 return;
7473 }
7474
7475 let mut head = selection.head();
7476 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7477 if head.column() == display_map.line_len(head.row()) {
7478 transpose_offset = display_map
7479 .buffer_snapshot
7480 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7481 }
7482
7483 if transpose_offset == 0 {
7484 return;
7485 }
7486
7487 *head.column_mut() += 1;
7488 head = display_map.clip_point(head, Bias::Right);
7489 let goal = SelectionGoal::HorizontalPosition(
7490 display_map
7491 .x_for_display_point(head, text_layout_details)
7492 .into(),
7493 );
7494 selection.collapse_to(head, goal);
7495
7496 let transpose_start = display_map
7497 .buffer_snapshot
7498 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7499 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7500 let transpose_end = display_map
7501 .buffer_snapshot
7502 .clip_offset(transpose_offset + 1, Bias::Right);
7503 if let Some(ch) =
7504 display_map.buffer_snapshot.chars_at(transpose_start).next()
7505 {
7506 edits.push((transpose_start..transpose_offset, String::new()));
7507 edits.push((transpose_end..transpose_end, ch.to_string()));
7508 }
7509 }
7510 });
7511 edits
7512 });
7513 this.buffer
7514 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7515 let selections = this.selections.all::<usize>(cx);
7516 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7517 s.select(selections);
7518 });
7519 });
7520 }
7521
7522 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7523 self.rewrap_impl(IsVimMode::No, cx)
7524 }
7525
7526 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7527 let buffer = self.buffer.read(cx).snapshot(cx);
7528 let selections = self.selections.all::<Point>(cx);
7529 let mut selections = selections.iter().peekable();
7530
7531 let mut edits = Vec::new();
7532 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7533
7534 while let Some(selection) = selections.next() {
7535 let mut start_row = selection.start.row;
7536 let mut end_row = selection.end.row;
7537
7538 // Skip selections that overlap with a range that has already been rewrapped.
7539 let selection_range = start_row..end_row;
7540 if rewrapped_row_ranges
7541 .iter()
7542 .any(|range| range.overlaps(&selection_range))
7543 {
7544 continue;
7545 }
7546
7547 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7548
7549 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7550 match language_scope.language_name().as_ref() {
7551 "Markdown" | "Plain Text" => {
7552 should_rewrap = true;
7553 }
7554 _ => {}
7555 }
7556 }
7557
7558 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7559
7560 // Since not all lines in the selection may be at the same indent
7561 // level, choose the indent size that is the most common between all
7562 // of the lines.
7563 //
7564 // If there is a tie, we use the deepest indent.
7565 let (indent_size, indent_end) = {
7566 let mut indent_size_occurrences = HashMap::default();
7567 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7568
7569 for row in start_row..=end_row {
7570 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7571 rows_by_indent_size.entry(indent).or_default().push(row);
7572 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7573 }
7574
7575 let indent_size = indent_size_occurrences
7576 .into_iter()
7577 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7578 .map(|(indent, _)| indent)
7579 .unwrap_or_default();
7580 let row = rows_by_indent_size[&indent_size][0];
7581 let indent_end = Point::new(row, indent_size.len);
7582
7583 (indent_size, indent_end)
7584 };
7585
7586 let mut line_prefix = indent_size.chars().collect::<String>();
7587
7588 if let Some(comment_prefix) =
7589 buffer
7590 .language_scope_at(selection.head())
7591 .and_then(|language| {
7592 language
7593 .line_comment_prefixes()
7594 .iter()
7595 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7596 .cloned()
7597 })
7598 {
7599 line_prefix.push_str(&comment_prefix);
7600 should_rewrap = true;
7601 }
7602
7603 if !should_rewrap {
7604 continue;
7605 }
7606
7607 if selection.is_empty() {
7608 'expand_upwards: while start_row > 0 {
7609 let prev_row = start_row - 1;
7610 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7611 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7612 {
7613 start_row = prev_row;
7614 } else {
7615 break 'expand_upwards;
7616 }
7617 }
7618
7619 'expand_downwards: while end_row < buffer.max_point().row {
7620 let next_row = end_row + 1;
7621 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7622 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7623 {
7624 end_row = next_row;
7625 } else {
7626 break 'expand_downwards;
7627 }
7628 }
7629 }
7630
7631 let start = Point::new(start_row, 0);
7632 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7633 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7634 let Some(lines_without_prefixes) = selection_text
7635 .lines()
7636 .map(|line| {
7637 line.strip_prefix(&line_prefix)
7638 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7639 .ok_or_else(|| {
7640 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7641 })
7642 })
7643 .collect::<Result<Vec<_>, _>>()
7644 .log_err()
7645 else {
7646 continue;
7647 };
7648
7649 let wrap_column = buffer
7650 .settings_at(Point::new(start_row, 0), cx)
7651 .preferred_line_length as usize;
7652 let wrapped_text = wrap_with_prefix(
7653 line_prefix,
7654 lines_without_prefixes.join(" "),
7655 wrap_column,
7656 tab_size,
7657 );
7658
7659 // TODO: should always use char-based diff while still supporting cursor behavior that
7660 // matches vim.
7661 let diff = match is_vim_mode {
7662 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7663 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7664 };
7665 let mut offset = start.to_offset(&buffer);
7666 let mut moved_since_edit = true;
7667
7668 for change in diff.iter_all_changes() {
7669 let value = change.value();
7670 match change.tag() {
7671 ChangeTag::Equal => {
7672 offset += value.len();
7673 moved_since_edit = true;
7674 }
7675 ChangeTag::Delete => {
7676 let start = buffer.anchor_after(offset);
7677 let end = buffer.anchor_before(offset + value.len());
7678
7679 if moved_since_edit {
7680 edits.push((start..end, String::new()));
7681 } else {
7682 edits.last_mut().unwrap().0.end = end;
7683 }
7684
7685 offset += value.len();
7686 moved_since_edit = false;
7687 }
7688 ChangeTag::Insert => {
7689 if moved_since_edit {
7690 let anchor = buffer.anchor_after(offset);
7691 edits.push((anchor..anchor, value.to_string()));
7692 } else {
7693 edits.last_mut().unwrap().1.push_str(value);
7694 }
7695
7696 moved_since_edit = false;
7697 }
7698 }
7699 }
7700
7701 rewrapped_row_ranges.push(start_row..=end_row);
7702 }
7703
7704 self.buffer
7705 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7706 }
7707
7708 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7709 let mut text = String::new();
7710 let buffer = self.buffer.read(cx).snapshot(cx);
7711 let mut selections = self.selections.all::<Point>(cx);
7712 let mut clipboard_selections = Vec::with_capacity(selections.len());
7713 {
7714 let max_point = buffer.max_point();
7715 let mut is_first = true;
7716 for selection in &mut selections {
7717 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7718 if is_entire_line {
7719 selection.start = Point::new(selection.start.row, 0);
7720 if !selection.is_empty() && selection.end.column == 0 {
7721 selection.end = cmp::min(max_point, selection.end);
7722 } else {
7723 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7724 }
7725 selection.goal = SelectionGoal::None;
7726 }
7727 if is_first {
7728 is_first = false;
7729 } else {
7730 text += "\n";
7731 }
7732 let mut len = 0;
7733 for chunk in buffer.text_for_range(selection.start..selection.end) {
7734 text.push_str(chunk);
7735 len += chunk.len();
7736 }
7737 clipboard_selections.push(ClipboardSelection {
7738 len,
7739 is_entire_line,
7740 first_line_indent: buffer
7741 .indent_size_for_line(MultiBufferRow(selection.start.row))
7742 .len,
7743 });
7744 }
7745 }
7746
7747 self.transact(window, cx, |this, window, cx| {
7748 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7749 s.select(selections);
7750 });
7751 this.insert("", window, cx);
7752 });
7753 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7754 }
7755
7756 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7757 let item = self.cut_common(window, cx);
7758 cx.write_to_clipboard(item);
7759 }
7760
7761 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7762 self.change_selections(None, window, cx, |s| {
7763 s.move_with(|snapshot, sel| {
7764 if sel.is_empty() {
7765 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7766 }
7767 });
7768 });
7769 let item = self.cut_common(window, cx);
7770 cx.set_global(KillRing(item))
7771 }
7772
7773 pub fn kill_ring_yank(
7774 &mut self,
7775 _: &KillRingYank,
7776 window: &mut Window,
7777 cx: &mut Context<Self>,
7778 ) {
7779 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7780 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7781 (kill_ring.text().to_string(), kill_ring.metadata_json())
7782 } else {
7783 return;
7784 }
7785 } else {
7786 return;
7787 };
7788 self.do_paste(&text, metadata, false, window, cx);
7789 }
7790
7791 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7792 let selections = self.selections.all::<Point>(cx);
7793 let buffer = self.buffer.read(cx).read(cx);
7794 let mut text = String::new();
7795
7796 let mut clipboard_selections = Vec::with_capacity(selections.len());
7797 {
7798 let max_point = buffer.max_point();
7799 let mut is_first = true;
7800 for selection in selections.iter() {
7801 let mut start = selection.start;
7802 let mut end = selection.end;
7803 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7804 if is_entire_line {
7805 start = Point::new(start.row, 0);
7806 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7807 }
7808 if is_first {
7809 is_first = false;
7810 } else {
7811 text += "\n";
7812 }
7813 let mut len = 0;
7814 for chunk in buffer.text_for_range(start..end) {
7815 text.push_str(chunk);
7816 len += chunk.len();
7817 }
7818 clipboard_selections.push(ClipboardSelection {
7819 len,
7820 is_entire_line,
7821 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7822 });
7823 }
7824 }
7825
7826 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7827 text,
7828 clipboard_selections,
7829 ));
7830 }
7831
7832 pub fn do_paste(
7833 &mut self,
7834 text: &String,
7835 clipboard_selections: Option<Vec<ClipboardSelection>>,
7836 handle_entire_lines: bool,
7837 window: &mut Window,
7838 cx: &mut Context<Self>,
7839 ) {
7840 if self.read_only(cx) {
7841 return;
7842 }
7843
7844 let clipboard_text = Cow::Borrowed(text);
7845
7846 self.transact(window, cx, |this, window, cx| {
7847 if let Some(mut clipboard_selections) = clipboard_selections {
7848 let old_selections = this.selections.all::<usize>(cx);
7849 let all_selections_were_entire_line =
7850 clipboard_selections.iter().all(|s| s.is_entire_line);
7851 let first_selection_indent_column =
7852 clipboard_selections.first().map(|s| s.first_line_indent);
7853 if clipboard_selections.len() != old_selections.len() {
7854 clipboard_selections.drain(..);
7855 }
7856 let cursor_offset = this.selections.last::<usize>(cx).head();
7857 let mut auto_indent_on_paste = true;
7858
7859 this.buffer.update(cx, |buffer, cx| {
7860 let snapshot = buffer.read(cx);
7861 auto_indent_on_paste =
7862 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7863
7864 let mut start_offset = 0;
7865 let mut edits = Vec::new();
7866 let mut original_indent_columns = Vec::new();
7867 for (ix, selection) in old_selections.iter().enumerate() {
7868 let to_insert;
7869 let entire_line;
7870 let original_indent_column;
7871 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7872 let end_offset = start_offset + clipboard_selection.len;
7873 to_insert = &clipboard_text[start_offset..end_offset];
7874 entire_line = clipboard_selection.is_entire_line;
7875 start_offset = end_offset + 1;
7876 original_indent_column = Some(clipboard_selection.first_line_indent);
7877 } else {
7878 to_insert = clipboard_text.as_str();
7879 entire_line = all_selections_were_entire_line;
7880 original_indent_column = first_selection_indent_column
7881 }
7882
7883 // If the corresponding selection was empty when this slice of the
7884 // clipboard text was written, then the entire line containing the
7885 // selection was copied. If this selection is also currently empty,
7886 // then paste the line before the current line of the buffer.
7887 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7888 let column = selection.start.to_point(&snapshot).column as usize;
7889 let line_start = selection.start - column;
7890 line_start..line_start
7891 } else {
7892 selection.range()
7893 };
7894
7895 edits.push((range, to_insert));
7896 original_indent_columns.extend(original_indent_column);
7897 }
7898 drop(snapshot);
7899
7900 buffer.edit(
7901 edits,
7902 if auto_indent_on_paste {
7903 Some(AutoindentMode::Block {
7904 original_indent_columns,
7905 })
7906 } else {
7907 None
7908 },
7909 cx,
7910 );
7911 });
7912
7913 let selections = this.selections.all::<usize>(cx);
7914 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7915 s.select(selections)
7916 });
7917 } else {
7918 this.insert(&clipboard_text, window, cx);
7919 }
7920 });
7921 }
7922
7923 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7924 if let Some(item) = cx.read_from_clipboard() {
7925 let entries = item.entries();
7926
7927 match entries.first() {
7928 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7929 // of all the pasted entries.
7930 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7931 .do_paste(
7932 clipboard_string.text(),
7933 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7934 true,
7935 window,
7936 cx,
7937 ),
7938 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7939 }
7940 }
7941 }
7942
7943 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7944 if self.read_only(cx) {
7945 return;
7946 }
7947
7948 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7949 if let Some((selections, _)) =
7950 self.selection_history.transaction(transaction_id).cloned()
7951 {
7952 self.change_selections(None, window, cx, |s| {
7953 s.select_anchors(selections.to_vec());
7954 });
7955 }
7956 self.request_autoscroll(Autoscroll::fit(), cx);
7957 self.unmark_text(window, cx);
7958 self.refresh_inline_completion(true, false, window, cx);
7959 cx.emit(EditorEvent::Edited { transaction_id });
7960 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7961 }
7962 }
7963
7964 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7965 if self.read_only(cx) {
7966 return;
7967 }
7968
7969 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7970 if let Some((_, Some(selections))) =
7971 self.selection_history.transaction(transaction_id).cloned()
7972 {
7973 self.change_selections(None, window, cx, |s| {
7974 s.select_anchors(selections.to_vec());
7975 });
7976 }
7977 self.request_autoscroll(Autoscroll::fit(), cx);
7978 self.unmark_text(window, cx);
7979 self.refresh_inline_completion(true, false, window, cx);
7980 cx.emit(EditorEvent::Edited { transaction_id });
7981 }
7982 }
7983
7984 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7985 self.buffer
7986 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7987 }
7988
7989 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7990 self.buffer
7991 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7992 }
7993
7994 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7996 let line_mode = s.line_mode;
7997 s.move_with(|map, selection| {
7998 let cursor = if selection.is_empty() && !line_mode {
7999 movement::left(map, selection.start)
8000 } else {
8001 selection.start
8002 };
8003 selection.collapse_to(cursor, SelectionGoal::None);
8004 });
8005 })
8006 }
8007
8008 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8009 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8010 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8011 })
8012 }
8013
8014 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8015 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8016 let line_mode = s.line_mode;
8017 s.move_with(|map, selection| {
8018 let cursor = if selection.is_empty() && !line_mode {
8019 movement::right(map, selection.end)
8020 } else {
8021 selection.end
8022 };
8023 selection.collapse_to(cursor, SelectionGoal::None)
8024 });
8025 })
8026 }
8027
8028 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8029 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8030 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8031 })
8032 }
8033
8034 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8035 if self.take_rename(true, window, cx).is_some() {
8036 return;
8037 }
8038
8039 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8040 cx.propagate();
8041 return;
8042 }
8043
8044 let text_layout_details = &self.text_layout_details(window);
8045 let selection_count = self.selections.count();
8046 let first_selection = self.selections.first_anchor();
8047
8048 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8049 let line_mode = s.line_mode;
8050 s.move_with(|map, selection| {
8051 if !selection.is_empty() && !line_mode {
8052 selection.goal = SelectionGoal::None;
8053 }
8054 let (cursor, goal) = movement::up(
8055 map,
8056 selection.start,
8057 selection.goal,
8058 false,
8059 text_layout_details,
8060 );
8061 selection.collapse_to(cursor, goal);
8062 });
8063 });
8064
8065 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8066 {
8067 cx.propagate();
8068 }
8069 }
8070
8071 pub fn move_up_by_lines(
8072 &mut self,
8073 action: &MoveUpByLines,
8074 window: &mut Window,
8075 cx: &mut Context<Self>,
8076 ) {
8077 if self.take_rename(true, window, cx).is_some() {
8078 return;
8079 }
8080
8081 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8082 cx.propagate();
8083 return;
8084 }
8085
8086 let text_layout_details = &self.text_layout_details(window);
8087
8088 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8089 let line_mode = s.line_mode;
8090 s.move_with(|map, selection| {
8091 if !selection.is_empty() && !line_mode {
8092 selection.goal = SelectionGoal::None;
8093 }
8094 let (cursor, goal) = movement::up_by_rows(
8095 map,
8096 selection.start,
8097 action.lines,
8098 selection.goal,
8099 false,
8100 text_layout_details,
8101 );
8102 selection.collapse_to(cursor, goal);
8103 });
8104 })
8105 }
8106
8107 pub fn move_down_by_lines(
8108 &mut self,
8109 action: &MoveDownByLines,
8110 window: &mut Window,
8111 cx: &mut Context<Self>,
8112 ) {
8113 if self.take_rename(true, window, cx).is_some() {
8114 return;
8115 }
8116
8117 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8118 cx.propagate();
8119 return;
8120 }
8121
8122 let text_layout_details = &self.text_layout_details(window);
8123
8124 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8125 let line_mode = s.line_mode;
8126 s.move_with(|map, selection| {
8127 if !selection.is_empty() && !line_mode {
8128 selection.goal = SelectionGoal::None;
8129 }
8130 let (cursor, goal) = movement::down_by_rows(
8131 map,
8132 selection.start,
8133 action.lines,
8134 selection.goal,
8135 false,
8136 text_layout_details,
8137 );
8138 selection.collapse_to(cursor, goal);
8139 });
8140 })
8141 }
8142
8143 pub fn select_down_by_lines(
8144 &mut self,
8145 action: &SelectDownByLines,
8146 window: &mut Window,
8147 cx: &mut Context<Self>,
8148 ) {
8149 let text_layout_details = &self.text_layout_details(window);
8150 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8151 s.move_heads_with(|map, head, goal| {
8152 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8153 })
8154 })
8155 }
8156
8157 pub fn select_up_by_lines(
8158 &mut self,
8159 action: &SelectUpByLines,
8160 window: &mut Window,
8161 cx: &mut Context<Self>,
8162 ) {
8163 let text_layout_details = &self.text_layout_details(window);
8164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8165 s.move_heads_with(|map, head, goal| {
8166 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8167 })
8168 })
8169 }
8170
8171 pub fn select_page_up(
8172 &mut self,
8173 _: &SelectPageUp,
8174 window: &mut Window,
8175 cx: &mut Context<Self>,
8176 ) {
8177 let Some(row_count) = self.visible_row_count() else {
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 s.move_heads_with(|map, head, goal| {
8185 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8186 })
8187 })
8188 }
8189
8190 pub fn move_page_up(
8191 &mut self,
8192 action: &MovePageUp,
8193 window: &mut Window,
8194 cx: &mut Context<Self>,
8195 ) {
8196 if self.take_rename(true, window, cx).is_some() {
8197 return;
8198 }
8199
8200 if self
8201 .context_menu
8202 .borrow_mut()
8203 .as_mut()
8204 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8205 .unwrap_or(false)
8206 {
8207 return;
8208 }
8209
8210 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8211 cx.propagate();
8212 return;
8213 }
8214
8215 let Some(row_count) = self.visible_row_count() else {
8216 return;
8217 };
8218
8219 let autoscroll = if action.center_cursor {
8220 Autoscroll::center()
8221 } else {
8222 Autoscroll::fit()
8223 };
8224
8225 let text_layout_details = &self.text_layout_details(window);
8226
8227 self.change_selections(Some(autoscroll), window, cx, |s| {
8228 let line_mode = s.line_mode;
8229 s.move_with(|map, selection| {
8230 if !selection.is_empty() && !line_mode {
8231 selection.goal = SelectionGoal::None;
8232 }
8233 let (cursor, goal) = movement::up_by_rows(
8234 map,
8235 selection.end,
8236 row_count,
8237 selection.goal,
8238 false,
8239 text_layout_details,
8240 );
8241 selection.collapse_to(cursor, goal);
8242 });
8243 });
8244 }
8245
8246 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8247 let text_layout_details = &self.text_layout_details(window);
8248 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8249 s.move_heads_with(|map, head, goal| {
8250 movement::up(map, head, goal, false, text_layout_details)
8251 })
8252 })
8253 }
8254
8255 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8256 self.take_rename(true, window, cx);
8257
8258 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8259 cx.propagate();
8260 return;
8261 }
8262
8263 let text_layout_details = &self.text_layout_details(window);
8264 let selection_count = self.selections.count();
8265 let first_selection = self.selections.first_anchor();
8266
8267 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8268 let line_mode = s.line_mode;
8269 s.move_with(|map, selection| {
8270 if !selection.is_empty() && !line_mode {
8271 selection.goal = SelectionGoal::None;
8272 }
8273 let (cursor, goal) = movement::down(
8274 map,
8275 selection.end,
8276 selection.goal,
8277 false,
8278 text_layout_details,
8279 );
8280 selection.collapse_to(cursor, goal);
8281 });
8282 });
8283
8284 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8285 {
8286 cx.propagate();
8287 }
8288 }
8289
8290 pub fn select_page_down(
8291 &mut self,
8292 _: &SelectPageDown,
8293 window: &mut Window,
8294 cx: &mut Context<Self>,
8295 ) {
8296 let Some(row_count) = self.visible_row_count() else {
8297 return;
8298 };
8299
8300 let text_layout_details = &self.text_layout_details(window);
8301
8302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8303 s.move_heads_with(|map, head, goal| {
8304 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8305 })
8306 })
8307 }
8308
8309 pub fn move_page_down(
8310 &mut self,
8311 action: &MovePageDown,
8312 window: &mut Window,
8313 cx: &mut Context<Self>,
8314 ) {
8315 if self.take_rename(true, window, cx).is_some() {
8316 return;
8317 }
8318
8319 if self
8320 .context_menu
8321 .borrow_mut()
8322 .as_mut()
8323 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8324 .unwrap_or(false)
8325 {
8326 return;
8327 }
8328
8329 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8330 cx.propagate();
8331 return;
8332 }
8333
8334 let Some(row_count) = self.visible_row_count() else {
8335 return;
8336 };
8337
8338 let autoscroll = if action.center_cursor {
8339 Autoscroll::center()
8340 } else {
8341 Autoscroll::fit()
8342 };
8343
8344 let text_layout_details = &self.text_layout_details(window);
8345 self.change_selections(Some(autoscroll), window, cx, |s| {
8346 let line_mode = s.line_mode;
8347 s.move_with(|map, selection| {
8348 if !selection.is_empty() && !line_mode {
8349 selection.goal = SelectionGoal::None;
8350 }
8351 let (cursor, goal) = movement::down_by_rows(
8352 map,
8353 selection.end,
8354 row_count,
8355 selection.goal,
8356 false,
8357 text_layout_details,
8358 );
8359 selection.collapse_to(cursor, goal);
8360 });
8361 });
8362 }
8363
8364 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8365 let text_layout_details = &self.text_layout_details(window);
8366 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8367 s.move_heads_with(|map, head, goal| {
8368 movement::down(map, head, goal, false, text_layout_details)
8369 })
8370 });
8371 }
8372
8373 pub fn context_menu_first(
8374 &mut self,
8375 _: &ContextMenuFirst,
8376 _window: &mut Window,
8377 cx: &mut Context<Self>,
8378 ) {
8379 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8380 context_menu.select_first(self.completion_provider.as_deref(), cx);
8381 }
8382 }
8383
8384 pub fn context_menu_prev(
8385 &mut self,
8386 _: &ContextMenuPrev,
8387 _window: &mut Window,
8388 cx: &mut Context<Self>,
8389 ) {
8390 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8391 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8392 }
8393 }
8394
8395 pub fn context_menu_next(
8396 &mut self,
8397 _: &ContextMenuNext,
8398 _window: &mut Window,
8399 cx: &mut Context<Self>,
8400 ) {
8401 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8402 context_menu.select_next(self.completion_provider.as_deref(), cx);
8403 }
8404 }
8405
8406 pub fn context_menu_last(
8407 &mut self,
8408 _: &ContextMenuLast,
8409 _window: &mut Window,
8410 cx: &mut Context<Self>,
8411 ) {
8412 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8413 context_menu.select_last(self.completion_provider.as_deref(), cx);
8414 }
8415 }
8416
8417 pub fn move_to_previous_word_start(
8418 &mut self,
8419 _: &MoveToPreviousWordStart,
8420 window: &mut Window,
8421 cx: &mut Context<Self>,
8422 ) {
8423 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8424 s.move_cursors_with(|map, head, _| {
8425 (
8426 movement::previous_word_start(map, head),
8427 SelectionGoal::None,
8428 )
8429 });
8430 })
8431 }
8432
8433 pub fn move_to_previous_subword_start(
8434 &mut self,
8435 _: &MoveToPreviousSubwordStart,
8436 window: &mut Window,
8437 cx: &mut Context<Self>,
8438 ) {
8439 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8440 s.move_cursors_with(|map, head, _| {
8441 (
8442 movement::previous_subword_start(map, head),
8443 SelectionGoal::None,
8444 )
8445 });
8446 })
8447 }
8448
8449 pub fn select_to_previous_word_start(
8450 &mut self,
8451 _: &SelectToPreviousWordStart,
8452 window: &mut Window,
8453 cx: &mut Context<Self>,
8454 ) {
8455 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8456 s.move_heads_with(|map, head, _| {
8457 (
8458 movement::previous_word_start(map, head),
8459 SelectionGoal::None,
8460 )
8461 });
8462 })
8463 }
8464
8465 pub fn select_to_previous_subword_start(
8466 &mut self,
8467 _: &SelectToPreviousSubwordStart,
8468 window: &mut Window,
8469 cx: &mut Context<Self>,
8470 ) {
8471 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8472 s.move_heads_with(|map, head, _| {
8473 (
8474 movement::previous_subword_start(map, head),
8475 SelectionGoal::None,
8476 )
8477 });
8478 })
8479 }
8480
8481 pub fn delete_to_previous_word_start(
8482 &mut self,
8483 action: &DeleteToPreviousWordStart,
8484 window: &mut Window,
8485 cx: &mut Context<Self>,
8486 ) {
8487 self.transact(window, cx, |this, window, cx| {
8488 this.select_autoclose_pair(window, cx);
8489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8490 let line_mode = s.line_mode;
8491 s.move_with(|map, selection| {
8492 if selection.is_empty() && !line_mode {
8493 let cursor = if action.ignore_newlines {
8494 movement::previous_word_start(map, selection.head())
8495 } else {
8496 movement::previous_word_start_or_newline(map, selection.head())
8497 };
8498 selection.set_head(cursor, SelectionGoal::None);
8499 }
8500 });
8501 });
8502 this.insert("", window, cx);
8503 });
8504 }
8505
8506 pub fn delete_to_previous_subword_start(
8507 &mut self,
8508 _: &DeleteToPreviousSubwordStart,
8509 window: &mut Window,
8510 cx: &mut Context<Self>,
8511 ) {
8512 self.transact(window, cx, |this, window, cx| {
8513 this.select_autoclose_pair(window, cx);
8514 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8515 let line_mode = s.line_mode;
8516 s.move_with(|map, selection| {
8517 if selection.is_empty() && !line_mode {
8518 let cursor = movement::previous_subword_start(map, selection.head());
8519 selection.set_head(cursor, SelectionGoal::None);
8520 }
8521 });
8522 });
8523 this.insert("", window, cx);
8524 });
8525 }
8526
8527 pub fn move_to_next_word_end(
8528 &mut self,
8529 _: &MoveToNextWordEnd,
8530 window: &mut Window,
8531 cx: &mut Context<Self>,
8532 ) {
8533 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8534 s.move_cursors_with(|map, head, _| {
8535 (movement::next_word_end(map, head), SelectionGoal::None)
8536 });
8537 })
8538 }
8539
8540 pub fn move_to_next_subword_end(
8541 &mut self,
8542 _: &MoveToNextSubwordEnd,
8543 window: &mut Window,
8544 cx: &mut Context<Self>,
8545 ) {
8546 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8547 s.move_cursors_with(|map, head, _| {
8548 (movement::next_subword_end(map, head), SelectionGoal::None)
8549 });
8550 })
8551 }
8552
8553 pub fn select_to_next_word_end(
8554 &mut self,
8555 _: &SelectToNextWordEnd,
8556 window: &mut Window,
8557 cx: &mut Context<Self>,
8558 ) {
8559 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8560 s.move_heads_with(|map, head, _| {
8561 (movement::next_word_end(map, head), SelectionGoal::None)
8562 });
8563 })
8564 }
8565
8566 pub fn select_to_next_subword_end(
8567 &mut self,
8568 _: &SelectToNextSubwordEnd,
8569 window: &mut Window,
8570 cx: &mut Context<Self>,
8571 ) {
8572 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8573 s.move_heads_with(|map, head, _| {
8574 (movement::next_subword_end(map, head), SelectionGoal::None)
8575 });
8576 })
8577 }
8578
8579 pub fn delete_to_next_word_end(
8580 &mut self,
8581 action: &DeleteToNextWordEnd,
8582 window: &mut Window,
8583 cx: &mut Context<Self>,
8584 ) {
8585 self.transact(window, cx, |this, window, cx| {
8586 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8587 let line_mode = s.line_mode;
8588 s.move_with(|map, selection| {
8589 if selection.is_empty() && !line_mode {
8590 let cursor = if action.ignore_newlines {
8591 movement::next_word_end(map, selection.head())
8592 } else {
8593 movement::next_word_end_or_newline(map, selection.head())
8594 };
8595 selection.set_head(cursor, SelectionGoal::None);
8596 }
8597 });
8598 });
8599 this.insert("", window, cx);
8600 });
8601 }
8602
8603 pub fn delete_to_next_subword_end(
8604 &mut self,
8605 _: &DeleteToNextSubwordEnd,
8606 window: &mut Window,
8607 cx: &mut Context<Self>,
8608 ) {
8609 self.transact(window, cx, |this, window, cx| {
8610 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8611 s.move_with(|map, selection| {
8612 if selection.is_empty() {
8613 let cursor = movement::next_subword_end(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_beginning_of_line(
8623 &mut self,
8624 action: &MoveToBeginningOfLine,
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 (
8631 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8632 SelectionGoal::None,
8633 )
8634 });
8635 })
8636 }
8637
8638 pub fn select_to_beginning_of_line(
8639 &mut self,
8640 action: &SelectToBeginningOfLine,
8641 window: &mut Window,
8642 cx: &mut Context<Self>,
8643 ) {
8644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8645 s.move_heads_with(|map, head, _| {
8646 (
8647 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8648 SelectionGoal::None,
8649 )
8650 });
8651 });
8652 }
8653
8654 pub fn delete_to_beginning_of_line(
8655 &mut self,
8656 _: &DeleteToBeginningOfLine,
8657 window: &mut Window,
8658 cx: &mut Context<Self>,
8659 ) {
8660 self.transact(window, cx, |this, window, cx| {
8661 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8662 s.move_with(|_, selection| {
8663 selection.reversed = true;
8664 });
8665 });
8666
8667 this.select_to_beginning_of_line(
8668 &SelectToBeginningOfLine {
8669 stop_at_soft_wraps: false,
8670 },
8671 window,
8672 cx,
8673 );
8674 this.backspace(&Backspace, window, cx);
8675 });
8676 }
8677
8678 pub fn move_to_end_of_line(
8679 &mut self,
8680 action: &MoveToEndOfLine,
8681 window: &mut Window,
8682 cx: &mut Context<Self>,
8683 ) {
8684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8685 s.move_cursors_with(|map, head, _| {
8686 (
8687 movement::line_end(map, head, action.stop_at_soft_wraps),
8688 SelectionGoal::None,
8689 )
8690 });
8691 })
8692 }
8693
8694 pub fn select_to_end_of_line(
8695 &mut self,
8696 action: &SelectToEndOfLine,
8697 window: &mut Window,
8698 cx: &mut Context<Self>,
8699 ) {
8700 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8701 s.move_heads_with(|map, head, _| {
8702 (
8703 movement::line_end(map, head, action.stop_at_soft_wraps),
8704 SelectionGoal::None,
8705 )
8706 });
8707 })
8708 }
8709
8710 pub fn delete_to_end_of_line(
8711 &mut self,
8712 _: &DeleteToEndOfLine,
8713 window: &mut Window,
8714 cx: &mut Context<Self>,
8715 ) {
8716 self.transact(window, cx, |this, window, cx| {
8717 this.select_to_end_of_line(
8718 &SelectToEndOfLine {
8719 stop_at_soft_wraps: false,
8720 },
8721 window,
8722 cx,
8723 );
8724 this.delete(&Delete, window, cx);
8725 });
8726 }
8727
8728 pub fn cut_to_end_of_line(
8729 &mut self,
8730 _: &CutToEndOfLine,
8731 window: &mut Window,
8732 cx: &mut Context<Self>,
8733 ) {
8734 self.transact(window, cx, |this, window, cx| {
8735 this.select_to_end_of_line(
8736 &SelectToEndOfLine {
8737 stop_at_soft_wraps: false,
8738 },
8739 window,
8740 cx,
8741 );
8742 this.cut(&Cut, window, cx);
8743 });
8744 }
8745
8746 pub fn move_to_start_of_paragraph(
8747 &mut self,
8748 _: &MoveToStartOfParagraph,
8749 window: &mut Window,
8750 cx: &mut Context<Self>,
8751 ) {
8752 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8753 cx.propagate();
8754 return;
8755 }
8756
8757 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8758 s.move_with(|map, selection| {
8759 selection.collapse_to(
8760 movement::start_of_paragraph(map, selection.head(), 1),
8761 SelectionGoal::None,
8762 )
8763 });
8764 })
8765 }
8766
8767 pub fn move_to_end_of_paragraph(
8768 &mut self,
8769 _: &MoveToEndOfParagraph,
8770 window: &mut Window,
8771 cx: &mut Context<Self>,
8772 ) {
8773 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8774 cx.propagate();
8775 return;
8776 }
8777
8778 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8779 s.move_with(|map, selection| {
8780 selection.collapse_to(
8781 movement::end_of_paragraph(map, selection.head(), 1),
8782 SelectionGoal::None,
8783 )
8784 });
8785 })
8786 }
8787
8788 pub fn select_to_start_of_paragraph(
8789 &mut self,
8790 _: &SelectToStartOfParagraph,
8791 window: &mut Window,
8792 cx: &mut Context<Self>,
8793 ) {
8794 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8795 cx.propagate();
8796 return;
8797 }
8798
8799 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8800 s.move_heads_with(|map, head, _| {
8801 (
8802 movement::start_of_paragraph(map, head, 1),
8803 SelectionGoal::None,
8804 )
8805 });
8806 })
8807 }
8808
8809 pub fn select_to_end_of_paragraph(
8810 &mut self,
8811 _: &SelectToEndOfParagraph,
8812 window: &mut Window,
8813 cx: &mut Context<Self>,
8814 ) {
8815 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8816 cx.propagate();
8817 return;
8818 }
8819
8820 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8821 s.move_heads_with(|map, head, _| {
8822 (
8823 movement::end_of_paragraph(map, head, 1),
8824 SelectionGoal::None,
8825 )
8826 });
8827 })
8828 }
8829
8830 pub fn move_to_beginning(
8831 &mut self,
8832 _: &MoveToBeginning,
8833 window: &mut Window,
8834 cx: &mut Context<Self>,
8835 ) {
8836 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8837 cx.propagate();
8838 return;
8839 }
8840
8841 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8842 s.select_ranges(vec![0..0]);
8843 });
8844 }
8845
8846 pub fn select_to_beginning(
8847 &mut self,
8848 _: &SelectToBeginning,
8849 window: &mut Window,
8850 cx: &mut Context<Self>,
8851 ) {
8852 let mut selection = self.selections.last::<Point>(cx);
8853 selection.set_head(Point::zero(), SelectionGoal::None);
8854
8855 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8856 s.select(vec![selection]);
8857 });
8858 }
8859
8860 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8861 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8862 cx.propagate();
8863 return;
8864 }
8865
8866 let cursor = self.buffer.read(cx).read(cx).len();
8867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8868 s.select_ranges(vec![cursor..cursor])
8869 });
8870 }
8871
8872 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8873 self.nav_history = nav_history;
8874 }
8875
8876 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8877 self.nav_history.as_ref()
8878 }
8879
8880 fn push_to_nav_history(
8881 &mut self,
8882 cursor_anchor: Anchor,
8883 new_position: Option<Point>,
8884 cx: &mut Context<Self>,
8885 ) {
8886 if let Some(nav_history) = self.nav_history.as_mut() {
8887 let buffer = self.buffer.read(cx).read(cx);
8888 let cursor_position = cursor_anchor.to_point(&buffer);
8889 let scroll_state = self.scroll_manager.anchor();
8890 let scroll_top_row = scroll_state.top_row(&buffer);
8891 drop(buffer);
8892
8893 if let Some(new_position) = new_position {
8894 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8895 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8896 return;
8897 }
8898 }
8899
8900 nav_history.push(
8901 Some(NavigationData {
8902 cursor_anchor,
8903 cursor_position,
8904 scroll_anchor: scroll_state,
8905 scroll_top_row,
8906 }),
8907 cx,
8908 );
8909 }
8910 }
8911
8912 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8913 let buffer = self.buffer.read(cx).snapshot(cx);
8914 let mut selection = self.selections.first::<usize>(cx);
8915 selection.set_head(buffer.len(), SelectionGoal::None);
8916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8917 s.select(vec![selection]);
8918 });
8919 }
8920
8921 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8922 let end = self.buffer.read(cx).read(cx).len();
8923 self.change_selections(None, window, cx, |s| {
8924 s.select_ranges(vec![0..end]);
8925 });
8926 }
8927
8928 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8930 let mut selections = self.selections.all::<Point>(cx);
8931 let max_point = display_map.buffer_snapshot.max_point();
8932 for selection in &mut selections {
8933 let rows = selection.spanned_rows(true, &display_map);
8934 selection.start = Point::new(rows.start.0, 0);
8935 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8936 selection.reversed = false;
8937 }
8938 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8939 s.select(selections);
8940 });
8941 }
8942
8943 pub fn split_selection_into_lines(
8944 &mut self,
8945 _: &SplitSelectionIntoLines,
8946 window: &mut Window,
8947 cx: &mut Context<Self>,
8948 ) {
8949 let mut to_unfold = Vec::new();
8950 let mut new_selection_ranges = Vec::new();
8951 {
8952 let selections = self.selections.all::<Point>(cx);
8953 let buffer = self.buffer.read(cx).read(cx);
8954 for selection in selections {
8955 for row in selection.start.row..selection.end.row {
8956 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8957 new_selection_ranges.push(cursor..cursor);
8958 }
8959 new_selection_ranges.push(selection.end..selection.end);
8960 to_unfold.push(selection.start..selection.end);
8961 }
8962 }
8963 self.unfold_ranges(&to_unfold, true, true, cx);
8964 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8965 s.select_ranges(new_selection_ranges);
8966 });
8967 }
8968
8969 pub fn add_selection_above(
8970 &mut self,
8971 _: &AddSelectionAbove,
8972 window: &mut Window,
8973 cx: &mut Context<Self>,
8974 ) {
8975 self.add_selection(true, window, cx);
8976 }
8977
8978 pub fn add_selection_below(
8979 &mut self,
8980 _: &AddSelectionBelow,
8981 window: &mut Window,
8982 cx: &mut Context<Self>,
8983 ) {
8984 self.add_selection(false, window, cx);
8985 }
8986
8987 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8988 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8989 let mut selections = self.selections.all::<Point>(cx);
8990 let text_layout_details = self.text_layout_details(window);
8991 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8992 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8993 let range = oldest_selection.display_range(&display_map).sorted();
8994
8995 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8996 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8997 let positions = start_x.min(end_x)..start_x.max(end_x);
8998
8999 selections.clear();
9000 let mut stack = Vec::new();
9001 for row in range.start.row().0..=range.end.row().0 {
9002 if let Some(selection) = self.selections.build_columnar_selection(
9003 &display_map,
9004 DisplayRow(row),
9005 &positions,
9006 oldest_selection.reversed,
9007 &text_layout_details,
9008 ) {
9009 stack.push(selection.id);
9010 selections.push(selection);
9011 }
9012 }
9013
9014 if above {
9015 stack.reverse();
9016 }
9017
9018 AddSelectionsState { above, stack }
9019 });
9020
9021 let last_added_selection = *state.stack.last().unwrap();
9022 let mut new_selections = Vec::new();
9023 if above == state.above {
9024 let end_row = if above {
9025 DisplayRow(0)
9026 } else {
9027 display_map.max_point().row()
9028 };
9029
9030 'outer: for selection in selections {
9031 if selection.id == last_added_selection {
9032 let range = selection.display_range(&display_map).sorted();
9033 debug_assert_eq!(range.start.row(), range.end.row());
9034 let mut row = range.start.row();
9035 let positions =
9036 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9037 px(start)..px(end)
9038 } else {
9039 let start_x =
9040 display_map.x_for_display_point(range.start, &text_layout_details);
9041 let end_x =
9042 display_map.x_for_display_point(range.end, &text_layout_details);
9043 start_x.min(end_x)..start_x.max(end_x)
9044 };
9045
9046 while row != end_row {
9047 if above {
9048 row.0 -= 1;
9049 } else {
9050 row.0 += 1;
9051 }
9052
9053 if let Some(new_selection) = self.selections.build_columnar_selection(
9054 &display_map,
9055 row,
9056 &positions,
9057 selection.reversed,
9058 &text_layout_details,
9059 ) {
9060 state.stack.push(new_selection.id);
9061 if above {
9062 new_selections.push(new_selection);
9063 new_selections.push(selection);
9064 } else {
9065 new_selections.push(selection);
9066 new_selections.push(new_selection);
9067 }
9068
9069 continue 'outer;
9070 }
9071 }
9072 }
9073
9074 new_selections.push(selection);
9075 }
9076 } else {
9077 new_selections = selections;
9078 new_selections.retain(|s| s.id != last_added_selection);
9079 state.stack.pop();
9080 }
9081
9082 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9083 s.select(new_selections);
9084 });
9085 if state.stack.len() > 1 {
9086 self.add_selections_state = Some(state);
9087 }
9088 }
9089
9090 pub fn select_next_match_internal(
9091 &mut self,
9092 display_map: &DisplaySnapshot,
9093 replace_newest: bool,
9094 autoscroll: Option<Autoscroll>,
9095 window: &mut Window,
9096 cx: &mut Context<Self>,
9097 ) -> Result<()> {
9098 fn select_next_match_ranges(
9099 this: &mut Editor,
9100 range: Range<usize>,
9101 replace_newest: bool,
9102 auto_scroll: Option<Autoscroll>,
9103 window: &mut Window,
9104 cx: &mut Context<Editor>,
9105 ) {
9106 this.unfold_ranges(&[range.clone()], false, true, cx);
9107 this.change_selections(auto_scroll, window, cx, |s| {
9108 if replace_newest {
9109 s.delete(s.newest_anchor().id);
9110 }
9111 s.insert_range(range.clone());
9112 });
9113 }
9114
9115 let buffer = &display_map.buffer_snapshot;
9116 let mut selections = self.selections.all::<usize>(cx);
9117 if let Some(mut select_next_state) = self.select_next_state.take() {
9118 let query = &select_next_state.query;
9119 if !select_next_state.done {
9120 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9121 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9122 let mut next_selected_range = None;
9123
9124 let bytes_after_last_selection =
9125 buffer.bytes_in_range(last_selection.end..buffer.len());
9126 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9127 let query_matches = query
9128 .stream_find_iter(bytes_after_last_selection)
9129 .map(|result| (last_selection.end, result))
9130 .chain(
9131 query
9132 .stream_find_iter(bytes_before_first_selection)
9133 .map(|result| (0, result)),
9134 );
9135
9136 for (start_offset, query_match) in query_matches {
9137 let query_match = query_match.unwrap(); // can only fail due to I/O
9138 let offset_range =
9139 start_offset + query_match.start()..start_offset + query_match.end();
9140 let display_range = offset_range.start.to_display_point(display_map)
9141 ..offset_range.end.to_display_point(display_map);
9142
9143 if !select_next_state.wordwise
9144 || (!movement::is_inside_word(display_map, display_range.start)
9145 && !movement::is_inside_word(display_map, display_range.end))
9146 {
9147 // TODO: This is n^2, because we might check all the selections
9148 if !selections
9149 .iter()
9150 .any(|selection| selection.range().overlaps(&offset_range))
9151 {
9152 next_selected_range = Some(offset_range);
9153 break;
9154 }
9155 }
9156 }
9157
9158 if let Some(next_selected_range) = next_selected_range {
9159 select_next_match_ranges(
9160 self,
9161 next_selected_range,
9162 replace_newest,
9163 autoscroll,
9164 window,
9165 cx,
9166 );
9167 } else {
9168 select_next_state.done = true;
9169 }
9170 }
9171
9172 self.select_next_state = Some(select_next_state);
9173 } else {
9174 let mut only_carets = true;
9175 let mut same_text_selected = true;
9176 let mut selected_text = None;
9177
9178 let mut selections_iter = selections.iter().peekable();
9179 while let Some(selection) = selections_iter.next() {
9180 if selection.start != selection.end {
9181 only_carets = false;
9182 }
9183
9184 if same_text_selected {
9185 if selected_text.is_none() {
9186 selected_text =
9187 Some(buffer.text_for_range(selection.range()).collect::<String>());
9188 }
9189
9190 if let Some(next_selection) = selections_iter.peek() {
9191 if next_selection.range().len() == selection.range().len() {
9192 let next_selected_text = buffer
9193 .text_for_range(next_selection.range())
9194 .collect::<String>();
9195 if Some(next_selected_text) != selected_text {
9196 same_text_selected = false;
9197 selected_text = None;
9198 }
9199 } else {
9200 same_text_selected = false;
9201 selected_text = None;
9202 }
9203 }
9204 }
9205 }
9206
9207 if only_carets {
9208 for selection in &mut selections {
9209 let word_range = movement::surrounding_word(
9210 display_map,
9211 selection.start.to_display_point(display_map),
9212 );
9213 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9214 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9215 selection.goal = SelectionGoal::None;
9216 selection.reversed = false;
9217 select_next_match_ranges(
9218 self,
9219 selection.start..selection.end,
9220 replace_newest,
9221 autoscroll,
9222 window,
9223 cx,
9224 );
9225 }
9226
9227 if selections.len() == 1 {
9228 let selection = selections
9229 .last()
9230 .expect("ensured that there's only one selection");
9231 let query = buffer
9232 .text_for_range(selection.start..selection.end)
9233 .collect::<String>();
9234 let is_empty = query.is_empty();
9235 let select_state = SelectNextState {
9236 query: AhoCorasick::new(&[query])?,
9237 wordwise: true,
9238 done: is_empty,
9239 };
9240 self.select_next_state = Some(select_state);
9241 } else {
9242 self.select_next_state = None;
9243 }
9244 } else if let Some(selected_text) = selected_text {
9245 self.select_next_state = Some(SelectNextState {
9246 query: AhoCorasick::new(&[selected_text])?,
9247 wordwise: false,
9248 done: false,
9249 });
9250 self.select_next_match_internal(
9251 display_map,
9252 replace_newest,
9253 autoscroll,
9254 window,
9255 cx,
9256 )?;
9257 }
9258 }
9259 Ok(())
9260 }
9261
9262 pub fn select_all_matches(
9263 &mut self,
9264 _action: &SelectAllMatches,
9265 window: &mut Window,
9266 cx: &mut Context<Self>,
9267 ) -> Result<()> {
9268 self.push_to_selection_history();
9269 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9270
9271 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9272 let Some(select_next_state) = self.select_next_state.as_mut() else {
9273 return Ok(());
9274 };
9275 if select_next_state.done {
9276 return Ok(());
9277 }
9278
9279 let mut new_selections = self.selections.all::<usize>(cx);
9280
9281 let buffer = &display_map.buffer_snapshot;
9282 let query_matches = select_next_state
9283 .query
9284 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9285
9286 for query_match in query_matches {
9287 let query_match = query_match.unwrap(); // can only fail due to I/O
9288 let offset_range = query_match.start()..query_match.end();
9289 let display_range = offset_range.start.to_display_point(&display_map)
9290 ..offset_range.end.to_display_point(&display_map);
9291
9292 if !select_next_state.wordwise
9293 || (!movement::is_inside_word(&display_map, display_range.start)
9294 && !movement::is_inside_word(&display_map, display_range.end))
9295 {
9296 self.selections.change_with(cx, |selections| {
9297 new_selections.push(Selection {
9298 id: selections.new_selection_id(),
9299 start: offset_range.start,
9300 end: offset_range.end,
9301 reversed: false,
9302 goal: SelectionGoal::None,
9303 });
9304 });
9305 }
9306 }
9307
9308 new_selections.sort_by_key(|selection| selection.start);
9309 let mut ix = 0;
9310 while ix + 1 < new_selections.len() {
9311 let current_selection = &new_selections[ix];
9312 let next_selection = &new_selections[ix + 1];
9313 if current_selection.range().overlaps(&next_selection.range()) {
9314 if current_selection.id < next_selection.id {
9315 new_selections.remove(ix + 1);
9316 } else {
9317 new_selections.remove(ix);
9318 }
9319 } else {
9320 ix += 1;
9321 }
9322 }
9323
9324 let reversed = self.selections.oldest::<usize>(cx).reversed;
9325
9326 for selection in new_selections.iter_mut() {
9327 selection.reversed = reversed;
9328 }
9329
9330 select_next_state.done = true;
9331 self.unfold_ranges(
9332 &new_selections
9333 .iter()
9334 .map(|selection| selection.range())
9335 .collect::<Vec<_>>(),
9336 false,
9337 false,
9338 cx,
9339 );
9340 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9341 selections.select(new_selections)
9342 });
9343
9344 Ok(())
9345 }
9346
9347 pub fn select_next(
9348 &mut self,
9349 action: &SelectNext,
9350 window: &mut Window,
9351 cx: &mut Context<Self>,
9352 ) -> Result<()> {
9353 self.push_to_selection_history();
9354 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9355 self.select_next_match_internal(
9356 &display_map,
9357 action.replace_newest,
9358 Some(Autoscroll::newest()),
9359 window,
9360 cx,
9361 )?;
9362 Ok(())
9363 }
9364
9365 pub fn select_previous(
9366 &mut self,
9367 action: &SelectPrevious,
9368 window: &mut Window,
9369 cx: &mut Context<Self>,
9370 ) -> Result<()> {
9371 self.push_to_selection_history();
9372 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9373 let buffer = &display_map.buffer_snapshot;
9374 let mut selections = self.selections.all::<usize>(cx);
9375 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9376 let query = &select_prev_state.query;
9377 if !select_prev_state.done {
9378 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9379 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9380 let mut next_selected_range = None;
9381 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9382 let bytes_before_last_selection =
9383 buffer.reversed_bytes_in_range(0..last_selection.start);
9384 let bytes_after_first_selection =
9385 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9386 let query_matches = query
9387 .stream_find_iter(bytes_before_last_selection)
9388 .map(|result| (last_selection.start, result))
9389 .chain(
9390 query
9391 .stream_find_iter(bytes_after_first_selection)
9392 .map(|result| (buffer.len(), result)),
9393 );
9394 for (end_offset, query_match) in query_matches {
9395 let query_match = query_match.unwrap(); // can only fail due to I/O
9396 let offset_range =
9397 end_offset - query_match.end()..end_offset - query_match.start();
9398 let display_range = offset_range.start.to_display_point(&display_map)
9399 ..offset_range.end.to_display_point(&display_map);
9400
9401 if !select_prev_state.wordwise
9402 || (!movement::is_inside_word(&display_map, display_range.start)
9403 && !movement::is_inside_word(&display_map, display_range.end))
9404 {
9405 next_selected_range = Some(offset_range);
9406 break;
9407 }
9408 }
9409
9410 if let Some(next_selected_range) = next_selected_range {
9411 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9412 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9413 if action.replace_newest {
9414 s.delete(s.newest_anchor().id);
9415 }
9416 s.insert_range(next_selected_range);
9417 });
9418 } else {
9419 select_prev_state.done = true;
9420 }
9421 }
9422
9423 self.select_prev_state = Some(select_prev_state);
9424 } else {
9425 let mut only_carets = true;
9426 let mut same_text_selected = true;
9427 let mut selected_text = None;
9428
9429 let mut selections_iter = selections.iter().peekable();
9430 while let Some(selection) = selections_iter.next() {
9431 if selection.start != selection.end {
9432 only_carets = false;
9433 }
9434
9435 if same_text_selected {
9436 if selected_text.is_none() {
9437 selected_text =
9438 Some(buffer.text_for_range(selection.range()).collect::<String>());
9439 }
9440
9441 if let Some(next_selection) = selections_iter.peek() {
9442 if next_selection.range().len() == selection.range().len() {
9443 let next_selected_text = buffer
9444 .text_for_range(next_selection.range())
9445 .collect::<String>();
9446 if Some(next_selected_text) != selected_text {
9447 same_text_selected = false;
9448 selected_text = None;
9449 }
9450 } else {
9451 same_text_selected = false;
9452 selected_text = None;
9453 }
9454 }
9455 }
9456 }
9457
9458 if only_carets {
9459 for selection in &mut selections {
9460 let word_range = movement::surrounding_word(
9461 &display_map,
9462 selection.start.to_display_point(&display_map),
9463 );
9464 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9465 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9466 selection.goal = SelectionGoal::None;
9467 selection.reversed = false;
9468 }
9469 if selections.len() == 1 {
9470 let selection = selections
9471 .last()
9472 .expect("ensured that there's only one selection");
9473 let query = buffer
9474 .text_for_range(selection.start..selection.end)
9475 .collect::<String>();
9476 let is_empty = query.is_empty();
9477 let select_state = SelectNextState {
9478 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9479 wordwise: true,
9480 done: is_empty,
9481 };
9482 self.select_prev_state = Some(select_state);
9483 } else {
9484 self.select_prev_state = None;
9485 }
9486
9487 self.unfold_ranges(
9488 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9489 false,
9490 true,
9491 cx,
9492 );
9493 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9494 s.select(selections);
9495 });
9496 } else if let Some(selected_text) = selected_text {
9497 self.select_prev_state = Some(SelectNextState {
9498 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9499 wordwise: false,
9500 done: false,
9501 });
9502 self.select_previous(action, window, cx)?;
9503 }
9504 }
9505 Ok(())
9506 }
9507
9508 pub fn toggle_comments(
9509 &mut self,
9510 action: &ToggleComments,
9511 window: &mut Window,
9512 cx: &mut Context<Self>,
9513 ) {
9514 if self.read_only(cx) {
9515 return;
9516 }
9517 let text_layout_details = &self.text_layout_details(window);
9518 self.transact(window, cx, |this, window, cx| {
9519 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9520 let mut edits = Vec::new();
9521 let mut selection_edit_ranges = Vec::new();
9522 let mut last_toggled_row = None;
9523 let snapshot = this.buffer.read(cx).read(cx);
9524 let empty_str: Arc<str> = Arc::default();
9525 let mut suffixes_inserted = Vec::new();
9526 let ignore_indent = action.ignore_indent;
9527
9528 fn comment_prefix_range(
9529 snapshot: &MultiBufferSnapshot,
9530 row: MultiBufferRow,
9531 comment_prefix: &str,
9532 comment_prefix_whitespace: &str,
9533 ignore_indent: bool,
9534 ) -> Range<Point> {
9535 let indent_size = if ignore_indent {
9536 0
9537 } else {
9538 snapshot.indent_size_for_line(row).len
9539 };
9540
9541 let start = Point::new(row.0, indent_size);
9542
9543 let mut line_bytes = snapshot
9544 .bytes_in_range(start..snapshot.max_point())
9545 .flatten()
9546 .copied();
9547
9548 // If this line currently begins with the line comment prefix, then record
9549 // the range containing the prefix.
9550 if line_bytes
9551 .by_ref()
9552 .take(comment_prefix.len())
9553 .eq(comment_prefix.bytes())
9554 {
9555 // Include any whitespace that matches the comment prefix.
9556 let matching_whitespace_len = line_bytes
9557 .zip(comment_prefix_whitespace.bytes())
9558 .take_while(|(a, b)| a == b)
9559 .count() as u32;
9560 let end = Point::new(
9561 start.row,
9562 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9563 );
9564 start..end
9565 } else {
9566 start..start
9567 }
9568 }
9569
9570 fn comment_suffix_range(
9571 snapshot: &MultiBufferSnapshot,
9572 row: MultiBufferRow,
9573 comment_suffix: &str,
9574 comment_suffix_has_leading_space: bool,
9575 ) -> Range<Point> {
9576 let end = Point::new(row.0, snapshot.line_len(row));
9577 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9578
9579 let mut line_end_bytes = snapshot
9580 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9581 .flatten()
9582 .copied();
9583
9584 let leading_space_len = if suffix_start_column > 0
9585 && line_end_bytes.next() == Some(b' ')
9586 && comment_suffix_has_leading_space
9587 {
9588 1
9589 } else {
9590 0
9591 };
9592
9593 // If this line currently begins with the line comment prefix, then record
9594 // the range containing the prefix.
9595 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9596 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9597 start..end
9598 } else {
9599 end..end
9600 }
9601 }
9602
9603 // TODO: Handle selections that cross excerpts
9604 for selection in &mut selections {
9605 let start_column = snapshot
9606 .indent_size_for_line(MultiBufferRow(selection.start.row))
9607 .len;
9608 let language = if let Some(language) =
9609 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9610 {
9611 language
9612 } else {
9613 continue;
9614 };
9615
9616 selection_edit_ranges.clear();
9617
9618 // If multiple selections contain a given row, avoid processing that
9619 // row more than once.
9620 let mut start_row = MultiBufferRow(selection.start.row);
9621 if last_toggled_row == Some(start_row) {
9622 start_row = start_row.next_row();
9623 }
9624 let end_row =
9625 if selection.end.row > selection.start.row && selection.end.column == 0 {
9626 MultiBufferRow(selection.end.row - 1)
9627 } else {
9628 MultiBufferRow(selection.end.row)
9629 };
9630 last_toggled_row = Some(end_row);
9631
9632 if start_row > end_row {
9633 continue;
9634 }
9635
9636 // If the language has line comments, toggle those.
9637 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9638
9639 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9640 if ignore_indent {
9641 full_comment_prefixes = full_comment_prefixes
9642 .into_iter()
9643 .map(|s| Arc::from(s.trim_end()))
9644 .collect();
9645 }
9646
9647 if !full_comment_prefixes.is_empty() {
9648 let first_prefix = full_comment_prefixes
9649 .first()
9650 .expect("prefixes is non-empty");
9651 let prefix_trimmed_lengths = full_comment_prefixes
9652 .iter()
9653 .map(|p| p.trim_end_matches(' ').len())
9654 .collect::<SmallVec<[usize; 4]>>();
9655
9656 let mut all_selection_lines_are_comments = true;
9657
9658 for row in start_row.0..=end_row.0 {
9659 let row = MultiBufferRow(row);
9660 if start_row < end_row && snapshot.is_line_blank(row) {
9661 continue;
9662 }
9663
9664 let prefix_range = full_comment_prefixes
9665 .iter()
9666 .zip(prefix_trimmed_lengths.iter().copied())
9667 .map(|(prefix, trimmed_prefix_len)| {
9668 comment_prefix_range(
9669 snapshot.deref(),
9670 row,
9671 &prefix[..trimmed_prefix_len],
9672 &prefix[trimmed_prefix_len..],
9673 ignore_indent,
9674 )
9675 })
9676 .max_by_key(|range| range.end.column - range.start.column)
9677 .expect("prefixes is non-empty");
9678
9679 if prefix_range.is_empty() {
9680 all_selection_lines_are_comments = false;
9681 }
9682
9683 selection_edit_ranges.push(prefix_range);
9684 }
9685
9686 if all_selection_lines_are_comments {
9687 edits.extend(
9688 selection_edit_ranges
9689 .iter()
9690 .cloned()
9691 .map(|range| (range, empty_str.clone())),
9692 );
9693 } else {
9694 let min_column = selection_edit_ranges
9695 .iter()
9696 .map(|range| range.start.column)
9697 .min()
9698 .unwrap_or(0);
9699 edits.extend(selection_edit_ranges.iter().map(|range| {
9700 let position = Point::new(range.start.row, min_column);
9701 (position..position, first_prefix.clone())
9702 }));
9703 }
9704 } else if let Some((full_comment_prefix, comment_suffix)) =
9705 language.block_comment_delimiters()
9706 {
9707 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9708 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9709 let prefix_range = comment_prefix_range(
9710 snapshot.deref(),
9711 start_row,
9712 comment_prefix,
9713 comment_prefix_whitespace,
9714 ignore_indent,
9715 );
9716 let suffix_range = comment_suffix_range(
9717 snapshot.deref(),
9718 end_row,
9719 comment_suffix.trim_start_matches(' '),
9720 comment_suffix.starts_with(' '),
9721 );
9722
9723 if prefix_range.is_empty() || suffix_range.is_empty() {
9724 edits.push((
9725 prefix_range.start..prefix_range.start,
9726 full_comment_prefix.clone(),
9727 ));
9728 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9729 suffixes_inserted.push((end_row, comment_suffix.len()));
9730 } else {
9731 edits.push((prefix_range, empty_str.clone()));
9732 edits.push((suffix_range, empty_str.clone()));
9733 }
9734 } else {
9735 continue;
9736 }
9737 }
9738
9739 drop(snapshot);
9740 this.buffer.update(cx, |buffer, cx| {
9741 buffer.edit(edits, None, cx);
9742 });
9743
9744 // Adjust selections so that they end before any comment suffixes that
9745 // were inserted.
9746 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9747 let mut selections = this.selections.all::<Point>(cx);
9748 let snapshot = this.buffer.read(cx).read(cx);
9749 for selection in &mut selections {
9750 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9751 match row.cmp(&MultiBufferRow(selection.end.row)) {
9752 Ordering::Less => {
9753 suffixes_inserted.next();
9754 continue;
9755 }
9756 Ordering::Greater => break,
9757 Ordering::Equal => {
9758 if selection.end.column == snapshot.line_len(row) {
9759 if selection.is_empty() {
9760 selection.start.column -= suffix_len as u32;
9761 }
9762 selection.end.column -= suffix_len as u32;
9763 }
9764 break;
9765 }
9766 }
9767 }
9768 }
9769
9770 drop(snapshot);
9771 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9772 s.select(selections)
9773 });
9774
9775 let selections = this.selections.all::<Point>(cx);
9776 let selections_on_single_row = selections.windows(2).all(|selections| {
9777 selections[0].start.row == selections[1].start.row
9778 && selections[0].end.row == selections[1].end.row
9779 && selections[0].start.row == selections[0].end.row
9780 });
9781 let selections_selecting = selections
9782 .iter()
9783 .any(|selection| selection.start != selection.end);
9784 let advance_downwards = action.advance_downwards
9785 && selections_on_single_row
9786 && !selections_selecting
9787 && !matches!(this.mode, EditorMode::SingleLine { .. });
9788
9789 if advance_downwards {
9790 let snapshot = this.buffer.read(cx).snapshot(cx);
9791
9792 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9793 s.move_cursors_with(|display_snapshot, display_point, _| {
9794 let mut point = display_point.to_point(display_snapshot);
9795 point.row += 1;
9796 point = snapshot.clip_point(point, Bias::Left);
9797 let display_point = point.to_display_point(display_snapshot);
9798 let goal = SelectionGoal::HorizontalPosition(
9799 display_snapshot
9800 .x_for_display_point(display_point, text_layout_details)
9801 .into(),
9802 );
9803 (display_point, goal)
9804 })
9805 });
9806 }
9807 });
9808 }
9809
9810 pub fn select_enclosing_symbol(
9811 &mut self,
9812 _: &SelectEnclosingSymbol,
9813 window: &mut Window,
9814 cx: &mut Context<Self>,
9815 ) {
9816 let buffer = self.buffer.read(cx).snapshot(cx);
9817 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9818
9819 fn update_selection(
9820 selection: &Selection<usize>,
9821 buffer_snap: &MultiBufferSnapshot,
9822 ) -> Option<Selection<usize>> {
9823 let cursor = selection.head();
9824 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9825 for symbol in symbols.iter().rev() {
9826 let start = symbol.range.start.to_offset(buffer_snap);
9827 let end = symbol.range.end.to_offset(buffer_snap);
9828 let new_range = start..end;
9829 if start < selection.start || end > selection.end {
9830 return Some(Selection {
9831 id: selection.id,
9832 start: new_range.start,
9833 end: new_range.end,
9834 goal: SelectionGoal::None,
9835 reversed: selection.reversed,
9836 });
9837 }
9838 }
9839 None
9840 }
9841
9842 let mut selected_larger_symbol = false;
9843 let new_selections = old_selections
9844 .iter()
9845 .map(|selection| match update_selection(selection, &buffer) {
9846 Some(new_selection) => {
9847 if new_selection.range() != selection.range() {
9848 selected_larger_symbol = true;
9849 }
9850 new_selection
9851 }
9852 None => selection.clone(),
9853 })
9854 .collect::<Vec<_>>();
9855
9856 if selected_larger_symbol {
9857 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9858 s.select(new_selections);
9859 });
9860 }
9861 }
9862
9863 pub fn select_larger_syntax_node(
9864 &mut self,
9865 _: &SelectLargerSyntaxNode,
9866 window: &mut Window,
9867 cx: &mut Context<Self>,
9868 ) {
9869 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9870 let buffer = self.buffer.read(cx).snapshot(cx);
9871 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9872
9873 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9874 let mut selected_larger_node = false;
9875 let new_selections = old_selections
9876 .iter()
9877 .map(|selection| {
9878 let old_range = selection.start..selection.end;
9879 let mut new_range = old_range.clone();
9880 let mut new_node = None;
9881 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9882 {
9883 new_node = Some(node);
9884 new_range = containing_range;
9885 if !display_map.intersects_fold(new_range.start)
9886 && !display_map.intersects_fold(new_range.end)
9887 {
9888 break;
9889 }
9890 }
9891
9892 if let Some(node) = new_node {
9893 // Log the ancestor, to support using this action as a way to explore TreeSitter
9894 // nodes. Parent and grandparent are also logged because this operation will not
9895 // visit nodes that have the same range as their parent.
9896 log::info!("Node: {node:?}");
9897 let parent = node.parent();
9898 log::info!("Parent: {parent:?}");
9899 let grandparent = parent.and_then(|x| x.parent());
9900 log::info!("Grandparent: {grandparent:?}");
9901 }
9902
9903 selected_larger_node |= new_range != old_range;
9904 Selection {
9905 id: selection.id,
9906 start: new_range.start,
9907 end: new_range.end,
9908 goal: SelectionGoal::None,
9909 reversed: selection.reversed,
9910 }
9911 })
9912 .collect::<Vec<_>>();
9913
9914 if selected_larger_node {
9915 stack.push(old_selections);
9916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9917 s.select(new_selections);
9918 });
9919 }
9920 self.select_larger_syntax_node_stack = stack;
9921 }
9922
9923 pub fn select_smaller_syntax_node(
9924 &mut self,
9925 _: &SelectSmallerSyntaxNode,
9926 window: &mut Window,
9927 cx: &mut Context<Self>,
9928 ) {
9929 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9930 if let Some(selections) = stack.pop() {
9931 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9932 s.select(selections.to_vec());
9933 });
9934 }
9935 self.select_larger_syntax_node_stack = stack;
9936 }
9937
9938 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9939 if !EditorSettings::get_global(cx).gutter.runnables {
9940 self.clear_tasks();
9941 return Task::ready(());
9942 }
9943 let project = self.project.as_ref().map(Entity::downgrade);
9944 cx.spawn_in(window, |this, mut cx| async move {
9945 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9946 let Some(project) = project.and_then(|p| p.upgrade()) else {
9947 return;
9948 };
9949 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9950 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9951 }) else {
9952 return;
9953 };
9954
9955 let hide_runnables = project
9956 .update(&mut cx, |project, cx| {
9957 // Do not display any test indicators in non-dev server remote projects.
9958 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9959 })
9960 .unwrap_or(true);
9961 if hide_runnables {
9962 return;
9963 }
9964 let new_rows =
9965 cx.background_executor()
9966 .spawn({
9967 let snapshot = display_snapshot.clone();
9968 async move {
9969 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9970 }
9971 })
9972 .await;
9973
9974 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9975 this.update(&mut cx, |this, _| {
9976 this.clear_tasks();
9977 for (key, value) in rows {
9978 this.insert_tasks(key, value);
9979 }
9980 })
9981 .ok();
9982 })
9983 }
9984 fn fetch_runnable_ranges(
9985 snapshot: &DisplaySnapshot,
9986 range: Range<Anchor>,
9987 ) -> Vec<language::RunnableRange> {
9988 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9989 }
9990
9991 fn runnable_rows(
9992 project: Entity<Project>,
9993 snapshot: DisplaySnapshot,
9994 runnable_ranges: Vec<RunnableRange>,
9995 mut cx: AsyncWindowContext,
9996 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9997 runnable_ranges
9998 .into_iter()
9999 .filter_map(|mut runnable| {
10000 let tasks = cx
10001 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10002 .ok()?;
10003 if tasks.is_empty() {
10004 return None;
10005 }
10006
10007 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10008
10009 let row = snapshot
10010 .buffer_snapshot
10011 .buffer_line_for_row(MultiBufferRow(point.row))?
10012 .1
10013 .start
10014 .row;
10015
10016 let context_range =
10017 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10018 Some((
10019 (runnable.buffer_id, row),
10020 RunnableTasks {
10021 templates: tasks,
10022 offset: MultiBufferOffset(runnable.run_range.start),
10023 context_range,
10024 column: point.column,
10025 extra_variables: runnable.extra_captures,
10026 },
10027 ))
10028 })
10029 .collect()
10030 }
10031
10032 fn templates_with_tags(
10033 project: &Entity<Project>,
10034 runnable: &mut Runnable,
10035 cx: &mut App,
10036 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10037 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10038 let (worktree_id, file) = project
10039 .buffer_for_id(runnable.buffer, cx)
10040 .and_then(|buffer| buffer.read(cx).file())
10041 .map(|file| (file.worktree_id(cx), file.clone()))
10042 .unzip();
10043
10044 (
10045 project.task_store().read(cx).task_inventory().cloned(),
10046 worktree_id,
10047 file,
10048 )
10049 });
10050
10051 let tags = mem::take(&mut runnable.tags);
10052 let mut tags: Vec<_> = tags
10053 .into_iter()
10054 .flat_map(|tag| {
10055 let tag = tag.0.clone();
10056 inventory
10057 .as_ref()
10058 .into_iter()
10059 .flat_map(|inventory| {
10060 inventory.read(cx).list_tasks(
10061 file.clone(),
10062 Some(runnable.language.clone()),
10063 worktree_id,
10064 cx,
10065 )
10066 })
10067 .filter(move |(_, template)| {
10068 template.tags.iter().any(|source_tag| source_tag == &tag)
10069 })
10070 })
10071 .sorted_by_key(|(kind, _)| kind.to_owned())
10072 .collect();
10073 if let Some((leading_tag_source, _)) = tags.first() {
10074 // Strongest source wins; if we have worktree tag binding, prefer that to
10075 // global and language bindings;
10076 // if we have a global binding, prefer that to language binding.
10077 let first_mismatch = tags
10078 .iter()
10079 .position(|(tag_source, _)| tag_source != leading_tag_source);
10080 if let Some(index) = first_mismatch {
10081 tags.truncate(index);
10082 }
10083 }
10084
10085 tags
10086 }
10087
10088 pub fn move_to_enclosing_bracket(
10089 &mut self,
10090 _: &MoveToEnclosingBracket,
10091 window: &mut Window,
10092 cx: &mut Context<Self>,
10093 ) {
10094 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10095 s.move_offsets_with(|snapshot, selection| {
10096 let Some(enclosing_bracket_ranges) =
10097 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10098 else {
10099 return;
10100 };
10101
10102 let mut best_length = usize::MAX;
10103 let mut best_inside = false;
10104 let mut best_in_bracket_range = false;
10105 let mut best_destination = None;
10106 for (open, close) in enclosing_bracket_ranges {
10107 let close = close.to_inclusive();
10108 let length = close.end() - open.start;
10109 let inside = selection.start >= open.end && selection.end <= *close.start();
10110 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10111 || close.contains(&selection.head());
10112
10113 // If best is next to a bracket and current isn't, skip
10114 if !in_bracket_range && best_in_bracket_range {
10115 continue;
10116 }
10117
10118 // Prefer smaller lengths unless best is inside and current isn't
10119 if length > best_length && (best_inside || !inside) {
10120 continue;
10121 }
10122
10123 best_length = length;
10124 best_inside = inside;
10125 best_in_bracket_range = in_bracket_range;
10126 best_destination = Some(
10127 if close.contains(&selection.start) && close.contains(&selection.end) {
10128 if inside {
10129 open.end
10130 } else {
10131 open.start
10132 }
10133 } else if inside {
10134 *close.start()
10135 } else {
10136 *close.end()
10137 },
10138 );
10139 }
10140
10141 if let Some(destination) = best_destination {
10142 selection.collapse_to(destination, SelectionGoal::None);
10143 }
10144 })
10145 });
10146 }
10147
10148 pub fn undo_selection(
10149 &mut self,
10150 _: &UndoSelection,
10151 window: &mut Window,
10152 cx: &mut Context<Self>,
10153 ) {
10154 self.end_selection(window, cx);
10155 self.selection_history.mode = SelectionHistoryMode::Undoing;
10156 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10157 self.change_selections(None, window, cx, |s| {
10158 s.select_anchors(entry.selections.to_vec())
10159 });
10160 self.select_next_state = entry.select_next_state;
10161 self.select_prev_state = entry.select_prev_state;
10162 self.add_selections_state = entry.add_selections_state;
10163 self.request_autoscroll(Autoscroll::newest(), cx);
10164 }
10165 self.selection_history.mode = SelectionHistoryMode::Normal;
10166 }
10167
10168 pub fn redo_selection(
10169 &mut self,
10170 _: &RedoSelection,
10171 window: &mut Window,
10172 cx: &mut Context<Self>,
10173 ) {
10174 self.end_selection(window, cx);
10175 self.selection_history.mode = SelectionHistoryMode::Redoing;
10176 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10177 self.change_selections(None, window, cx, |s| {
10178 s.select_anchors(entry.selections.to_vec())
10179 });
10180 self.select_next_state = entry.select_next_state;
10181 self.select_prev_state = entry.select_prev_state;
10182 self.add_selections_state = entry.add_selections_state;
10183 self.request_autoscroll(Autoscroll::newest(), cx);
10184 }
10185 self.selection_history.mode = SelectionHistoryMode::Normal;
10186 }
10187
10188 pub fn expand_excerpts(
10189 &mut self,
10190 action: &ExpandExcerpts,
10191 _: &mut Window,
10192 cx: &mut Context<Self>,
10193 ) {
10194 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10195 }
10196
10197 pub fn expand_excerpts_down(
10198 &mut self,
10199 action: &ExpandExcerptsDown,
10200 _: &mut Window,
10201 cx: &mut Context<Self>,
10202 ) {
10203 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10204 }
10205
10206 pub fn expand_excerpts_up(
10207 &mut self,
10208 action: &ExpandExcerptsUp,
10209 _: &mut Window,
10210 cx: &mut Context<Self>,
10211 ) {
10212 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10213 }
10214
10215 pub fn expand_excerpts_for_direction(
10216 &mut self,
10217 lines: u32,
10218 direction: ExpandExcerptDirection,
10219
10220 cx: &mut Context<Self>,
10221 ) {
10222 let selections = self.selections.disjoint_anchors();
10223
10224 let lines = if lines == 0 {
10225 EditorSettings::get_global(cx).expand_excerpt_lines
10226 } else {
10227 lines
10228 };
10229
10230 self.buffer.update(cx, |buffer, cx| {
10231 let snapshot = buffer.snapshot(cx);
10232 let mut excerpt_ids = selections
10233 .iter()
10234 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10235 .collect::<Vec<_>>();
10236 excerpt_ids.sort();
10237 excerpt_ids.dedup();
10238 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10239 })
10240 }
10241
10242 pub fn expand_excerpt(
10243 &mut self,
10244 excerpt: ExcerptId,
10245 direction: ExpandExcerptDirection,
10246 cx: &mut Context<Self>,
10247 ) {
10248 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10249 self.buffer.update(cx, |buffer, cx| {
10250 buffer.expand_excerpts([excerpt], lines, direction, cx)
10251 })
10252 }
10253
10254 pub fn go_to_singleton_buffer_point(
10255 &mut self,
10256 point: Point,
10257 window: &mut Window,
10258 cx: &mut Context<Self>,
10259 ) {
10260 self.go_to_singleton_buffer_range(point..point, window, cx);
10261 }
10262
10263 pub fn go_to_singleton_buffer_range(
10264 &mut self,
10265 range: Range<Point>,
10266 window: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) {
10269 let multibuffer = self.buffer().read(cx);
10270 let Some(buffer) = multibuffer.as_singleton() else {
10271 return;
10272 };
10273 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10274 return;
10275 };
10276 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10277 return;
10278 };
10279 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10280 s.select_anchor_ranges([start..end])
10281 });
10282 }
10283
10284 fn go_to_diagnostic(
10285 &mut self,
10286 _: &GoToDiagnostic,
10287 window: &mut Window,
10288 cx: &mut Context<Self>,
10289 ) {
10290 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10291 }
10292
10293 fn go_to_prev_diagnostic(
10294 &mut self,
10295 _: &GoToPrevDiagnostic,
10296 window: &mut Window,
10297 cx: &mut Context<Self>,
10298 ) {
10299 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10300 }
10301
10302 pub fn go_to_diagnostic_impl(
10303 &mut self,
10304 direction: Direction,
10305 window: &mut Window,
10306 cx: &mut Context<Self>,
10307 ) {
10308 let buffer = self.buffer.read(cx).snapshot(cx);
10309 let selection = self.selections.newest::<usize>(cx);
10310
10311 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10312 if direction == Direction::Next {
10313 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10314 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10315 return;
10316 };
10317 self.activate_diagnostics(
10318 buffer_id,
10319 popover.local_diagnostic.diagnostic.group_id,
10320 window,
10321 cx,
10322 );
10323 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10324 let primary_range_start = active_diagnostics.primary_range.start;
10325 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10326 let mut new_selection = s.newest_anchor().clone();
10327 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10328 s.select_anchors(vec![new_selection.clone()]);
10329 });
10330 self.refresh_inline_completion(false, true, window, cx);
10331 }
10332 return;
10333 }
10334 }
10335
10336 let active_group_id = self
10337 .active_diagnostics
10338 .as_ref()
10339 .map(|active_group| active_group.group_id);
10340 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10341 active_diagnostics
10342 .primary_range
10343 .to_offset(&buffer)
10344 .to_inclusive()
10345 });
10346 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10347 if active_primary_range.contains(&selection.head()) {
10348 *active_primary_range.start()
10349 } else {
10350 selection.head()
10351 }
10352 } else {
10353 selection.head()
10354 };
10355
10356 let snapshot = self.snapshot(window, cx);
10357 let primary_diagnostics_before = buffer
10358 .diagnostics_in_range::<usize>(0..search_start)
10359 .filter(|entry| entry.diagnostic.is_primary)
10360 .filter(|entry| entry.range.start != entry.range.end)
10361 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10362 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10363 .collect::<Vec<_>>();
10364 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10365 primary_diagnostics_before
10366 .iter()
10367 .position(|entry| entry.diagnostic.group_id == active_group_id)
10368 });
10369
10370 let primary_diagnostics_after = buffer
10371 .diagnostics_in_range::<usize>(search_start..buffer.len())
10372 .filter(|entry| entry.diagnostic.is_primary)
10373 .filter(|entry| entry.range.start != entry.range.end)
10374 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10375 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10376 .collect::<Vec<_>>();
10377 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10378 primary_diagnostics_after
10379 .iter()
10380 .enumerate()
10381 .rev()
10382 .find_map(|(i, entry)| {
10383 if entry.diagnostic.group_id == active_group_id {
10384 Some(i)
10385 } else {
10386 None
10387 }
10388 })
10389 });
10390
10391 let next_primary_diagnostic = match direction {
10392 Direction::Prev => primary_diagnostics_before
10393 .iter()
10394 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10395 .rev()
10396 .next(),
10397 Direction::Next => primary_diagnostics_after
10398 .iter()
10399 .skip(
10400 last_same_group_diagnostic_after
10401 .map(|index| index + 1)
10402 .unwrap_or(0),
10403 )
10404 .next(),
10405 };
10406
10407 // Cycle around to the start of the buffer, potentially moving back to the start of
10408 // the currently active diagnostic.
10409 let cycle_around = || match direction {
10410 Direction::Prev => primary_diagnostics_after
10411 .iter()
10412 .rev()
10413 .chain(primary_diagnostics_before.iter().rev())
10414 .next(),
10415 Direction::Next => primary_diagnostics_before
10416 .iter()
10417 .chain(primary_diagnostics_after.iter())
10418 .next(),
10419 };
10420
10421 if let Some((primary_range, group_id)) = next_primary_diagnostic
10422 .or_else(cycle_around)
10423 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10424 {
10425 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10426 return;
10427 };
10428 self.activate_diagnostics(buffer_id, group_id, window, cx);
10429 if self.active_diagnostics.is_some() {
10430 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10431 s.select(vec![Selection {
10432 id: selection.id,
10433 start: primary_range.start,
10434 end: primary_range.start,
10435 reversed: false,
10436 goal: SelectionGoal::None,
10437 }]);
10438 });
10439 self.refresh_inline_completion(false, true, window, cx);
10440 }
10441 }
10442 }
10443
10444 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10445 let snapshot = self.snapshot(window, cx);
10446 let selection = self.selections.newest::<Point>(cx);
10447 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10448 }
10449
10450 fn go_to_hunk_after_position(
10451 &mut self,
10452 snapshot: &EditorSnapshot,
10453 position: Point,
10454 window: &mut Window,
10455 cx: &mut Context<Editor>,
10456 ) -> Option<MultiBufferDiffHunk> {
10457 let mut hunk = snapshot
10458 .buffer_snapshot
10459 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10460 .find(|hunk| hunk.row_range.start.0 > position.row);
10461 if hunk.is_none() {
10462 hunk = snapshot
10463 .buffer_snapshot
10464 .diff_hunks_in_range(Point::zero()..position)
10465 .find(|hunk| hunk.row_range.end.0 < position.row)
10466 }
10467 if let Some(hunk) = &hunk {
10468 let destination = Point::new(hunk.row_range.start.0, 0);
10469 self.unfold_ranges(&[destination..destination], false, false, cx);
10470 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10471 s.select_ranges(vec![destination..destination]);
10472 });
10473 }
10474
10475 hunk
10476 }
10477
10478 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10479 let snapshot = self.snapshot(window, cx);
10480 let selection = self.selections.newest::<Point>(cx);
10481 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10482 }
10483
10484 fn go_to_hunk_before_position(
10485 &mut self,
10486 snapshot: &EditorSnapshot,
10487 position: Point,
10488 window: &mut Window,
10489 cx: &mut Context<Editor>,
10490 ) -> Option<MultiBufferDiffHunk> {
10491 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10492 if hunk.is_none() {
10493 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10494 }
10495 if let Some(hunk) = &hunk {
10496 let destination = Point::new(hunk.row_range.start.0, 0);
10497 self.unfold_ranges(&[destination..destination], false, false, cx);
10498 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10499 s.select_ranges(vec![destination..destination]);
10500 });
10501 }
10502
10503 hunk
10504 }
10505
10506 pub fn go_to_definition(
10507 &mut self,
10508 _: &GoToDefinition,
10509 window: &mut Window,
10510 cx: &mut Context<Self>,
10511 ) -> Task<Result<Navigated>> {
10512 let definition =
10513 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10514 cx.spawn_in(window, |editor, mut cx| async move {
10515 if definition.await? == Navigated::Yes {
10516 return Ok(Navigated::Yes);
10517 }
10518 match editor.update_in(&mut cx, |editor, window, cx| {
10519 editor.find_all_references(&FindAllReferences, window, cx)
10520 })? {
10521 Some(references) => references.await,
10522 None => Ok(Navigated::No),
10523 }
10524 })
10525 }
10526
10527 pub fn go_to_declaration(
10528 &mut self,
10529 _: &GoToDeclaration,
10530 window: &mut Window,
10531 cx: &mut Context<Self>,
10532 ) -> Task<Result<Navigated>> {
10533 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10534 }
10535
10536 pub fn go_to_declaration_split(
10537 &mut self,
10538 _: &GoToDeclaration,
10539 window: &mut Window,
10540 cx: &mut Context<Self>,
10541 ) -> Task<Result<Navigated>> {
10542 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10543 }
10544
10545 pub fn go_to_implementation(
10546 &mut self,
10547 _: &GoToImplementation,
10548 window: &mut Window,
10549 cx: &mut Context<Self>,
10550 ) -> Task<Result<Navigated>> {
10551 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10552 }
10553
10554 pub fn go_to_implementation_split(
10555 &mut self,
10556 _: &GoToImplementationSplit,
10557 window: &mut Window,
10558 cx: &mut Context<Self>,
10559 ) -> Task<Result<Navigated>> {
10560 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10561 }
10562
10563 pub fn go_to_type_definition(
10564 &mut self,
10565 _: &GoToTypeDefinition,
10566 window: &mut Window,
10567 cx: &mut Context<Self>,
10568 ) -> Task<Result<Navigated>> {
10569 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10570 }
10571
10572 pub fn go_to_definition_split(
10573 &mut self,
10574 _: &GoToDefinitionSplit,
10575 window: &mut Window,
10576 cx: &mut Context<Self>,
10577 ) -> Task<Result<Navigated>> {
10578 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10579 }
10580
10581 pub fn go_to_type_definition_split(
10582 &mut self,
10583 _: &GoToTypeDefinitionSplit,
10584 window: &mut Window,
10585 cx: &mut Context<Self>,
10586 ) -> Task<Result<Navigated>> {
10587 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10588 }
10589
10590 fn go_to_definition_of_kind(
10591 &mut self,
10592 kind: GotoDefinitionKind,
10593 split: bool,
10594 window: &mut Window,
10595 cx: &mut Context<Self>,
10596 ) -> Task<Result<Navigated>> {
10597 let Some(provider) = self.semantics_provider.clone() else {
10598 return Task::ready(Ok(Navigated::No));
10599 };
10600 let head = self.selections.newest::<usize>(cx).head();
10601 let buffer = self.buffer.read(cx);
10602 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10603 text_anchor
10604 } else {
10605 return Task::ready(Ok(Navigated::No));
10606 };
10607
10608 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10609 return Task::ready(Ok(Navigated::No));
10610 };
10611
10612 cx.spawn_in(window, |editor, mut cx| async move {
10613 let definitions = definitions.await?;
10614 let navigated = editor
10615 .update_in(&mut cx, |editor, window, cx| {
10616 editor.navigate_to_hover_links(
10617 Some(kind),
10618 definitions
10619 .into_iter()
10620 .filter(|location| {
10621 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10622 })
10623 .map(HoverLink::Text)
10624 .collect::<Vec<_>>(),
10625 split,
10626 window,
10627 cx,
10628 )
10629 })?
10630 .await?;
10631 anyhow::Ok(navigated)
10632 })
10633 }
10634
10635 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10636 let selection = self.selections.newest_anchor();
10637 let head = selection.head();
10638 let tail = selection.tail();
10639
10640 let Some((buffer, start_position)) =
10641 self.buffer.read(cx).text_anchor_for_position(head, cx)
10642 else {
10643 return;
10644 };
10645
10646 let end_position = if head != tail {
10647 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10648 return;
10649 };
10650 Some(pos)
10651 } else {
10652 None
10653 };
10654
10655 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10656 let url = if let Some(end_pos) = end_position {
10657 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10658 } else {
10659 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10660 };
10661
10662 if let Some(url) = url {
10663 editor.update(&mut cx, |_, cx| {
10664 cx.open_url(&url);
10665 })
10666 } else {
10667 Ok(())
10668 }
10669 });
10670
10671 url_finder.detach();
10672 }
10673
10674 pub fn open_selected_filename(
10675 &mut self,
10676 _: &OpenSelectedFilename,
10677 window: &mut Window,
10678 cx: &mut Context<Self>,
10679 ) {
10680 let Some(workspace) = self.workspace() else {
10681 return;
10682 };
10683
10684 let position = self.selections.newest_anchor().head();
10685
10686 let Some((buffer, buffer_position)) =
10687 self.buffer.read(cx).text_anchor_for_position(position, cx)
10688 else {
10689 return;
10690 };
10691
10692 let project = self.project.clone();
10693
10694 cx.spawn_in(window, |_, mut cx| async move {
10695 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10696
10697 if let Some((_, path)) = result {
10698 workspace
10699 .update_in(&mut cx, |workspace, window, cx| {
10700 workspace.open_resolved_path(path, window, cx)
10701 })?
10702 .await?;
10703 }
10704 anyhow::Ok(())
10705 })
10706 .detach();
10707 }
10708
10709 pub(crate) fn navigate_to_hover_links(
10710 &mut self,
10711 kind: Option<GotoDefinitionKind>,
10712 mut definitions: Vec<HoverLink>,
10713 split: bool,
10714 window: &mut Window,
10715 cx: &mut Context<Editor>,
10716 ) -> Task<Result<Navigated>> {
10717 // If there is one definition, just open it directly
10718 if definitions.len() == 1 {
10719 let definition = definitions.pop().unwrap();
10720
10721 enum TargetTaskResult {
10722 Location(Option<Location>),
10723 AlreadyNavigated,
10724 }
10725
10726 let target_task = match definition {
10727 HoverLink::Text(link) => {
10728 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10729 }
10730 HoverLink::InlayHint(lsp_location, server_id) => {
10731 let computation =
10732 self.compute_target_location(lsp_location, server_id, window, cx);
10733 cx.background_executor().spawn(async move {
10734 let location = computation.await?;
10735 Ok(TargetTaskResult::Location(location))
10736 })
10737 }
10738 HoverLink::Url(url) => {
10739 cx.open_url(&url);
10740 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10741 }
10742 HoverLink::File(path) => {
10743 if let Some(workspace) = self.workspace() {
10744 cx.spawn_in(window, |_, mut cx| async move {
10745 workspace
10746 .update_in(&mut cx, |workspace, window, cx| {
10747 workspace.open_resolved_path(path, window, cx)
10748 })?
10749 .await
10750 .map(|_| TargetTaskResult::AlreadyNavigated)
10751 })
10752 } else {
10753 Task::ready(Ok(TargetTaskResult::Location(None)))
10754 }
10755 }
10756 };
10757 cx.spawn_in(window, |editor, mut cx| async move {
10758 let target = match target_task.await.context("target resolution task")? {
10759 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10760 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10761 TargetTaskResult::Location(Some(target)) => target,
10762 };
10763
10764 editor.update_in(&mut cx, |editor, window, cx| {
10765 let Some(workspace) = editor.workspace() else {
10766 return Navigated::No;
10767 };
10768 let pane = workspace.read(cx).active_pane().clone();
10769
10770 let range = target.range.to_point(target.buffer.read(cx));
10771 let range = editor.range_for_match(&range);
10772 let range = collapse_multiline_range(range);
10773
10774 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10775 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10776 } else {
10777 window.defer(cx, move |window, cx| {
10778 let target_editor: Entity<Self> =
10779 workspace.update(cx, |workspace, cx| {
10780 let pane = if split {
10781 workspace.adjacent_pane(window, cx)
10782 } else {
10783 workspace.active_pane().clone()
10784 };
10785
10786 workspace.open_project_item(
10787 pane,
10788 target.buffer.clone(),
10789 true,
10790 true,
10791 window,
10792 cx,
10793 )
10794 });
10795 target_editor.update(cx, |target_editor, cx| {
10796 // When selecting a definition in a different buffer, disable the nav history
10797 // to avoid creating a history entry at the previous cursor location.
10798 pane.update(cx, |pane, _| pane.disable_history());
10799 target_editor.go_to_singleton_buffer_range(range, window, cx);
10800 pane.update(cx, |pane, _| pane.enable_history());
10801 });
10802 });
10803 }
10804 Navigated::Yes
10805 })
10806 })
10807 } else if !definitions.is_empty() {
10808 cx.spawn_in(window, |editor, mut cx| async move {
10809 let (title, location_tasks, workspace) = editor
10810 .update_in(&mut cx, |editor, window, cx| {
10811 let tab_kind = match kind {
10812 Some(GotoDefinitionKind::Implementation) => "Implementations",
10813 _ => "Definitions",
10814 };
10815 let title = definitions
10816 .iter()
10817 .find_map(|definition| match definition {
10818 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10819 let buffer = origin.buffer.read(cx);
10820 format!(
10821 "{} for {}",
10822 tab_kind,
10823 buffer
10824 .text_for_range(origin.range.clone())
10825 .collect::<String>()
10826 )
10827 }),
10828 HoverLink::InlayHint(_, _) => None,
10829 HoverLink::Url(_) => None,
10830 HoverLink::File(_) => None,
10831 })
10832 .unwrap_or(tab_kind.to_string());
10833 let location_tasks = definitions
10834 .into_iter()
10835 .map(|definition| match definition {
10836 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10837 HoverLink::InlayHint(lsp_location, server_id) => editor
10838 .compute_target_location(lsp_location, server_id, window, cx),
10839 HoverLink::Url(_) => Task::ready(Ok(None)),
10840 HoverLink::File(_) => Task::ready(Ok(None)),
10841 })
10842 .collect::<Vec<_>>();
10843 (title, location_tasks, editor.workspace().clone())
10844 })
10845 .context("location tasks preparation")?;
10846
10847 let locations = future::join_all(location_tasks)
10848 .await
10849 .into_iter()
10850 .filter_map(|location| location.transpose())
10851 .collect::<Result<_>>()
10852 .context("location tasks")?;
10853
10854 let Some(workspace) = workspace else {
10855 return Ok(Navigated::No);
10856 };
10857 let opened = workspace
10858 .update_in(&mut cx, |workspace, window, cx| {
10859 Self::open_locations_in_multibuffer(
10860 workspace,
10861 locations,
10862 title,
10863 split,
10864 MultibufferSelectionMode::First,
10865 window,
10866 cx,
10867 )
10868 })
10869 .ok();
10870
10871 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10872 })
10873 } else {
10874 Task::ready(Ok(Navigated::No))
10875 }
10876 }
10877
10878 fn compute_target_location(
10879 &self,
10880 lsp_location: lsp::Location,
10881 server_id: LanguageServerId,
10882 window: &mut Window,
10883 cx: &mut Context<Self>,
10884 ) -> Task<anyhow::Result<Option<Location>>> {
10885 let Some(project) = self.project.clone() else {
10886 return Task::ready(Ok(None));
10887 };
10888
10889 cx.spawn_in(window, move |editor, mut cx| async move {
10890 let location_task = editor.update(&mut cx, |_, cx| {
10891 project.update(cx, |project, cx| {
10892 let language_server_name = project
10893 .language_server_statuses(cx)
10894 .find(|(id, _)| server_id == *id)
10895 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10896 language_server_name.map(|language_server_name| {
10897 project.open_local_buffer_via_lsp(
10898 lsp_location.uri.clone(),
10899 server_id,
10900 language_server_name,
10901 cx,
10902 )
10903 })
10904 })
10905 })?;
10906 let location = match location_task {
10907 Some(task) => Some({
10908 let target_buffer_handle = task.await.context("open local buffer")?;
10909 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10910 let target_start = target_buffer
10911 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10912 let target_end = target_buffer
10913 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10914 target_buffer.anchor_after(target_start)
10915 ..target_buffer.anchor_before(target_end)
10916 })?;
10917 Location {
10918 buffer: target_buffer_handle,
10919 range,
10920 }
10921 }),
10922 None => None,
10923 };
10924 Ok(location)
10925 })
10926 }
10927
10928 pub fn find_all_references(
10929 &mut self,
10930 _: &FindAllReferences,
10931 window: &mut Window,
10932 cx: &mut Context<Self>,
10933 ) -> Option<Task<Result<Navigated>>> {
10934 let selection = self.selections.newest::<usize>(cx);
10935 let multi_buffer = self.buffer.read(cx);
10936 let head = selection.head();
10937
10938 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10939 let head_anchor = multi_buffer_snapshot.anchor_at(
10940 head,
10941 if head < selection.tail() {
10942 Bias::Right
10943 } else {
10944 Bias::Left
10945 },
10946 );
10947
10948 match self
10949 .find_all_references_task_sources
10950 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10951 {
10952 Ok(_) => {
10953 log::info!(
10954 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10955 );
10956 return None;
10957 }
10958 Err(i) => {
10959 self.find_all_references_task_sources.insert(i, head_anchor);
10960 }
10961 }
10962
10963 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10964 let workspace = self.workspace()?;
10965 let project = workspace.read(cx).project().clone();
10966 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10967 Some(cx.spawn_in(window, |editor, mut cx| async move {
10968 let _cleanup = defer({
10969 let mut cx = cx.clone();
10970 move || {
10971 let _ = editor.update(&mut cx, |editor, _| {
10972 if let Ok(i) =
10973 editor
10974 .find_all_references_task_sources
10975 .binary_search_by(|anchor| {
10976 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10977 })
10978 {
10979 editor.find_all_references_task_sources.remove(i);
10980 }
10981 });
10982 }
10983 });
10984
10985 let locations = references.await?;
10986 if locations.is_empty() {
10987 return anyhow::Ok(Navigated::No);
10988 }
10989
10990 workspace.update_in(&mut cx, |workspace, window, cx| {
10991 let title = locations
10992 .first()
10993 .as_ref()
10994 .map(|location| {
10995 let buffer = location.buffer.read(cx);
10996 format!(
10997 "References to `{}`",
10998 buffer
10999 .text_for_range(location.range.clone())
11000 .collect::<String>()
11001 )
11002 })
11003 .unwrap();
11004 Self::open_locations_in_multibuffer(
11005 workspace,
11006 locations,
11007 title,
11008 false,
11009 MultibufferSelectionMode::First,
11010 window,
11011 cx,
11012 );
11013 Navigated::Yes
11014 })
11015 }))
11016 }
11017
11018 /// Opens a multibuffer with the given project locations in it
11019 pub fn open_locations_in_multibuffer(
11020 workspace: &mut Workspace,
11021 mut locations: Vec<Location>,
11022 title: String,
11023 split: bool,
11024 multibuffer_selection_mode: MultibufferSelectionMode,
11025 window: &mut Window,
11026 cx: &mut Context<Workspace>,
11027 ) {
11028 // If there are multiple definitions, open them in a multibuffer
11029 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11030 let mut locations = locations.into_iter().peekable();
11031 let mut ranges = Vec::new();
11032 let capability = workspace.project().read(cx).capability();
11033
11034 let excerpt_buffer = cx.new(|cx| {
11035 let mut multibuffer = MultiBuffer::new(capability);
11036 while let Some(location) = locations.next() {
11037 let buffer = location.buffer.read(cx);
11038 let mut ranges_for_buffer = Vec::new();
11039 let range = location.range.to_offset(buffer);
11040 ranges_for_buffer.push(range.clone());
11041
11042 while let Some(next_location) = locations.peek() {
11043 if next_location.buffer == location.buffer {
11044 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11045 locations.next();
11046 } else {
11047 break;
11048 }
11049 }
11050
11051 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11052 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11053 location.buffer.clone(),
11054 ranges_for_buffer,
11055 DEFAULT_MULTIBUFFER_CONTEXT,
11056 cx,
11057 ))
11058 }
11059
11060 multibuffer.with_title(title)
11061 });
11062
11063 let editor = cx.new(|cx| {
11064 Editor::for_multibuffer(
11065 excerpt_buffer,
11066 Some(workspace.project().clone()),
11067 true,
11068 window,
11069 cx,
11070 )
11071 });
11072 editor.update(cx, |editor, cx| {
11073 match multibuffer_selection_mode {
11074 MultibufferSelectionMode::First => {
11075 if let Some(first_range) = ranges.first() {
11076 editor.change_selections(None, window, cx, |selections| {
11077 selections.clear_disjoint();
11078 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11079 });
11080 }
11081 editor.highlight_background::<Self>(
11082 &ranges,
11083 |theme| theme.editor_highlighted_line_background,
11084 cx,
11085 );
11086 }
11087 MultibufferSelectionMode::All => {
11088 editor.change_selections(None, window, cx, |selections| {
11089 selections.clear_disjoint();
11090 selections.select_anchor_ranges(ranges);
11091 });
11092 }
11093 }
11094 editor.register_buffers_with_language_servers(cx);
11095 });
11096
11097 let item = Box::new(editor);
11098 let item_id = item.item_id();
11099
11100 if split {
11101 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11102 } else {
11103 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11104 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11105 pane.close_current_preview_item(window, cx)
11106 } else {
11107 None
11108 }
11109 });
11110 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11111 }
11112 workspace.active_pane().update(cx, |pane, cx| {
11113 pane.set_preview_item_id(Some(item_id), cx);
11114 });
11115 }
11116
11117 pub fn rename(
11118 &mut self,
11119 _: &Rename,
11120 window: &mut Window,
11121 cx: &mut Context<Self>,
11122 ) -> Option<Task<Result<()>>> {
11123 use language::ToOffset as _;
11124
11125 let provider = self.semantics_provider.clone()?;
11126 let selection = self.selections.newest_anchor().clone();
11127 let (cursor_buffer, cursor_buffer_position) = self
11128 .buffer
11129 .read(cx)
11130 .text_anchor_for_position(selection.head(), cx)?;
11131 let (tail_buffer, cursor_buffer_position_end) = self
11132 .buffer
11133 .read(cx)
11134 .text_anchor_for_position(selection.tail(), cx)?;
11135 if tail_buffer != cursor_buffer {
11136 return None;
11137 }
11138
11139 let snapshot = cursor_buffer.read(cx).snapshot();
11140 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11141 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11142 let prepare_rename = provider
11143 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11144 .unwrap_or_else(|| Task::ready(Ok(None)));
11145 drop(snapshot);
11146
11147 Some(cx.spawn_in(window, |this, mut cx| async move {
11148 let rename_range = if let Some(range) = prepare_rename.await? {
11149 Some(range)
11150 } else {
11151 this.update(&mut cx, |this, cx| {
11152 let buffer = this.buffer.read(cx).snapshot(cx);
11153 let mut buffer_highlights = this
11154 .document_highlights_for_position(selection.head(), &buffer)
11155 .filter(|highlight| {
11156 highlight.start.excerpt_id == selection.head().excerpt_id
11157 && highlight.end.excerpt_id == selection.head().excerpt_id
11158 });
11159 buffer_highlights
11160 .next()
11161 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11162 })?
11163 };
11164 if let Some(rename_range) = rename_range {
11165 this.update_in(&mut cx, |this, window, cx| {
11166 let snapshot = cursor_buffer.read(cx).snapshot();
11167 let rename_buffer_range = rename_range.to_offset(&snapshot);
11168 let cursor_offset_in_rename_range =
11169 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11170 let cursor_offset_in_rename_range_end =
11171 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11172
11173 this.take_rename(false, window, cx);
11174 let buffer = this.buffer.read(cx).read(cx);
11175 let cursor_offset = selection.head().to_offset(&buffer);
11176 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11177 let rename_end = rename_start + rename_buffer_range.len();
11178 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11179 let mut old_highlight_id = None;
11180 let old_name: Arc<str> = buffer
11181 .chunks(rename_start..rename_end, true)
11182 .map(|chunk| {
11183 if old_highlight_id.is_none() {
11184 old_highlight_id = chunk.syntax_highlight_id;
11185 }
11186 chunk.text
11187 })
11188 .collect::<String>()
11189 .into();
11190
11191 drop(buffer);
11192
11193 // Position the selection in the rename editor so that it matches the current selection.
11194 this.show_local_selections = false;
11195 let rename_editor = cx.new(|cx| {
11196 let mut editor = Editor::single_line(window, cx);
11197 editor.buffer.update(cx, |buffer, cx| {
11198 buffer.edit([(0..0, old_name.clone())], None, cx)
11199 });
11200 let rename_selection_range = match cursor_offset_in_rename_range
11201 .cmp(&cursor_offset_in_rename_range_end)
11202 {
11203 Ordering::Equal => {
11204 editor.select_all(&SelectAll, window, cx);
11205 return editor;
11206 }
11207 Ordering::Less => {
11208 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11209 }
11210 Ordering::Greater => {
11211 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11212 }
11213 };
11214 if rename_selection_range.end > old_name.len() {
11215 editor.select_all(&SelectAll, window, cx);
11216 } else {
11217 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11218 s.select_ranges([rename_selection_range]);
11219 });
11220 }
11221 editor
11222 });
11223 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11224 if e == &EditorEvent::Focused {
11225 cx.emit(EditorEvent::FocusedIn)
11226 }
11227 })
11228 .detach();
11229
11230 let write_highlights =
11231 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11232 let read_highlights =
11233 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11234 let ranges = write_highlights
11235 .iter()
11236 .flat_map(|(_, ranges)| ranges.iter())
11237 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11238 .cloned()
11239 .collect();
11240
11241 this.highlight_text::<Rename>(
11242 ranges,
11243 HighlightStyle {
11244 fade_out: Some(0.6),
11245 ..Default::default()
11246 },
11247 cx,
11248 );
11249 let rename_focus_handle = rename_editor.focus_handle(cx);
11250 window.focus(&rename_focus_handle);
11251 let block_id = this.insert_blocks(
11252 [BlockProperties {
11253 style: BlockStyle::Flex,
11254 placement: BlockPlacement::Below(range.start),
11255 height: 1,
11256 render: Arc::new({
11257 let rename_editor = rename_editor.clone();
11258 move |cx: &mut BlockContext| {
11259 let mut text_style = cx.editor_style.text.clone();
11260 if let Some(highlight_style) = old_highlight_id
11261 .and_then(|h| h.style(&cx.editor_style.syntax))
11262 {
11263 text_style = text_style.highlight(highlight_style);
11264 }
11265 div()
11266 .block_mouse_down()
11267 .pl(cx.anchor_x)
11268 .child(EditorElement::new(
11269 &rename_editor,
11270 EditorStyle {
11271 background: cx.theme().system().transparent,
11272 local_player: cx.editor_style.local_player,
11273 text: text_style,
11274 scrollbar_width: cx.editor_style.scrollbar_width,
11275 syntax: cx.editor_style.syntax.clone(),
11276 status: cx.editor_style.status.clone(),
11277 inlay_hints_style: HighlightStyle {
11278 font_weight: Some(FontWeight::BOLD),
11279 ..make_inlay_hints_style(cx.app)
11280 },
11281 inline_completion_styles: make_suggestion_styles(
11282 cx.app,
11283 ),
11284 ..EditorStyle::default()
11285 },
11286 ))
11287 .into_any_element()
11288 }
11289 }),
11290 priority: 0,
11291 }],
11292 Some(Autoscroll::fit()),
11293 cx,
11294 )[0];
11295 this.pending_rename = Some(RenameState {
11296 range,
11297 old_name,
11298 editor: rename_editor,
11299 block_id,
11300 });
11301 })?;
11302 }
11303
11304 Ok(())
11305 }))
11306 }
11307
11308 pub fn confirm_rename(
11309 &mut self,
11310 _: &ConfirmRename,
11311 window: &mut Window,
11312 cx: &mut Context<Self>,
11313 ) -> Option<Task<Result<()>>> {
11314 let rename = self.take_rename(false, window, cx)?;
11315 let workspace = self.workspace()?.downgrade();
11316 let (buffer, start) = self
11317 .buffer
11318 .read(cx)
11319 .text_anchor_for_position(rename.range.start, cx)?;
11320 let (end_buffer, _) = self
11321 .buffer
11322 .read(cx)
11323 .text_anchor_for_position(rename.range.end, cx)?;
11324 if buffer != end_buffer {
11325 return None;
11326 }
11327
11328 let old_name = rename.old_name;
11329 let new_name = rename.editor.read(cx).text(cx);
11330
11331 let rename = self.semantics_provider.as_ref()?.perform_rename(
11332 &buffer,
11333 start,
11334 new_name.clone(),
11335 cx,
11336 )?;
11337
11338 Some(cx.spawn_in(window, |editor, mut cx| async move {
11339 let project_transaction = rename.await?;
11340 Self::open_project_transaction(
11341 &editor,
11342 workspace,
11343 project_transaction,
11344 format!("Rename: {} → {}", old_name, new_name),
11345 cx.clone(),
11346 )
11347 .await?;
11348
11349 editor.update(&mut cx, |editor, cx| {
11350 editor.refresh_document_highlights(cx);
11351 })?;
11352 Ok(())
11353 }))
11354 }
11355
11356 fn take_rename(
11357 &mut self,
11358 moving_cursor: bool,
11359 window: &mut Window,
11360 cx: &mut Context<Self>,
11361 ) -> Option<RenameState> {
11362 let rename = self.pending_rename.take()?;
11363 if rename.editor.focus_handle(cx).is_focused(window) {
11364 window.focus(&self.focus_handle);
11365 }
11366
11367 self.remove_blocks(
11368 [rename.block_id].into_iter().collect(),
11369 Some(Autoscroll::fit()),
11370 cx,
11371 );
11372 self.clear_highlights::<Rename>(cx);
11373 self.show_local_selections = true;
11374
11375 if moving_cursor {
11376 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11377 editor.selections.newest::<usize>(cx).head()
11378 });
11379
11380 // Update the selection to match the position of the selection inside
11381 // the rename editor.
11382 let snapshot = self.buffer.read(cx).read(cx);
11383 let rename_range = rename.range.to_offset(&snapshot);
11384 let cursor_in_editor = snapshot
11385 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11386 .min(rename_range.end);
11387 drop(snapshot);
11388
11389 self.change_selections(None, window, cx, |s| {
11390 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11391 });
11392 } else {
11393 self.refresh_document_highlights(cx);
11394 }
11395
11396 Some(rename)
11397 }
11398
11399 pub fn pending_rename(&self) -> Option<&RenameState> {
11400 self.pending_rename.as_ref()
11401 }
11402
11403 fn format(
11404 &mut self,
11405 _: &Format,
11406 window: &mut Window,
11407 cx: &mut Context<Self>,
11408 ) -> Option<Task<Result<()>>> {
11409 let project = match &self.project {
11410 Some(project) => project.clone(),
11411 None => return None,
11412 };
11413
11414 Some(self.perform_format(
11415 project,
11416 FormatTrigger::Manual,
11417 FormatTarget::Buffers,
11418 window,
11419 cx,
11420 ))
11421 }
11422
11423 fn format_selections(
11424 &mut self,
11425 _: &FormatSelections,
11426 window: &mut Window,
11427 cx: &mut Context<Self>,
11428 ) -> Option<Task<Result<()>>> {
11429 let project = match &self.project {
11430 Some(project) => project.clone(),
11431 None => return None,
11432 };
11433
11434 let ranges = self
11435 .selections
11436 .all_adjusted(cx)
11437 .into_iter()
11438 .map(|selection| selection.range())
11439 .collect_vec();
11440
11441 Some(self.perform_format(
11442 project,
11443 FormatTrigger::Manual,
11444 FormatTarget::Ranges(ranges),
11445 window,
11446 cx,
11447 ))
11448 }
11449
11450 fn perform_format(
11451 &mut self,
11452 project: Entity<Project>,
11453 trigger: FormatTrigger,
11454 target: FormatTarget,
11455 window: &mut Window,
11456 cx: &mut Context<Self>,
11457 ) -> Task<Result<()>> {
11458 let buffer = self.buffer.clone();
11459 let (buffers, target) = match target {
11460 FormatTarget::Buffers => {
11461 let mut buffers = buffer.read(cx).all_buffers();
11462 if trigger == FormatTrigger::Save {
11463 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11464 }
11465 (buffers, LspFormatTarget::Buffers)
11466 }
11467 FormatTarget::Ranges(selection_ranges) => {
11468 let multi_buffer = buffer.read(cx);
11469 let snapshot = multi_buffer.read(cx);
11470 let mut buffers = HashSet::default();
11471 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11472 BTreeMap::new();
11473 for selection_range in selection_ranges {
11474 for (buffer, buffer_range, _) in
11475 snapshot.range_to_buffer_ranges(selection_range)
11476 {
11477 let buffer_id = buffer.remote_id();
11478 let start = buffer.anchor_before(buffer_range.start);
11479 let end = buffer.anchor_after(buffer_range.end);
11480 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11481 buffer_id_to_ranges
11482 .entry(buffer_id)
11483 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11484 .or_insert_with(|| vec![start..end]);
11485 }
11486 }
11487 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11488 }
11489 };
11490
11491 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11492 let format = project.update(cx, |project, cx| {
11493 project.format(buffers, target, true, trigger, cx)
11494 });
11495
11496 cx.spawn_in(window, |_, mut cx| async move {
11497 let transaction = futures::select_biased! {
11498 () = timeout => {
11499 log::warn!("timed out waiting for formatting");
11500 None
11501 }
11502 transaction = format.log_err().fuse() => transaction,
11503 };
11504
11505 buffer
11506 .update(&mut cx, |buffer, cx| {
11507 if let Some(transaction) = transaction {
11508 if !buffer.is_singleton() {
11509 buffer.push_transaction(&transaction.0, cx);
11510 }
11511 }
11512
11513 cx.notify();
11514 })
11515 .ok();
11516
11517 Ok(())
11518 })
11519 }
11520
11521 fn restart_language_server(
11522 &mut self,
11523 _: &RestartLanguageServer,
11524 _: &mut Window,
11525 cx: &mut Context<Self>,
11526 ) {
11527 if let Some(project) = self.project.clone() {
11528 self.buffer.update(cx, |multi_buffer, cx| {
11529 project.update(cx, |project, cx| {
11530 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11531 });
11532 })
11533 }
11534 }
11535
11536 fn cancel_language_server_work(
11537 workspace: &mut Workspace,
11538 _: &actions::CancelLanguageServerWork,
11539 _: &mut Window,
11540 cx: &mut Context<Workspace>,
11541 ) {
11542 let project = workspace.project();
11543 let buffers = workspace
11544 .active_item(cx)
11545 .and_then(|item| item.act_as::<Editor>(cx))
11546 .map_or(HashSet::default(), |editor| {
11547 editor.read(cx).buffer.read(cx).all_buffers()
11548 });
11549 project.update(cx, |project, cx| {
11550 project.cancel_language_server_work_for_buffers(buffers, cx);
11551 });
11552 }
11553
11554 fn show_character_palette(
11555 &mut self,
11556 _: &ShowCharacterPalette,
11557 window: &mut Window,
11558 _: &mut Context<Self>,
11559 ) {
11560 window.show_character_palette();
11561 }
11562
11563 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11564 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11565 let buffer = self.buffer.read(cx).snapshot(cx);
11566 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11567 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11568 let is_valid = buffer
11569 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11570 .any(|entry| {
11571 entry.diagnostic.is_primary
11572 && !entry.range.is_empty()
11573 && entry.range.start == primary_range_start
11574 && entry.diagnostic.message == active_diagnostics.primary_message
11575 });
11576
11577 if is_valid != active_diagnostics.is_valid {
11578 active_diagnostics.is_valid = is_valid;
11579 let mut new_styles = HashMap::default();
11580 for (block_id, diagnostic) in &active_diagnostics.blocks {
11581 new_styles.insert(
11582 *block_id,
11583 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11584 );
11585 }
11586 self.display_map.update(cx, |display_map, _cx| {
11587 display_map.replace_blocks(new_styles)
11588 });
11589 }
11590 }
11591 }
11592
11593 fn activate_diagnostics(
11594 &mut self,
11595 buffer_id: BufferId,
11596 group_id: usize,
11597 window: &mut Window,
11598 cx: &mut Context<Self>,
11599 ) {
11600 self.dismiss_diagnostics(cx);
11601 let snapshot = self.snapshot(window, cx);
11602 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11603 let buffer = self.buffer.read(cx).snapshot(cx);
11604
11605 let mut primary_range = None;
11606 let mut primary_message = None;
11607 let diagnostic_group = buffer
11608 .diagnostic_group(buffer_id, group_id)
11609 .filter_map(|entry| {
11610 let start = entry.range.start;
11611 let end = entry.range.end;
11612 if snapshot.is_line_folded(MultiBufferRow(start.row))
11613 && (start.row == end.row
11614 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11615 {
11616 return None;
11617 }
11618 if entry.diagnostic.is_primary {
11619 primary_range = Some(entry.range.clone());
11620 primary_message = Some(entry.diagnostic.message.clone());
11621 }
11622 Some(entry)
11623 })
11624 .collect::<Vec<_>>();
11625 let primary_range = primary_range?;
11626 let primary_message = primary_message?;
11627
11628 let blocks = display_map
11629 .insert_blocks(
11630 diagnostic_group.iter().map(|entry| {
11631 let diagnostic = entry.diagnostic.clone();
11632 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11633 BlockProperties {
11634 style: BlockStyle::Fixed,
11635 placement: BlockPlacement::Below(
11636 buffer.anchor_after(entry.range.start),
11637 ),
11638 height: message_height,
11639 render: diagnostic_block_renderer(diagnostic, None, true, true),
11640 priority: 0,
11641 }
11642 }),
11643 cx,
11644 )
11645 .into_iter()
11646 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11647 .collect();
11648
11649 Some(ActiveDiagnosticGroup {
11650 primary_range: buffer.anchor_before(primary_range.start)
11651 ..buffer.anchor_after(primary_range.end),
11652 primary_message,
11653 group_id,
11654 blocks,
11655 is_valid: true,
11656 })
11657 });
11658 }
11659
11660 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11661 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11662 self.display_map.update(cx, |display_map, cx| {
11663 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11664 });
11665 cx.notify();
11666 }
11667 }
11668
11669 pub fn set_selections_from_remote(
11670 &mut self,
11671 selections: Vec<Selection<Anchor>>,
11672 pending_selection: Option<Selection<Anchor>>,
11673 window: &mut Window,
11674 cx: &mut Context<Self>,
11675 ) {
11676 let old_cursor_position = self.selections.newest_anchor().head();
11677 self.selections.change_with(cx, |s| {
11678 s.select_anchors(selections);
11679 if let Some(pending_selection) = pending_selection {
11680 s.set_pending(pending_selection, SelectMode::Character);
11681 } else {
11682 s.clear_pending();
11683 }
11684 });
11685 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11686 }
11687
11688 fn push_to_selection_history(&mut self) {
11689 self.selection_history.push(SelectionHistoryEntry {
11690 selections: self.selections.disjoint_anchors(),
11691 select_next_state: self.select_next_state.clone(),
11692 select_prev_state: self.select_prev_state.clone(),
11693 add_selections_state: self.add_selections_state.clone(),
11694 });
11695 }
11696
11697 pub fn transact(
11698 &mut self,
11699 window: &mut Window,
11700 cx: &mut Context<Self>,
11701 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11702 ) -> Option<TransactionId> {
11703 self.start_transaction_at(Instant::now(), window, cx);
11704 update(self, window, cx);
11705 self.end_transaction_at(Instant::now(), cx)
11706 }
11707
11708 pub fn start_transaction_at(
11709 &mut self,
11710 now: Instant,
11711 window: &mut Window,
11712 cx: &mut Context<Self>,
11713 ) {
11714 self.end_selection(window, cx);
11715 if let Some(tx_id) = self
11716 .buffer
11717 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11718 {
11719 self.selection_history
11720 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11721 cx.emit(EditorEvent::TransactionBegun {
11722 transaction_id: tx_id,
11723 })
11724 }
11725 }
11726
11727 pub fn end_transaction_at(
11728 &mut self,
11729 now: Instant,
11730 cx: &mut Context<Self>,
11731 ) -> Option<TransactionId> {
11732 if let Some(transaction_id) = self
11733 .buffer
11734 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11735 {
11736 if let Some((_, end_selections)) =
11737 self.selection_history.transaction_mut(transaction_id)
11738 {
11739 *end_selections = Some(self.selections.disjoint_anchors());
11740 } else {
11741 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11742 }
11743
11744 cx.emit(EditorEvent::Edited { transaction_id });
11745 Some(transaction_id)
11746 } else {
11747 None
11748 }
11749 }
11750
11751 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11752 if self.selection_mark_mode {
11753 self.change_selections(None, window, cx, |s| {
11754 s.move_with(|_, sel| {
11755 sel.collapse_to(sel.head(), SelectionGoal::None);
11756 });
11757 })
11758 }
11759 self.selection_mark_mode = true;
11760 cx.notify();
11761 }
11762
11763 pub fn swap_selection_ends(
11764 &mut self,
11765 _: &actions::SwapSelectionEnds,
11766 window: &mut Window,
11767 cx: &mut Context<Self>,
11768 ) {
11769 self.change_selections(None, window, cx, |s| {
11770 s.move_with(|_, sel| {
11771 if sel.start != sel.end {
11772 sel.reversed = !sel.reversed
11773 }
11774 });
11775 });
11776 self.request_autoscroll(Autoscroll::newest(), cx);
11777 cx.notify();
11778 }
11779
11780 pub fn toggle_fold(
11781 &mut self,
11782 _: &actions::ToggleFold,
11783 window: &mut Window,
11784 cx: &mut Context<Self>,
11785 ) {
11786 if self.is_singleton(cx) {
11787 let selection = self.selections.newest::<Point>(cx);
11788
11789 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11790 let range = if selection.is_empty() {
11791 let point = selection.head().to_display_point(&display_map);
11792 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11793 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11794 .to_point(&display_map);
11795 start..end
11796 } else {
11797 selection.range()
11798 };
11799 if display_map.folds_in_range(range).next().is_some() {
11800 self.unfold_lines(&Default::default(), window, cx)
11801 } else {
11802 self.fold(&Default::default(), window, cx)
11803 }
11804 } else {
11805 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11806 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11807 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11808 .map(|(snapshot, _, _)| snapshot.remote_id())
11809 .collect();
11810
11811 for buffer_id in buffer_ids {
11812 if self.is_buffer_folded(buffer_id, cx) {
11813 self.unfold_buffer(buffer_id, cx);
11814 } else {
11815 self.fold_buffer(buffer_id, cx);
11816 }
11817 }
11818 }
11819 }
11820
11821 pub fn toggle_fold_recursive(
11822 &mut self,
11823 _: &actions::ToggleFoldRecursive,
11824 window: &mut Window,
11825 cx: &mut Context<Self>,
11826 ) {
11827 let selection = self.selections.newest::<Point>(cx);
11828
11829 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11830 let range = if selection.is_empty() {
11831 let point = selection.head().to_display_point(&display_map);
11832 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11833 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11834 .to_point(&display_map);
11835 start..end
11836 } else {
11837 selection.range()
11838 };
11839 if display_map.folds_in_range(range).next().is_some() {
11840 self.unfold_recursive(&Default::default(), window, cx)
11841 } else {
11842 self.fold_recursive(&Default::default(), window, cx)
11843 }
11844 }
11845
11846 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11847 if self.is_singleton(cx) {
11848 let mut to_fold = Vec::new();
11849 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11850 let selections = self.selections.all_adjusted(cx);
11851
11852 for selection in selections {
11853 let range = selection.range().sorted();
11854 let buffer_start_row = range.start.row;
11855
11856 if range.start.row != range.end.row {
11857 let mut found = false;
11858 let mut row = range.start.row;
11859 while row <= range.end.row {
11860 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11861 {
11862 found = true;
11863 row = crease.range().end.row + 1;
11864 to_fold.push(crease);
11865 } else {
11866 row += 1
11867 }
11868 }
11869 if found {
11870 continue;
11871 }
11872 }
11873
11874 for row in (0..=range.start.row).rev() {
11875 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11876 if crease.range().end.row >= buffer_start_row {
11877 to_fold.push(crease);
11878 if row <= range.start.row {
11879 break;
11880 }
11881 }
11882 }
11883 }
11884 }
11885
11886 self.fold_creases(to_fold, true, window, cx);
11887 } else {
11888 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11889
11890 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11891 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11892 .map(|(snapshot, _, _)| snapshot.remote_id())
11893 .collect();
11894 for buffer_id in buffer_ids {
11895 self.fold_buffer(buffer_id, cx);
11896 }
11897 }
11898 }
11899
11900 fn fold_at_level(
11901 &mut self,
11902 fold_at: &FoldAtLevel,
11903 window: &mut Window,
11904 cx: &mut Context<Self>,
11905 ) {
11906 if !self.buffer.read(cx).is_singleton() {
11907 return;
11908 }
11909
11910 let fold_at_level = fold_at.0;
11911 let snapshot = self.buffer.read(cx).snapshot(cx);
11912 let mut to_fold = Vec::new();
11913 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11914
11915 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11916 while start_row < end_row {
11917 match self
11918 .snapshot(window, cx)
11919 .crease_for_buffer_row(MultiBufferRow(start_row))
11920 {
11921 Some(crease) => {
11922 let nested_start_row = crease.range().start.row + 1;
11923 let nested_end_row = crease.range().end.row;
11924
11925 if current_level < fold_at_level {
11926 stack.push((nested_start_row, nested_end_row, current_level + 1));
11927 } else if current_level == fold_at_level {
11928 to_fold.push(crease);
11929 }
11930
11931 start_row = nested_end_row + 1;
11932 }
11933 None => start_row += 1,
11934 }
11935 }
11936 }
11937
11938 self.fold_creases(to_fold, true, window, cx);
11939 }
11940
11941 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11942 if self.buffer.read(cx).is_singleton() {
11943 let mut fold_ranges = Vec::new();
11944 let snapshot = self.buffer.read(cx).snapshot(cx);
11945
11946 for row in 0..snapshot.max_row().0 {
11947 if let Some(foldable_range) = self
11948 .snapshot(window, cx)
11949 .crease_for_buffer_row(MultiBufferRow(row))
11950 {
11951 fold_ranges.push(foldable_range);
11952 }
11953 }
11954
11955 self.fold_creases(fold_ranges, true, window, cx);
11956 } else {
11957 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11958 editor
11959 .update_in(&mut cx, |editor, _, cx| {
11960 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11961 editor.fold_buffer(buffer_id, cx);
11962 }
11963 })
11964 .ok();
11965 });
11966 }
11967 }
11968
11969 pub fn fold_function_bodies(
11970 &mut self,
11971 _: &actions::FoldFunctionBodies,
11972 window: &mut Window,
11973 cx: &mut Context<Self>,
11974 ) {
11975 let snapshot = self.buffer.read(cx).snapshot(cx);
11976
11977 let ranges = snapshot
11978 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11979 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11980 .collect::<Vec<_>>();
11981
11982 let creases = ranges
11983 .into_iter()
11984 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11985 .collect();
11986
11987 self.fold_creases(creases, true, window, cx);
11988 }
11989
11990 pub fn fold_recursive(
11991 &mut self,
11992 _: &actions::FoldRecursive,
11993 window: &mut Window,
11994 cx: &mut Context<Self>,
11995 ) {
11996 let mut to_fold = Vec::new();
11997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11998 let selections = self.selections.all_adjusted(cx);
11999
12000 for selection in selections {
12001 let range = selection.range().sorted();
12002 let buffer_start_row = range.start.row;
12003
12004 if range.start.row != range.end.row {
12005 let mut found = false;
12006 for row in range.start.row..=range.end.row {
12007 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12008 found = true;
12009 to_fold.push(crease);
12010 }
12011 }
12012 if found {
12013 continue;
12014 }
12015 }
12016
12017 for row in (0..=range.start.row).rev() {
12018 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12019 if crease.range().end.row >= buffer_start_row {
12020 to_fold.push(crease);
12021 } else {
12022 break;
12023 }
12024 }
12025 }
12026 }
12027
12028 self.fold_creases(to_fold, true, window, cx);
12029 }
12030
12031 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12032 let buffer_row = fold_at.buffer_row;
12033 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12034
12035 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12036 let autoscroll = self
12037 .selections
12038 .all::<Point>(cx)
12039 .iter()
12040 .any(|selection| crease.range().overlaps(&selection.range()));
12041
12042 self.fold_creases(vec![crease], autoscroll, window, cx);
12043 }
12044 }
12045
12046 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12047 if self.is_singleton(cx) {
12048 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12049 let buffer = &display_map.buffer_snapshot;
12050 let selections = self.selections.all::<Point>(cx);
12051 let ranges = selections
12052 .iter()
12053 .map(|s| {
12054 let range = s.display_range(&display_map).sorted();
12055 let mut start = range.start.to_point(&display_map);
12056 let mut end = range.end.to_point(&display_map);
12057 start.column = 0;
12058 end.column = buffer.line_len(MultiBufferRow(end.row));
12059 start..end
12060 })
12061 .collect::<Vec<_>>();
12062
12063 self.unfold_ranges(&ranges, true, true, cx);
12064 } else {
12065 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12066 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12067 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12068 .map(|(snapshot, _, _)| snapshot.remote_id())
12069 .collect();
12070 for buffer_id in buffer_ids {
12071 self.unfold_buffer(buffer_id, cx);
12072 }
12073 }
12074 }
12075
12076 pub fn unfold_recursive(
12077 &mut self,
12078 _: &UnfoldRecursive,
12079 _window: &mut Window,
12080 cx: &mut Context<Self>,
12081 ) {
12082 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12083 let selections = self.selections.all::<Point>(cx);
12084 let ranges = selections
12085 .iter()
12086 .map(|s| {
12087 let mut range = s.display_range(&display_map).sorted();
12088 *range.start.column_mut() = 0;
12089 *range.end.column_mut() = display_map.line_len(range.end.row());
12090 let start = range.start.to_point(&display_map);
12091 let end = range.end.to_point(&display_map);
12092 start..end
12093 })
12094 .collect::<Vec<_>>();
12095
12096 self.unfold_ranges(&ranges, true, true, cx);
12097 }
12098
12099 pub fn unfold_at(
12100 &mut self,
12101 unfold_at: &UnfoldAt,
12102 _window: &mut Window,
12103 cx: &mut Context<Self>,
12104 ) {
12105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12106
12107 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12108 ..Point::new(
12109 unfold_at.buffer_row.0,
12110 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12111 );
12112
12113 let autoscroll = self
12114 .selections
12115 .all::<Point>(cx)
12116 .iter()
12117 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12118
12119 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12120 }
12121
12122 pub fn unfold_all(
12123 &mut self,
12124 _: &actions::UnfoldAll,
12125 _window: &mut Window,
12126 cx: &mut Context<Self>,
12127 ) {
12128 if self.buffer.read(cx).is_singleton() {
12129 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12130 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12131 } else {
12132 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12133 editor
12134 .update(&mut cx, |editor, cx| {
12135 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12136 editor.unfold_buffer(buffer_id, cx);
12137 }
12138 })
12139 .ok();
12140 });
12141 }
12142 }
12143
12144 pub fn fold_selected_ranges(
12145 &mut self,
12146 _: &FoldSelectedRanges,
12147 window: &mut Window,
12148 cx: &mut Context<Self>,
12149 ) {
12150 let selections = self.selections.all::<Point>(cx);
12151 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12152 let line_mode = self.selections.line_mode;
12153 let ranges = selections
12154 .into_iter()
12155 .map(|s| {
12156 if line_mode {
12157 let start = Point::new(s.start.row, 0);
12158 let end = Point::new(
12159 s.end.row,
12160 display_map
12161 .buffer_snapshot
12162 .line_len(MultiBufferRow(s.end.row)),
12163 );
12164 Crease::simple(start..end, display_map.fold_placeholder.clone())
12165 } else {
12166 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12167 }
12168 })
12169 .collect::<Vec<_>>();
12170 self.fold_creases(ranges, true, window, cx);
12171 }
12172
12173 pub fn fold_ranges<T: ToOffset + Clone>(
12174 &mut self,
12175 ranges: Vec<Range<T>>,
12176 auto_scroll: bool,
12177 window: &mut Window,
12178 cx: &mut Context<Self>,
12179 ) {
12180 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12181 let ranges = ranges
12182 .into_iter()
12183 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12184 .collect::<Vec<_>>();
12185 self.fold_creases(ranges, auto_scroll, window, cx);
12186 }
12187
12188 pub fn fold_creases<T: ToOffset + Clone>(
12189 &mut self,
12190 creases: Vec<Crease<T>>,
12191 auto_scroll: bool,
12192 window: &mut Window,
12193 cx: &mut Context<Self>,
12194 ) {
12195 if creases.is_empty() {
12196 return;
12197 }
12198
12199 let mut buffers_affected = HashSet::default();
12200 let multi_buffer = self.buffer().read(cx);
12201 for crease in &creases {
12202 if let Some((_, buffer, _)) =
12203 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12204 {
12205 buffers_affected.insert(buffer.read(cx).remote_id());
12206 };
12207 }
12208
12209 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12210
12211 if auto_scroll {
12212 self.request_autoscroll(Autoscroll::fit(), cx);
12213 }
12214
12215 cx.notify();
12216
12217 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12218 // Clear diagnostics block when folding a range that contains it.
12219 let snapshot = self.snapshot(window, cx);
12220 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12221 drop(snapshot);
12222 self.active_diagnostics = Some(active_diagnostics);
12223 self.dismiss_diagnostics(cx);
12224 } else {
12225 self.active_diagnostics = Some(active_diagnostics);
12226 }
12227 }
12228
12229 self.scrollbar_marker_state.dirty = true;
12230 }
12231
12232 /// Removes any folds whose ranges intersect any of the given ranges.
12233 pub fn unfold_ranges<T: ToOffset + Clone>(
12234 &mut self,
12235 ranges: &[Range<T>],
12236 inclusive: bool,
12237 auto_scroll: bool,
12238 cx: &mut Context<Self>,
12239 ) {
12240 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12241 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12242 });
12243 }
12244
12245 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12246 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12247 return;
12248 }
12249 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12250 self.display_map
12251 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12252 cx.emit(EditorEvent::BufferFoldToggled {
12253 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12254 folded: true,
12255 });
12256 cx.notify();
12257 }
12258
12259 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12260 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12261 return;
12262 }
12263 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12264 self.display_map.update(cx, |display_map, cx| {
12265 display_map.unfold_buffer(buffer_id, cx);
12266 });
12267 cx.emit(EditorEvent::BufferFoldToggled {
12268 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12269 folded: false,
12270 });
12271 cx.notify();
12272 }
12273
12274 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12275 self.display_map.read(cx).is_buffer_folded(buffer)
12276 }
12277
12278 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12279 self.display_map.read(cx).folded_buffers()
12280 }
12281
12282 /// Removes any folds with the given ranges.
12283 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12284 &mut self,
12285 ranges: &[Range<T>],
12286 type_id: TypeId,
12287 auto_scroll: bool,
12288 cx: &mut Context<Self>,
12289 ) {
12290 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12291 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12292 });
12293 }
12294
12295 fn remove_folds_with<T: ToOffset + Clone>(
12296 &mut self,
12297 ranges: &[Range<T>],
12298 auto_scroll: bool,
12299 cx: &mut Context<Self>,
12300 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12301 ) {
12302 if ranges.is_empty() {
12303 return;
12304 }
12305
12306 let mut buffers_affected = HashSet::default();
12307 let multi_buffer = self.buffer().read(cx);
12308 for range in ranges {
12309 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12310 buffers_affected.insert(buffer.read(cx).remote_id());
12311 };
12312 }
12313
12314 self.display_map.update(cx, update);
12315
12316 if auto_scroll {
12317 self.request_autoscroll(Autoscroll::fit(), cx);
12318 }
12319
12320 cx.notify();
12321 self.scrollbar_marker_state.dirty = true;
12322 self.active_indent_guides_state.dirty = true;
12323 }
12324
12325 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12326 self.display_map.read(cx).fold_placeholder.clone()
12327 }
12328
12329 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12330 self.buffer.update(cx, |buffer, cx| {
12331 buffer.set_all_diff_hunks_expanded(cx);
12332 });
12333 }
12334
12335 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12336 self.distinguish_unstaged_diff_hunks = true;
12337 }
12338
12339 pub fn expand_all_diff_hunks(
12340 &mut self,
12341 _: &ExpandAllHunkDiffs,
12342 _window: &mut Window,
12343 cx: &mut Context<Self>,
12344 ) {
12345 self.buffer.update(cx, |buffer, cx| {
12346 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12347 });
12348 }
12349
12350 pub fn toggle_selected_diff_hunks(
12351 &mut self,
12352 _: &ToggleSelectedDiffHunks,
12353 _window: &mut Window,
12354 cx: &mut Context<Self>,
12355 ) {
12356 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12357 self.toggle_diff_hunks_in_ranges(ranges, cx);
12358 }
12359
12360 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12361 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12362 self.buffer
12363 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12364 }
12365
12366 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12367 self.buffer.update(cx, |buffer, cx| {
12368 let ranges = vec![Anchor::min()..Anchor::max()];
12369 if !buffer.all_diff_hunks_expanded()
12370 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12371 {
12372 buffer.collapse_diff_hunks(ranges, cx);
12373 true
12374 } else {
12375 false
12376 }
12377 })
12378 }
12379
12380 fn toggle_diff_hunks_in_ranges(
12381 &mut self,
12382 ranges: Vec<Range<Anchor>>,
12383 cx: &mut Context<'_, Editor>,
12384 ) {
12385 self.buffer.update(cx, |buffer, cx| {
12386 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12387 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12388 })
12389 }
12390
12391 fn toggle_diff_hunks_in_ranges_narrow(
12392 &mut self,
12393 ranges: Vec<Range<Anchor>>,
12394 cx: &mut Context<'_, Editor>,
12395 ) {
12396 self.buffer.update(cx, |buffer, cx| {
12397 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12398 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12399 })
12400 }
12401
12402 pub(crate) fn apply_all_diff_hunks(
12403 &mut self,
12404 _: &ApplyAllDiffHunks,
12405 window: &mut Window,
12406 cx: &mut Context<Self>,
12407 ) {
12408 let buffers = self.buffer.read(cx).all_buffers();
12409 for branch_buffer in buffers {
12410 branch_buffer.update(cx, |branch_buffer, cx| {
12411 branch_buffer.merge_into_base(Vec::new(), cx);
12412 });
12413 }
12414
12415 if let Some(project) = self.project.clone() {
12416 self.save(true, project, window, cx).detach_and_log_err(cx);
12417 }
12418 }
12419
12420 pub(crate) fn apply_selected_diff_hunks(
12421 &mut self,
12422 _: &ApplyDiffHunk,
12423 window: &mut Window,
12424 cx: &mut Context<Self>,
12425 ) {
12426 let snapshot = self.snapshot(window, cx);
12427 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12428 let mut ranges_by_buffer = HashMap::default();
12429 self.transact(window, cx, |editor, _window, cx| {
12430 for hunk in hunks {
12431 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12432 ranges_by_buffer
12433 .entry(buffer.clone())
12434 .or_insert_with(Vec::new)
12435 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12436 }
12437 }
12438
12439 for (buffer, ranges) in ranges_by_buffer {
12440 buffer.update(cx, |buffer, cx| {
12441 buffer.merge_into_base(ranges, cx);
12442 });
12443 }
12444 });
12445
12446 if let Some(project) = self.project.clone() {
12447 self.save(true, project, window, cx).detach_and_log_err(cx);
12448 }
12449 }
12450
12451 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12452 if hovered != self.gutter_hovered {
12453 self.gutter_hovered = hovered;
12454 cx.notify();
12455 }
12456 }
12457
12458 pub fn insert_blocks(
12459 &mut self,
12460 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12461 autoscroll: Option<Autoscroll>,
12462 cx: &mut Context<Self>,
12463 ) -> Vec<CustomBlockId> {
12464 let blocks = self
12465 .display_map
12466 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12467 if let Some(autoscroll) = autoscroll {
12468 self.request_autoscroll(autoscroll, cx);
12469 }
12470 cx.notify();
12471 blocks
12472 }
12473
12474 pub fn resize_blocks(
12475 &mut self,
12476 heights: HashMap<CustomBlockId, u32>,
12477 autoscroll: Option<Autoscroll>,
12478 cx: &mut Context<Self>,
12479 ) {
12480 self.display_map
12481 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12482 if let Some(autoscroll) = autoscroll {
12483 self.request_autoscroll(autoscroll, cx);
12484 }
12485 cx.notify();
12486 }
12487
12488 pub fn replace_blocks(
12489 &mut self,
12490 renderers: HashMap<CustomBlockId, RenderBlock>,
12491 autoscroll: Option<Autoscroll>,
12492 cx: &mut Context<Self>,
12493 ) {
12494 self.display_map
12495 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12496 if let Some(autoscroll) = autoscroll {
12497 self.request_autoscroll(autoscroll, cx);
12498 }
12499 cx.notify();
12500 }
12501
12502 pub fn remove_blocks(
12503 &mut self,
12504 block_ids: HashSet<CustomBlockId>,
12505 autoscroll: Option<Autoscroll>,
12506 cx: &mut Context<Self>,
12507 ) {
12508 self.display_map.update(cx, |display_map, cx| {
12509 display_map.remove_blocks(block_ids, cx)
12510 });
12511 if let Some(autoscroll) = autoscroll {
12512 self.request_autoscroll(autoscroll, cx);
12513 }
12514 cx.notify();
12515 }
12516
12517 pub fn row_for_block(
12518 &self,
12519 block_id: CustomBlockId,
12520 cx: &mut Context<Self>,
12521 ) -> Option<DisplayRow> {
12522 self.display_map
12523 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12524 }
12525
12526 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12527 self.focused_block = Some(focused_block);
12528 }
12529
12530 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12531 self.focused_block.take()
12532 }
12533
12534 pub fn insert_creases(
12535 &mut self,
12536 creases: impl IntoIterator<Item = Crease<Anchor>>,
12537 cx: &mut Context<Self>,
12538 ) -> Vec<CreaseId> {
12539 self.display_map
12540 .update(cx, |map, cx| map.insert_creases(creases, cx))
12541 }
12542
12543 pub fn remove_creases(
12544 &mut self,
12545 ids: impl IntoIterator<Item = CreaseId>,
12546 cx: &mut Context<Self>,
12547 ) {
12548 self.display_map
12549 .update(cx, |map, cx| map.remove_creases(ids, cx));
12550 }
12551
12552 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12553 self.display_map
12554 .update(cx, |map, cx| map.snapshot(cx))
12555 .longest_row()
12556 }
12557
12558 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12559 self.display_map
12560 .update(cx, |map, cx| map.snapshot(cx))
12561 .max_point()
12562 }
12563
12564 pub fn text(&self, cx: &App) -> String {
12565 self.buffer.read(cx).read(cx).text()
12566 }
12567
12568 pub fn is_empty(&self, cx: &App) -> bool {
12569 self.buffer.read(cx).read(cx).is_empty()
12570 }
12571
12572 pub fn text_option(&self, cx: &App) -> Option<String> {
12573 let text = self.text(cx);
12574 let text = text.trim();
12575
12576 if text.is_empty() {
12577 return None;
12578 }
12579
12580 Some(text.to_string())
12581 }
12582
12583 pub fn set_text(
12584 &mut self,
12585 text: impl Into<Arc<str>>,
12586 window: &mut Window,
12587 cx: &mut Context<Self>,
12588 ) {
12589 self.transact(window, cx, |this, _, cx| {
12590 this.buffer
12591 .read(cx)
12592 .as_singleton()
12593 .expect("you can only call set_text on editors for singleton buffers")
12594 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12595 });
12596 }
12597
12598 pub fn display_text(&self, cx: &mut App) -> String {
12599 self.display_map
12600 .update(cx, |map, cx| map.snapshot(cx))
12601 .text()
12602 }
12603
12604 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12605 let mut wrap_guides = smallvec::smallvec![];
12606
12607 if self.show_wrap_guides == Some(false) {
12608 return wrap_guides;
12609 }
12610
12611 let settings = self.buffer.read(cx).settings_at(0, cx);
12612 if settings.show_wrap_guides {
12613 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12614 wrap_guides.push((soft_wrap as usize, true));
12615 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12616 wrap_guides.push((soft_wrap as usize, true));
12617 }
12618 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12619 }
12620
12621 wrap_guides
12622 }
12623
12624 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12625 let settings = self.buffer.read(cx).settings_at(0, cx);
12626 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12627 match mode {
12628 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12629 SoftWrap::None
12630 }
12631 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12632 language_settings::SoftWrap::PreferredLineLength => {
12633 SoftWrap::Column(settings.preferred_line_length)
12634 }
12635 language_settings::SoftWrap::Bounded => {
12636 SoftWrap::Bounded(settings.preferred_line_length)
12637 }
12638 }
12639 }
12640
12641 pub fn set_soft_wrap_mode(
12642 &mut self,
12643 mode: language_settings::SoftWrap,
12644
12645 cx: &mut Context<Self>,
12646 ) {
12647 self.soft_wrap_mode_override = Some(mode);
12648 cx.notify();
12649 }
12650
12651 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12652 self.text_style_refinement = Some(style);
12653 }
12654
12655 /// called by the Element so we know what style we were most recently rendered with.
12656 pub(crate) fn set_style(
12657 &mut self,
12658 style: EditorStyle,
12659 window: &mut Window,
12660 cx: &mut Context<Self>,
12661 ) {
12662 let rem_size = window.rem_size();
12663 self.display_map.update(cx, |map, cx| {
12664 map.set_font(
12665 style.text.font(),
12666 style.text.font_size.to_pixels(rem_size),
12667 cx,
12668 )
12669 });
12670 self.style = Some(style);
12671 }
12672
12673 pub fn style(&self) -> Option<&EditorStyle> {
12674 self.style.as_ref()
12675 }
12676
12677 // Called by the element. This method is not designed to be called outside of the editor
12678 // element's layout code because it does not notify when rewrapping is computed synchronously.
12679 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12680 self.display_map
12681 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12682 }
12683
12684 pub fn set_soft_wrap(&mut self) {
12685 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12686 }
12687
12688 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12689 if self.soft_wrap_mode_override.is_some() {
12690 self.soft_wrap_mode_override.take();
12691 } else {
12692 let soft_wrap = match self.soft_wrap_mode(cx) {
12693 SoftWrap::GitDiff => return,
12694 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12695 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12696 language_settings::SoftWrap::None
12697 }
12698 };
12699 self.soft_wrap_mode_override = Some(soft_wrap);
12700 }
12701 cx.notify();
12702 }
12703
12704 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12705 let Some(workspace) = self.workspace() else {
12706 return;
12707 };
12708 let fs = workspace.read(cx).app_state().fs.clone();
12709 let current_show = TabBarSettings::get_global(cx).show;
12710 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12711 setting.show = Some(!current_show);
12712 });
12713 }
12714
12715 pub fn toggle_indent_guides(
12716 &mut self,
12717 _: &ToggleIndentGuides,
12718 _: &mut Window,
12719 cx: &mut Context<Self>,
12720 ) {
12721 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12722 self.buffer
12723 .read(cx)
12724 .settings_at(0, cx)
12725 .indent_guides
12726 .enabled
12727 });
12728 self.show_indent_guides = Some(!currently_enabled);
12729 cx.notify();
12730 }
12731
12732 fn should_show_indent_guides(&self) -> Option<bool> {
12733 self.show_indent_guides
12734 }
12735
12736 pub fn toggle_line_numbers(
12737 &mut self,
12738 _: &ToggleLineNumbers,
12739 _: &mut Window,
12740 cx: &mut Context<Self>,
12741 ) {
12742 let mut editor_settings = EditorSettings::get_global(cx).clone();
12743 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12744 EditorSettings::override_global(editor_settings, cx);
12745 }
12746
12747 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12748 self.use_relative_line_numbers
12749 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12750 }
12751
12752 pub fn toggle_relative_line_numbers(
12753 &mut self,
12754 _: &ToggleRelativeLineNumbers,
12755 _: &mut Window,
12756 cx: &mut Context<Self>,
12757 ) {
12758 let is_relative = self.should_use_relative_line_numbers(cx);
12759 self.set_relative_line_number(Some(!is_relative), cx)
12760 }
12761
12762 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12763 self.use_relative_line_numbers = is_relative;
12764 cx.notify();
12765 }
12766
12767 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12768 self.show_gutter = show_gutter;
12769 cx.notify();
12770 }
12771
12772 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12773 self.show_scrollbars = show_scrollbars;
12774 cx.notify();
12775 }
12776
12777 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12778 self.show_line_numbers = Some(show_line_numbers);
12779 cx.notify();
12780 }
12781
12782 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12783 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12784 cx.notify();
12785 }
12786
12787 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12788 self.show_code_actions = Some(show_code_actions);
12789 cx.notify();
12790 }
12791
12792 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12793 self.show_runnables = Some(show_runnables);
12794 cx.notify();
12795 }
12796
12797 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12798 if self.display_map.read(cx).masked != masked {
12799 self.display_map.update(cx, |map, _| map.masked = masked);
12800 }
12801 cx.notify()
12802 }
12803
12804 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12805 self.show_wrap_guides = Some(show_wrap_guides);
12806 cx.notify();
12807 }
12808
12809 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12810 self.show_indent_guides = Some(show_indent_guides);
12811 cx.notify();
12812 }
12813
12814 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12815 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12816 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12817 if let Some(dir) = file.abs_path(cx).parent() {
12818 return Some(dir.to_owned());
12819 }
12820 }
12821
12822 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12823 return Some(project_path.path.to_path_buf());
12824 }
12825 }
12826
12827 None
12828 }
12829
12830 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12831 self.active_excerpt(cx)?
12832 .1
12833 .read(cx)
12834 .file()
12835 .and_then(|f| f.as_local())
12836 }
12837
12838 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12839 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12840 let project_path = buffer.read(cx).project_path(cx)?;
12841 let project = self.project.as_ref()?.read(cx);
12842 project.absolute_path(&project_path, cx)
12843 })
12844 }
12845
12846 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12847 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12848 let project_path = buffer.read(cx).project_path(cx)?;
12849 let project = self.project.as_ref()?.read(cx);
12850 let entry = project.entry_for_path(&project_path, cx)?;
12851 let path = entry.path.to_path_buf();
12852 Some(path)
12853 })
12854 }
12855
12856 pub fn reveal_in_finder(
12857 &mut self,
12858 _: &RevealInFileManager,
12859 _window: &mut Window,
12860 cx: &mut Context<Self>,
12861 ) {
12862 if let Some(target) = self.target_file(cx) {
12863 cx.reveal_path(&target.abs_path(cx));
12864 }
12865 }
12866
12867 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12868 if let Some(path) = self.target_file_abs_path(cx) {
12869 if let Some(path) = path.to_str() {
12870 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12871 }
12872 }
12873 }
12874
12875 pub fn copy_relative_path(
12876 &mut self,
12877 _: &CopyRelativePath,
12878 _window: &mut Window,
12879 cx: &mut Context<Self>,
12880 ) {
12881 if let Some(path) = self.target_file_path(cx) {
12882 if let Some(path) = path.to_str() {
12883 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12884 }
12885 }
12886 }
12887
12888 pub fn copy_file_name_without_extension(
12889 &mut self,
12890 _: &CopyFileNameWithoutExtension,
12891 _: &mut Window,
12892 cx: &mut Context<Self>,
12893 ) {
12894 if let Some(file) = self.target_file(cx) {
12895 if let Some(file_stem) = file.path().file_stem() {
12896 if let Some(name) = file_stem.to_str() {
12897 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12898 }
12899 }
12900 }
12901 }
12902
12903 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
12904 if let Some(file) = self.target_file(cx) {
12905 if let Some(file_name) = file.path().file_name() {
12906 if let Some(name) = file_name.to_str() {
12907 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
12908 }
12909 }
12910 }
12911 }
12912
12913 pub fn toggle_git_blame(
12914 &mut self,
12915 _: &ToggleGitBlame,
12916 window: &mut Window,
12917 cx: &mut Context<Self>,
12918 ) {
12919 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12920
12921 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12922 self.start_git_blame(true, window, cx);
12923 }
12924
12925 cx.notify();
12926 }
12927
12928 pub fn toggle_git_blame_inline(
12929 &mut self,
12930 _: &ToggleGitBlameInline,
12931 window: &mut Window,
12932 cx: &mut Context<Self>,
12933 ) {
12934 self.toggle_git_blame_inline_internal(true, window, cx);
12935 cx.notify();
12936 }
12937
12938 pub fn git_blame_inline_enabled(&self) -> bool {
12939 self.git_blame_inline_enabled
12940 }
12941
12942 pub fn toggle_selection_menu(
12943 &mut self,
12944 _: &ToggleSelectionMenu,
12945 _: &mut Window,
12946 cx: &mut Context<Self>,
12947 ) {
12948 self.show_selection_menu = self
12949 .show_selection_menu
12950 .map(|show_selections_menu| !show_selections_menu)
12951 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12952
12953 cx.notify();
12954 }
12955
12956 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12957 self.show_selection_menu
12958 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12959 }
12960
12961 fn start_git_blame(
12962 &mut self,
12963 user_triggered: bool,
12964 window: &mut Window,
12965 cx: &mut Context<Self>,
12966 ) {
12967 if let Some(project) = self.project.as_ref() {
12968 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12969 return;
12970 };
12971
12972 if buffer.read(cx).file().is_none() {
12973 return;
12974 }
12975
12976 let focused = self.focus_handle(cx).contains_focused(window, cx);
12977
12978 let project = project.clone();
12979 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12980 self.blame_subscription =
12981 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12982 self.blame = Some(blame);
12983 }
12984 }
12985
12986 fn toggle_git_blame_inline_internal(
12987 &mut self,
12988 user_triggered: bool,
12989 window: &mut Window,
12990 cx: &mut Context<Self>,
12991 ) {
12992 if self.git_blame_inline_enabled {
12993 self.git_blame_inline_enabled = false;
12994 self.show_git_blame_inline = false;
12995 self.show_git_blame_inline_delay_task.take();
12996 } else {
12997 self.git_blame_inline_enabled = true;
12998 self.start_git_blame_inline(user_triggered, window, cx);
12999 }
13000
13001 cx.notify();
13002 }
13003
13004 fn start_git_blame_inline(
13005 &mut self,
13006 user_triggered: bool,
13007 window: &mut Window,
13008 cx: &mut Context<Self>,
13009 ) {
13010 self.start_git_blame(user_triggered, window, cx);
13011
13012 if ProjectSettings::get_global(cx)
13013 .git
13014 .inline_blame_delay()
13015 .is_some()
13016 {
13017 self.start_inline_blame_timer(window, cx);
13018 } else {
13019 self.show_git_blame_inline = true
13020 }
13021 }
13022
13023 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13024 self.blame.as_ref()
13025 }
13026
13027 pub fn show_git_blame_gutter(&self) -> bool {
13028 self.show_git_blame_gutter
13029 }
13030
13031 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13032 self.show_git_blame_gutter && self.has_blame_entries(cx)
13033 }
13034
13035 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13036 self.show_git_blame_inline
13037 && self.focus_handle.is_focused(window)
13038 && !self.newest_selection_head_on_empty_line(cx)
13039 && self.has_blame_entries(cx)
13040 }
13041
13042 fn has_blame_entries(&self, cx: &App) -> bool {
13043 self.blame()
13044 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13045 }
13046
13047 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13048 let cursor_anchor = self.selections.newest_anchor().head();
13049
13050 let snapshot = self.buffer.read(cx).snapshot(cx);
13051 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13052
13053 snapshot.line_len(buffer_row) == 0
13054 }
13055
13056 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13057 let buffer_and_selection = maybe!({
13058 let selection = self.selections.newest::<Point>(cx);
13059 let selection_range = selection.range();
13060
13061 let multi_buffer = self.buffer().read(cx);
13062 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13063 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13064
13065 let (buffer, range, _) = if selection.reversed {
13066 buffer_ranges.first()
13067 } else {
13068 buffer_ranges.last()
13069 }?;
13070
13071 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13072 ..text::ToPoint::to_point(&range.end, &buffer).row;
13073 Some((
13074 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13075 selection,
13076 ))
13077 });
13078
13079 let Some((buffer, selection)) = buffer_and_selection else {
13080 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13081 };
13082
13083 let Some(project) = self.project.as_ref() else {
13084 return Task::ready(Err(anyhow!("editor does not have project")));
13085 };
13086
13087 project.update(cx, |project, cx| {
13088 project.get_permalink_to_line(&buffer, selection, cx)
13089 })
13090 }
13091
13092 pub fn copy_permalink_to_line(
13093 &mut self,
13094 _: &CopyPermalinkToLine,
13095 window: &mut Window,
13096 cx: &mut Context<Self>,
13097 ) {
13098 let permalink_task = self.get_permalink_to_line(cx);
13099 let workspace = self.workspace();
13100
13101 cx.spawn_in(window, |_, mut cx| async move {
13102 match permalink_task.await {
13103 Ok(permalink) => {
13104 cx.update(|_, cx| {
13105 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13106 })
13107 .ok();
13108 }
13109 Err(err) => {
13110 let message = format!("Failed to copy permalink: {err}");
13111
13112 Err::<(), anyhow::Error>(err).log_err();
13113
13114 if let Some(workspace) = workspace {
13115 workspace
13116 .update_in(&mut cx, |workspace, _, cx| {
13117 struct CopyPermalinkToLine;
13118
13119 workspace.show_toast(
13120 Toast::new(
13121 NotificationId::unique::<CopyPermalinkToLine>(),
13122 message,
13123 ),
13124 cx,
13125 )
13126 })
13127 .ok();
13128 }
13129 }
13130 }
13131 })
13132 .detach();
13133 }
13134
13135 pub fn copy_file_location(
13136 &mut self,
13137 _: &CopyFileLocation,
13138 _: &mut Window,
13139 cx: &mut Context<Self>,
13140 ) {
13141 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13142 if let Some(file) = self.target_file(cx) {
13143 if let Some(path) = file.path().to_str() {
13144 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13145 }
13146 }
13147 }
13148
13149 pub fn open_permalink_to_line(
13150 &mut self,
13151 _: &OpenPermalinkToLine,
13152 window: &mut Window,
13153 cx: &mut Context<Self>,
13154 ) {
13155 let permalink_task = self.get_permalink_to_line(cx);
13156 let workspace = self.workspace();
13157
13158 cx.spawn_in(window, |_, mut cx| async move {
13159 match permalink_task.await {
13160 Ok(permalink) => {
13161 cx.update(|_, cx| {
13162 cx.open_url(permalink.as_ref());
13163 })
13164 .ok();
13165 }
13166 Err(err) => {
13167 let message = format!("Failed to open permalink: {err}");
13168
13169 Err::<(), anyhow::Error>(err).log_err();
13170
13171 if let Some(workspace) = workspace {
13172 workspace
13173 .update(&mut cx, |workspace, cx| {
13174 struct OpenPermalinkToLine;
13175
13176 workspace.show_toast(
13177 Toast::new(
13178 NotificationId::unique::<OpenPermalinkToLine>(),
13179 message,
13180 ),
13181 cx,
13182 )
13183 })
13184 .ok();
13185 }
13186 }
13187 }
13188 })
13189 .detach();
13190 }
13191
13192 pub fn insert_uuid_v4(
13193 &mut self,
13194 _: &InsertUuidV4,
13195 window: &mut Window,
13196 cx: &mut Context<Self>,
13197 ) {
13198 self.insert_uuid(UuidVersion::V4, window, cx);
13199 }
13200
13201 pub fn insert_uuid_v7(
13202 &mut self,
13203 _: &InsertUuidV7,
13204 window: &mut Window,
13205 cx: &mut Context<Self>,
13206 ) {
13207 self.insert_uuid(UuidVersion::V7, window, cx);
13208 }
13209
13210 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13211 self.transact(window, cx, |this, window, cx| {
13212 let edits = this
13213 .selections
13214 .all::<Point>(cx)
13215 .into_iter()
13216 .map(|selection| {
13217 let uuid = match version {
13218 UuidVersion::V4 => uuid::Uuid::new_v4(),
13219 UuidVersion::V7 => uuid::Uuid::now_v7(),
13220 };
13221
13222 (selection.range(), uuid.to_string())
13223 });
13224 this.edit(edits, cx);
13225 this.refresh_inline_completion(true, false, window, cx);
13226 });
13227 }
13228
13229 pub fn open_selections_in_multibuffer(
13230 &mut self,
13231 _: &OpenSelectionsInMultibuffer,
13232 window: &mut Window,
13233 cx: &mut Context<Self>,
13234 ) {
13235 let multibuffer = self.buffer.read(cx);
13236
13237 let Some(buffer) = multibuffer.as_singleton() else {
13238 return;
13239 };
13240
13241 let Some(workspace) = self.workspace() else {
13242 return;
13243 };
13244
13245 let locations = self
13246 .selections
13247 .disjoint_anchors()
13248 .iter()
13249 .map(|range| Location {
13250 buffer: buffer.clone(),
13251 range: range.start.text_anchor..range.end.text_anchor,
13252 })
13253 .collect::<Vec<_>>();
13254
13255 let title = multibuffer.title(cx).to_string();
13256
13257 cx.spawn_in(window, |_, mut cx| async move {
13258 workspace.update_in(&mut cx, |workspace, window, cx| {
13259 Self::open_locations_in_multibuffer(
13260 workspace,
13261 locations,
13262 format!("Selections for '{title}'"),
13263 false,
13264 MultibufferSelectionMode::All,
13265 window,
13266 cx,
13267 );
13268 })
13269 })
13270 .detach();
13271 }
13272
13273 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13274 /// last highlight added will be used.
13275 ///
13276 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13277 pub fn highlight_rows<T: 'static>(
13278 &mut self,
13279 range: Range<Anchor>,
13280 color: Hsla,
13281 should_autoscroll: bool,
13282 cx: &mut Context<Self>,
13283 ) {
13284 let snapshot = self.buffer().read(cx).snapshot(cx);
13285 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13286 let ix = row_highlights.binary_search_by(|highlight| {
13287 Ordering::Equal
13288 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13289 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13290 });
13291
13292 if let Err(mut ix) = ix {
13293 let index = post_inc(&mut self.highlight_order);
13294
13295 // If this range intersects with the preceding highlight, then merge it with
13296 // the preceding highlight. Otherwise insert a new highlight.
13297 let mut merged = false;
13298 if ix > 0 {
13299 let prev_highlight = &mut row_highlights[ix - 1];
13300 if prev_highlight
13301 .range
13302 .end
13303 .cmp(&range.start, &snapshot)
13304 .is_ge()
13305 {
13306 ix -= 1;
13307 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13308 prev_highlight.range.end = range.end;
13309 }
13310 merged = true;
13311 prev_highlight.index = index;
13312 prev_highlight.color = color;
13313 prev_highlight.should_autoscroll = should_autoscroll;
13314 }
13315 }
13316
13317 if !merged {
13318 row_highlights.insert(
13319 ix,
13320 RowHighlight {
13321 range: range.clone(),
13322 index,
13323 color,
13324 should_autoscroll,
13325 },
13326 );
13327 }
13328
13329 // If any of the following highlights intersect with this one, merge them.
13330 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13331 let highlight = &row_highlights[ix];
13332 if next_highlight
13333 .range
13334 .start
13335 .cmp(&highlight.range.end, &snapshot)
13336 .is_le()
13337 {
13338 if next_highlight
13339 .range
13340 .end
13341 .cmp(&highlight.range.end, &snapshot)
13342 .is_gt()
13343 {
13344 row_highlights[ix].range.end = next_highlight.range.end;
13345 }
13346 row_highlights.remove(ix + 1);
13347 } else {
13348 break;
13349 }
13350 }
13351 }
13352 }
13353
13354 /// Remove any highlighted row ranges of the given type that intersect the
13355 /// given ranges.
13356 pub fn remove_highlighted_rows<T: 'static>(
13357 &mut self,
13358 ranges_to_remove: Vec<Range<Anchor>>,
13359 cx: &mut Context<Self>,
13360 ) {
13361 let snapshot = self.buffer().read(cx).snapshot(cx);
13362 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13363 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13364 row_highlights.retain(|highlight| {
13365 while let Some(range_to_remove) = ranges_to_remove.peek() {
13366 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13367 Ordering::Less | Ordering::Equal => {
13368 ranges_to_remove.next();
13369 }
13370 Ordering::Greater => {
13371 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13372 Ordering::Less | Ordering::Equal => {
13373 return false;
13374 }
13375 Ordering::Greater => break,
13376 }
13377 }
13378 }
13379 }
13380
13381 true
13382 })
13383 }
13384
13385 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13386 pub fn clear_row_highlights<T: 'static>(&mut self) {
13387 self.highlighted_rows.remove(&TypeId::of::<T>());
13388 }
13389
13390 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13391 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13392 self.highlighted_rows
13393 .get(&TypeId::of::<T>())
13394 .map_or(&[] as &[_], |vec| vec.as_slice())
13395 .iter()
13396 .map(|highlight| (highlight.range.clone(), highlight.color))
13397 }
13398
13399 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13400 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13401 /// Allows to ignore certain kinds of highlights.
13402 pub fn highlighted_display_rows(
13403 &self,
13404 window: &mut Window,
13405 cx: &mut App,
13406 ) -> BTreeMap<DisplayRow, Background> {
13407 let snapshot = self.snapshot(window, cx);
13408 let mut used_highlight_orders = HashMap::default();
13409 self.highlighted_rows
13410 .iter()
13411 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13412 .fold(
13413 BTreeMap::<DisplayRow, Background>::new(),
13414 |mut unique_rows, highlight| {
13415 let start = highlight.range.start.to_display_point(&snapshot);
13416 let end = highlight.range.end.to_display_point(&snapshot);
13417 let start_row = start.row().0;
13418 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13419 && end.column() == 0
13420 {
13421 end.row().0.saturating_sub(1)
13422 } else {
13423 end.row().0
13424 };
13425 for row in start_row..=end_row {
13426 let used_index =
13427 used_highlight_orders.entry(row).or_insert(highlight.index);
13428 if highlight.index >= *used_index {
13429 *used_index = highlight.index;
13430 unique_rows.insert(DisplayRow(row), highlight.color.into());
13431 }
13432 }
13433 unique_rows
13434 },
13435 )
13436 }
13437
13438 pub fn highlighted_display_row_for_autoscroll(
13439 &self,
13440 snapshot: &DisplaySnapshot,
13441 ) -> Option<DisplayRow> {
13442 self.highlighted_rows
13443 .values()
13444 .flat_map(|highlighted_rows| highlighted_rows.iter())
13445 .filter_map(|highlight| {
13446 if highlight.should_autoscroll {
13447 Some(highlight.range.start.to_display_point(snapshot).row())
13448 } else {
13449 None
13450 }
13451 })
13452 .min()
13453 }
13454
13455 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13456 self.highlight_background::<SearchWithinRange>(
13457 ranges,
13458 |colors| colors.editor_document_highlight_read_background,
13459 cx,
13460 )
13461 }
13462
13463 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13464 self.breadcrumb_header = Some(new_header);
13465 }
13466
13467 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13468 self.clear_background_highlights::<SearchWithinRange>(cx);
13469 }
13470
13471 pub fn highlight_background<T: 'static>(
13472 &mut self,
13473 ranges: &[Range<Anchor>],
13474 color_fetcher: fn(&ThemeColors) -> Hsla,
13475 cx: &mut Context<Self>,
13476 ) {
13477 self.background_highlights
13478 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13479 self.scrollbar_marker_state.dirty = true;
13480 cx.notify();
13481 }
13482
13483 pub fn clear_background_highlights<T: 'static>(
13484 &mut self,
13485 cx: &mut Context<Self>,
13486 ) -> Option<BackgroundHighlight> {
13487 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13488 if !text_highlights.1.is_empty() {
13489 self.scrollbar_marker_state.dirty = true;
13490 cx.notify();
13491 }
13492 Some(text_highlights)
13493 }
13494
13495 pub fn highlight_gutter<T: 'static>(
13496 &mut self,
13497 ranges: &[Range<Anchor>],
13498 color_fetcher: fn(&App) -> Hsla,
13499 cx: &mut Context<Self>,
13500 ) {
13501 self.gutter_highlights
13502 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13503 cx.notify();
13504 }
13505
13506 pub fn clear_gutter_highlights<T: 'static>(
13507 &mut self,
13508 cx: &mut Context<Self>,
13509 ) -> Option<GutterHighlight> {
13510 cx.notify();
13511 self.gutter_highlights.remove(&TypeId::of::<T>())
13512 }
13513
13514 #[cfg(feature = "test-support")]
13515 pub fn all_text_background_highlights(
13516 &self,
13517 window: &mut Window,
13518 cx: &mut Context<Self>,
13519 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13520 let snapshot = self.snapshot(window, cx);
13521 let buffer = &snapshot.buffer_snapshot;
13522 let start = buffer.anchor_before(0);
13523 let end = buffer.anchor_after(buffer.len());
13524 let theme = cx.theme().colors();
13525 self.background_highlights_in_range(start..end, &snapshot, theme)
13526 }
13527
13528 #[cfg(feature = "test-support")]
13529 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13530 let snapshot = self.buffer().read(cx).snapshot(cx);
13531
13532 let highlights = self
13533 .background_highlights
13534 .get(&TypeId::of::<items::BufferSearchHighlights>());
13535
13536 if let Some((_color, ranges)) = highlights {
13537 ranges
13538 .iter()
13539 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13540 .collect_vec()
13541 } else {
13542 vec![]
13543 }
13544 }
13545
13546 fn document_highlights_for_position<'a>(
13547 &'a self,
13548 position: Anchor,
13549 buffer: &'a MultiBufferSnapshot,
13550 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13551 let read_highlights = self
13552 .background_highlights
13553 .get(&TypeId::of::<DocumentHighlightRead>())
13554 .map(|h| &h.1);
13555 let write_highlights = self
13556 .background_highlights
13557 .get(&TypeId::of::<DocumentHighlightWrite>())
13558 .map(|h| &h.1);
13559 let left_position = position.bias_left(buffer);
13560 let right_position = position.bias_right(buffer);
13561 read_highlights
13562 .into_iter()
13563 .chain(write_highlights)
13564 .flat_map(move |ranges| {
13565 let start_ix = match ranges.binary_search_by(|probe| {
13566 let cmp = probe.end.cmp(&left_position, buffer);
13567 if cmp.is_ge() {
13568 Ordering::Greater
13569 } else {
13570 Ordering::Less
13571 }
13572 }) {
13573 Ok(i) | Err(i) => i,
13574 };
13575
13576 ranges[start_ix..]
13577 .iter()
13578 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13579 })
13580 }
13581
13582 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13583 self.background_highlights
13584 .get(&TypeId::of::<T>())
13585 .map_or(false, |(_, highlights)| !highlights.is_empty())
13586 }
13587
13588 pub fn background_highlights_in_range(
13589 &self,
13590 search_range: Range<Anchor>,
13591 display_snapshot: &DisplaySnapshot,
13592 theme: &ThemeColors,
13593 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13594 let mut results = Vec::new();
13595 for (color_fetcher, ranges) in self.background_highlights.values() {
13596 let color = color_fetcher(theme);
13597 let start_ix = match ranges.binary_search_by(|probe| {
13598 let cmp = probe
13599 .end
13600 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13601 if cmp.is_gt() {
13602 Ordering::Greater
13603 } else {
13604 Ordering::Less
13605 }
13606 }) {
13607 Ok(i) | Err(i) => i,
13608 };
13609 for range in &ranges[start_ix..] {
13610 if range
13611 .start
13612 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13613 .is_ge()
13614 {
13615 break;
13616 }
13617
13618 let start = range.start.to_display_point(display_snapshot);
13619 let end = range.end.to_display_point(display_snapshot);
13620 results.push((start..end, color))
13621 }
13622 }
13623 results
13624 }
13625
13626 pub fn background_highlight_row_ranges<T: 'static>(
13627 &self,
13628 search_range: Range<Anchor>,
13629 display_snapshot: &DisplaySnapshot,
13630 count: usize,
13631 ) -> Vec<RangeInclusive<DisplayPoint>> {
13632 let mut results = Vec::new();
13633 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13634 return vec![];
13635 };
13636
13637 let start_ix = match ranges.binary_search_by(|probe| {
13638 let cmp = probe
13639 .end
13640 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13641 if cmp.is_gt() {
13642 Ordering::Greater
13643 } else {
13644 Ordering::Less
13645 }
13646 }) {
13647 Ok(i) | Err(i) => i,
13648 };
13649 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13650 if let (Some(start_display), Some(end_display)) = (start, end) {
13651 results.push(
13652 start_display.to_display_point(display_snapshot)
13653 ..=end_display.to_display_point(display_snapshot),
13654 );
13655 }
13656 };
13657 let mut start_row: Option<Point> = None;
13658 let mut end_row: Option<Point> = None;
13659 if ranges.len() > count {
13660 return Vec::new();
13661 }
13662 for range in &ranges[start_ix..] {
13663 if range
13664 .start
13665 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13666 .is_ge()
13667 {
13668 break;
13669 }
13670 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13671 if let Some(current_row) = &end_row {
13672 if end.row == current_row.row {
13673 continue;
13674 }
13675 }
13676 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13677 if start_row.is_none() {
13678 assert_eq!(end_row, None);
13679 start_row = Some(start);
13680 end_row = Some(end);
13681 continue;
13682 }
13683 if let Some(current_end) = end_row.as_mut() {
13684 if start.row > current_end.row + 1 {
13685 push_region(start_row, end_row);
13686 start_row = Some(start);
13687 end_row = Some(end);
13688 } else {
13689 // Merge two hunks.
13690 *current_end = end;
13691 }
13692 } else {
13693 unreachable!();
13694 }
13695 }
13696 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13697 push_region(start_row, end_row);
13698 results
13699 }
13700
13701 pub fn gutter_highlights_in_range(
13702 &self,
13703 search_range: Range<Anchor>,
13704 display_snapshot: &DisplaySnapshot,
13705 cx: &App,
13706 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13707 let mut results = Vec::new();
13708 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13709 let color = color_fetcher(cx);
13710 let start_ix = match ranges.binary_search_by(|probe| {
13711 let cmp = probe
13712 .end
13713 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13714 if cmp.is_gt() {
13715 Ordering::Greater
13716 } else {
13717 Ordering::Less
13718 }
13719 }) {
13720 Ok(i) | Err(i) => i,
13721 };
13722 for range in &ranges[start_ix..] {
13723 if range
13724 .start
13725 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13726 .is_ge()
13727 {
13728 break;
13729 }
13730
13731 let start = range.start.to_display_point(display_snapshot);
13732 let end = range.end.to_display_point(display_snapshot);
13733 results.push((start..end, color))
13734 }
13735 }
13736 results
13737 }
13738
13739 /// Get the text ranges corresponding to the redaction query
13740 pub fn redacted_ranges(
13741 &self,
13742 search_range: Range<Anchor>,
13743 display_snapshot: &DisplaySnapshot,
13744 cx: &App,
13745 ) -> Vec<Range<DisplayPoint>> {
13746 display_snapshot
13747 .buffer_snapshot
13748 .redacted_ranges(search_range, |file| {
13749 if let Some(file) = file {
13750 file.is_private()
13751 && EditorSettings::get(
13752 Some(SettingsLocation {
13753 worktree_id: file.worktree_id(cx),
13754 path: file.path().as_ref(),
13755 }),
13756 cx,
13757 )
13758 .redact_private_values
13759 } else {
13760 false
13761 }
13762 })
13763 .map(|range| {
13764 range.start.to_display_point(display_snapshot)
13765 ..range.end.to_display_point(display_snapshot)
13766 })
13767 .collect()
13768 }
13769
13770 pub fn highlight_text<T: 'static>(
13771 &mut self,
13772 ranges: Vec<Range<Anchor>>,
13773 style: HighlightStyle,
13774 cx: &mut Context<Self>,
13775 ) {
13776 self.display_map.update(cx, |map, _| {
13777 map.highlight_text(TypeId::of::<T>(), ranges, style)
13778 });
13779 cx.notify();
13780 }
13781
13782 pub(crate) fn highlight_inlays<T: 'static>(
13783 &mut self,
13784 highlights: Vec<InlayHighlight>,
13785 style: HighlightStyle,
13786 cx: &mut Context<Self>,
13787 ) {
13788 self.display_map.update(cx, |map, _| {
13789 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13790 });
13791 cx.notify();
13792 }
13793
13794 pub fn text_highlights<'a, T: 'static>(
13795 &'a self,
13796 cx: &'a App,
13797 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13798 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13799 }
13800
13801 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13802 let cleared = self
13803 .display_map
13804 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13805 if cleared {
13806 cx.notify();
13807 }
13808 }
13809
13810 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13811 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13812 && self.focus_handle.is_focused(window)
13813 }
13814
13815 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13816 self.show_cursor_when_unfocused = is_enabled;
13817 cx.notify();
13818 }
13819
13820 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13821 self.project
13822 .as_ref()
13823 .map(|project| project.read(cx).lsp_store())
13824 }
13825
13826 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13827 cx.notify();
13828 }
13829
13830 fn on_buffer_event(
13831 &mut self,
13832 multibuffer: &Entity<MultiBuffer>,
13833 event: &multi_buffer::Event,
13834 window: &mut Window,
13835 cx: &mut Context<Self>,
13836 ) {
13837 match event {
13838 multi_buffer::Event::Edited {
13839 singleton_buffer_edited,
13840 edited_buffer: buffer_edited,
13841 } => {
13842 self.scrollbar_marker_state.dirty = true;
13843 self.active_indent_guides_state.dirty = true;
13844 self.refresh_active_diagnostics(cx);
13845 self.refresh_code_actions(window, cx);
13846 if self.has_active_inline_completion() {
13847 self.update_visible_inline_completion(window, cx);
13848 }
13849 if let Some(buffer) = buffer_edited {
13850 let buffer_id = buffer.read(cx).remote_id();
13851 if !self.registered_buffers.contains_key(&buffer_id) {
13852 if let Some(lsp_store) = self.lsp_store(cx) {
13853 lsp_store.update(cx, |lsp_store, cx| {
13854 self.registered_buffers.insert(
13855 buffer_id,
13856 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13857 );
13858 })
13859 }
13860 }
13861 }
13862 cx.emit(EditorEvent::BufferEdited);
13863 cx.emit(SearchEvent::MatchesInvalidated);
13864 if *singleton_buffer_edited {
13865 if let Some(project) = &self.project {
13866 let project = project.read(cx);
13867 #[allow(clippy::mutable_key_type)]
13868 let languages_affected = multibuffer
13869 .read(cx)
13870 .all_buffers()
13871 .into_iter()
13872 .filter_map(|buffer| {
13873 let buffer = buffer.read(cx);
13874 let language = buffer.language()?;
13875 if project.is_local()
13876 && project
13877 .language_servers_for_local_buffer(buffer, cx)
13878 .count()
13879 == 0
13880 {
13881 None
13882 } else {
13883 Some(language)
13884 }
13885 })
13886 .cloned()
13887 .collect::<HashSet<_>>();
13888 if !languages_affected.is_empty() {
13889 self.refresh_inlay_hints(
13890 InlayHintRefreshReason::BufferEdited(languages_affected),
13891 cx,
13892 );
13893 }
13894 }
13895 }
13896
13897 let Some(project) = &self.project else { return };
13898 let (telemetry, is_via_ssh) = {
13899 let project = project.read(cx);
13900 let telemetry = project.client().telemetry().clone();
13901 let is_via_ssh = project.is_via_ssh();
13902 (telemetry, is_via_ssh)
13903 };
13904 refresh_linked_ranges(self, window, cx);
13905 telemetry.log_edit_event("editor", is_via_ssh);
13906 }
13907 multi_buffer::Event::ExcerptsAdded {
13908 buffer,
13909 predecessor,
13910 excerpts,
13911 } => {
13912 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13913 let buffer_id = buffer.read(cx).remote_id();
13914 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13915 if let Some(project) = &self.project {
13916 get_uncommitted_diff_for_buffer(
13917 project,
13918 [buffer.clone()],
13919 self.buffer.clone(),
13920 cx,
13921 );
13922 }
13923 }
13924 cx.emit(EditorEvent::ExcerptsAdded {
13925 buffer: buffer.clone(),
13926 predecessor: *predecessor,
13927 excerpts: excerpts.clone(),
13928 });
13929 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13930 }
13931 multi_buffer::Event::ExcerptsRemoved { ids } => {
13932 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13933 let buffer = self.buffer.read(cx);
13934 self.registered_buffers
13935 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13936 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13937 }
13938 multi_buffer::Event::ExcerptsEdited { ids } => {
13939 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13940 }
13941 multi_buffer::Event::ExcerptsExpanded { ids } => {
13942 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13943 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13944 }
13945 multi_buffer::Event::Reparsed(buffer_id) => {
13946 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13947
13948 cx.emit(EditorEvent::Reparsed(*buffer_id));
13949 }
13950 multi_buffer::Event::DiffHunksToggled => {
13951 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13952 }
13953 multi_buffer::Event::LanguageChanged(buffer_id) => {
13954 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13955 cx.emit(EditorEvent::Reparsed(*buffer_id));
13956 cx.notify();
13957 }
13958 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13959 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13960 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13961 cx.emit(EditorEvent::TitleChanged)
13962 }
13963 // multi_buffer::Event::DiffBaseChanged => {
13964 // self.scrollbar_marker_state.dirty = true;
13965 // cx.emit(EditorEvent::DiffBaseChanged);
13966 // cx.notify();
13967 // }
13968 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13969 multi_buffer::Event::DiagnosticsUpdated => {
13970 self.refresh_active_diagnostics(cx);
13971 self.scrollbar_marker_state.dirty = true;
13972 cx.notify();
13973 }
13974 _ => {}
13975 };
13976 }
13977
13978 fn on_display_map_changed(
13979 &mut self,
13980 _: Entity<DisplayMap>,
13981 _: &mut Window,
13982 cx: &mut Context<Self>,
13983 ) {
13984 cx.notify();
13985 }
13986
13987 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13988 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13989 self.refresh_inline_completion(true, false, window, cx);
13990 self.refresh_inlay_hints(
13991 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13992 self.selections.newest_anchor().head(),
13993 &self.buffer.read(cx).snapshot(cx),
13994 cx,
13995 )),
13996 cx,
13997 );
13998
13999 let old_cursor_shape = self.cursor_shape;
14000
14001 {
14002 let editor_settings = EditorSettings::get_global(cx);
14003 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14004 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14005 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14006 }
14007
14008 if old_cursor_shape != self.cursor_shape {
14009 cx.emit(EditorEvent::CursorShapeChanged);
14010 }
14011
14012 let project_settings = ProjectSettings::get_global(cx);
14013 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14014
14015 if self.mode == EditorMode::Full {
14016 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14017 if self.git_blame_inline_enabled != inline_blame_enabled {
14018 self.toggle_git_blame_inline_internal(false, window, cx);
14019 }
14020 }
14021
14022 cx.notify();
14023 }
14024
14025 pub fn set_searchable(&mut self, searchable: bool) {
14026 self.searchable = searchable;
14027 }
14028
14029 pub fn searchable(&self) -> bool {
14030 self.searchable
14031 }
14032
14033 fn open_proposed_changes_editor(
14034 &mut self,
14035 _: &OpenProposedChangesEditor,
14036 window: &mut Window,
14037 cx: &mut Context<Self>,
14038 ) {
14039 let Some(workspace) = self.workspace() else {
14040 cx.propagate();
14041 return;
14042 };
14043
14044 let selections = self.selections.all::<usize>(cx);
14045 let multi_buffer = self.buffer.read(cx);
14046 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14047 let mut new_selections_by_buffer = HashMap::default();
14048 for selection in selections {
14049 for (buffer, range, _) in
14050 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14051 {
14052 let mut range = range.to_point(buffer);
14053 range.start.column = 0;
14054 range.end.column = buffer.line_len(range.end.row);
14055 new_selections_by_buffer
14056 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14057 .or_insert(Vec::new())
14058 .push(range)
14059 }
14060 }
14061
14062 let proposed_changes_buffers = new_selections_by_buffer
14063 .into_iter()
14064 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14065 .collect::<Vec<_>>();
14066 let proposed_changes_editor = cx.new(|cx| {
14067 ProposedChangesEditor::new(
14068 "Proposed changes",
14069 proposed_changes_buffers,
14070 self.project.clone(),
14071 window,
14072 cx,
14073 )
14074 });
14075
14076 window.defer(cx, move |window, cx| {
14077 workspace.update(cx, |workspace, cx| {
14078 workspace.active_pane().update(cx, |pane, cx| {
14079 pane.add_item(
14080 Box::new(proposed_changes_editor),
14081 true,
14082 true,
14083 None,
14084 window,
14085 cx,
14086 );
14087 });
14088 });
14089 });
14090 }
14091
14092 pub fn open_excerpts_in_split(
14093 &mut self,
14094 _: &OpenExcerptsSplit,
14095 window: &mut Window,
14096 cx: &mut Context<Self>,
14097 ) {
14098 self.open_excerpts_common(None, true, window, cx)
14099 }
14100
14101 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14102 self.open_excerpts_common(None, false, window, cx)
14103 }
14104
14105 fn open_excerpts_common(
14106 &mut self,
14107 jump_data: Option<JumpData>,
14108 split: bool,
14109 window: &mut Window,
14110 cx: &mut Context<Self>,
14111 ) {
14112 let Some(workspace) = self.workspace() else {
14113 cx.propagate();
14114 return;
14115 };
14116
14117 if self.buffer.read(cx).is_singleton() {
14118 cx.propagate();
14119 return;
14120 }
14121
14122 let mut new_selections_by_buffer = HashMap::default();
14123 match &jump_data {
14124 Some(JumpData::MultiBufferPoint {
14125 excerpt_id,
14126 position,
14127 anchor,
14128 line_offset_from_top,
14129 }) => {
14130 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14131 if let Some(buffer) = multi_buffer_snapshot
14132 .buffer_id_for_excerpt(*excerpt_id)
14133 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14134 {
14135 let buffer_snapshot = buffer.read(cx).snapshot();
14136 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14137 language::ToPoint::to_point(anchor, &buffer_snapshot)
14138 } else {
14139 buffer_snapshot.clip_point(*position, Bias::Left)
14140 };
14141 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14142 new_selections_by_buffer.insert(
14143 buffer,
14144 (
14145 vec![jump_to_offset..jump_to_offset],
14146 Some(*line_offset_from_top),
14147 ),
14148 );
14149 }
14150 }
14151 Some(JumpData::MultiBufferRow {
14152 row,
14153 line_offset_from_top,
14154 }) => {
14155 let point = MultiBufferPoint::new(row.0, 0);
14156 if let Some((buffer, buffer_point, _)) =
14157 self.buffer.read(cx).point_to_buffer_point(point, cx)
14158 {
14159 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14160 new_selections_by_buffer
14161 .entry(buffer)
14162 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14163 .0
14164 .push(buffer_offset..buffer_offset)
14165 }
14166 }
14167 None => {
14168 let selections = self.selections.all::<usize>(cx);
14169 let multi_buffer = self.buffer.read(cx);
14170 for selection in selections {
14171 for (buffer, mut range, _) in multi_buffer
14172 .snapshot(cx)
14173 .range_to_buffer_ranges(selection.range())
14174 {
14175 // When editing branch buffers, jump to the corresponding location
14176 // in their base buffer.
14177 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14178 let buffer = buffer_handle.read(cx);
14179 if let Some(base_buffer) = buffer.base_buffer() {
14180 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14181 buffer_handle = base_buffer;
14182 }
14183
14184 if selection.reversed {
14185 mem::swap(&mut range.start, &mut range.end);
14186 }
14187 new_selections_by_buffer
14188 .entry(buffer_handle)
14189 .or_insert((Vec::new(), None))
14190 .0
14191 .push(range)
14192 }
14193 }
14194 }
14195 }
14196
14197 if new_selections_by_buffer.is_empty() {
14198 return;
14199 }
14200
14201 // We defer the pane interaction because we ourselves are a workspace item
14202 // and activating a new item causes the pane to call a method on us reentrantly,
14203 // which panics if we're on the stack.
14204 window.defer(cx, move |window, cx| {
14205 workspace.update(cx, |workspace, cx| {
14206 let pane = if split {
14207 workspace.adjacent_pane(window, cx)
14208 } else {
14209 workspace.active_pane().clone()
14210 };
14211
14212 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14213 let editor = buffer
14214 .read(cx)
14215 .file()
14216 .is_none()
14217 .then(|| {
14218 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14219 // so `workspace.open_project_item` will never find them, always opening a new editor.
14220 // Instead, we try to activate the existing editor in the pane first.
14221 let (editor, pane_item_index) =
14222 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14223 let editor = item.downcast::<Editor>()?;
14224 let singleton_buffer =
14225 editor.read(cx).buffer().read(cx).as_singleton()?;
14226 if singleton_buffer == buffer {
14227 Some((editor, i))
14228 } else {
14229 None
14230 }
14231 })?;
14232 pane.update(cx, |pane, cx| {
14233 pane.activate_item(pane_item_index, true, true, window, cx)
14234 });
14235 Some(editor)
14236 })
14237 .flatten()
14238 .unwrap_or_else(|| {
14239 workspace.open_project_item::<Self>(
14240 pane.clone(),
14241 buffer,
14242 true,
14243 true,
14244 window,
14245 cx,
14246 )
14247 });
14248
14249 editor.update(cx, |editor, cx| {
14250 let autoscroll = match scroll_offset {
14251 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14252 None => Autoscroll::newest(),
14253 };
14254 let nav_history = editor.nav_history.take();
14255 editor.change_selections(Some(autoscroll), window, cx, |s| {
14256 s.select_ranges(ranges);
14257 });
14258 editor.nav_history = nav_history;
14259 });
14260 }
14261 })
14262 });
14263 }
14264
14265 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14266 let snapshot = self.buffer.read(cx).read(cx);
14267 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14268 Some(
14269 ranges
14270 .iter()
14271 .map(move |range| {
14272 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14273 })
14274 .collect(),
14275 )
14276 }
14277
14278 fn selection_replacement_ranges(
14279 &self,
14280 range: Range<OffsetUtf16>,
14281 cx: &mut App,
14282 ) -> Vec<Range<OffsetUtf16>> {
14283 let selections = self.selections.all::<OffsetUtf16>(cx);
14284 let newest_selection = selections
14285 .iter()
14286 .max_by_key(|selection| selection.id)
14287 .unwrap();
14288 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14289 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14290 let snapshot = self.buffer.read(cx).read(cx);
14291 selections
14292 .into_iter()
14293 .map(|mut selection| {
14294 selection.start.0 =
14295 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14296 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14297 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14298 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14299 })
14300 .collect()
14301 }
14302
14303 fn report_editor_event(
14304 &self,
14305 event_type: &'static str,
14306 file_extension: Option<String>,
14307 cx: &App,
14308 ) {
14309 if cfg!(any(test, feature = "test-support")) {
14310 return;
14311 }
14312
14313 let Some(project) = &self.project else { return };
14314
14315 // If None, we are in a file without an extension
14316 let file = self
14317 .buffer
14318 .read(cx)
14319 .as_singleton()
14320 .and_then(|b| b.read(cx).file());
14321 let file_extension = file_extension.or(file
14322 .as_ref()
14323 .and_then(|file| Path::new(file.file_name(cx)).extension())
14324 .and_then(|e| e.to_str())
14325 .map(|a| a.to_string()));
14326
14327 let vim_mode = cx
14328 .global::<SettingsStore>()
14329 .raw_user_settings()
14330 .get("vim_mode")
14331 == Some(&serde_json::Value::Bool(true));
14332
14333 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14334 let copilot_enabled = edit_predictions_provider
14335 == language::language_settings::EditPredictionProvider::Copilot;
14336 let copilot_enabled_for_language = self
14337 .buffer
14338 .read(cx)
14339 .settings_at(0, cx)
14340 .show_edit_predictions;
14341
14342 let project = project.read(cx);
14343 telemetry::event!(
14344 event_type,
14345 file_extension,
14346 vim_mode,
14347 copilot_enabled,
14348 copilot_enabled_for_language,
14349 edit_predictions_provider,
14350 is_via_ssh = project.is_via_ssh(),
14351 );
14352 }
14353
14354 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14355 /// with each line being an array of {text, highlight} objects.
14356 fn copy_highlight_json(
14357 &mut self,
14358 _: &CopyHighlightJson,
14359 window: &mut Window,
14360 cx: &mut Context<Self>,
14361 ) {
14362 #[derive(Serialize)]
14363 struct Chunk<'a> {
14364 text: String,
14365 highlight: Option<&'a str>,
14366 }
14367
14368 let snapshot = self.buffer.read(cx).snapshot(cx);
14369 let range = self
14370 .selected_text_range(false, window, cx)
14371 .and_then(|selection| {
14372 if selection.range.is_empty() {
14373 None
14374 } else {
14375 Some(selection.range)
14376 }
14377 })
14378 .unwrap_or_else(|| 0..snapshot.len());
14379
14380 let chunks = snapshot.chunks(range, true);
14381 let mut lines = Vec::new();
14382 let mut line: VecDeque<Chunk> = VecDeque::new();
14383
14384 let Some(style) = self.style.as_ref() else {
14385 return;
14386 };
14387
14388 for chunk in chunks {
14389 let highlight = chunk
14390 .syntax_highlight_id
14391 .and_then(|id| id.name(&style.syntax));
14392 let mut chunk_lines = chunk.text.split('\n').peekable();
14393 while let Some(text) = chunk_lines.next() {
14394 let mut merged_with_last_token = false;
14395 if let Some(last_token) = line.back_mut() {
14396 if last_token.highlight == highlight {
14397 last_token.text.push_str(text);
14398 merged_with_last_token = true;
14399 }
14400 }
14401
14402 if !merged_with_last_token {
14403 line.push_back(Chunk {
14404 text: text.into(),
14405 highlight,
14406 });
14407 }
14408
14409 if chunk_lines.peek().is_some() {
14410 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14411 line.pop_front();
14412 }
14413 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14414 line.pop_back();
14415 }
14416
14417 lines.push(mem::take(&mut line));
14418 }
14419 }
14420 }
14421
14422 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14423 return;
14424 };
14425 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14426 }
14427
14428 pub fn open_context_menu(
14429 &mut self,
14430 _: &OpenContextMenu,
14431 window: &mut Window,
14432 cx: &mut Context<Self>,
14433 ) {
14434 self.request_autoscroll(Autoscroll::newest(), cx);
14435 let position = self.selections.newest_display(cx).start;
14436 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14437 }
14438
14439 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14440 &self.inlay_hint_cache
14441 }
14442
14443 pub fn replay_insert_event(
14444 &mut self,
14445 text: &str,
14446 relative_utf16_range: Option<Range<isize>>,
14447 window: &mut Window,
14448 cx: &mut Context<Self>,
14449 ) {
14450 if !self.input_enabled {
14451 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14452 return;
14453 }
14454 if let Some(relative_utf16_range) = relative_utf16_range {
14455 let selections = self.selections.all::<OffsetUtf16>(cx);
14456 self.change_selections(None, window, cx, |s| {
14457 let new_ranges = selections.into_iter().map(|range| {
14458 let start = OffsetUtf16(
14459 range
14460 .head()
14461 .0
14462 .saturating_add_signed(relative_utf16_range.start),
14463 );
14464 let end = OffsetUtf16(
14465 range
14466 .head()
14467 .0
14468 .saturating_add_signed(relative_utf16_range.end),
14469 );
14470 start..end
14471 });
14472 s.select_ranges(new_ranges);
14473 });
14474 }
14475
14476 self.handle_input(text, window, cx);
14477 }
14478
14479 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14480 let Some(provider) = self.semantics_provider.as_ref() else {
14481 return false;
14482 };
14483
14484 let mut supports = false;
14485 self.buffer().read(cx).for_each_buffer(|buffer| {
14486 supports |= provider.supports_inlay_hints(buffer, cx);
14487 });
14488 supports
14489 }
14490
14491 pub fn is_focused(&self, window: &Window) -> bool {
14492 self.focus_handle.is_focused(window)
14493 }
14494
14495 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14496 cx.emit(EditorEvent::Focused);
14497
14498 if let Some(descendant) = self
14499 .last_focused_descendant
14500 .take()
14501 .and_then(|descendant| descendant.upgrade())
14502 {
14503 window.focus(&descendant);
14504 } else {
14505 if let Some(blame) = self.blame.as_ref() {
14506 blame.update(cx, GitBlame::focus)
14507 }
14508
14509 self.blink_manager.update(cx, BlinkManager::enable);
14510 self.show_cursor_names(window, cx);
14511 self.buffer.update(cx, |buffer, cx| {
14512 buffer.finalize_last_transaction(cx);
14513 if self.leader_peer_id.is_none() {
14514 buffer.set_active_selections(
14515 &self.selections.disjoint_anchors(),
14516 self.selections.line_mode,
14517 self.cursor_shape,
14518 cx,
14519 );
14520 }
14521 });
14522 }
14523 }
14524
14525 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14526 cx.emit(EditorEvent::FocusedIn)
14527 }
14528
14529 fn handle_focus_out(
14530 &mut self,
14531 event: FocusOutEvent,
14532 _window: &mut Window,
14533 _cx: &mut Context<Self>,
14534 ) {
14535 if event.blurred != self.focus_handle {
14536 self.last_focused_descendant = Some(event.blurred);
14537 }
14538 }
14539
14540 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14541 self.blink_manager.update(cx, BlinkManager::disable);
14542 self.buffer
14543 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14544
14545 if let Some(blame) = self.blame.as_ref() {
14546 blame.update(cx, GitBlame::blur)
14547 }
14548 if !self.hover_state.focused(window, cx) {
14549 hide_hover(self, cx);
14550 }
14551
14552 self.hide_context_menu(window, cx);
14553 cx.emit(EditorEvent::Blurred);
14554 cx.notify();
14555 }
14556
14557 pub fn register_action<A: Action>(
14558 &mut self,
14559 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14560 ) -> Subscription {
14561 let id = self.next_editor_action_id.post_inc();
14562 let listener = Arc::new(listener);
14563 self.editor_actions.borrow_mut().insert(
14564 id,
14565 Box::new(move |window, _| {
14566 let listener = listener.clone();
14567 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14568 let action = action.downcast_ref().unwrap();
14569 if phase == DispatchPhase::Bubble {
14570 listener(action, window, cx)
14571 }
14572 })
14573 }),
14574 );
14575
14576 let editor_actions = self.editor_actions.clone();
14577 Subscription::new(move || {
14578 editor_actions.borrow_mut().remove(&id);
14579 })
14580 }
14581
14582 pub fn file_header_size(&self) -> u32 {
14583 FILE_HEADER_HEIGHT
14584 }
14585
14586 pub fn revert(
14587 &mut self,
14588 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14589 window: &mut Window,
14590 cx: &mut Context<Self>,
14591 ) {
14592 self.buffer().update(cx, |multi_buffer, cx| {
14593 for (buffer_id, changes) in revert_changes {
14594 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14595 buffer.update(cx, |buffer, cx| {
14596 buffer.edit(
14597 changes.into_iter().map(|(range, text)| {
14598 (range, text.to_string().map(Arc::<str>::from))
14599 }),
14600 None,
14601 cx,
14602 );
14603 });
14604 }
14605 }
14606 });
14607 self.change_selections(None, window, cx, |selections| selections.refresh());
14608 }
14609
14610 pub fn to_pixel_point(
14611 &self,
14612 source: multi_buffer::Anchor,
14613 editor_snapshot: &EditorSnapshot,
14614 window: &mut Window,
14615 ) -> Option<gpui::Point<Pixels>> {
14616 let source_point = source.to_display_point(editor_snapshot);
14617 self.display_to_pixel_point(source_point, editor_snapshot, window)
14618 }
14619
14620 pub fn display_to_pixel_point(
14621 &self,
14622 source: DisplayPoint,
14623 editor_snapshot: &EditorSnapshot,
14624 window: &mut Window,
14625 ) -> Option<gpui::Point<Pixels>> {
14626 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14627 let text_layout_details = self.text_layout_details(window);
14628 let scroll_top = text_layout_details
14629 .scroll_anchor
14630 .scroll_position(editor_snapshot)
14631 .y;
14632
14633 if source.row().as_f32() < scroll_top.floor() {
14634 return None;
14635 }
14636 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14637 let source_y = line_height * (source.row().as_f32() - scroll_top);
14638 Some(gpui::Point::new(source_x, source_y))
14639 }
14640
14641 pub fn has_visible_completions_menu(&self) -> bool {
14642 !self.edit_prediction_preview_is_active()
14643 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14644 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14645 })
14646 }
14647
14648 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14649 self.addons
14650 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14651 }
14652
14653 pub fn unregister_addon<T: Addon>(&mut self) {
14654 self.addons.remove(&std::any::TypeId::of::<T>());
14655 }
14656
14657 pub fn addon<T: Addon>(&self) -> Option<&T> {
14658 let type_id = std::any::TypeId::of::<T>();
14659 self.addons
14660 .get(&type_id)
14661 .and_then(|item| item.to_any().downcast_ref::<T>())
14662 }
14663
14664 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14665 let text_layout_details = self.text_layout_details(window);
14666 let style = &text_layout_details.editor_style;
14667 let font_id = window.text_system().resolve_font(&style.text.font());
14668 let font_size = style.text.font_size.to_pixels(window.rem_size());
14669 let line_height = style.text.line_height_in_pixels(window.rem_size());
14670 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14671
14672 gpui::Size::new(em_width, line_height)
14673 }
14674}
14675
14676fn get_uncommitted_diff_for_buffer(
14677 project: &Entity<Project>,
14678 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14679 buffer: Entity<MultiBuffer>,
14680 cx: &mut App,
14681) {
14682 let mut tasks = Vec::new();
14683 project.update(cx, |project, cx| {
14684 for buffer in buffers {
14685 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14686 }
14687 });
14688 cx.spawn(|mut cx| async move {
14689 let diffs = futures::future::join_all(tasks).await;
14690 buffer
14691 .update(&mut cx, |buffer, cx| {
14692 for diff in diffs.into_iter().flatten() {
14693 buffer.add_diff(diff, cx);
14694 }
14695 })
14696 .ok();
14697 })
14698 .detach();
14699}
14700
14701fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14702 let tab_size = tab_size.get() as usize;
14703 let mut width = offset;
14704
14705 for ch in text.chars() {
14706 width += if ch == '\t' {
14707 tab_size - (width % tab_size)
14708 } else {
14709 1
14710 };
14711 }
14712
14713 width - offset
14714}
14715
14716#[cfg(test)]
14717mod tests {
14718 use super::*;
14719
14720 #[test]
14721 fn test_string_size_with_expanded_tabs() {
14722 let nz = |val| NonZeroU32::new(val).unwrap();
14723 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14724 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14725 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14726 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14727 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14728 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14729 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14730 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14731 }
14732}
14733
14734/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14735struct WordBreakingTokenizer<'a> {
14736 input: &'a str,
14737}
14738
14739impl<'a> WordBreakingTokenizer<'a> {
14740 fn new(input: &'a str) -> Self {
14741 Self { input }
14742 }
14743}
14744
14745fn is_char_ideographic(ch: char) -> bool {
14746 use unicode_script::Script::*;
14747 use unicode_script::UnicodeScript;
14748 matches!(ch.script(), Han | Tangut | Yi)
14749}
14750
14751fn is_grapheme_ideographic(text: &str) -> bool {
14752 text.chars().any(is_char_ideographic)
14753}
14754
14755fn is_grapheme_whitespace(text: &str) -> bool {
14756 text.chars().any(|x| x.is_whitespace())
14757}
14758
14759fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14760 text.chars().next().map_or(false, |ch| {
14761 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14762 })
14763}
14764
14765#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14766struct WordBreakToken<'a> {
14767 token: &'a str,
14768 grapheme_len: usize,
14769 is_whitespace: bool,
14770}
14771
14772impl<'a> Iterator for WordBreakingTokenizer<'a> {
14773 /// Yields a span, the count of graphemes in the token, and whether it was
14774 /// whitespace. Note that it also breaks at word boundaries.
14775 type Item = WordBreakToken<'a>;
14776
14777 fn next(&mut self) -> Option<Self::Item> {
14778 use unicode_segmentation::UnicodeSegmentation;
14779 if self.input.is_empty() {
14780 return None;
14781 }
14782
14783 let mut iter = self.input.graphemes(true).peekable();
14784 let mut offset = 0;
14785 let mut graphemes = 0;
14786 if let Some(first_grapheme) = iter.next() {
14787 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14788 offset += first_grapheme.len();
14789 graphemes += 1;
14790 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14791 if let Some(grapheme) = iter.peek().copied() {
14792 if should_stay_with_preceding_ideograph(grapheme) {
14793 offset += grapheme.len();
14794 graphemes += 1;
14795 }
14796 }
14797 } else {
14798 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14799 let mut next_word_bound = words.peek().copied();
14800 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14801 next_word_bound = words.next();
14802 }
14803 while let Some(grapheme) = iter.peek().copied() {
14804 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14805 break;
14806 };
14807 if is_grapheme_whitespace(grapheme) != is_whitespace {
14808 break;
14809 };
14810 offset += grapheme.len();
14811 graphemes += 1;
14812 iter.next();
14813 }
14814 }
14815 let token = &self.input[..offset];
14816 self.input = &self.input[offset..];
14817 if is_whitespace {
14818 Some(WordBreakToken {
14819 token: " ",
14820 grapheme_len: 1,
14821 is_whitespace: true,
14822 })
14823 } else {
14824 Some(WordBreakToken {
14825 token,
14826 grapheme_len: graphemes,
14827 is_whitespace: false,
14828 })
14829 }
14830 } else {
14831 None
14832 }
14833 }
14834}
14835
14836#[test]
14837fn test_word_breaking_tokenizer() {
14838 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14839 ("", &[]),
14840 (" ", &[(" ", 1, true)]),
14841 ("Ʒ", &[("Ʒ", 1, false)]),
14842 ("Ǽ", &[("Ǽ", 1, false)]),
14843 ("⋑", &[("⋑", 1, false)]),
14844 ("⋑⋑", &[("⋑⋑", 2, false)]),
14845 (
14846 "原理,进而",
14847 &[
14848 ("原", 1, false),
14849 ("理,", 2, false),
14850 ("进", 1, false),
14851 ("而", 1, false),
14852 ],
14853 ),
14854 (
14855 "hello world",
14856 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14857 ),
14858 (
14859 "hello, world",
14860 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14861 ),
14862 (
14863 " hello world",
14864 &[
14865 (" ", 1, true),
14866 ("hello", 5, false),
14867 (" ", 1, true),
14868 ("world", 5, false),
14869 ],
14870 ),
14871 (
14872 "这是什么 \n 钢笔",
14873 &[
14874 ("这", 1, false),
14875 ("是", 1, false),
14876 ("什", 1, false),
14877 ("么", 1, false),
14878 (" ", 1, true),
14879 ("钢", 1, false),
14880 ("笔", 1, false),
14881 ],
14882 ),
14883 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14884 ];
14885
14886 for (input, result) in tests {
14887 assert_eq!(
14888 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14889 result
14890 .iter()
14891 .copied()
14892 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14893 token,
14894 grapheme_len,
14895 is_whitespace,
14896 })
14897 .collect::<Vec<_>>()
14898 );
14899 }
14900}
14901
14902fn wrap_with_prefix(
14903 line_prefix: String,
14904 unwrapped_text: String,
14905 wrap_column: usize,
14906 tab_size: NonZeroU32,
14907) -> String {
14908 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14909 let mut wrapped_text = String::new();
14910 let mut current_line = line_prefix.clone();
14911
14912 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14913 let mut current_line_len = line_prefix_len;
14914 for WordBreakToken {
14915 token,
14916 grapheme_len,
14917 is_whitespace,
14918 } in tokenizer
14919 {
14920 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14921 wrapped_text.push_str(current_line.trim_end());
14922 wrapped_text.push('\n');
14923 current_line.truncate(line_prefix.len());
14924 current_line_len = line_prefix_len;
14925 if !is_whitespace {
14926 current_line.push_str(token);
14927 current_line_len += grapheme_len;
14928 }
14929 } else if !is_whitespace {
14930 current_line.push_str(token);
14931 current_line_len += grapheme_len;
14932 } else if current_line_len != line_prefix_len {
14933 current_line.push(' ');
14934 current_line_len += 1;
14935 }
14936 }
14937
14938 if !current_line.is_empty() {
14939 wrapped_text.push_str(¤t_line);
14940 }
14941 wrapped_text
14942}
14943
14944#[test]
14945fn test_wrap_with_prefix() {
14946 assert_eq!(
14947 wrap_with_prefix(
14948 "# ".to_string(),
14949 "abcdefg".to_string(),
14950 4,
14951 NonZeroU32::new(4).unwrap()
14952 ),
14953 "# abcdefg"
14954 );
14955 assert_eq!(
14956 wrap_with_prefix(
14957 "".to_string(),
14958 "\thello world".to_string(),
14959 8,
14960 NonZeroU32::new(4).unwrap()
14961 ),
14962 "hello\nworld"
14963 );
14964 assert_eq!(
14965 wrap_with_prefix(
14966 "// ".to_string(),
14967 "xx \nyy zz aa bb cc".to_string(),
14968 12,
14969 NonZeroU32::new(4).unwrap()
14970 ),
14971 "// xx yy zz\n// aa bb cc"
14972 );
14973 assert_eq!(
14974 wrap_with_prefix(
14975 String::new(),
14976 "这是什么 \n 钢笔".to_string(),
14977 3,
14978 NonZeroU32::new(4).unwrap()
14979 ),
14980 "这是什\n么 钢\n笔"
14981 );
14982}
14983
14984pub trait CollaborationHub {
14985 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14986 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14987 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14988}
14989
14990impl CollaborationHub for Entity<Project> {
14991 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14992 self.read(cx).collaborators()
14993 }
14994
14995 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14996 self.read(cx).user_store().read(cx).participant_indices()
14997 }
14998
14999 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15000 let this = self.read(cx);
15001 let user_ids = this.collaborators().values().map(|c| c.user_id);
15002 this.user_store().read_with(cx, |user_store, cx| {
15003 user_store.participant_names(user_ids, cx)
15004 })
15005 }
15006}
15007
15008pub trait SemanticsProvider {
15009 fn hover(
15010 &self,
15011 buffer: &Entity<Buffer>,
15012 position: text::Anchor,
15013 cx: &mut App,
15014 ) -> Option<Task<Vec<project::Hover>>>;
15015
15016 fn inlay_hints(
15017 &self,
15018 buffer_handle: Entity<Buffer>,
15019 range: Range<text::Anchor>,
15020 cx: &mut App,
15021 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15022
15023 fn resolve_inlay_hint(
15024 &self,
15025 hint: InlayHint,
15026 buffer_handle: Entity<Buffer>,
15027 server_id: LanguageServerId,
15028 cx: &mut App,
15029 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15030
15031 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15032
15033 fn document_highlights(
15034 &self,
15035 buffer: &Entity<Buffer>,
15036 position: text::Anchor,
15037 cx: &mut App,
15038 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15039
15040 fn definitions(
15041 &self,
15042 buffer: &Entity<Buffer>,
15043 position: text::Anchor,
15044 kind: GotoDefinitionKind,
15045 cx: &mut App,
15046 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15047
15048 fn range_for_rename(
15049 &self,
15050 buffer: &Entity<Buffer>,
15051 position: text::Anchor,
15052 cx: &mut App,
15053 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15054
15055 fn perform_rename(
15056 &self,
15057 buffer: &Entity<Buffer>,
15058 position: text::Anchor,
15059 new_name: String,
15060 cx: &mut App,
15061 ) -> Option<Task<Result<ProjectTransaction>>>;
15062}
15063
15064pub trait CompletionProvider {
15065 fn completions(
15066 &self,
15067 buffer: &Entity<Buffer>,
15068 buffer_position: text::Anchor,
15069 trigger: CompletionContext,
15070 window: &mut Window,
15071 cx: &mut Context<Editor>,
15072 ) -> Task<Result<Vec<Completion>>>;
15073
15074 fn resolve_completions(
15075 &self,
15076 buffer: Entity<Buffer>,
15077 completion_indices: Vec<usize>,
15078 completions: Rc<RefCell<Box<[Completion]>>>,
15079 cx: &mut Context<Editor>,
15080 ) -> Task<Result<bool>>;
15081
15082 fn apply_additional_edits_for_completion(
15083 &self,
15084 _buffer: Entity<Buffer>,
15085 _completions: Rc<RefCell<Box<[Completion]>>>,
15086 _completion_index: usize,
15087 _push_to_history: bool,
15088 _cx: &mut Context<Editor>,
15089 ) -> Task<Result<Option<language::Transaction>>> {
15090 Task::ready(Ok(None))
15091 }
15092
15093 fn is_completion_trigger(
15094 &self,
15095 buffer: &Entity<Buffer>,
15096 position: language::Anchor,
15097 text: &str,
15098 trigger_in_words: bool,
15099 cx: &mut Context<Editor>,
15100 ) -> bool;
15101
15102 fn sort_completions(&self) -> bool {
15103 true
15104 }
15105}
15106
15107pub trait CodeActionProvider {
15108 fn id(&self) -> Arc<str>;
15109
15110 fn code_actions(
15111 &self,
15112 buffer: &Entity<Buffer>,
15113 range: Range<text::Anchor>,
15114 window: &mut Window,
15115 cx: &mut App,
15116 ) -> Task<Result<Vec<CodeAction>>>;
15117
15118 fn apply_code_action(
15119 &self,
15120 buffer_handle: Entity<Buffer>,
15121 action: CodeAction,
15122 excerpt_id: ExcerptId,
15123 push_to_history: bool,
15124 window: &mut Window,
15125 cx: &mut App,
15126 ) -> Task<Result<ProjectTransaction>>;
15127}
15128
15129impl CodeActionProvider for Entity<Project> {
15130 fn id(&self) -> Arc<str> {
15131 "project".into()
15132 }
15133
15134 fn code_actions(
15135 &self,
15136 buffer: &Entity<Buffer>,
15137 range: Range<text::Anchor>,
15138 _window: &mut Window,
15139 cx: &mut App,
15140 ) -> Task<Result<Vec<CodeAction>>> {
15141 self.update(cx, |project, cx| {
15142 project.code_actions(buffer, range, None, cx)
15143 })
15144 }
15145
15146 fn apply_code_action(
15147 &self,
15148 buffer_handle: Entity<Buffer>,
15149 action: CodeAction,
15150 _excerpt_id: ExcerptId,
15151 push_to_history: bool,
15152 _window: &mut Window,
15153 cx: &mut App,
15154 ) -> Task<Result<ProjectTransaction>> {
15155 self.update(cx, |project, cx| {
15156 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15157 })
15158 }
15159}
15160
15161fn snippet_completions(
15162 project: &Project,
15163 buffer: &Entity<Buffer>,
15164 buffer_position: text::Anchor,
15165 cx: &mut App,
15166) -> Task<Result<Vec<Completion>>> {
15167 let language = buffer.read(cx).language_at(buffer_position);
15168 let language_name = language.as_ref().map(|language| language.lsp_id());
15169 let snippet_store = project.snippets().read(cx);
15170 let snippets = snippet_store.snippets_for(language_name, cx);
15171
15172 if snippets.is_empty() {
15173 return Task::ready(Ok(vec![]));
15174 }
15175 let snapshot = buffer.read(cx).text_snapshot();
15176 let chars: String = snapshot
15177 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15178 .collect();
15179
15180 let scope = language.map(|language| language.default_scope());
15181 let executor = cx.background_executor().clone();
15182
15183 cx.background_executor().spawn(async move {
15184 let classifier = CharClassifier::new(scope).for_completion(true);
15185 let mut last_word = chars
15186 .chars()
15187 .take_while(|c| classifier.is_word(*c))
15188 .collect::<String>();
15189 last_word = last_word.chars().rev().collect();
15190
15191 if last_word.is_empty() {
15192 return Ok(vec![]);
15193 }
15194
15195 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15196 let to_lsp = |point: &text::Anchor| {
15197 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15198 point_to_lsp(end)
15199 };
15200 let lsp_end = to_lsp(&buffer_position);
15201
15202 let candidates = snippets
15203 .iter()
15204 .enumerate()
15205 .flat_map(|(ix, snippet)| {
15206 snippet
15207 .prefix
15208 .iter()
15209 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15210 })
15211 .collect::<Vec<StringMatchCandidate>>();
15212
15213 let mut matches = fuzzy::match_strings(
15214 &candidates,
15215 &last_word,
15216 last_word.chars().any(|c| c.is_uppercase()),
15217 100,
15218 &Default::default(),
15219 executor,
15220 )
15221 .await;
15222
15223 // Remove all candidates where the query's start does not match the start of any word in the candidate
15224 if let Some(query_start) = last_word.chars().next() {
15225 matches.retain(|string_match| {
15226 split_words(&string_match.string).any(|word| {
15227 // Check that the first codepoint of the word as lowercase matches the first
15228 // codepoint of the query as lowercase
15229 word.chars()
15230 .flat_map(|codepoint| codepoint.to_lowercase())
15231 .zip(query_start.to_lowercase())
15232 .all(|(word_cp, query_cp)| word_cp == query_cp)
15233 })
15234 });
15235 }
15236
15237 let matched_strings = matches
15238 .into_iter()
15239 .map(|m| m.string)
15240 .collect::<HashSet<_>>();
15241
15242 let result: Vec<Completion> = snippets
15243 .into_iter()
15244 .filter_map(|snippet| {
15245 let matching_prefix = snippet
15246 .prefix
15247 .iter()
15248 .find(|prefix| matched_strings.contains(*prefix))?;
15249 let start = as_offset - last_word.len();
15250 let start = snapshot.anchor_before(start);
15251 let range = start..buffer_position;
15252 let lsp_start = to_lsp(&start);
15253 let lsp_range = lsp::Range {
15254 start: lsp_start,
15255 end: lsp_end,
15256 };
15257 Some(Completion {
15258 old_range: range,
15259 new_text: snippet.body.clone(),
15260 resolved: false,
15261 label: CodeLabel {
15262 text: matching_prefix.clone(),
15263 runs: vec![],
15264 filter_range: 0..matching_prefix.len(),
15265 },
15266 server_id: LanguageServerId(usize::MAX),
15267 documentation: snippet
15268 .description
15269 .clone()
15270 .map(CompletionDocumentation::SingleLine),
15271 lsp_completion: lsp::CompletionItem {
15272 label: snippet.prefix.first().unwrap().clone(),
15273 kind: Some(CompletionItemKind::SNIPPET),
15274 label_details: snippet.description.as_ref().map(|description| {
15275 lsp::CompletionItemLabelDetails {
15276 detail: Some(description.clone()),
15277 description: None,
15278 }
15279 }),
15280 insert_text_format: Some(InsertTextFormat::SNIPPET),
15281 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15282 lsp::InsertReplaceEdit {
15283 new_text: snippet.body.clone(),
15284 insert: lsp_range,
15285 replace: lsp_range,
15286 },
15287 )),
15288 filter_text: Some(snippet.body.clone()),
15289 sort_text: Some(char::MAX.to_string()),
15290 ..Default::default()
15291 },
15292 confirm: None,
15293 })
15294 })
15295 .collect();
15296
15297 Ok(result)
15298 })
15299}
15300
15301impl CompletionProvider for Entity<Project> {
15302 fn completions(
15303 &self,
15304 buffer: &Entity<Buffer>,
15305 buffer_position: text::Anchor,
15306 options: CompletionContext,
15307 _window: &mut Window,
15308 cx: &mut Context<Editor>,
15309 ) -> Task<Result<Vec<Completion>>> {
15310 self.update(cx, |project, cx| {
15311 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15312 let project_completions = project.completions(buffer, buffer_position, options, cx);
15313 cx.background_executor().spawn(async move {
15314 let mut completions = project_completions.await?;
15315 let snippets_completions = snippets.await?;
15316 completions.extend(snippets_completions);
15317 Ok(completions)
15318 })
15319 })
15320 }
15321
15322 fn resolve_completions(
15323 &self,
15324 buffer: Entity<Buffer>,
15325 completion_indices: Vec<usize>,
15326 completions: Rc<RefCell<Box<[Completion]>>>,
15327 cx: &mut Context<Editor>,
15328 ) -> Task<Result<bool>> {
15329 self.update(cx, |project, cx| {
15330 project.lsp_store().update(cx, |lsp_store, cx| {
15331 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15332 })
15333 })
15334 }
15335
15336 fn apply_additional_edits_for_completion(
15337 &self,
15338 buffer: Entity<Buffer>,
15339 completions: Rc<RefCell<Box<[Completion]>>>,
15340 completion_index: usize,
15341 push_to_history: bool,
15342 cx: &mut Context<Editor>,
15343 ) -> Task<Result<Option<language::Transaction>>> {
15344 self.update(cx, |project, cx| {
15345 project.lsp_store().update(cx, |lsp_store, cx| {
15346 lsp_store.apply_additional_edits_for_completion(
15347 buffer,
15348 completions,
15349 completion_index,
15350 push_to_history,
15351 cx,
15352 )
15353 })
15354 })
15355 }
15356
15357 fn is_completion_trigger(
15358 &self,
15359 buffer: &Entity<Buffer>,
15360 position: language::Anchor,
15361 text: &str,
15362 trigger_in_words: bool,
15363 cx: &mut Context<Editor>,
15364 ) -> bool {
15365 let mut chars = text.chars();
15366 let char = if let Some(char) = chars.next() {
15367 char
15368 } else {
15369 return false;
15370 };
15371 if chars.next().is_some() {
15372 return false;
15373 }
15374
15375 let buffer = buffer.read(cx);
15376 let snapshot = buffer.snapshot();
15377 if !snapshot.settings_at(position, cx).show_completions_on_input {
15378 return false;
15379 }
15380 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15381 if trigger_in_words && classifier.is_word(char) {
15382 return true;
15383 }
15384
15385 buffer.completion_triggers().contains(text)
15386 }
15387}
15388
15389impl SemanticsProvider for Entity<Project> {
15390 fn hover(
15391 &self,
15392 buffer: &Entity<Buffer>,
15393 position: text::Anchor,
15394 cx: &mut App,
15395 ) -> Option<Task<Vec<project::Hover>>> {
15396 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15397 }
15398
15399 fn document_highlights(
15400 &self,
15401 buffer: &Entity<Buffer>,
15402 position: text::Anchor,
15403 cx: &mut App,
15404 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15405 Some(self.update(cx, |project, cx| {
15406 project.document_highlights(buffer, position, cx)
15407 }))
15408 }
15409
15410 fn definitions(
15411 &self,
15412 buffer: &Entity<Buffer>,
15413 position: text::Anchor,
15414 kind: GotoDefinitionKind,
15415 cx: &mut App,
15416 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15417 Some(self.update(cx, |project, cx| match kind {
15418 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15419 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15420 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15421 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15422 }))
15423 }
15424
15425 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15426 // TODO: make this work for remote projects
15427 self.read(cx)
15428 .language_servers_for_local_buffer(buffer.read(cx), cx)
15429 .any(
15430 |(_, server)| match server.capabilities().inlay_hint_provider {
15431 Some(lsp::OneOf::Left(enabled)) => enabled,
15432 Some(lsp::OneOf::Right(_)) => true,
15433 None => false,
15434 },
15435 )
15436 }
15437
15438 fn inlay_hints(
15439 &self,
15440 buffer_handle: Entity<Buffer>,
15441 range: Range<text::Anchor>,
15442 cx: &mut App,
15443 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15444 Some(self.update(cx, |project, cx| {
15445 project.inlay_hints(buffer_handle, range, cx)
15446 }))
15447 }
15448
15449 fn resolve_inlay_hint(
15450 &self,
15451 hint: InlayHint,
15452 buffer_handle: Entity<Buffer>,
15453 server_id: LanguageServerId,
15454 cx: &mut App,
15455 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15456 Some(self.update(cx, |project, cx| {
15457 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15458 }))
15459 }
15460
15461 fn range_for_rename(
15462 &self,
15463 buffer: &Entity<Buffer>,
15464 position: text::Anchor,
15465 cx: &mut App,
15466 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15467 Some(self.update(cx, |project, cx| {
15468 let buffer = buffer.clone();
15469 let task = project.prepare_rename(buffer.clone(), position, cx);
15470 cx.spawn(|_, mut cx| async move {
15471 Ok(match task.await? {
15472 PrepareRenameResponse::Success(range) => Some(range),
15473 PrepareRenameResponse::InvalidPosition => None,
15474 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15475 // Fallback on using TreeSitter info to determine identifier range
15476 buffer.update(&mut cx, |buffer, _| {
15477 let snapshot = buffer.snapshot();
15478 let (range, kind) = snapshot.surrounding_word(position);
15479 if kind != Some(CharKind::Word) {
15480 return None;
15481 }
15482 Some(
15483 snapshot.anchor_before(range.start)
15484 ..snapshot.anchor_after(range.end),
15485 )
15486 })?
15487 }
15488 })
15489 })
15490 }))
15491 }
15492
15493 fn perform_rename(
15494 &self,
15495 buffer: &Entity<Buffer>,
15496 position: text::Anchor,
15497 new_name: String,
15498 cx: &mut App,
15499 ) -> Option<Task<Result<ProjectTransaction>>> {
15500 Some(self.update(cx, |project, cx| {
15501 project.perform_rename(buffer.clone(), position, new_name, cx)
15502 }))
15503 }
15504}
15505
15506fn inlay_hint_settings(
15507 location: Anchor,
15508 snapshot: &MultiBufferSnapshot,
15509 cx: &mut Context<Editor>,
15510) -> InlayHintSettings {
15511 let file = snapshot.file_at(location);
15512 let language = snapshot.language_at(location).map(|l| l.name());
15513 language_settings(language, file, cx).inlay_hints
15514}
15515
15516fn consume_contiguous_rows(
15517 contiguous_row_selections: &mut Vec<Selection<Point>>,
15518 selection: &Selection<Point>,
15519 display_map: &DisplaySnapshot,
15520 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15521) -> (MultiBufferRow, MultiBufferRow) {
15522 contiguous_row_selections.push(selection.clone());
15523 let start_row = MultiBufferRow(selection.start.row);
15524 let mut end_row = ending_row(selection, display_map);
15525
15526 while let Some(next_selection) = selections.peek() {
15527 if next_selection.start.row <= end_row.0 {
15528 end_row = ending_row(next_selection, display_map);
15529 contiguous_row_selections.push(selections.next().unwrap().clone());
15530 } else {
15531 break;
15532 }
15533 }
15534 (start_row, end_row)
15535}
15536
15537fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15538 if next_selection.end.column > 0 || next_selection.is_empty() {
15539 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15540 } else {
15541 MultiBufferRow(next_selection.end.row)
15542 }
15543}
15544
15545impl EditorSnapshot {
15546 pub fn remote_selections_in_range<'a>(
15547 &'a self,
15548 range: &'a Range<Anchor>,
15549 collaboration_hub: &dyn CollaborationHub,
15550 cx: &'a App,
15551 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15552 let participant_names = collaboration_hub.user_names(cx);
15553 let participant_indices = collaboration_hub.user_participant_indices(cx);
15554 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15555 let collaborators_by_replica_id = collaborators_by_peer_id
15556 .iter()
15557 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15558 .collect::<HashMap<_, _>>();
15559 self.buffer_snapshot
15560 .selections_in_range(range, false)
15561 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15562 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15563 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15564 let user_name = participant_names.get(&collaborator.user_id).cloned();
15565 Some(RemoteSelection {
15566 replica_id,
15567 selection,
15568 cursor_shape,
15569 line_mode,
15570 participant_index,
15571 peer_id: collaborator.peer_id,
15572 user_name,
15573 })
15574 })
15575 }
15576
15577 pub fn hunks_for_ranges(
15578 &self,
15579 ranges: impl Iterator<Item = Range<Point>>,
15580 ) -> Vec<MultiBufferDiffHunk> {
15581 let mut hunks = Vec::new();
15582 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15583 HashMap::default();
15584 for query_range in ranges {
15585 let query_rows =
15586 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15587 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15588 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15589 ) {
15590 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15591 // when the caret is just above or just below the deleted hunk.
15592 let allow_adjacent = hunk.status().is_removed();
15593 let related_to_selection = if allow_adjacent {
15594 hunk.row_range.overlaps(&query_rows)
15595 || hunk.row_range.start == query_rows.end
15596 || hunk.row_range.end == query_rows.start
15597 } else {
15598 hunk.row_range.overlaps(&query_rows)
15599 };
15600 if related_to_selection {
15601 if !processed_buffer_rows
15602 .entry(hunk.buffer_id)
15603 .or_default()
15604 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15605 {
15606 continue;
15607 }
15608 hunks.push(hunk);
15609 }
15610 }
15611 }
15612
15613 hunks
15614 }
15615
15616 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15617 self.display_snapshot.buffer_snapshot.language_at(position)
15618 }
15619
15620 pub fn is_focused(&self) -> bool {
15621 self.is_focused
15622 }
15623
15624 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15625 self.placeholder_text.as_ref()
15626 }
15627
15628 pub fn scroll_position(&self) -> gpui::Point<f32> {
15629 self.scroll_anchor.scroll_position(&self.display_snapshot)
15630 }
15631
15632 fn gutter_dimensions(
15633 &self,
15634 font_id: FontId,
15635 font_size: Pixels,
15636 max_line_number_width: Pixels,
15637 cx: &App,
15638 ) -> Option<GutterDimensions> {
15639 if !self.show_gutter {
15640 return None;
15641 }
15642
15643 let descent = cx.text_system().descent(font_id, font_size);
15644 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15645 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15646
15647 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15648 matches!(
15649 ProjectSettings::get_global(cx).git.git_gutter,
15650 Some(GitGutterSetting::TrackedFiles)
15651 )
15652 });
15653 let gutter_settings = EditorSettings::get_global(cx).gutter;
15654 let show_line_numbers = self
15655 .show_line_numbers
15656 .unwrap_or(gutter_settings.line_numbers);
15657 let line_gutter_width = if show_line_numbers {
15658 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15659 let min_width_for_number_on_gutter = em_advance * 4.0;
15660 max_line_number_width.max(min_width_for_number_on_gutter)
15661 } else {
15662 0.0.into()
15663 };
15664
15665 let show_code_actions = self
15666 .show_code_actions
15667 .unwrap_or(gutter_settings.code_actions);
15668
15669 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15670
15671 let git_blame_entries_width =
15672 self.git_blame_gutter_max_author_length
15673 .map(|max_author_length| {
15674 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15675
15676 /// The number of characters to dedicate to gaps and margins.
15677 const SPACING_WIDTH: usize = 4;
15678
15679 let max_char_count = max_author_length
15680 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15681 + ::git::SHORT_SHA_LENGTH
15682 + MAX_RELATIVE_TIMESTAMP.len()
15683 + SPACING_WIDTH;
15684
15685 em_advance * max_char_count
15686 });
15687
15688 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15689 left_padding += if show_code_actions || show_runnables {
15690 em_width * 3.0
15691 } else if show_git_gutter && show_line_numbers {
15692 em_width * 2.0
15693 } else if show_git_gutter || show_line_numbers {
15694 em_width
15695 } else {
15696 px(0.)
15697 };
15698
15699 let right_padding = if gutter_settings.folds && show_line_numbers {
15700 em_width * 4.0
15701 } else if gutter_settings.folds {
15702 em_width * 3.0
15703 } else if show_line_numbers {
15704 em_width
15705 } else {
15706 px(0.)
15707 };
15708
15709 Some(GutterDimensions {
15710 left_padding,
15711 right_padding,
15712 width: line_gutter_width + left_padding + right_padding,
15713 margin: -descent,
15714 git_blame_entries_width,
15715 })
15716 }
15717
15718 pub fn render_crease_toggle(
15719 &self,
15720 buffer_row: MultiBufferRow,
15721 row_contains_cursor: bool,
15722 editor: Entity<Editor>,
15723 window: &mut Window,
15724 cx: &mut App,
15725 ) -> Option<AnyElement> {
15726 let folded = self.is_line_folded(buffer_row);
15727 let mut is_foldable = false;
15728
15729 if let Some(crease) = self
15730 .crease_snapshot
15731 .query_row(buffer_row, &self.buffer_snapshot)
15732 {
15733 is_foldable = true;
15734 match crease {
15735 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15736 if let Some(render_toggle) = render_toggle {
15737 let toggle_callback =
15738 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15739 if folded {
15740 editor.update(cx, |editor, cx| {
15741 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15742 });
15743 } else {
15744 editor.update(cx, |editor, cx| {
15745 editor.unfold_at(
15746 &crate::UnfoldAt { buffer_row },
15747 window,
15748 cx,
15749 )
15750 });
15751 }
15752 });
15753 return Some((render_toggle)(
15754 buffer_row,
15755 folded,
15756 toggle_callback,
15757 window,
15758 cx,
15759 ));
15760 }
15761 }
15762 }
15763 }
15764
15765 is_foldable |= self.starts_indent(buffer_row);
15766
15767 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15768 Some(
15769 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15770 .toggle_state(folded)
15771 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15772 if folded {
15773 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15774 } else {
15775 this.fold_at(&FoldAt { buffer_row }, window, cx);
15776 }
15777 }))
15778 .into_any_element(),
15779 )
15780 } else {
15781 None
15782 }
15783 }
15784
15785 pub fn render_crease_trailer(
15786 &self,
15787 buffer_row: MultiBufferRow,
15788 window: &mut Window,
15789 cx: &mut App,
15790 ) -> Option<AnyElement> {
15791 let folded = self.is_line_folded(buffer_row);
15792 if let Crease::Inline { render_trailer, .. } = self
15793 .crease_snapshot
15794 .query_row(buffer_row, &self.buffer_snapshot)?
15795 {
15796 let render_trailer = render_trailer.as_ref()?;
15797 Some(render_trailer(buffer_row, folded, window, cx))
15798 } else {
15799 None
15800 }
15801 }
15802}
15803
15804impl Deref for EditorSnapshot {
15805 type Target = DisplaySnapshot;
15806
15807 fn deref(&self) -> &Self::Target {
15808 &self.display_snapshot
15809 }
15810}
15811
15812#[derive(Clone, Debug, PartialEq, Eq)]
15813pub enum EditorEvent {
15814 InputIgnored {
15815 text: Arc<str>,
15816 },
15817 InputHandled {
15818 utf16_range_to_replace: Option<Range<isize>>,
15819 text: Arc<str>,
15820 },
15821 ExcerptsAdded {
15822 buffer: Entity<Buffer>,
15823 predecessor: ExcerptId,
15824 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15825 },
15826 ExcerptsRemoved {
15827 ids: Vec<ExcerptId>,
15828 },
15829 BufferFoldToggled {
15830 ids: Vec<ExcerptId>,
15831 folded: bool,
15832 },
15833 ExcerptsEdited {
15834 ids: Vec<ExcerptId>,
15835 },
15836 ExcerptsExpanded {
15837 ids: Vec<ExcerptId>,
15838 },
15839 BufferEdited,
15840 Edited {
15841 transaction_id: clock::Lamport,
15842 },
15843 Reparsed(BufferId),
15844 Focused,
15845 FocusedIn,
15846 Blurred,
15847 DirtyChanged,
15848 Saved,
15849 TitleChanged,
15850 DiffBaseChanged,
15851 SelectionsChanged {
15852 local: bool,
15853 },
15854 ScrollPositionChanged {
15855 local: bool,
15856 autoscroll: bool,
15857 },
15858 Closed,
15859 TransactionUndone {
15860 transaction_id: clock::Lamport,
15861 },
15862 TransactionBegun {
15863 transaction_id: clock::Lamport,
15864 },
15865 Reloaded,
15866 CursorShapeChanged,
15867}
15868
15869impl EventEmitter<EditorEvent> for Editor {}
15870
15871impl Focusable for Editor {
15872 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15873 self.focus_handle.clone()
15874 }
15875}
15876
15877impl Render for Editor {
15878 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15879 let settings = ThemeSettings::get_global(cx);
15880
15881 let mut text_style = match self.mode {
15882 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15883 color: cx.theme().colors().editor_foreground,
15884 font_family: settings.ui_font.family.clone(),
15885 font_features: settings.ui_font.features.clone(),
15886 font_fallbacks: settings.ui_font.fallbacks.clone(),
15887 font_size: rems(0.875).into(),
15888 font_weight: settings.ui_font.weight,
15889 line_height: relative(settings.buffer_line_height.value()),
15890 ..Default::default()
15891 },
15892 EditorMode::Full => TextStyle {
15893 color: cx.theme().colors().editor_foreground,
15894 font_family: settings.buffer_font.family.clone(),
15895 font_features: settings.buffer_font.features.clone(),
15896 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15897 font_size: settings.buffer_font_size().into(),
15898 font_weight: settings.buffer_font.weight,
15899 line_height: relative(settings.buffer_line_height.value()),
15900 ..Default::default()
15901 },
15902 };
15903 if let Some(text_style_refinement) = &self.text_style_refinement {
15904 text_style.refine(text_style_refinement)
15905 }
15906
15907 let background = match self.mode {
15908 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15909 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15910 EditorMode::Full => cx.theme().colors().editor_background,
15911 };
15912
15913 EditorElement::new(
15914 &cx.entity(),
15915 EditorStyle {
15916 background,
15917 local_player: cx.theme().players().local(),
15918 text: text_style,
15919 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15920 syntax: cx.theme().syntax().clone(),
15921 status: cx.theme().status().clone(),
15922 inlay_hints_style: make_inlay_hints_style(cx),
15923 inline_completion_styles: make_suggestion_styles(cx),
15924 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15925 },
15926 )
15927 }
15928}
15929
15930impl EntityInputHandler for Editor {
15931 fn text_for_range(
15932 &mut self,
15933 range_utf16: Range<usize>,
15934 adjusted_range: &mut Option<Range<usize>>,
15935 _: &mut Window,
15936 cx: &mut Context<Self>,
15937 ) -> Option<String> {
15938 let snapshot = self.buffer.read(cx).read(cx);
15939 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15940 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15941 if (start.0..end.0) != range_utf16 {
15942 adjusted_range.replace(start.0..end.0);
15943 }
15944 Some(snapshot.text_for_range(start..end).collect())
15945 }
15946
15947 fn selected_text_range(
15948 &mut self,
15949 ignore_disabled_input: bool,
15950 _: &mut Window,
15951 cx: &mut Context<Self>,
15952 ) -> Option<UTF16Selection> {
15953 // Prevent the IME menu from appearing when holding down an alphabetic key
15954 // while input is disabled.
15955 if !ignore_disabled_input && !self.input_enabled {
15956 return None;
15957 }
15958
15959 let selection = self.selections.newest::<OffsetUtf16>(cx);
15960 let range = selection.range();
15961
15962 Some(UTF16Selection {
15963 range: range.start.0..range.end.0,
15964 reversed: selection.reversed,
15965 })
15966 }
15967
15968 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15969 let snapshot = self.buffer.read(cx).read(cx);
15970 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15971 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15972 }
15973
15974 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15975 self.clear_highlights::<InputComposition>(cx);
15976 self.ime_transaction.take();
15977 }
15978
15979 fn replace_text_in_range(
15980 &mut self,
15981 range_utf16: Option<Range<usize>>,
15982 text: &str,
15983 window: &mut Window,
15984 cx: &mut Context<Self>,
15985 ) {
15986 if !self.input_enabled {
15987 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15988 return;
15989 }
15990
15991 self.transact(window, cx, |this, window, cx| {
15992 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15993 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15994 Some(this.selection_replacement_ranges(range_utf16, cx))
15995 } else {
15996 this.marked_text_ranges(cx)
15997 };
15998
15999 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16000 let newest_selection_id = this.selections.newest_anchor().id;
16001 this.selections
16002 .all::<OffsetUtf16>(cx)
16003 .iter()
16004 .zip(ranges_to_replace.iter())
16005 .find_map(|(selection, range)| {
16006 if selection.id == newest_selection_id {
16007 Some(
16008 (range.start.0 as isize - selection.head().0 as isize)
16009 ..(range.end.0 as isize - selection.head().0 as isize),
16010 )
16011 } else {
16012 None
16013 }
16014 })
16015 });
16016
16017 cx.emit(EditorEvent::InputHandled {
16018 utf16_range_to_replace: range_to_replace,
16019 text: text.into(),
16020 });
16021
16022 if let Some(new_selected_ranges) = new_selected_ranges {
16023 this.change_selections(None, window, cx, |selections| {
16024 selections.select_ranges(new_selected_ranges)
16025 });
16026 this.backspace(&Default::default(), window, cx);
16027 }
16028
16029 this.handle_input(text, window, cx);
16030 });
16031
16032 if let Some(transaction) = self.ime_transaction {
16033 self.buffer.update(cx, |buffer, cx| {
16034 buffer.group_until_transaction(transaction, cx);
16035 });
16036 }
16037
16038 self.unmark_text(window, cx);
16039 }
16040
16041 fn replace_and_mark_text_in_range(
16042 &mut self,
16043 range_utf16: Option<Range<usize>>,
16044 text: &str,
16045 new_selected_range_utf16: Option<Range<usize>>,
16046 window: &mut Window,
16047 cx: &mut Context<Self>,
16048 ) {
16049 if !self.input_enabled {
16050 return;
16051 }
16052
16053 let transaction = self.transact(window, cx, |this, window, cx| {
16054 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16055 let snapshot = this.buffer.read(cx).read(cx);
16056 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16057 for marked_range in &mut marked_ranges {
16058 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16059 marked_range.start.0 += relative_range_utf16.start;
16060 marked_range.start =
16061 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16062 marked_range.end =
16063 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16064 }
16065 }
16066 Some(marked_ranges)
16067 } else if let Some(range_utf16) = range_utf16 {
16068 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16069 Some(this.selection_replacement_ranges(range_utf16, cx))
16070 } else {
16071 None
16072 };
16073
16074 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16075 let newest_selection_id = this.selections.newest_anchor().id;
16076 this.selections
16077 .all::<OffsetUtf16>(cx)
16078 .iter()
16079 .zip(ranges_to_replace.iter())
16080 .find_map(|(selection, range)| {
16081 if selection.id == newest_selection_id {
16082 Some(
16083 (range.start.0 as isize - selection.head().0 as isize)
16084 ..(range.end.0 as isize - selection.head().0 as isize),
16085 )
16086 } else {
16087 None
16088 }
16089 })
16090 });
16091
16092 cx.emit(EditorEvent::InputHandled {
16093 utf16_range_to_replace: range_to_replace,
16094 text: text.into(),
16095 });
16096
16097 if let Some(ranges) = ranges_to_replace {
16098 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16099 }
16100
16101 let marked_ranges = {
16102 let snapshot = this.buffer.read(cx).read(cx);
16103 this.selections
16104 .disjoint_anchors()
16105 .iter()
16106 .map(|selection| {
16107 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16108 })
16109 .collect::<Vec<_>>()
16110 };
16111
16112 if text.is_empty() {
16113 this.unmark_text(window, cx);
16114 } else {
16115 this.highlight_text::<InputComposition>(
16116 marked_ranges.clone(),
16117 HighlightStyle {
16118 underline: Some(UnderlineStyle {
16119 thickness: px(1.),
16120 color: None,
16121 wavy: false,
16122 }),
16123 ..Default::default()
16124 },
16125 cx,
16126 );
16127 }
16128
16129 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16130 let use_autoclose = this.use_autoclose;
16131 let use_auto_surround = this.use_auto_surround;
16132 this.set_use_autoclose(false);
16133 this.set_use_auto_surround(false);
16134 this.handle_input(text, window, cx);
16135 this.set_use_autoclose(use_autoclose);
16136 this.set_use_auto_surround(use_auto_surround);
16137
16138 if let Some(new_selected_range) = new_selected_range_utf16 {
16139 let snapshot = this.buffer.read(cx).read(cx);
16140 let new_selected_ranges = marked_ranges
16141 .into_iter()
16142 .map(|marked_range| {
16143 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16144 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16145 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16146 snapshot.clip_offset_utf16(new_start, Bias::Left)
16147 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16148 })
16149 .collect::<Vec<_>>();
16150
16151 drop(snapshot);
16152 this.change_selections(None, window, cx, |selections| {
16153 selections.select_ranges(new_selected_ranges)
16154 });
16155 }
16156 });
16157
16158 self.ime_transaction = self.ime_transaction.or(transaction);
16159 if let Some(transaction) = self.ime_transaction {
16160 self.buffer.update(cx, |buffer, cx| {
16161 buffer.group_until_transaction(transaction, cx);
16162 });
16163 }
16164
16165 if self.text_highlights::<InputComposition>(cx).is_none() {
16166 self.ime_transaction.take();
16167 }
16168 }
16169
16170 fn bounds_for_range(
16171 &mut self,
16172 range_utf16: Range<usize>,
16173 element_bounds: gpui::Bounds<Pixels>,
16174 window: &mut Window,
16175 cx: &mut Context<Self>,
16176 ) -> Option<gpui::Bounds<Pixels>> {
16177 let text_layout_details = self.text_layout_details(window);
16178 let gpui::Size {
16179 width: em_width,
16180 height: line_height,
16181 } = self.character_size(window);
16182
16183 let snapshot = self.snapshot(window, cx);
16184 let scroll_position = snapshot.scroll_position();
16185 let scroll_left = scroll_position.x * em_width;
16186
16187 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16188 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16189 + self.gutter_dimensions.width
16190 + self.gutter_dimensions.margin;
16191 let y = line_height * (start.row().as_f32() - scroll_position.y);
16192
16193 Some(Bounds {
16194 origin: element_bounds.origin + point(x, y),
16195 size: size(em_width, line_height),
16196 })
16197 }
16198
16199 fn character_index_for_point(
16200 &mut self,
16201 point: gpui::Point<Pixels>,
16202 _window: &mut Window,
16203 _cx: &mut Context<Self>,
16204 ) -> Option<usize> {
16205 let position_map = self.last_position_map.as_ref()?;
16206 if !position_map.text_hitbox.contains(&point) {
16207 return None;
16208 }
16209 let display_point = position_map.point_for_position(point).previous_valid;
16210 let anchor = position_map
16211 .snapshot
16212 .display_point_to_anchor(display_point, Bias::Left);
16213 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16214 Some(utf16_offset.0)
16215 }
16216}
16217
16218trait SelectionExt {
16219 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16220 fn spanned_rows(
16221 &self,
16222 include_end_if_at_line_start: bool,
16223 map: &DisplaySnapshot,
16224 ) -> Range<MultiBufferRow>;
16225}
16226
16227impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16228 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16229 let start = self
16230 .start
16231 .to_point(&map.buffer_snapshot)
16232 .to_display_point(map);
16233 let end = self
16234 .end
16235 .to_point(&map.buffer_snapshot)
16236 .to_display_point(map);
16237 if self.reversed {
16238 end..start
16239 } else {
16240 start..end
16241 }
16242 }
16243
16244 fn spanned_rows(
16245 &self,
16246 include_end_if_at_line_start: bool,
16247 map: &DisplaySnapshot,
16248 ) -> Range<MultiBufferRow> {
16249 let start = self.start.to_point(&map.buffer_snapshot);
16250 let mut end = self.end.to_point(&map.buffer_snapshot);
16251 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16252 end.row -= 1;
16253 }
16254
16255 let buffer_start = map.prev_line_boundary(start).0;
16256 let buffer_end = map.next_line_boundary(end).0;
16257 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16258 }
16259}
16260
16261impl<T: InvalidationRegion> InvalidationStack<T> {
16262 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16263 where
16264 S: Clone + ToOffset,
16265 {
16266 while let Some(region) = self.last() {
16267 let all_selections_inside_invalidation_ranges =
16268 if selections.len() == region.ranges().len() {
16269 selections
16270 .iter()
16271 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16272 .all(|(selection, invalidation_range)| {
16273 let head = selection.head().to_offset(buffer);
16274 invalidation_range.start <= head && invalidation_range.end >= head
16275 })
16276 } else {
16277 false
16278 };
16279
16280 if all_selections_inside_invalidation_ranges {
16281 break;
16282 } else {
16283 self.pop();
16284 }
16285 }
16286 }
16287}
16288
16289impl<T> Default for InvalidationStack<T> {
16290 fn default() -> Self {
16291 Self(Default::default())
16292 }
16293}
16294
16295impl<T> Deref for InvalidationStack<T> {
16296 type Target = Vec<T>;
16297
16298 fn deref(&self) -> &Self::Target {
16299 &self.0
16300 }
16301}
16302
16303impl<T> DerefMut for InvalidationStack<T> {
16304 fn deref_mut(&mut self) -> &mut Self::Target {
16305 &mut self.0
16306 }
16307}
16308
16309impl InvalidationRegion for SnippetState {
16310 fn ranges(&self) -> &[Range<Anchor>] {
16311 &self.ranges[self.active_index]
16312 }
16313}
16314
16315pub fn diagnostic_block_renderer(
16316 diagnostic: Diagnostic,
16317 max_message_rows: Option<u8>,
16318 allow_closing: bool,
16319 _is_valid: bool,
16320) -> RenderBlock {
16321 let (text_without_backticks, code_ranges) =
16322 highlight_diagnostic_message(&diagnostic, max_message_rows);
16323
16324 Arc::new(move |cx: &mut BlockContext| {
16325 let group_id: SharedString = cx.block_id.to_string().into();
16326
16327 let mut text_style = cx.window.text_style().clone();
16328 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16329 let theme_settings = ThemeSettings::get_global(cx);
16330 text_style.font_family = theme_settings.buffer_font.family.clone();
16331 text_style.font_style = theme_settings.buffer_font.style;
16332 text_style.font_features = theme_settings.buffer_font.features.clone();
16333 text_style.font_weight = theme_settings.buffer_font.weight;
16334
16335 let multi_line_diagnostic = diagnostic.message.contains('\n');
16336
16337 let buttons = |diagnostic: &Diagnostic| {
16338 if multi_line_diagnostic {
16339 v_flex()
16340 } else {
16341 h_flex()
16342 }
16343 .when(allow_closing, |div| {
16344 div.children(diagnostic.is_primary.then(|| {
16345 IconButton::new("close-block", IconName::XCircle)
16346 .icon_color(Color::Muted)
16347 .size(ButtonSize::Compact)
16348 .style(ButtonStyle::Transparent)
16349 .visible_on_hover(group_id.clone())
16350 .on_click(move |_click, window, cx| {
16351 window.dispatch_action(Box::new(Cancel), cx)
16352 })
16353 .tooltip(|window, cx| {
16354 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16355 })
16356 }))
16357 })
16358 .child(
16359 IconButton::new("copy-block", IconName::Copy)
16360 .icon_color(Color::Muted)
16361 .size(ButtonSize::Compact)
16362 .style(ButtonStyle::Transparent)
16363 .visible_on_hover(group_id.clone())
16364 .on_click({
16365 let message = diagnostic.message.clone();
16366 move |_click, _, cx| {
16367 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16368 }
16369 })
16370 .tooltip(Tooltip::text("Copy diagnostic message")),
16371 )
16372 };
16373
16374 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16375 AvailableSpace::min_size(),
16376 cx.window,
16377 cx.app,
16378 );
16379
16380 h_flex()
16381 .id(cx.block_id)
16382 .group(group_id.clone())
16383 .relative()
16384 .size_full()
16385 .block_mouse_down()
16386 .pl(cx.gutter_dimensions.width)
16387 .w(cx.max_width - cx.gutter_dimensions.full_width())
16388 .child(
16389 div()
16390 .flex()
16391 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16392 .flex_shrink(),
16393 )
16394 .child(buttons(&diagnostic))
16395 .child(div().flex().flex_shrink_0().child(
16396 StyledText::new(text_without_backticks.clone()).with_highlights(
16397 &text_style,
16398 code_ranges.iter().map(|range| {
16399 (
16400 range.clone(),
16401 HighlightStyle {
16402 font_weight: Some(FontWeight::BOLD),
16403 ..Default::default()
16404 },
16405 )
16406 }),
16407 ),
16408 ))
16409 .into_any_element()
16410 })
16411}
16412
16413fn inline_completion_edit_text(
16414 current_snapshot: &BufferSnapshot,
16415 edits: &[(Range<Anchor>, String)],
16416 edit_preview: &EditPreview,
16417 include_deletions: bool,
16418 cx: &App,
16419) -> HighlightedText {
16420 let edits = edits
16421 .iter()
16422 .map(|(anchor, text)| {
16423 (
16424 anchor.start.text_anchor..anchor.end.text_anchor,
16425 text.clone(),
16426 )
16427 })
16428 .collect::<Vec<_>>();
16429
16430 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16431}
16432
16433pub fn highlight_diagnostic_message(
16434 diagnostic: &Diagnostic,
16435 mut max_message_rows: Option<u8>,
16436) -> (SharedString, Vec<Range<usize>>) {
16437 let mut text_without_backticks = String::new();
16438 let mut code_ranges = Vec::new();
16439
16440 if let Some(source) = &diagnostic.source {
16441 text_without_backticks.push_str(source);
16442 code_ranges.push(0..source.len());
16443 text_without_backticks.push_str(": ");
16444 }
16445
16446 let mut prev_offset = 0;
16447 let mut in_code_block = false;
16448 let has_row_limit = max_message_rows.is_some();
16449 let mut newline_indices = diagnostic
16450 .message
16451 .match_indices('\n')
16452 .filter(|_| has_row_limit)
16453 .map(|(ix, _)| ix)
16454 .fuse()
16455 .peekable();
16456
16457 for (quote_ix, _) in diagnostic
16458 .message
16459 .match_indices('`')
16460 .chain([(diagnostic.message.len(), "")])
16461 {
16462 let mut first_newline_ix = None;
16463 let mut last_newline_ix = None;
16464 while let Some(newline_ix) = newline_indices.peek() {
16465 if *newline_ix < quote_ix {
16466 if first_newline_ix.is_none() {
16467 first_newline_ix = Some(*newline_ix);
16468 }
16469 last_newline_ix = Some(*newline_ix);
16470
16471 if let Some(rows_left) = &mut max_message_rows {
16472 if *rows_left == 0 {
16473 break;
16474 } else {
16475 *rows_left -= 1;
16476 }
16477 }
16478 let _ = newline_indices.next();
16479 } else {
16480 break;
16481 }
16482 }
16483 let prev_len = text_without_backticks.len();
16484 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16485 text_without_backticks.push_str(new_text);
16486 if in_code_block {
16487 code_ranges.push(prev_len..text_without_backticks.len());
16488 }
16489 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16490 in_code_block = !in_code_block;
16491 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16492 text_without_backticks.push_str("...");
16493 break;
16494 }
16495 }
16496
16497 (text_without_backticks.into(), code_ranges)
16498}
16499
16500fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16501 match severity {
16502 DiagnosticSeverity::ERROR => colors.error,
16503 DiagnosticSeverity::WARNING => colors.warning,
16504 DiagnosticSeverity::INFORMATION => colors.info,
16505 DiagnosticSeverity::HINT => colors.info,
16506 _ => colors.ignored,
16507 }
16508}
16509
16510pub fn styled_runs_for_code_label<'a>(
16511 label: &'a CodeLabel,
16512 syntax_theme: &'a theme::SyntaxTheme,
16513) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16514 let fade_out = HighlightStyle {
16515 fade_out: Some(0.35),
16516 ..Default::default()
16517 };
16518
16519 let mut prev_end = label.filter_range.end;
16520 label
16521 .runs
16522 .iter()
16523 .enumerate()
16524 .flat_map(move |(ix, (range, highlight_id))| {
16525 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16526 style
16527 } else {
16528 return Default::default();
16529 };
16530 let mut muted_style = style;
16531 muted_style.highlight(fade_out);
16532
16533 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16534 if range.start >= label.filter_range.end {
16535 if range.start > prev_end {
16536 runs.push((prev_end..range.start, fade_out));
16537 }
16538 runs.push((range.clone(), muted_style));
16539 } else if range.end <= label.filter_range.end {
16540 runs.push((range.clone(), style));
16541 } else {
16542 runs.push((range.start..label.filter_range.end, style));
16543 runs.push((label.filter_range.end..range.end, muted_style));
16544 }
16545 prev_end = cmp::max(prev_end, range.end);
16546
16547 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16548 runs.push((prev_end..label.text.len(), fade_out));
16549 }
16550
16551 runs
16552 })
16553}
16554
16555pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16556 let mut prev_index = 0;
16557 let mut prev_codepoint: Option<char> = None;
16558 text.char_indices()
16559 .chain([(text.len(), '\0')])
16560 .filter_map(move |(index, codepoint)| {
16561 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16562 let is_boundary = index == text.len()
16563 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16564 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16565 if is_boundary {
16566 let chunk = &text[prev_index..index];
16567 prev_index = index;
16568 Some(chunk)
16569 } else {
16570 None
16571 }
16572 })
16573}
16574
16575pub trait RangeToAnchorExt: Sized {
16576 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16577
16578 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16579 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16580 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16581 }
16582}
16583
16584impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16585 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16586 let start_offset = self.start.to_offset(snapshot);
16587 let end_offset = self.end.to_offset(snapshot);
16588 if start_offset == end_offset {
16589 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16590 } else {
16591 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16592 }
16593 }
16594}
16595
16596pub trait RowExt {
16597 fn as_f32(&self) -> f32;
16598
16599 fn next_row(&self) -> Self;
16600
16601 fn previous_row(&self) -> Self;
16602
16603 fn minus(&self, other: Self) -> u32;
16604}
16605
16606impl RowExt for DisplayRow {
16607 fn as_f32(&self) -> f32 {
16608 self.0 as f32
16609 }
16610
16611 fn next_row(&self) -> Self {
16612 Self(self.0 + 1)
16613 }
16614
16615 fn previous_row(&self) -> Self {
16616 Self(self.0.saturating_sub(1))
16617 }
16618
16619 fn minus(&self, other: Self) -> u32 {
16620 self.0 - other.0
16621 }
16622}
16623
16624impl RowExt for MultiBufferRow {
16625 fn as_f32(&self) -> f32 {
16626 self.0 as f32
16627 }
16628
16629 fn next_row(&self) -> Self {
16630 Self(self.0 + 1)
16631 }
16632
16633 fn previous_row(&self) -> Self {
16634 Self(self.0.saturating_sub(1))
16635 }
16636
16637 fn minus(&self, other: Self) -> u32 {
16638 self.0 - other.0
16639 }
16640}
16641
16642trait RowRangeExt {
16643 type Row;
16644
16645 fn len(&self) -> usize;
16646
16647 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16648}
16649
16650impl RowRangeExt for Range<MultiBufferRow> {
16651 type Row = MultiBufferRow;
16652
16653 fn len(&self) -> usize {
16654 (self.end.0 - self.start.0) as usize
16655 }
16656
16657 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16658 (self.start.0..self.end.0).map(MultiBufferRow)
16659 }
16660}
16661
16662impl RowRangeExt for Range<DisplayRow> {
16663 type Row = DisplayRow;
16664
16665 fn len(&self) -> usize {
16666 (self.end.0 - self.start.0) as usize
16667 }
16668
16669 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16670 (self.start.0..self.end.0).map(DisplayRow)
16671 }
16672}
16673
16674/// If select range has more than one line, we
16675/// just point the cursor to range.start.
16676fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16677 if range.start.row == range.end.row {
16678 range
16679 } else {
16680 range.start..range.start
16681 }
16682}
16683pub struct KillRing(ClipboardItem);
16684impl Global for KillRing {}
16685
16686const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16687
16688fn all_edits_insertions_or_deletions(
16689 edits: &Vec<(Range<Anchor>, String)>,
16690 snapshot: &MultiBufferSnapshot,
16691) -> bool {
16692 let mut all_insertions = true;
16693 let mut all_deletions = true;
16694
16695 for (range, new_text) in edits.iter() {
16696 let range_is_empty = range.to_offset(&snapshot).is_empty();
16697 let text_is_empty = new_text.is_empty();
16698
16699 if range_is_empty != text_is_empty {
16700 if range_is_empty {
16701 all_deletions = false;
16702 } else {
16703 all_insertions = false;
16704 }
16705 } else {
16706 return false;
16707 }
16708
16709 if !all_insertions && !all_deletions {
16710 return false;
16711 }
16712 }
16713 all_insertions || all_deletions
16714}