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
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72use zed_predict_tos::ZedPredictTos;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91use indent_guides::ActiveIndentGuidesState;
92use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
93pub use inline_completion::Direction;
94use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
95pub use items::MAX_TAB_TITLE_LEN;
96use itertools::Itertools;
97use language::{
98 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
99 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
100 CursorShape, Diagnostic, Documentation, EditPreview, HighlightedEdits, IndentKind, IndentSize,
101 Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId,
102 TreeSitterOptions,
103};
104use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
105use linked_editing_ranges::refresh_linked_ranges;
106use mouse_context_menu::MouseContextMenu;
107pub use proposed_changes_editor::{
108 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
109};
110use similar::{ChangeTag, TextDiff};
111use std::iter::Peekable;
112use task::{ResolvedTask, TaskTemplate, TaskVariables};
113
114use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
115pub use lsp::CompletionContext;
116use lsp::{
117 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
118 LanguageServerId, LanguageServerName,
119};
120
121use language::BufferSnapshot;
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
125 ToOffset, ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::{find_url, find_url_from_range};
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakView<Workspace>>,
198 cx: &mut WindowContext,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(link_ranges, move |clicked_range_ix, cx| {
243 match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace.open_abs_path(path.clone(), false, cx).detach();
249 });
250 }
251 }
252 }
253 })
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
257pub enum InlayId {
258 InlineCompletion(usize),
259 Hint(usize),
260}
261
262impl InlayId {
263 fn id(&self) -> usize {
264 match self {
265 Self::InlineCompletion(id) => *id,
266 Self::Hint(id) => *id,
267 }
268 }
269}
270
271enum DocumentHighlightRead {}
272enum DocumentHighlightWrite {}
273enum InputComposition {}
274
275#[derive(Debug, Copy, Clone, PartialEq, Eq)]
276pub enum Navigated {
277 Yes,
278 No,
279}
280
281impl Navigated {
282 pub fn from_bool(yes: bool) -> Navigated {
283 if yes {
284 Navigated::Yes
285 } else {
286 Navigated::No
287 }
288 }
289}
290
291pub fn init_settings(cx: &mut AppContext) {
292 EditorSettings::register(cx);
293}
294
295pub fn init(cx: &mut AppContext) {
296 init_settings(cx);
297
298 workspace::register_project_item::<Editor>(cx);
299 workspace::FollowableViewRegistry::register::<Editor>(cx);
300 workspace::register_serializable_item::<Editor>(cx);
301
302 cx.observe_new_views(
303 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
304 workspace.register_action(Editor::new_file);
305 workspace.register_action(Editor::new_file_vertical);
306 workspace.register_action(Editor::new_file_horizontal);
307 },
308 )
309 .detach();
310
311 cx.on_action(move |_: &workspace::NewFile, cx| {
312 let app_state = workspace::AppState::global(cx);
313 if let Some(app_state) = app_state.upgrade() {
314 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
315 Editor::new_file(workspace, &Default::default(), cx)
316 })
317 .detach();
318 }
319 });
320 cx.on_action(move |_: &workspace::NewWindow, cx| {
321 let app_state = workspace::AppState::global(cx);
322 if let Some(app_state) = app_state.upgrade() {
323 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
324 Editor::new_file(workspace, &Default::default(), cx)
325 })
326 .detach();
327 }
328 });
329 git::project_diff::init(cx);
330}
331
332pub struct SearchWithinRange;
333
334trait InvalidationRegion {
335 fn ranges(&self) -> &[Range<Anchor>];
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub enum SelectPhase {
340 Begin {
341 position: DisplayPoint,
342 add: bool,
343 click_count: usize,
344 },
345 BeginColumnar {
346 position: DisplayPoint,
347 reset: bool,
348 goal_column: u32,
349 },
350 Extend {
351 position: DisplayPoint,
352 click_count: usize,
353 },
354 Update {
355 position: DisplayPoint,
356 goal_column: u32,
357 scroll_delta: gpui::Point<f32>,
358 },
359 End,
360}
361
362#[derive(Clone, Debug)]
363pub enum SelectMode {
364 Character,
365 Word(Range<Anchor>),
366 Line(Range<Anchor>),
367 All,
368}
369
370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
371pub enum EditorMode {
372 SingleLine { auto_width: bool },
373 AutoHeight { max_lines: usize },
374 Full,
375}
376
377#[derive(Copy, Clone, Debug)]
378pub enum SoftWrap {
379 /// Prefer not to wrap at all.
380 ///
381 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
382 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
383 GitDiff,
384 /// Prefer a single line generally, unless an overly long line is encountered.
385 None,
386 /// Soft wrap lines that exceed the editor width.
387 EditorWidth,
388 /// Soft wrap lines at the preferred line length.
389 Column(u32),
390 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
391 Bounded(u32),
392}
393
394#[derive(Clone)]
395pub struct EditorStyle {
396 pub background: Hsla,
397 pub local_player: PlayerColor,
398 pub text: TextStyle,
399 pub scrollbar_width: Pixels,
400 pub syntax: Arc<SyntaxTheme>,
401 pub status: StatusColors,
402 pub inlay_hints_style: HighlightStyle,
403 pub inline_completion_styles: InlineCompletionStyles,
404 pub unnecessary_code_fade: f32,
405}
406
407impl Default for EditorStyle {
408 fn default() -> Self {
409 Self {
410 background: Hsla::default(),
411 local_player: PlayerColor::default(),
412 text: TextStyle::default(),
413 scrollbar_width: Pixels::default(),
414 syntax: Default::default(),
415 // HACK: Status colors don't have a real default.
416 // We should look into removing the status colors from the editor
417 // style and retrieve them directly from the theme.
418 status: StatusColors::dark(),
419 inlay_hints_style: HighlightStyle::default(),
420 inline_completion_styles: InlineCompletionStyles {
421 insertion: HighlightStyle::default(),
422 whitespace: HighlightStyle::default(),
423 },
424 unnecessary_code_fade: Default::default(),
425 }
426 }
427}
428
429pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
430 let show_background = language_settings::language_settings(None, None, cx)
431 .inlay_hints
432 .show_background;
433
434 HighlightStyle {
435 color: Some(cx.theme().status().hint),
436 background_color: show_background.then(|| cx.theme().status().hint_background),
437 ..HighlightStyle::default()
438 }
439}
440
441pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
442 InlineCompletionStyles {
443 insertion: HighlightStyle {
444 color: Some(cx.theme().status().predictive),
445 ..HighlightStyle::default()
446 },
447 whitespace: HighlightStyle {
448 background_color: Some(cx.theme().status().created_background),
449 ..HighlightStyle::default()
450 },
451 }
452}
453
454type CompletionId = usize;
455
456#[derive(Debug, Clone)]
457enum InlineCompletionMenuHint {
458 Loading,
459 Loaded { text: InlineCompletionText },
460 PendingTermsAcceptance,
461 None,
462}
463
464impl InlineCompletionMenuHint {
465 pub fn label(&self) -> &'static str {
466 match self {
467 InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
468 "Edit Prediction"
469 }
470 InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
471 InlineCompletionMenuHint::None => "No Prediction",
472 }
473 }
474}
475
476#[derive(Clone, Debug)]
477enum InlineCompletionText {
478 Move(SharedString),
479 Edit(HighlightedEdits),
480}
481
482pub(crate) enum EditDisplayMode {
483 TabAccept,
484 DiffPopover,
485 Inline,
486}
487
488enum InlineCompletion {
489 Edit {
490 edits: Vec<(Range<Anchor>, String)>,
491 edit_preview: Option<EditPreview>,
492 display_mode: EditDisplayMode,
493 snapshot: BufferSnapshot,
494 },
495 Move(Anchor),
496}
497
498struct InlineCompletionState {
499 inlay_ids: Vec<InlayId>,
500 completion: InlineCompletion,
501 invalidation_range: Range<Anchor>,
502}
503
504enum InlineCompletionHighlight {}
505
506pub enum MenuInlineCompletionsPolicy {
507 Never,
508 ByProvider,
509}
510
511#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
512struct EditorActionId(usize);
513
514impl EditorActionId {
515 pub fn post_inc(&mut self) -> Self {
516 let answer = self.0;
517
518 *self = Self(answer + 1);
519
520 Self(answer)
521 }
522}
523
524// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
525// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
526
527type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
528type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
529
530#[derive(Default)]
531struct ScrollbarMarkerState {
532 scrollbar_size: Size<Pixels>,
533 dirty: bool,
534 markers: Arc<[PaintQuad]>,
535 pending_refresh: Option<Task<Result<()>>>,
536}
537
538impl ScrollbarMarkerState {
539 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
540 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
541 }
542}
543
544#[derive(Clone, Debug)]
545struct RunnableTasks {
546 templates: Vec<(TaskSourceKind, TaskTemplate)>,
547 offset: MultiBufferOffset,
548 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
549 column: u32,
550 // Values of all named captures, including those starting with '_'
551 extra_variables: HashMap<String, String>,
552 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
553 context_range: Range<BufferOffset>,
554}
555
556impl RunnableTasks {
557 fn resolve<'a>(
558 &'a self,
559 cx: &'a task::TaskContext,
560 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
561 self.templates.iter().filter_map(|(kind, template)| {
562 template
563 .resolve_task(&kind.to_id_base(), cx)
564 .map(|task| (kind.clone(), task))
565 })
566 }
567}
568
569#[derive(Clone)]
570struct ResolvedTasks {
571 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
572 position: Anchor,
573}
574#[derive(Copy, Clone, Debug)]
575struct MultiBufferOffset(usize);
576#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
577struct BufferOffset(usize);
578
579// Addons allow storing per-editor state in other crates (e.g. Vim)
580pub trait Addon: 'static {
581 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
582
583 fn to_any(&self) -> &dyn std::any::Any;
584}
585
586#[derive(Debug, Copy, Clone, PartialEq, Eq)]
587pub enum IsVimMode {
588 Yes,
589 No,
590}
591
592/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
593///
594/// See the [module level documentation](self) for more information.
595pub struct Editor {
596 focus_handle: FocusHandle,
597 last_focused_descendant: Option<WeakFocusHandle>,
598 /// The text buffer being edited
599 buffer: Model<MultiBuffer>,
600 /// Map of how text in the buffer should be displayed.
601 /// Handles soft wraps, folds, fake inlay text insertions, etc.
602 pub display_map: Model<DisplayMap>,
603 pub selections: SelectionsCollection,
604 pub scroll_manager: ScrollManager,
605 /// When inline assist editors are linked, they all render cursors because
606 /// typing enters text into each of them, even the ones that aren't focused.
607 pub(crate) show_cursor_when_unfocused: bool,
608 columnar_selection_tail: Option<Anchor>,
609 add_selections_state: Option<AddSelectionsState>,
610 select_next_state: Option<SelectNextState>,
611 select_prev_state: Option<SelectNextState>,
612 selection_history: SelectionHistory,
613 autoclose_regions: Vec<AutocloseRegion>,
614 snippet_stack: InvalidationStack<SnippetState>,
615 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
616 ime_transaction: Option<TransactionId>,
617 active_diagnostics: Option<ActiveDiagnosticGroup>,
618 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
619
620 project: Option<Model<Project>>,
621 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
622 completion_provider: Option<Box<dyn CompletionProvider>>,
623 collaboration_hub: Option<Box<dyn CollaborationHub>>,
624 blink_manager: Model<BlinkManager>,
625 show_cursor_names: bool,
626 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
627 pub show_local_selections: bool,
628 mode: EditorMode,
629 show_breadcrumbs: bool,
630 show_gutter: bool,
631 show_scrollbars: bool,
632 show_line_numbers: Option<bool>,
633 use_relative_line_numbers: Option<bool>,
634 show_git_diff_gutter: Option<bool>,
635 show_code_actions: Option<bool>,
636 show_runnables: Option<bool>,
637 show_wrap_guides: Option<bool>,
638 show_indent_guides: Option<bool>,
639 placeholder_text: Option<Arc<str>>,
640 highlight_order: usize,
641 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
642 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
643 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
644 scrollbar_marker_state: ScrollbarMarkerState,
645 active_indent_guides_state: ActiveIndentGuidesState,
646 nav_history: Option<ItemNavHistory>,
647 context_menu: RefCell<Option<CodeContextMenu>>,
648 mouse_context_menu: Option<MouseContextMenu>,
649 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
650 signature_help_state: SignatureHelpState,
651 auto_signature_help: Option<bool>,
652 find_all_references_task_sources: Vec<Anchor>,
653 next_completion_id: CompletionId,
654 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
655 code_actions_task: Option<Task<Result<()>>>,
656 document_highlights_task: Option<Task<()>>,
657 linked_editing_range_task: Option<Task<Option<()>>>,
658 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
659 pending_rename: Option<RenameState>,
660 searchable: bool,
661 cursor_shape: CursorShape,
662 current_line_highlight: Option<CurrentLineHighlight>,
663 collapse_matches: bool,
664 autoindent_mode: Option<AutoindentMode>,
665 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
666 input_enabled: bool,
667 use_modal_editing: bool,
668 read_only: bool,
669 leader_peer_id: Option<PeerId>,
670 remote_id: Option<ViewId>,
671 hover_state: HoverState,
672 gutter_hovered: bool,
673 hovered_link_state: Option<HoveredLinkState>,
674 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
675 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
676 active_inline_completion: Option<InlineCompletionState>,
677 // enable_inline_completions is a switch that Vim can use to disable
678 // inline completions based on its mode.
679 enable_inline_completions: bool,
680 show_inline_completions_override: Option<bool>,
681 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
682 inlay_hint_cache: InlayHintCache,
683 next_inlay_id: usize,
684 _subscriptions: Vec<Subscription>,
685 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
686 gutter_dimensions: GutterDimensions,
687 style: Option<EditorStyle>,
688 text_style_refinement: Option<TextStyleRefinement>,
689 next_editor_action_id: EditorActionId,
690 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
691 use_autoclose: bool,
692 use_auto_surround: bool,
693 auto_replace_emoji_shortcode: bool,
694 show_git_blame_gutter: bool,
695 show_git_blame_inline: bool,
696 show_git_blame_inline_delay_task: Option<Task<()>>,
697 git_blame_inline_enabled: bool,
698 serialize_dirty_buffers: bool,
699 show_selection_menu: Option<bool>,
700 blame: Option<Model<GitBlame>>,
701 blame_subscription: Option<Subscription>,
702 custom_context_menu: Option<
703 Box<
704 dyn 'static
705 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
706 >,
707 >,
708 last_bounds: Option<Bounds<Pixels>>,
709 expect_bounds_change: Option<Bounds<Pixels>>,
710 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
711 tasks_update_task: Option<Task<()>>,
712 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
713 breadcrumb_header: Option<String>,
714 focused_block: Option<FocusedBlock>,
715 next_scroll_position: NextScrollCursorCenterTopBottom,
716 addons: HashMap<TypeId, Box<dyn Addon>>,
717 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
718 selection_mark_mode: bool,
719 toggle_fold_multiple_buffers: Task<()>,
720 _scroll_cursor_center_top_bottom_task: Task<()>,
721}
722
723#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
724enum NextScrollCursorCenterTopBottom {
725 #[default]
726 Center,
727 Top,
728 Bottom,
729}
730
731impl NextScrollCursorCenterTopBottom {
732 fn next(&self) -> Self {
733 match self {
734 Self::Center => Self::Top,
735 Self::Top => Self::Bottom,
736 Self::Bottom => Self::Center,
737 }
738 }
739}
740
741#[derive(Clone)]
742pub struct EditorSnapshot {
743 pub mode: EditorMode,
744 show_gutter: bool,
745 show_line_numbers: Option<bool>,
746 show_git_diff_gutter: Option<bool>,
747 show_code_actions: Option<bool>,
748 show_runnables: Option<bool>,
749 git_blame_gutter_max_author_length: Option<usize>,
750 pub display_snapshot: DisplaySnapshot,
751 pub placeholder_text: Option<Arc<str>>,
752 is_focused: bool,
753 scroll_anchor: ScrollAnchor,
754 ongoing_scroll: OngoingScroll,
755 current_line_highlight: CurrentLineHighlight,
756 gutter_hovered: bool,
757}
758
759const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
760
761#[derive(Default, Debug, Clone, Copy)]
762pub struct GutterDimensions {
763 pub left_padding: Pixels,
764 pub right_padding: Pixels,
765 pub width: Pixels,
766 pub margin: Pixels,
767 pub git_blame_entries_width: Option<Pixels>,
768}
769
770impl GutterDimensions {
771 /// The full width of the space taken up by the gutter.
772 pub fn full_width(&self) -> Pixels {
773 self.margin + self.width
774 }
775
776 /// The width of the space reserved for the fold indicators,
777 /// use alongside 'justify_end' and `gutter_width` to
778 /// right align content with the line numbers
779 pub fn fold_area_width(&self) -> Pixels {
780 self.margin + self.right_padding
781 }
782}
783
784#[derive(Debug)]
785pub struct RemoteSelection {
786 pub replica_id: ReplicaId,
787 pub selection: Selection<Anchor>,
788 pub cursor_shape: CursorShape,
789 pub peer_id: PeerId,
790 pub line_mode: bool,
791 pub participant_index: Option<ParticipantIndex>,
792 pub user_name: Option<SharedString>,
793}
794
795#[derive(Clone, Debug)]
796struct SelectionHistoryEntry {
797 selections: Arc<[Selection<Anchor>]>,
798 select_next_state: Option<SelectNextState>,
799 select_prev_state: Option<SelectNextState>,
800 add_selections_state: Option<AddSelectionsState>,
801}
802
803enum SelectionHistoryMode {
804 Normal,
805 Undoing,
806 Redoing,
807}
808
809#[derive(Clone, PartialEq, Eq, Hash)]
810struct HoveredCursor {
811 replica_id: u16,
812 selection_id: usize,
813}
814
815impl Default for SelectionHistoryMode {
816 fn default() -> Self {
817 Self::Normal
818 }
819}
820
821#[derive(Default)]
822struct SelectionHistory {
823 #[allow(clippy::type_complexity)]
824 selections_by_transaction:
825 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
826 mode: SelectionHistoryMode,
827 undo_stack: VecDeque<SelectionHistoryEntry>,
828 redo_stack: VecDeque<SelectionHistoryEntry>,
829}
830
831impl SelectionHistory {
832 fn insert_transaction(
833 &mut self,
834 transaction_id: TransactionId,
835 selections: Arc<[Selection<Anchor>]>,
836 ) {
837 self.selections_by_transaction
838 .insert(transaction_id, (selections, None));
839 }
840
841 #[allow(clippy::type_complexity)]
842 fn transaction(
843 &self,
844 transaction_id: TransactionId,
845 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
846 self.selections_by_transaction.get(&transaction_id)
847 }
848
849 #[allow(clippy::type_complexity)]
850 fn transaction_mut(
851 &mut self,
852 transaction_id: TransactionId,
853 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
854 self.selections_by_transaction.get_mut(&transaction_id)
855 }
856
857 fn push(&mut self, entry: SelectionHistoryEntry) {
858 if !entry.selections.is_empty() {
859 match self.mode {
860 SelectionHistoryMode::Normal => {
861 self.push_undo(entry);
862 self.redo_stack.clear();
863 }
864 SelectionHistoryMode::Undoing => self.push_redo(entry),
865 SelectionHistoryMode::Redoing => self.push_undo(entry),
866 }
867 }
868 }
869
870 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
871 if self
872 .undo_stack
873 .back()
874 .map_or(true, |e| e.selections != entry.selections)
875 {
876 self.undo_stack.push_back(entry);
877 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
878 self.undo_stack.pop_front();
879 }
880 }
881 }
882
883 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
884 if self
885 .redo_stack
886 .back()
887 .map_or(true, |e| e.selections != entry.selections)
888 {
889 self.redo_stack.push_back(entry);
890 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
891 self.redo_stack.pop_front();
892 }
893 }
894 }
895}
896
897struct RowHighlight {
898 index: usize,
899 range: Range<Anchor>,
900 color: Hsla,
901 should_autoscroll: bool,
902}
903
904#[derive(Clone, Debug)]
905struct AddSelectionsState {
906 above: bool,
907 stack: Vec<usize>,
908}
909
910#[derive(Clone)]
911struct SelectNextState {
912 query: AhoCorasick,
913 wordwise: bool,
914 done: bool,
915}
916
917impl std::fmt::Debug for SelectNextState {
918 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
919 f.debug_struct(std::any::type_name::<Self>())
920 .field("wordwise", &self.wordwise)
921 .field("done", &self.done)
922 .finish()
923 }
924}
925
926#[derive(Debug)]
927struct AutocloseRegion {
928 selection_id: usize,
929 range: Range<Anchor>,
930 pair: BracketPair,
931}
932
933#[derive(Debug)]
934struct SnippetState {
935 ranges: Vec<Vec<Range<Anchor>>>,
936 active_index: usize,
937 choices: Vec<Option<Vec<String>>>,
938}
939
940#[doc(hidden)]
941pub struct RenameState {
942 pub range: Range<Anchor>,
943 pub old_name: Arc<str>,
944 pub editor: View<Editor>,
945 block_id: CustomBlockId,
946}
947
948struct InvalidationStack<T>(Vec<T>);
949
950struct RegisteredInlineCompletionProvider {
951 provider: Arc<dyn InlineCompletionProviderHandle>,
952 _subscription: Subscription,
953}
954
955#[derive(Debug)]
956struct ActiveDiagnosticGroup {
957 primary_range: Range<Anchor>,
958 primary_message: String,
959 group_id: usize,
960 blocks: HashMap<CustomBlockId, Diagnostic>,
961 is_valid: bool,
962}
963
964#[derive(Serialize, Deserialize, Clone, Debug)]
965pub struct ClipboardSelection {
966 pub len: usize,
967 pub is_entire_line: bool,
968 pub first_line_indent: u32,
969}
970
971#[derive(Debug)]
972pub(crate) struct NavigationData {
973 cursor_anchor: Anchor,
974 cursor_position: Point,
975 scroll_anchor: ScrollAnchor,
976 scroll_top_row: u32,
977}
978
979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub enum GotoDefinitionKind {
981 Symbol,
982 Declaration,
983 Type,
984 Implementation,
985}
986
987#[derive(Debug, Clone)]
988enum InlayHintRefreshReason {
989 Toggle(bool),
990 SettingsChange(InlayHintSettings),
991 NewLinesShown,
992 BufferEdited(HashSet<Arc<Language>>),
993 RefreshRequested,
994 ExcerptsRemoved(Vec<ExcerptId>),
995}
996
997impl InlayHintRefreshReason {
998 fn description(&self) -> &'static str {
999 match self {
1000 Self::Toggle(_) => "toggle",
1001 Self::SettingsChange(_) => "settings change",
1002 Self::NewLinesShown => "new lines shown",
1003 Self::BufferEdited(_) => "buffer edited",
1004 Self::RefreshRequested => "refresh requested",
1005 Self::ExcerptsRemoved(_) => "excerpts removed",
1006 }
1007 }
1008}
1009
1010pub enum FormatTarget {
1011 Buffers,
1012 Ranges(Vec<Range<MultiBufferPoint>>),
1013}
1014
1015pub(crate) struct FocusedBlock {
1016 id: BlockId,
1017 focus_handle: WeakFocusHandle,
1018}
1019
1020#[derive(Clone)]
1021enum JumpData {
1022 MultiBufferRow {
1023 row: MultiBufferRow,
1024 line_offset_from_top: u32,
1025 },
1026 MultiBufferPoint {
1027 excerpt_id: ExcerptId,
1028 position: Point,
1029 anchor: text::Anchor,
1030 line_offset_from_top: u32,
1031 },
1032}
1033
1034impl Editor {
1035 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1036 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1037 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1038 Self::new(
1039 EditorMode::SingleLine { auto_width: false },
1040 buffer,
1041 None,
1042 false,
1043 cx,
1044 )
1045 }
1046
1047 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1048 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1049 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1050 Self::new(EditorMode::Full, buffer, None, false, cx)
1051 }
1052
1053 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1054 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1055 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1056 Self::new(
1057 EditorMode::SingleLine { auto_width: true },
1058 buffer,
1059 None,
1060 false,
1061 cx,
1062 )
1063 }
1064
1065 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1066 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1067 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1068 Self::new(
1069 EditorMode::AutoHeight { max_lines },
1070 buffer,
1071 None,
1072 false,
1073 cx,
1074 )
1075 }
1076
1077 pub fn for_buffer(
1078 buffer: Model<Buffer>,
1079 project: Option<Model<Project>>,
1080 cx: &mut ViewContext<Self>,
1081 ) -> Self {
1082 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1083 Self::new(EditorMode::Full, buffer, project, false, cx)
1084 }
1085
1086 pub fn for_multibuffer(
1087 buffer: Model<MultiBuffer>,
1088 project: Option<Model<Project>>,
1089 show_excerpt_controls: bool,
1090 cx: &mut ViewContext<Self>,
1091 ) -> Self {
1092 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1093 }
1094
1095 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1096 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1097 let mut clone = Self::new(
1098 self.mode,
1099 self.buffer.clone(),
1100 self.project.clone(),
1101 show_excerpt_controls,
1102 cx,
1103 );
1104 self.display_map.update(cx, |display_map, cx| {
1105 let snapshot = display_map.snapshot(cx);
1106 clone.display_map.update(cx, |display_map, cx| {
1107 display_map.set_state(&snapshot, cx);
1108 });
1109 });
1110 clone.selections.clone_state(&self.selections);
1111 clone.scroll_manager.clone_state(&self.scroll_manager);
1112 clone.searchable = self.searchable;
1113 clone
1114 }
1115
1116 pub fn new(
1117 mode: EditorMode,
1118 buffer: Model<MultiBuffer>,
1119 project: Option<Model<Project>>,
1120 show_excerpt_controls: bool,
1121 cx: &mut ViewContext<Self>,
1122 ) -> Self {
1123 let style = cx.text_style();
1124 let font_size = style.font_size.to_pixels(cx.rem_size());
1125 let editor = cx.view().downgrade();
1126 let fold_placeholder = FoldPlaceholder {
1127 constrain_width: true,
1128 render: Arc::new(move |fold_id, fold_range, cx| {
1129 let editor = editor.clone();
1130 div()
1131 .id(fold_id)
1132 .bg(cx.theme().colors().ghost_element_background)
1133 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1134 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1135 .rounded_sm()
1136 .size_full()
1137 .cursor_pointer()
1138 .child("⋯")
1139 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1140 .on_click(move |_, cx| {
1141 editor
1142 .update(cx, |editor, cx| {
1143 editor.unfold_ranges(
1144 &[fold_range.start..fold_range.end],
1145 true,
1146 false,
1147 cx,
1148 );
1149 cx.stop_propagation();
1150 })
1151 .ok();
1152 })
1153 .into_any()
1154 }),
1155 merge_adjacent: true,
1156 ..Default::default()
1157 };
1158 let display_map = cx.new_model(|cx| {
1159 DisplayMap::new(
1160 buffer.clone(),
1161 style.font(),
1162 font_size,
1163 None,
1164 show_excerpt_controls,
1165 FILE_HEADER_HEIGHT,
1166 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1167 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1168 fold_placeholder,
1169 cx,
1170 )
1171 });
1172
1173 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1174
1175 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1176
1177 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1178 .then(|| language_settings::SoftWrap::None);
1179
1180 let mut project_subscriptions = Vec::new();
1181 if mode == EditorMode::Full {
1182 if let Some(project) = project.as_ref() {
1183 if buffer.read(cx).is_singleton() {
1184 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1185 cx.emit(EditorEvent::TitleChanged);
1186 }));
1187 }
1188 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1189 if let project::Event::RefreshInlayHints = event {
1190 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1191 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1192 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1193 let focus_handle = editor.focus_handle(cx);
1194 if focus_handle.is_focused(cx) {
1195 let snapshot = buffer.read(cx).snapshot();
1196 for (range, snippet) in snippet_edits {
1197 let editor_range =
1198 language::range_from_lsp(*range).to_offset(&snapshot);
1199 editor
1200 .insert_snippet(&[editor_range], snippet.clone(), cx)
1201 .ok();
1202 }
1203 }
1204 }
1205 }
1206 }));
1207 if let Some(task_inventory) = project
1208 .read(cx)
1209 .task_store()
1210 .read(cx)
1211 .task_inventory()
1212 .cloned()
1213 {
1214 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1215 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1216 }));
1217 }
1218 }
1219 }
1220
1221 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1222
1223 let inlay_hint_settings =
1224 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1225 let focus_handle = cx.focus_handle();
1226 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1227 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1228 .detach();
1229 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1230 .detach();
1231 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1232
1233 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1234 Some(false)
1235 } else {
1236 None
1237 };
1238
1239 let mut code_action_providers = Vec::new();
1240 if let Some(project) = project.clone() {
1241 get_unstaged_changes_for_buffers(
1242 &project,
1243 buffer.read(cx).all_buffers(),
1244 buffer.clone(),
1245 cx,
1246 );
1247 code_action_providers.push(Rc::new(project) as Rc<_>);
1248 }
1249
1250 let mut this = Self {
1251 focus_handle,
1252 show_cursor_when_unfocused: false,
1253 last_focused_descendant: None,
1254 buffer: buffer.clone(),
1255 display_map: display_map.clone(),
1256 selections,
1257 scroll_manager: ScrollManager::new(cx),
1258 columnar_selection_tail: None,
1259 add_selections_state: None,
1260 select_next_state: None,
1261 select_prev_state: None,
1262 selection_history: Default::default(),
1263 autoclose_regions: Default::default(),
1264 snippet_stack: Default::default(),
1265 select_larger_syntax_node_stack: Vec::new(),
1266 ime_transaction: Default::default(),
1267 active_diagnostics: None,
1268 soft_wrap_mode_override,
1269 completion_provider: project.clone().map(|project| Box::new(project) as _),
1270 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1271 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1272 project,
1273 blink_manager: blink_manager.clone(),
1274 show_local_selections: true,
1275 show_scrollbars: true,
1276 mode,
1277 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1278 show_gutter: mode == EditorMode::Full,
1279 show_line_numbers: None,
1280 use_relative_line_numbers: None,
1281 show_git_diff_gutter: None,
1282 show_code_actions: None,
1283 show_runnables: None,
1284 show_wrap_guides: None,
1285 show_indent_guides,
1286 placeholder_text: None,
1287 highlight_order: 0,
1288 highlighted_rows: HashMap::default(),
1289 background_highlights: Default::default(),
1290 gutter_highlights: TreeMap::default(),
1291 scrollbar_marker_state: ScrollbarMarkerState::default(),
1292 active_indent_guides_state: ActiveIndentGuidesState::default(),
1293 nav_history: None,
1294 context_menu: RefCell::new(None),
1295 mouse_context_menu: None,
1296 completion_tasks: Default::default(),
1297 signature_help_state: SignatureHelpState::default(),
1298 auto_signature_help: None,
1299 find_all_references_task_sources: Vec::new(),
1300 next_completion_id: 0,
1301 next_inlay_id: 0,
1302 code_action_providers,
1303 available_code_actions: Default::default(),
1304 code_actions_task: Default::default(),
1305 document_highlights_task: Default::default(),
1306 linked_editing_range_task: Default::default(),
1307 pending_rename: Default::default(),
1308 searchable: true,
1309 cursor_shape: EditorSettings::get_global(cx)
1310 .cursor_shape
1311 .unwrap_or_default(),
1312 current_line_highlight: None,
1313 autoindent_mode: Some(AutoindentMode::EachLine),
1314 collapse_matches: false,
1315 workspace: None,
1316 input_enabled: true,
1317 use_modal_editing: mode == EditorMode::Full,
1318 read_only: false,
1319 use_autoclose: true,
1320 use_auto_surround: true,
1321 auto_replace_emoji_shortcode: false,
1322 leader_peer_id: None,
1323 remote_id: None,
1324 hover_state: Default::default(),
1325 hovered_link_state: Default::default(),
1326 inline_completion_provider: None,
1327 active_inline_completion: None,
1328 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1329
1330 gutter_hovered: false,
1331 pixel_position_of_newest_cursor: None,
1332 last_bounds: None,
1333 expect_bounds_change: None,
1334 gutter_dimensions: GutterDimensions::default(),
1335 style: None,
1336 show_cursor_names: false,
1337 hovered_cursors: Default::default(),
1338 next_editor_action_id: EditorActionId::default(),
1339 editor_actions: Rc::default(),
1340 show_inline_completions_override: None,
1341 enable_inline_completions: true,
1342 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1343 custom_context_menu: None,
1344 show_git_blame_gutter: false,
1345 show_git_blame_inline: false,
1346 show_selection_menu: None,
1347 show_git_blame_inline_delay_task: None,
1348 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1349 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1350 .session
1351 .restore_unsaved_buffers,
1352 blame: None,
1353 blame_subscription: None,
1354 tasks: Default::default(),
1355 _subscriptions: vec![
1356 cx.observe(&buffer, Self::on_buffer_changed),
1357 cx.subscribe(&buffer, Self::on_buffer_event),
1358 cx.observe(&display_map, Self::on_display_map_changed),
1359 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1360 cx.observe_global::<SettingsStore>(Self::settings_changed),
1361 cx.observe_window_activation(|editor, cx| {
1362 let active = cx.is_window_active();
1363 editor.blink_manager.update(cx, |blink_manager, cx| {
1364 if active {
1365 blink_manager.enable(cx);
1366 } else {
1367 blink_manager.disable(cx);
1368 }
1369 });
1370 }),
1371 ],
1372 tasks_update_task: None,
1373 linked_edit_ranges: Default::default(),
1374 previous_search_ranges: None,
1375 breadcrumb_header: None,
1376 focused_block: None,
1377 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1378 addons: HashMap::default(),
1379 registered_buffers: HashMap::default(),
1380 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1381 selection_mark_mode: false,
1382 toggle_fold_multiple_buffers: Task::ready(()),
1383 text_style_refinement: None,
1384 };
1385 this.tasks_update_task = Some(this.refresh_runnables(cx));
1386 this._subscriptions.extend(project_subscriptions);
1387
1388 this.end_selection(cx);
1389 this.scroll_manager.show_scrollbar(cx);
1390
1391 if mode == EditorMode::Full {
1392 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1393 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1394
1395 if this.git_blame_inline_enabled {
1396 this.git_blame_inline_enabled = true;
1397 this.start_git_blame_inline(false, cx);
1398 }
1399
1400 if let Some(buffer) = buffer.read(cx).as_singleton() {
1401 if let Some(project) = this.project.as_ref() {
1402 let lsp_store = project.read(cx).lsp_store();
1403 let handle = lsp_store.update(cx, |lsp_store, cx| {
1404 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1405 });
1406 this.registered_buffers
1407 .insert(buffer.read(cx).remote_id(), handle);
1408 }
1409 }
1410 }
1411
1412 this.report_editor_event("Editor Opened", None, cx);
1413 this
1414 }
1415
1416 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1417 self.mouse_context_menu
1418 .as_ref()
1419 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1420 }
1421
1422 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1423 let mut key_context = KeyContext::new_with_defaults();
1424 key_context.add("Editor");
1425 let mode = match self.mode {
1426 EditorMode::SingleLine { .. } => "single_line",
1427 EditorMode::AutoHeight { .. } => "auto_height",
1428 EditorMode::Full => "full",
1429 };
1430
1431 if EditorSettings::jupyter_enabled(cx) {
1432 key_context.add("jupyter");
1433 }
1434
1435 key_context.set("mode", mode);
1436 if self.pending_rename.is_some() {
1437 key_context.add("renaming");
1438 }
1439 match self.context_menu.borrow().as_ref() {
1440 Some(CodeContextMenu::Completions(_)) => {
1441 key_context.add("menu");
1442 key_context.add("showing_completions")
1443 }
1444 Some(CodeContextMenu::CodeActions(_)) => {
1445 key_context.add("menu");
1446 key_context.add("showing_code_actions")
1447 }
1448 None => {}
1449 }
1450
1451 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1452 if !self.focus_handle(cx).contains_focused(cx)
1453 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1454 {
1455 for addon in self.addons.values() {
1456 addon.extend_key_context(&mut key_context, cx)
1457 }
1458 }
1459
1460 if let Some(extension) = self
1461 .buffer
1462 .read(cx)
1463 .as_singleton()
1464 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1465 {
1466 key_context.set("extension", extension.to_string());
1467 }
1468
1469 if self.has_active_inline_completion() {
1470 key_context.add("copilot_suggestion");
1471 key_context.add("inline_completion");
1472 }
1473
1474 if self.selection_mark_mode {
1475 key_context.add("selection_mode");
1476 }
1477
1478 key_context
1479 }
1480
1481 pub fn new_file(
1482 workspace: &mut Workspace,
1483 _: &workspace::NewFile,
1484 cx: &mut ViewContext<Workspace>,
1485 ) {
1486 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1487 "Failed to create buffer",
1488 cx,
1489 |e, _| match e.error_code() {
1490 ErrorCode::RemoteUpgradeRequired => Some(format!(
1491 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1492 e.error_tag("required").unwrap_or("the latest version")
1493 )),
1494 _ => None,
1495 },
1496 );
1497 }
1498
1499 pub fn new_in_workspace(
1500 workspace: &mut Workspace,
1501 cx: &mut ViewContext<Workspace>,
1502 ) -> Task<Result<View<Editor>>> {
1503 let project = workspace.project().clone();
1504 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1505
1506 cx.spawn(|workspace, mut cx| async move {
1507 let buffer = create.await?;
1508 workspace.update(&mut cx, |workspace, cx| {
1509 let editor =
1510 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1511 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1512 editor
1513 })
1514 })
1515 }
1516
1517 fn new_file_vertical(
1518 workspace: &mut Workspace,
1519 _: &workspace::NewFileSplitVertical,
1520 cx: &mut ViewContext<Workspace>,
1521 ) {
1522 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1523 }
1524
1525 fn new_file_horizontal(
1526 workspace: &mut Workspace,
1527 _: &workspace::NewFileSplitHorizontal,
1528 cx: &mut ViewContext<Workspace>,
1529 ) {
1530 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1531 }
1532
1533 fn new_file_in_direction(
1534 workspace: &mut Workspace,
1535 direction: SplitDirection,
1536 cx: &mut ViewContext<Workspace>,
1537 ) {
1538 let project = workspace.project().clone();
1539 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1540
1541 cx.spawn(|workspace, mut cx| async move {
1542 let buffer = create.await?;
1543 workspace.update(&mut cx, move |workspace, cx| {
1544 workspace.split_item(
1545 direction,
1546 Box::new(
1547 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1548 ),
1549 cx,
1550 )
1551 })?;
1552 anyhow::Ok(())
1553 })
1554 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1555 ErrorCode::RemoteUpgradeRequired => Some(format!(
1556 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1557 e.error_tag("required").unwrap_or("the latest version")
1558 )),
1559 _ => None,
1560 });
1561 }
1562
1563 pub fn leader_peer_id(&self) -> Option<PeerId> {
1564 self.leader_peer_id
1565 }
1566
1567 pub fn buffer(&self) -> &Model<MultiBuffer> {
1568 &self.buffer
1569 }
1570
1571 pub fn workspace(&self) -> Option<View<Workspace>> {
1572 self.workspace.as_ref()?.0.upgrade()
1573 }
1574
1575 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1576 self.buffer().read(cx).title(cx)
1577 }
1578
1579 pub fn snapshot(&self, cx: &mut WindowContext) -> EditorSnapshot {
1580 let git_blame_gutter_max_author_length = self
1581 .render_git_blame_gutter(cx)
1582 .then(|| {
1583 if let Some(blame) = self.blame.as_ref() {
1584 let max_author_length =
1585 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1586 Some(max_author_length)
1587 } else {
1588 None
1589 }
1590 })
1591 .flatten();
1592
1593 EditorSnapshot {
1594 mode: self.mode,
1595 show_gutter: self.show_gutter,
1596 show_line_numbers: self.show_line_numbers,
1597 show_git_diff_gutter: self.show_git_diff_gutter,
1598 show_code_actions: self.show_code_actions,
1599 show_runnables: self.show_runnables,
1600 git_blame_gutter_max_author_length,
1601 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1602 scroll_anchor: self.scroll_manager.anchor(),
1603 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1604 placeholder_text: self.placeholder_text.clone(),
1605 is_focused: self.focus_handle.is_focused(cx),
1606 current_line_highlight: self
1607 .current_line_highlight
1608 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1609 gutter_hovered: self.gutter_hovered,
1610 }
1611 }
1612
1613 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1614 self.buffer.read(cx).language_at(point, cx)
1615 }
1616
1617 pub fn file_at<T: ToOffset>(
1618 &self,
1619 point: T,
1620 cx: &AppContext,
1621 ) -> Option<Arc<dyn language::File>> {
1622 self.buffer.read(cx).read(cx).file_at(point).cloned()
1623 }
1624
1625 pub fn active_excerpt(
1626 &self,
1627 cx: &AppContext,
1628 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1629 self.buffer
1630 .read(cx)
1631 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1632 }
1633
1634 pub fn mode(&self) -> EditorMode {
1635 self.mode
1636 }
1637
1638 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1639 self.collaboration_hub.as_deref()
1640 }
1641
1642 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1643 self.collaboration_hub = Some(hub);
1644 }
1645
1646 pub fn set_custom_context_menu(
1647 &mut self,
1648 f: impl 'static
1649 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1650 ) {
1651 self.custom_context_menu = Some(Box::new(f))
1652 }
1653
1654 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1655 self.completion_provider = provider;
1656 }
1657
1658 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1659 self.semantics_provider.clone()
1660 }
1661
1662 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1663 self.semantics_provider = provider;
1664 }
1665
1666 pub fn set_inline_completion_provider<T>(
1667 &mut self,
1668 provider: Option<Model<T>>,
1669 cx: &mut ViewContext<Self>,
1670 ) where
1671 T: InlineCompletionProvider,
1672 {
1673 self.inline_completion_provider =
1674 provider.map(|provider| RegisteredInlineCompletionProvider {
1675 _subscription: cx.observe(&provider, |this, _, cx| {
1676 if this.focus_handle.is_focused(cx) {
1677 this.update_visible_inline_completion(cx);
1678 }
1679 }),
1680 provider: Arc::new(provider),
1681 });
1682 self.refresh_inline_completion(false, false, cx);
1683 }
1684
1685 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1686 self.placeholder_text.as_deref()
1687 }
1688
1689 pub fn set_placeholder_text(
1690 &mut self,
1691 placeholder_text: impl Into<Arc<str>>,
1692 cx: &mut ViewContext<Self>,
1693 ) {
1694 let placeholder_text = Some(placeholder_text.into());
1695 if self.placeholder_text != placeholder_text {
1696 self.placeholder_text = placeholder_text;
1697 cx.notify();
1698 }
1699 }
1700
1701 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1702 self.cursor_shape = cursor_shape;
1703
1704 // Disrupt blink for immediate user feedback that the cursor shape has changed
1705 self.blink_manager.update(cx, BlinkManager::show_cursor);
1706
1707 cx.notify();
1708 }
1709
1710 pub fn set_current_line_highlight(
1711 &mut self,
1712 current_line_highlight: Option<CurrentLineHighlight>,
1713 ) {
1714 self.current_line_highlight = current_line_highlight;
1715 }
1716
1717 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1718 self.collapse_matches = collapse_matches;
1719 }
1720
1721 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1722 let buffers = self.buffer.read(cx).all_buffers();
1723 let Some(lsp_store) = self.lsp_store(cx) else {
1724 return;
1725 };
1726 lsp_store.update(cx, |lsp_store, cx| {
1727 for buffer in buffers {
1728 self.registered_buffers
1729 .entry(buffer.read(cx).remote_id())
1730 .or_insert_with(|| {
1731 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1732 });
1733 }
1734 })
1735 }
1736
1737 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1738 if self.collapse_matches {
1739 return range.start..range.start;
1740 }
1741 range.clone()
1742 }
1743
1744 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1745 if self.display_map.read(cx).clip_at_line_ends != clip {
1746 self.display_map
1747 .update(cx, |map, _| map.clip_at_line_ends = clip);
1748 }
1749 }
1750
1751 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1752 self.input_enabled = input_enabled;
1753 }
1754
1755 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1756 self.enable_inline_completions = enabled;
1757 if !self.enable_inline_completions {
1758 self.take_active_inline_completion(cx);
1759 cx.notify();
1760 }
1761 }
1762
1763 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1764 self.menu_inline_completions_policy = value;
1765 }
1766
1767 pub fn set_autoindent(&mut self, autoindent: bool) {
1768 if autoindent {
1769 self.autoindent_mode = Some(AutoindentMode::EachLine);
1770 } else {
1771 self.autoindent_mode = None;
1772 }
1773 }
1774
1775 pub fn read_only(&self, cx: &AppContext) -> bool {
1776 self.read_only || self.buffer.read(cx).read_only()
1777 }
1778
1779 pub fn set_read_only(&mut self, read_only: bool) {
1780 self.read_only = read_only;
1781 }
1782
1783 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1784 self.use_autoclose = autoclose;
1785 }
1786
1787 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1788 self.use_auto_surround = auto_surround;
1789 }
1790
1791 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1792 self.auto_replace_emoji_shortcode = auto_replace;
1793 }
1794
1795 pub fn toggle_inline_completions(
1796 &mut self,
1797 _: &ToggleInlineCompletions,
1798 cx: &mut ViewContext<Self>,
1799 ) {
1800 if self.show_inline_completions_override.is_some() {
1801 self.set_show_inline_completions(None, cx);
1802 } else {
1803 let cursor = self.selections.newest_anchor().head();
1804 if let Some((buffer, cursor_buffer_position)) =
1805 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1806 {
1807 let show_inline_completions =
1808 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1809 self.set_show_inline_completions(Some(show_inline_completions), cx);
1810 }
1811 }
1812 }
1813
1814 pub fn set_show_inline_completions(
1815 &mut self,
1816 show_inline_completions: Option<bool>,
1817 cx: &mut ViewContext<Self>,
1818 ) {
1819 self.show_inline_completions_override = show_inline_completions;
1820 self.refresh_inline_completion(false, true, cx);
1821 }
1822
1823 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1824 let cursor = self.selections.newest_anchor().head();
1825 if let Some((buffer, buffer_position)) =
1826 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1827 {
1828 self.should_show_inline_completions(&buffer, buffer_position, cx)
1829 } else {
1830 false
1831 }
1832 }
1833
1834 fn should_show_inline_completions(
1835 &self,
1836 buffer: &Model<Buffer>,
1837 buffer_position: language::Anchor,
1838 cx: &AppContext,
1839 ) -> bool {
1840 if !self.snippet_stack.is_empty() {
1841 return false;
1842 }
1843
1844 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1845 return false;
1846 }
1847
1848 if let Some(provider) = self.inline_completion_provider() {
1849 if let Some(show_inline_completions) = self.show_inline_completions_override {
1850 show_inline_completions
1851 } else {
1852 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1853 }
1854 } else {
1855 false
1856 }
1857 }
1858
1859 fn inline_completions_disabled_in_scope(
1860 &self,
1861 buffer: &Model<Buffer>,
1862 buffer_position: language::Anchor,
1863 cx: &AppContext,
1864 ) -> bool {
1865 let snapshot = buffer.read(cx).snapshot();
1866 let settings = snapshot.settings_at(buffer_position, cx);
1867
1868 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1869 return false;
1870 };
1871
1872 scope.override_name().map_or(false, |scope_name| {
1873 settings
1874 .inline_completions_disabled_in
1875 .iter()
1876 .any(|s| s == scope_name)
1877 })
1878 }
1879
1880 pub fn set_use_modal_editing(&mut self, to: bool) {
1881 self.use_modal_editing = to;
1882 }
1883
1884 pub fn use_modal_editing(&self) -> bool {
1885 self.use_modal_editing
1886 }
1887
1888 fn selections_did_change(
1889 &mut self,
1890 local: bool,
1891 old_cursor_position: &Anchor,
1892 show_completions: bool,
1893 cx: &mut ViewContext<Self>,
1894 ) {
1895 cx.invalidate_character_coordinates();
1896
1897 // Copy selections to primary selection buffer
1898 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1899 if local {
1900 let selections = self.selections.all::<usize>(cx);
1901 let buffer_handle = self.buffer.read(cx).read(cx);
1902
1903 let mut text = String::new();
1904 for (index, selection) in selections.iter().enumerate() {
1905 let text_for_selection = buffer_handle
1906 .text_for_range(selection.start..selection.end)
1907 .collect::<String>();
1908
1909 text.push_str(&text_for_selection);
1910 if index != selections.len() - 1 {
1911 text.push('\n');
1912 }
1913 }
1914
1915 if !text.is_empty() {
1916 cx.write_to_primary(ClipboardItem::new_string(text));
1917 }
1918 }
1919
1920 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1921 self.buffer.update(cx, |buffer, cx| {
1922 buffer.set_active_selections(
1923 &self.selections.disjoint_anchors(),
1924 self.selections.line_mode,
1925 self.cursor_shape,
1926 cx,
1927 )
1928 });
1929 }
1930 let display_map = self
1931 .display_map
1932 .update(cx, |display_map, cx| display_map.snapshot(cx));
1933 let buffer = &display_map.buffer_snapshot;
1934 self.add_selections_state = None;
1935 self.select_next_state = None;
1936 self.select_prev_state = None;
1937 self.select_larger_syntax_node_stack.clear();
1938 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1939 self.snippet_stack
1940 .invalidate(&self.selections.disjoint_anchors(), buffer);
1941 self.take_rename(false, cx);
1942
1943 let new_cursor_position = self.selections.newest_anchor().head();
1944
1945 self.push_to_nav_history(
1946 *old_cursor_position,
1947 Some(new_cursor_position.to_point(buffer)),
1948 cx,
1949 );
1950
1951 if local {
1952 let new_cursor_position = self.selections.newest_anchor().head();
1953 let mut context_menu = self.context_menu.borrow_mut();
1954 let completion_menu = match context_menu.as_ref() {
1955 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1956 _ => {
1957 *context_menu = None;
1958 None
1959 }
1960 };
1961
1962 if let Some(completion_menu) = completion_menu {
1963 let cursor_position = new_cursor_position.to_offset(buffer);
1964 let (word_range, kind) =
1965 buffer.surrounding_word(completion_menu.initial_position, true);
1966 if kind == Some(CharKind::Word)
1967 && word_range.to_inclusive().contains(&cursor_position)
1968 {
1969 let mut completion_menu = completion_menu.clone();
1970 drop(context_menu);
1971
1972 let query = Self::completion_query(buffer, cursor_position);
1973 cx.spawn(move |this, mut cx| async move {
1974 completion_menu
1975 .filter(query.as_deref(), cx.background_executor().clone())
1976 .await;
1977
1978 this.update(&mut cx, |this, cx| {
1979 let mut context_menu = this.context_menu.borrow_mut();
1980 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1981 else {
1982 return;
1983 };
1984
1985 if menu.id > completion_menu.id {
1986 return;
1987 }
1988
1989 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1990 drop(context_menu);
1991 cx.notify();
1992 })
1993 })
1994 .detach();
1995
1996 if show_completions {
1997 self.show_completions(&ShowCompletions { trigger: None }, cx);
1998 }
1999 } else {
2000 drop(context_menu);
2001 self.hide_context_menu(cx);
2002 }
2003 } else {
2004 drop(context_menu);
2005 }
2006
2007 hide_hover(self, cx);
2008
2009 if old_cursor_position.to_display_point(&display_map).row()
2010 != new_cursor_position.to_display_point(&display_map).row()
2011 {
2012 self.available_code_actions.take();
2013 }
2014 self.refresh_code_actions(cx);
2015 self.refresh_document_highlights(cx);
2016 refresh_matching_bracket_highlights(self, cx);
2017 self.update_visible_inline_completion(cx);
2018 linked_editing_ranges::refresh_linked_ranges(self, cx);
2019 if self.git_blame_inline_enabled {
2020 self.start_inline_blame_timer(cx);
2021 }
2022 }
2023
2024 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2025 cx.emit(EditorEvent::SelectionsChanged { local });
2026
2027 if self.selections.disjoint_anchors().len() == 1 {
2028 cx.emit(SearchEvent::ActiveMatchChanged)
2029 }
2030 cx.notify();
2031 }
2032
2033 pub fn change_selections<R>(
2034 &mut self,
2035 autoscroll: Option<Autoscroll>,
2036 cx: &mut ViewContext<Self>,
2037 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2038 ) -> R {
2039 self.change_selections_inner(autoscroll, true, cx, change)
2040 }
2041
2042 pub fn change_selections_inner<R>(
2043 &mut self,
2044 autoscroll: Option<Autoscroll>,
2045 request_completions: bool,
2046 cx: &mut ViewContext<Self>,
2047 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2048 ) -> R {
2049 let old_cursor_position = self.selections.newest_anchor().head();
2050 self.push_to_selection_history();
2051
2052 let (changed, result) = self.selections.change_with(cx, change);
2053
2054 if changed {
2055 if let Some(autoscroll) = autoscroll {
2056 self.request_autoscroll(autoscroll, cx);
2057 }
2058 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2059
2060 if self.should_open_signature_help_automatically(
2061 &old_cursor_position,
2062 self.signature_help_state.backspace_pressed(),
2063 cx,
2064 ) {
2065 self.show_signature_help(&ShowSignatureHelp, cx);
2066 }
2067 self.signature_help_state.set_backspace_pressed(false);
2068 }
2069
2070 result
2071 }
2072
2073 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2074 where
2075 I: IntoIterator<Item = (Range<S>, T)>,
2076 S: ToOffset,
2077 T: Into<Arc<str>>,
2078 {
2079 if self.read_only(cx) {
2080 return;
2081 }
2082
2083 self.buffer
2084 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2085 }
2086
2087 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2088 where
2089 I: IntoIterator<Item = (Range<S>, T)>,
2090 S: ToOffset,
2091 T: Into<Arc<str>>,
2092 {
2093 if self.read_only(cx) {
2094 return;
2095 }
2096
2097 self.buffer.update(cx, |buffer, cx| {
2098 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2099 });
2100 }
2101
2102 pub fn edit_with_block_indent<I, S, T>(
2103 &mut self,
2104 edits: I,
2105 original_indent_columns: Vec<u32>,
2106 cx: &mut ViewContext<Self>,
2107 ) where
2108 I: IntoIterator<Item = (Range<S>, T)>,
2109 S: ToOffset,
2110 T: Into<Arc<str>>,
2111 {
2112 if self.read_only(cx) {
2113 return;
2114 }
2115
2116 self.buffer.update(cx, |buffer, cx| {
2117 buffer.edit(
2118 edits,
2119 Some(AutoindentMode::Block {
2120 original_indent_columns,
2121 }),
2122 cx,
2123 )
2124 });
2125 }
2126
2127 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2128 self.hide_context_menu(cx);
2129
2130 match phase {
2131 SelectPhase::Begin {
2132 position,
2133 add,
2134 click_count,
2135 } => self.begin_selection(position, add, click_count, cx),
2136 SelectPhase::BeginColumnar {
2137 position,
2138 goal_column,
2139 reset,
2140 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2141 SelectPhase::Extend {
2142 position,
2143 click_count,
2144 } => self.extend_selection(position, click_count, cx),
2145 SelectPhase::Update {
2146 position,
2147 goal_column,
2148 scroll_delta,
2149 } => self.update_selection(position, goal_column, scroll_delta, cx),
2150 SelectPhase::End => self.end_selection(cx),
2151 }
2152 }
2153
2154 fn extend_selection(
2155 &mut self,
2156 position: DisplayPoint,
2157 click_count: usize,
2158 cx: &mut ViewContext<Self>,
2159 ) {
2160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2161 let tail = self.selections.newest::<usize>(cx).tail();
2162 self.begin_selection(position, false, click_count, cx);
2163
2164 let position = position.to_offset(&display_map, Bias::Left);
2165 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2166
2167 let mut pending_selection = self
2168 .selections
2169 .pending_anchor()
2170 .expect("extend_selection not called with pending selection");
2171 if position >= tail {
2172 pending_selection.start = tail_anchor;
2173 } else {
2174 pending_selection.end = tail_anchor;
2175 pending_selection.reversed = true;
2176 }
2177
2178 let mut pending_mode = self.selections.pending_mode().unwrap();
2179 match &mut pending_mode {
2180 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2181 _ => {}
2182 }
2183
2184 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2185 s.set_pending(pending_selection, pending_mode)
2186 });
2187 }
2188
2189 fn begin_selection(
2190 &mut self,
2191 position: DisplayPoint,
2192 add: bool,
2193 click_count: usize,
2194 cx: &mut ViewContext<Self>,
2195 ) {
2196 if !self.focus_handle.is_focused(cx) {
2197 self.last_focused_descendant = None;
2198 cx.focus(&self.focus_handle);
2199 }
2200
2201 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2202 let buffer = &display_map.buffer_snapshot;
2203 let newest_selection = self.selections.newest_anchor().clone();
2204 let position = display_map.clip_point(position, Bias::Left);
2205
2206 let start;
2207 let end;
2208 let mode;
2209 let mut auto_scroll;
2210 match click_count {
2211 1 => {
2212 start = buffer.anchor_before(position.to_point(&display_map));
2213 end = start;
2214 mode = SelectMode::Character;
2215 auto_scroll = true;
2216 }
2217 2 => {
2218 let range = movement::surrounding_word(&display_map, position);
2219 start = buffer.anchor_before(range.start.to_point(&display_map));
2220 end = buffer.anchor_before(range.end.to_point(&display_map));
2221 mode = SelectMode::Word(start..end);
2222 auto_scroll = true;
2223 }
2224 3 => {
2225 let position = display_map
2226 .clip_point(position, Bias::Left)
2227 .to_point(&display_map);
2228 let line_start = display_map.prev_line_boundary(position).0;
2229 let next_line_start = buffer.clip_point(
2230 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2231 Bias::Left,
2232 );
2233 start = buffer.anchor_before(line_start);
2234 end = buffer.anchor_before(next_line_start);
2235 mode = SelectMode::Line(start..end);
2236 auto_scroll = true;
2237 }
2238 _ => {
2239 start = buffer.anchor_before(0);
2240 end = buffer.anchor_before(buffer.len());
2241 mode = SelectMode::All;
2242 auto_scroll = false;
2243 }
2244 }
2245 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2246
2247 let point_to_delete: Option<usize> = {
2248 let selected_points: Vec<Selection<Point>> =
2249 self.selections.disjoint_in_range(start..end, cx);
2250
2251 if !add || click_count > 1 {
2252 None
2253 } else if !selected_points.is_empty() {
2254 Some(selected_points[0].id)
2255 } else {
2256 let clicked_point_already_selected =
2257 self.selections.disjoint.iter().find(|selection| {
2258 selection.start.to_point(buffer) == start.to_point(buffer)
2259 || selection.end.to_point(buffer) == end.to_point(buffer)
2260 });
2261
2262 clicked_point_already_selected.map(|selection| selection.id)
2263 }
2264 };
2265
2266 let selections_count = self.selections.count();
2267
2268 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2269 if let Some(point_to_delete) = point_to_delete {
2270 s.delete(point_to_delete);
2271
2272 if selections_count == 1 {
2273 s.set_pending_anchor_range(start..end, mode);
2274 }
2275 } else {
2276 if !add {
2277 s.clear_disjoint();
2278 } else if click_count > 1 {
2279 s.delete(newest_selection.id)
2280 }
2281
2282 s.set_pending_anchor_range(start..end, mode);
2283 }
2284 });
2285 }
2286
2287 fn begin_columnar_selection(
2288 &mut self,
2289 position: DisplayPoint,
2290 goal_column: u32,
2291 reset: bool,
2292 cx: &mut ViewContext<Self>,
2293 ) {
2294 if !self.focus_handle.is_focused(cx) {
2295 self.last_focused_descendant = None;
2296 cx.focus(&self.focus_handle);
2297 }
2298
2299 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2300
2301 if reset {
2302 let pointer_position = display_map
2303 .buffer_snapshot
2304 .anchor_before(position.to_point(&display_map));
2305
2306 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2307 s.clear_disjoint();
2308 s.set_pending_anchor_range(
2309 pointer_position..pointer_position,
2310 SelectMode::Character,
2311 );
2312 });
2313 }
2314
2315 let tail = self.selections.newest::<Point>(cx).tail();
2316 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2317
2318 if !reset {
2319 self.select_columns(
2320 tail.to_display_point(&display_map),
2321 position,
2322 goal_column,
2323 &display_map,
2324 cx,
2325 );
2326 }
2327 }
2328
2329 fn update_selection(
2330 &mut self,
2331 position: DisplayPoint,
2332 goal_column: u32,
2333 scroll_delta: gpui::Point<f32>,
2334 cx: &mut ViewContext<Self>,
2335 ) {
2336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2337
2338 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2339 let tail = tail.to_display_point(&display_map);
2340 self.select_columns(tail, position, goal_column, &display_map, cx);
2341 } else if let Some(mut pending) = self.selections.pending_anchor() {
2342 let buffer = self.buffer.read(cx).snapshot(cx);
2343 let head;
2344 let tail;
2345 let mode = self.selections.pending_mode().unwrap();
2346 match &mode {
2347 SelectMode::Character => {
2348 head = position.to_point(&display_map);
2349 tail = pending.tail().to_point(&buffer);
2350 }
2351 SelectMode::Word(original_range) => {
2352 let original_display_range = original_range.start.to_display_point(&display_map)
2353 ..original_range.end.to_display_point(&display_map);
2354 let original_buffer_range = original_display_range.start.to_point(&display_map)
2355 ..original_display_range.end.to_point(&display_map);
2356 if movement::is_inside_word(&display_map, position)
2357 || original_display_range.contains(&position)
2358 {
2359 let word_range = movement::surrounding_word(&display_map, position);
2360 if word_range.start < original_display_range.start {
2361 head = word_range.start.to_point(&display_map);
2362 } else {
2363 head = word_range.end.to_point(&display_map);
2364 }
2365 } else {
2366 head = position.to_point(&display_map);
2367 }
2368
2369 if head <= original_buffer_range.start {
2370 tail = original_buffer_range.end;
2371 } else {
2372 tail = original_buffer_range.start;
2373 }
2374 }
2375 SelectMode::Line(original_range) => {
2376 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2377
2378 let position = display_map
2379 .clip_point(position, Bias::Left)
2380 .to_point(&display_map);
2381 let line_start = display_map.prev_line_boundary(position).0;
2382 let next_line_start = buffer.clip_point(
2383 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2384 Bias::Left,
2385 );
2386
2387 if line_start < original_range.start {
2388 head = line_start
2389 } else {
2390 head = next_line_start
2391 }
2392
2393 if head <= original_range.start {
2394 tail = original_range.end;
2395 } else {
2396 tail = original_range.start;
2397 }
2398 }
2399 SelectMode::All => {
2400 return;
2401 }
2402 };
2403
2404 if head < tail {
2405 pending.start = buffer.anchor_before(head);
2406 pending.end = buffer.anchor_before(tail);
2407 pending.reversed = true;
2408 } else {
2409 pending.start = buffer.anchor_before(tail);
2410 pending.end = buffer.anchor_before(head);
2411 pending.reversed = false;
2412 }
2413
2414 self.change_selections(None, cx, |s| {
2415 s.set_pending(pending, mode);
2416 });
2417 } else {
2418 log::error!("update_selection dispatched with no pending selection");
2419 return;
2420 }
2421
2422 self.apply_scroll_delta(scroll_delta, cx);
2423 cx.notify();
2424 }
2425
2426 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2427 self.columnar_selection_tail.take();
2428 if self.selections.pending_anchor().is_some() {
2429 let selections = self.selections.all::<usize>(cx);
2430 self.change_selections(None, cx, |s| {
2431 s.select(selections);
2432 s.clear_pending();
2433 });
2434 }
2435 }
2436
2437 fn select_columns(
2438 &mut self,
2439 tail: DisplayPoint,
2440 head: DisplayPoint,
2441 goal_column: u32,
2442 display_map: &DisplaySnapshot,
2443 cx: &mut ViewContext<Self>,
2444 ) {
2445 let start_row = cmp::min(tail.row(), head.row());
2446 let end_row = cmp::max(tail.row(), head.row());
2447 let start_column = cmp::min(tail.column(), goal_column);
2448 let end_column = cmp::max(tail.column(), goal_column);
2449 let reversed = start_column < tail.column();
2450
2451 let selection_ranges = (start_row.0..=end_row.0)
2452 .map(DisplayRow)
2453 .filter_map(|row| {
2454 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2455 let start = display_map
2456 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2457 .to_point(display_map);
2458 let end = display_map
2459 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2460 .to_point(display_map);
2461 if reversed {
2462 Some(end..start)
2463 } else {
2464 Some(start..end)
2465 }
2466 } else {
2467 None
2468 }
2469 })
2470 .collect::<Vec<_>>();
2471
2472 self.change_selections(None, cx, |s| {
2473 s.select_ranges(selection_ranges);
2474 });
2475 cx.notify();
2476 }
2477
2478 pub fn has_pending_nonempty_selection(&self) -> bool {
2479 let pending_nonempty_selection = match self.selections.pending_anchor() {
2480 Some(Selection { start, end, .. }) => start != end,
2481 None => false,
2482 };
2483
2484 pending_nonempty_selection
2485 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2486 }
2487
2488 pub fn has_pending_selection(&self) -> bool {
2489 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2490 }
2491
2492 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2493 self.selection_mark_mode = false;
2494
2495 if self.clear_expanded_diff_hunks(cx) {
2496 cx.notify();
2497 return;
2498 }
2499 if self.dismiss_menus_and_popups(true, cx) {
2500 return;
2501 }
2502
2503 if self.mode == EditorMode::Full
2504 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2505 {
2506 return;
2507 }
2508
2509 cx.propagate();
2510 }
2511
2512 pub fn dismiss_menus_and_popups(
2513 &mut self,
2514 should_report_inline_completion_event: bool,
2515 cx: &mut ViewContext<Self>,
2516 ) -> bool {
2517 if self.take_rename(false, cx).is_some() {
2518 return true;
2519 }
2520
2521 if hide_hover(self, cx) {
2522 return true;
2523 }
2524
2525 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2526 return true;
2527 }
2528
2529 if self.hide_context_menu(cx).is_some() {
2530 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2531 self.update_visible_inline_completion(cx);
2532 }
2533 return true;
2534 }
2535
2536 if self.mouse_context_menu.take().is_some() {
2537 return true;
2538 }
2539
2540 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2541 return true;
2542 }
2543
2544 if self.snippet_stack.pop().is_some() {
2545 return true;
2546 }
2547
2548 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2549 self.dismiss_diagnostics(cx);
2550 return true;
2551 }
2552
2553 false
2554 }
2555
2556 fn linked_editing_ranges_for(
2557 &self,
2558 selection: Range<text::Anchor>,
2559 cx: &AppContext,
2560 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2561 if self.linked_edit_ranges.is_empty() {
2562 return None;
2563 }
2564 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2565 selection.end.buffer_id.and_then(|end_buffer_id| {
2566 if selection.start.buffer_id != Some(end_buffer_id) {
2567 return None;
2568 }
2569 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2570 let snapshot = buffer.read(cx).snapshot();
2571 self.linked_edit_ranges
2572 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2573 .map(|ranges| (ranges, snapshot, buffer))
2574 })?;
2575 use text::ToOffset as TO;
2576 // find offset from the start of current range to current cursor position
2577 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2578
2579 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2580 let start_difference = start_offset - start_byte_offset;
2581 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2582 let end_difference = end_offset - start_byte_offset;
2583 // Current range has associated linked ranges.
2584 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2585 for range in linked_ranges.iter() {
2586 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2587 let end_offset = start_offset + end_difference;
2588 let start_offset = start_offset + start_difference;
2589 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2590 continue;
2591 }
2592 if self.selections.disjoint_anchor_ranges().any(|s| {
2593 if s.start.buffer_id != selection.start.buffer_id
2594 || s.end.buffer_id != selection.end.buffer_id
2595 {
2596 return false;
2597 }
2598 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2599 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2600 }) {
2601 continue;
2602 }
2603 let start = buffer_snapshot.anchor_after(start_offset);
2604 let end = buffer_snapshot.anchor_after(end_offset);
2605 linked_edits
2606 .entry(buffer.clone())
2607 .or_default()
2608 .push(start..end);
2609 }
2610 Some(linked_edits)
2611 }
2612
2613 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2614 let text: Arc<str> = text.into();
2615
2616 if self.read_only(cx) {
2617 return;
2618 }
2619
2620 let selections = self.selections.all_adjusted(cx);
2621 let mut bracket_inserted = false;
2622 let mut edits = Vec::new();
2623 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2624 let mut new_selections = Vec::with_capacity(selections.len());
2625 let mut new_autoclose_regions = Vec::new();
2626 let snapshot = self.buffer.read(cx).read(cx);
2627
2628 for (selection, autoclose_region) in
2629 self.selections_with_autoclose_regions(selections, &snapshot)
2630 {
2631 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2632 // Determine if the inserted text matches the opening or closing
2633 // bracket of any of this language's bracket pairs.
2634 let mut bracket_pair = None;
2635 let mut is_bracket_pair_start = false;
2636 let mut is_bracket_pair_end = false;
2637 if !text.is_empty() {
2638 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2639 // and they are removing the character that triggered IME popup.
2640 for (pair, enabled) in scope.brackets() {
2641 if !pair.close && !pair.surround {
2642 continue;
2643 }
2644
2645 if enabled && pair.start.ends_with(text.as_ref()) {
2646 let prefix_len = pair.start.len() - text.len();
2647 let preceding_text_matches_prefix = prefix_len == 0
2648 || (selection.start.column >= (prefix_len as u32)
2649 && snapshot.contains_str_at(
2650 Point::new(
2651 selection.start.row,
2652 selection.start.column - (prefix_len as u32),
2653 ),
2654 &pair.start[..prefix_len],
2655 ));
2656 if preceding_text_matches_prefix {
2657 bracket_pair = Some(pair.clone());
2658 is_bracket_pair_start = true;
2659 break;
2660 }
2661 }
2662 if pair.end.as_str() == text.as_ref() {
2663 bracket_pair = Some(pair.clone());
2664 is_bracket_pair_end = true;
2665 break;
2666 }
2667 }
2668 }
2669
2670 if let Some(bracket_pair) = bracket_pair {
2671 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2672 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2673 let auto_surround =
2674 self.use_auto_surround && snapshot_settings.use_auto_surround;
2675 if selection.is_empty() {
2676 if is_bracket_pair_start {
2677 // If the inserted text is a suffix of an opening bracket and the
2678 // selection is preceded by the rest of the opening bracket, then
2679 // insert the closing bracket.
2680 let following_text_allows_autoclose = snapshot
2681 .chars_at(selection.start)
2682 .next()
2683 .map_or(true, |c| scope.should_autoclose_before(c));
2684
2685 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2686 && bracket_pair.start.len() == 1
2687 {
2688 let target = bracket_pair.start.chars().next().unwrap();
2689 let current_line_count = snapshot
2690 .reversed_chars_at(selection.start)
2691 .take_while(|&c| c != '\n')
2692 .filter(|&c| c == target)
2693 .count();
2694 current_line_count % 2 == 1
2695 } else {
2696 false
2697 };
2698
2699 if autoclose
2700 && bracket_pair.close
2701 && following_text_allows_autoclose
2702 && !is_closing_quote
2703 {
2704 let anchor = snapshot.anchor_before(selection.end);
2705 new_selections.push((selection.map(|_| anchor), text.len()));
2706 new_autoclose_regions.push((
2707 anchor,
2708 text.len(),
2709 selection.id,
2710 bracket_pair.clone(),
2711 ));
2712 edits.push((
2713 selection.range(),
2714 format!("{}{}", text, bracket_pair.end).into(),
2715 ));
2716 bracket_inserted = true;
2717 continue;
2718 }
2719 }
2720
2721 if let Some(region) = autoclose_region {
2722 // If the selection is followed by an auto-inserted closing bracket,
2723 // then don't insert that closing bracket again; just move the selection
2724 // past the closing bracket.
2725 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2726 && text.as_ref() == region.pair.end.as_str();
2727 if should_skip {
2728 let anchor = snapshot.anchor_after(selection.end);
2729 new_selections
2730 .push((selection.map(|_| anchor), region.pair.end.len()));
2731 continue;
2732 }
2733 }
2734
2735 let always_treat_brackets_as_autoclosed = snapshot
2736 .settings_at(selection.start, cx)
2737 .always_treat_brackets_as_autoclosed;
2738 if always_treat_brackets_as_autoclosed
2739 && is_bracket_pair_end
2740 && snapshot.contains_str_at(selection.end, text.as_ref())
2741 {
2742 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2743 // and the inserted text is a closing bracket and the selection is followed
2744 // by the closing bracket then move the selection past the closing bracket.
2745 let anchor = snapshot.anchor_after(selection.end);
2746 new_selections.push((selection.map(|_| anchor), text.len()));
2747 continue;
2748 }
2749 }
2750 // If an opening bracket is 1 character long and is typed while
2751 // text is selected, then surround that text with the bracket pair.
2752 else if auto_surround
2753 && bracket_pair.surround
2754 && is_bracket_pair_start
2755 && bracket_pair.start.chars().count() == 1
2756 {
2757 edits.push((selection.start..selection.start, text.clone()));
2758 edits.push((
2759 selection.end..selection.end,
2760 bracket_pair.end.as_str().into(),
2761 ));
2762 bracket_inserted = true;
2763 new_selections.push((
2764 Selection {
2765 id: selection.id,
2766 start: snapshot.anchor_after(selection.start),
2767 end: snapshot.anchor_before(selection.end),
2768 reversed: selection.reversed,
2769 goal: selection.goal,
2770 },
2771 0,
2772 ));
2773 continue;
2774 }
2775 }
2776 }
2777
2778 if self.auto_replace_emoji_shortcode
2779 && selection.is_empty()
2780 && text.as_ref().ends_with(':')
2781 {
2782 if let Some(possible_emoji_short_code) =
2783 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2784 {
2785 if !possible_emoji_short_code.is_empty() {
2786 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2787 let emoji_shortcode_start = Point::new(
2788 selection.start.row,
2789 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2790 );
2791
2792 // Remove shortcode from buffer
2793 edits.push((
2794 emoji_shortcode_start..selection.start,
2795 "".to_string().into(),
2796 ));
2797 new_selections.push((
2798 Selection {
2799 id: selection.id,
2800 start: snapshot.anchor_after(emoji_shortcode_start),
2801 end: snapshot.anchor_before(selection.start),
2802 reversed: selection.reversed,
2803 goal: selection.goal,
2804 },
2805 0,
2806 ));
2807
2808 // Insert emoji
2809 let selection_start_anchor = snapshot.anchor_after(selection.start);
2810 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2811 edits.push((selection.start..selection.end, emoji.to_string().into()));
2812
2813 continue;
2814 }
2815 }
2816 }
2817 }
2818
2819 // If not handling any auto-close operation, then just replace the selected
2820 // text with the given input and move the selection to the end of the
2821 // newly inserted text.
2822 let anchor = snapshot.anchor_after(selection.end);
2823 if !self.linked_edit_ranges.is_empty() {
2824 let start_anchor = snapshot.anchor_before(selection.start);
2825
2826 let is_word_char = text.chars().next().map_or(true, |char| {
2827 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2828 classifier.is_word(char)
2829 });
2830
2831 if is_word_char {
2832 if let Some(ranges) = self
2833 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2834 {
2835 for (buffer, edits) in ranges {
2836 linked_edits
2837 .entry(buffer.clone())
2838 .or_default()
2839 .extend(edits.into_iter().map(|range| (range, text.clone())));
2840 }
2841 }
2842 }
2843 }
2844
2845 new_selections.push((selection.map(|_| anchor), 0));
2846 edits.push((selection.start..selection.end, text.clone()));
2847 }
2848
2849 drop(snapshot);
2850
2851 self.transact(cx, |this, cx| {
2852 this.buffer.update(cx, |buffer, cx| {
2853 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2854 });
2855 for (buffer, edits) in linked_edits {
2856 buffer.update(cx, |buffer, cx| {
2857 let snapshot = buffer.snapshot();
2858 let edits = edits
2859 .into_iter()
2860 .map(|(range, text)| {
2861 use text::ToPoint as TP;
2862 let end_point = TP::to_point(&range.end, &snapshot);
2863 let start_point = TP::to_point(&range.start, &snapshot);
2864 (start_point..end_point, text)
2865 })
2866 .sorted_by_key(|(range, _)| range.start)
2867 .collect::<Vec<_>>();
2868 buffer.edit(edits, None, cx);
2869 })
2870 }
2871 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2872 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2873 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2874 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2875 .zip(new_selection_deltas)
2876 .map(|(selection, delta)| Selection {
2877 id: selection.id,
2878 start: selection.start + delta,
2879 end: selection.end + delta,
2880 reversed: selection.reversed,
2881 goal: SelectionGoal::None,
2882 })
2883 .collect::<Vec<_>>();
2884
2885 let mut i = 0;
2886 for (position, delta, selection_id, pair) in new_autoclose_regions {
2887 let position = position.to_offset(&map.buffer_snapshot) + delta;
2888 let start = map.buffer_snapshot.anchor_before(position);
2889 let end = map.buffer_snapshot.anchor_after(position);
2890 while let Some(existing_state) = this.autoclose_regions.get(i) {
2891 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2892 Ordering::Less => i += 1,
2893 Ordering::Greater => break,
2894 Ordering::Equal => {
2895 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2896 Ordering::Less => i += 1,
2897 Ordering::Equal => break,
2898 Ordering::Greater => break,
2899 }
2900 }
2901 }
2902 }
2903 this.autoclose_regions.insert(
2904 i,
2905 AutocloseRegion {
2906 selection_id,
2907 range: start..end,
2908 pair,
2909 },
2910 );
2911 }
2912
2913 let had_active_inline_completion = this.has_active_inline_completion();
2914 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2915 s.select(new_selections)
2916 });
2917
2918 if !bracket_inserted {
2919 if let Some(on_type_format_task) =
2920 this.trigger_on_type_formatting(text.to_string(), cx)
2921 {
2922 on_type_format_task.detach_and_log_err(cx);
2923 }
2924 }
2925
2926 let editor_settings = EditorSettings::get_global(cx);
2927 if bracket_inserted
2928 && (editor_settings.auto_signature_help
2929 || editor_settings.show_signature_help_after_edits)
2930 {
2931 this.show_signature_help(&ShowSignatureHelp, cx);
2932 }
2933
2934 let trigger_in_words =
2935 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2936 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2937 linked_editing_ranges::refresh_linked_ranges(this, cx);
2938 this.refresh_inline_completion(true, false, cx);
2939 });
2940 }
2941
2942 fn find_possible_emoji_shortcode_at_position(
2943 snapshot: &MultiBufferSnapshot,
2944 position: Point,
2945 ) -> Option<String> {
2946 let mut chars = Vec::new();
2947 let mut found_colon = false;
2948 for char in snapshot.reversed_chars_at(position).take(100) {
2949 // Found a possible emoji shortcode in the middle of the buffer
2950 if found_colon {
2951 if char.is_whitespace() {
2952 chars.reverse();
2953 return Some(chars.iter().collect());
2954 }
2955 // If the previous character is not a whitespace, we are in the middle of a word
2956 // and we only want to complete the shortcode if the word is made up of other emojis
2957 let mut containing_word = String::new();
2958 for ch in snapshot
2959 .reversed_chars_at(position)
2960 .skip(chars.len() + 1)
2961 .take(100)
2962 {
2963 if ch.is_whitespace() {
2964 break;
2965 }
2966 containing_word.push(ch);
2967 }
2968 let containing_word = containing_word.chars().rev().collect::<String>();
2969 if util::word_consists_of_emojis(containing_word.as_str()) {
2970 chars.reverse();
2971 return Some(chars.iter().collect());
2972 }
2973 }
2974
2975 if char.is_whitespace() || !char.is_ascii() {
2976 return None;
2977 }
2978 if char == ':' {
2979 found_colon = true;
2980 } else {
2981 chars.push(char);
2982 }
2983 }
2984 // Found a possible emoji shortcode at the beginning of the buffer
2985 chars.reverse();
2986 Some(chars.iter().collect())
2987 }
2988
2989 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2990 self.transact(cx, |this, cx| {
2991 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2992 let selections = this.selections.all::<usize>(cx);
2993 let multi_buffer = this.buffer.read(cx);
2994 let buffer = multi_buffer.snapshot(cx);
2995 selections
2996 .iter()
2997 .map(|selection| {
2998 let start_point = selection.start.to_point(&buffer);
2999 let mut indent =
3000 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3001 indent.len = cmp::min(indent.len, start_point.column);
3002 let start = selection.start;
3003 let end = selection.end;
3004 let selection_is_empty = start == end;
3005 let language_scope = buffer.language_scope_at(start);
3006 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3007 &language_scope
3008 {
3009 let leading_whitespace_len = buffer
3010 .reversed_chars_at(start)
3011 .take_while(|c| c.is_whitespace() && *c != '\n')
3012 .map(|c| c.len_utf8())
3013 .sum::<usize>();
3014
3015 let trailing_whitespace_len = buffer
3016 .chars_at(end)
3017 .take_while(|c| c.is_whitespace() && *c != '\n')
3018 .map(|c| c.len_utf8())
3019 .sum::<usize>();
3020
3021 let insert_extra_newline =
3022 language.brackets().any(|(pair, enabled)| {
3023 let pair_start = pair.start.trim_end();
3024 let pair_end = pair.end.trim_start();
3025
3026 enabled
3027 && pair.newline
3028 && buffer.contains_str_at(
3029 end + trailing_whitespace_len,
3030 pair_end,
3031 )
3032 && buffer.contains_str_at(
3033 (start - leading_whitespace_len)
3034 .saturating_sub(pair_start.len()),
3035 pair_start,
3036 )
3037 });
3038
3039 // Comment extension on newline is allowed only for cursor selections
3040 let comment_delimiter = maybe!({
3041 if !selection_is_empty {
3042 return None;
3043 }
3044
3045 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3046 return None;
3047 }
3048
3049 let delimiters = language.line_comment_prefixes();
3050 let max_len_of_delimiter =
3051 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3052 let (snapshot, range) =
3053 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3054
3055 let mut index_of_first_non_whitespace = 0;
3056 let comment_candidate = snapshot
3057 .chars_for_range(range)
3058 .skip_while(|c| {
3059 let should_skip = c.is_whitespace();
3060 if should_skip {
3061 index_of_first_non_whitespace += 1;
3062 }
3063 should_skip
3064 })
3065 .take(max_len_of_delimiter)
3066 .collect::<String>();
3067 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3068 comment_candidate.starts_with(comment_prefix.as_ref())
3069 })?;
3070 let cursor_is_placed_after_comment_marker =
3071 index_of_first_non_whitespace + comment_prefix.len()
3072 <= start_point.column as usize;
3073 if cursor_is_placed_after_comment_marker {
3074 Some(comment_prefix.clone())
3075 } else {
3076 None
3077 }
3078 });
3079 (comment_delimiter, insert_extra_newline)
3080 } else {
3081 (None, false)
3082 };
3083
3084 let capacity_for_delimiter = comment_delimiter
3085 .as_deref()
3086 .map(str::len)
3087 .unwrap_or_default();
3088 let mut new_text =
3089 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3090 new_text.push('\n');
3091 new_text.extend(indent.chars());
3092 if let Some(delimiter) = &comment_delimiter {
3093 new_text.push_str(delimiter);
3094 }
3095 if insert_extra_newline {
3096 new_text = new_text.repeat(2);
3097 }
3098
3099 let anchor = buffer.anchor_after(end);
3100 let new_selection = selection.map(|_| anchor);
3101 (
3102 (start..end, new_text),
3103 (insert_extra_newline, new_selection),
3104 )
3105 })
3106 .unzip()
3107 };
3108
3109 this.edit_with_autoindent(edits, cx);
3110 let buffer = this.buffer.read(cx).snapshot(cx);
3111 let new_selections = selection_fixup_info
3112 .into_iter()
3113 .map(|(extra_newline_inserted, new_selection)| {
3114 let mut cursor = new_selection.end.to_point(&buffer);
3115 if extra_newline_inserted {
3116 cursor.row -= 1;
3117 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3118 }
3119 new_selection.map(|_| cursor)
3120 })
3121 .collect();
3122
3123 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3124 this.refresh_inline_completion(true, false, cx);
3125 });
3126 }
3127
3128 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3129 let buffer = self.buffer.read(cx);
3130 let snapshot = buffer.snapshot(cx);
3131
3132 let mut edits = Vec::new();
3133 let mut rows = Vec::new();
3134
3135 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3136 let cursor = selection.head();
3137 let row = cursor.row;
3138
3139 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3140
3141 let newline = "\n".to_string();
3142 edits.push((start_of_line..start_of_line, newline));
3143
3144 rows.push(row + rows_inserted as u32);
3145 }
3146
3147 self.transact(cx, |editor, cx| {
3148 editor.edit(edits, cx);
3149
3150 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3151 let mut index = 0;
3152 s.move_cursors_with(|map, _, _| {
3153 let row = rows[index];
3154 index += 1;
3155
3156 let point = Point::new(row, 0);
3157 let boundary = map.next_line_boundary(point).1;
3158 let clipped = map.clip_point(boundary, Bias::Left);
3159
3160 (clipped, SelectionGoal::None)
3161 });
3162 });
3163
3164 let mut indent_edits = Vec::new();
3165 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3166 for row in rows {
3167 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3168 for (row, indent) in indents {
3169 if indent.len == 0 {
3170 continue;
3171 }
3172
3173 let text = match indent.kind {
3174 IndentKind::Space => " ".repeat(indent.len as usize),
3175 IndentKind::Tab => "\t".repeat(indent.len as usize),
3176 };
3177 let point = Point::new(row.0, 0);
3178 indent_edits.push((point..point, text));
3179 }
3180 }
3181 editor.edit(indent_edits, cx);
3182 });
3183 }
3184
3185 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3186 let buffer = self.buffer.read(cx);
3187 let snapshot = buffer.snapshot(cx);
3188
3189 let mut edits = Vec::new();
3190 let mut rows = Vec::new();
3191 let mut rows_inserted = 0;
3192
3193 for selection in self.selections.all_adjusted(cx) {
3194 let cursor = selection.head();
3195 let row = cursor.row;
3196
3197 let point = Point::new(row + 1, 0);
3198 let start_of_line = snapshot.clip_point(point, Bias::Left);
3199
3200 let newline = "\n".to_string();
3201 edits.push((start_of_line..start_of_line, newline));
3202
3203 rows_inserted += 1;
3204 rows.push(row + rows_inserted);
3205 }
3206
3207 self.transact(cx, |editor, cx| {
3208 editor.edit(edits, cx);
3209
3210 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3211 let mut index = 0;
3212 s.move_cursors_with(|map, _, _| {
3213 let row = rows[index];
3214 index += 1;
3215
3216 let point = Point::new(row, 0);
3217 let boundary = map.next_line_boundary(point).1;
3218 let clipped = map.clip_point(boundary, Bias::Left);
3219
3220 (clipped, SelectionGoal::None)
3221 });
3222 });
3223
3224 let mut indent_edits = Vec::new();
3225 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3226 for row in rows {
3227 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3228 for (row, indent) in indents {
3229 if indent.len == 0 {
3230 continue;
3231 }
3232
3233 let text = match indent.kind {
3234 IndentKind::Space => " ".repeat(indent.len as usize),
3235 IndentKind::Tab => "\t".repeat(indent.len as usize),
3236 };
3237 let point = Point::new(row.0, 0);
3238 indent_edits.push((point..point, text));
3239 }
3240 }
3241 editor.edit(indent_edits, cx);
3242 });
3243 }
3244
3245 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3246 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3247 original_indent_columns: Vec::new(),
3248 });
3249 self.insert_with_autoindent_mode(text, autoindent, cx);
3250 }
3251
3252 fn insert_with_autoindent_mode(
3253 &mut self,
3254 text: &str,
3255 autoindent_mode: Option<AutoindentMode>,
3256 cx: &mut ViewContext<Self>,
3257 ) {
3258 if self.read_only(cx) {
3259 return;
3260 }
3261
3262 let text: Arc<str> = text.into();
3263 self.transact(cx, |this, cx| {
3264 let old_selections = this.selections.all_adjusted(cx);
3265 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3266 let anchors = {
3267 let snapshot = buffer.read(cx);
3268 old_selections
3269 .iter()
3270 .map(|s| {
3271 let anchor = snapshot.anchor_after(s.head());
3272 s.map(|_| anchor)
3273 })
3274 .collect::<Vec<_>>()
3275 };
3276 buffer.edit(
3277 old_selections
3278 .iter()
3279 .map(|s| (s.start..s.end, text.clone())),
3280 autoindent_mode,
3281 cx,
3282 );
3283 anchors
3284 });
3285
3286 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3287 s.select_anchors(selection_anchors);
3288 })
3289 });
3290 }
3291
3292 fn trigger_completion_on_input(
3293 &mut self,
3294 text: &str,
3295 trigger_in_words: bool,
3296 cx: &mut ViewContext<Self>,
3297 ) {
3298 if self.is_completion_trigger(text, trigger_in_words, cx) {
3299 self.show_completions(
3300 &ShowCompletions {
3301 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3302 },
3303 cx,
3304 );
3305 } else {
3306 self.hide_context_menu(cx);
3307 }
3308 }
3309
3310 fn is_completion_trigger(
3311 &self,
3312 text: &str,
3313 trigger_in_words: bool,
3314 cx: &mut ViewContext<Self>,
3315 ) -> bool {
3316 let position = self.selections.newest_anchor().head();
3317 let multibuffer = self.buffer.read(cx);
3318 let Some(buffer) = position
3319 .buffer_id
3320 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3321 else {
3322 return false;
3323 };
3324
3325 if let Some(completion_provider) = &self.completion_provider {
3326 completion_provider.is_completion_trigger(
3327 &buffer,
3328 position.text_anchor,
3329 text,
3330 trigger_in_words,
3331 cx,
3332 )
3333 } else {
3334 false
3335 }
3336 }
3337
3338 /// If any empty selections is touching the start of its innermost containing autoclose
3339 /// region, expand it to select the brackets.
3340 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3341 let selections = self.selections.all::<usize>(cx);
3342 let buffer = self.buffer.read(cx).read(cx);
3343 let new_selections = self
3344 .selections_with_autoclose_regions(selections, &buffer)
3345 .map(|(mut selection, region)| {
3346 if !selection.is_empty() {
3347 return selection;
3348 }
3349
3350 if let Some(region) = region {
3351 let mut range = region.range.to_offset(&buffer);
3352 if selection.start == range.start && range.start >= region.pair.start.len() {
3353 range.start -= region.pair.start.len();
3354 if buffer.contains_str_at(range.start, ®ion.pair.start)
3355 && buffer.contains_str_at(range.end, ®ion.pair.end)
3356 {
3357 range.end += region.pair.end.len();
3358 selection.start = range.start;
3359 selection.end = range.end;
3360
3361 return selection;
3362 }
3363 }
3364 }
3365
3366 let always_treat_brackets_as_autoclosed = buffer
3367 .settings_at(selection.start, cx)
3368 .always_treat_brackets_as_autoclosed;
3369
3370 if !always_treat_brackets_as_autoclosed {
3371 return selection;
3372 }
3373
3374 if let Some(scope) = buffer.language_scope_at(selection.start) {
3375 for (pair, enabled) in scope.brackets() {
3376 if !enabled || !pair.close {
3377 continue;
3378 }
3379
3380 if buffer.contains_str_at(selection.start, &pair.end) {
3381 let pair_start_len = pair.start.len();
3382 if buffer.contains_str_at(
3383 selection.start.saturating_sub(pair_start_len),
3384 &pair.start,
3385 ) {
3386 selection.start -= pair_start_len;
3387 selection.end += pair.end.len();
3388
3389 return selection;
3390 }
3391 }
3392 }
3393 }
3394
3395 selection
3396 })
3397 .collect();
3398
3399 drop(buffer);
3400 self.change_selections(None, cx, |selections| selections.select(new_selections));
3401 }
3402
3403 /// Iterate the given selections, and for each one, find the smallest surrounding
3404 /// autoclose region. This uses the ordering of the selections and the autoclose
3405 /// regions to avoid repeated comparisons.
3406 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3407 &'a self,
3408 selections: impl IntoIterator<Item = Selection<D>>,
3409 buffer: &'a MultiBufferSnapshot,
3410 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3411 let mut i = 0;
3412 let mut regions = self.autoclose_regions.as_slice();
3413 selections.into_iter().map(move |selection| {
3414 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3415
3416 let mut enclosing = None;
3417 while let Some(pair_state) = regions.get(i) {
3418 if pair_state.range.end.to_offset(buffer) < range.start {
3419 regions = ®ions[i + 1..];
3420 i = 0;
3421 } else if pair_state.range.start.to_offset(buffer) > range.end {
3422 break;
3423 } else {
3424 if pair_state.selection_id == selection.id {
3425 enclosing = Some(pair_state);
3426 }
3427 i += 1;
3428 }
3429 }
3430
3431 (selection, enclosing)
3432 })
3433 }
3434
3435 /// Remove any autoclose regions that no longer contain their selection.
3436 fn invalidate_autoclose_regions(
3437 &mut self,
3438 mut selections: &[Selection<Anchor>],
3439 buffer: &MultiBufferSnapshot,
3440 ) {
3441 self.autoclose_regions.retain(|state| {
3442 let mut i = 0;
3443 while let Some(selection) = selections.get(i) {
3444 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3445 selections = &selections[1..];
3446 continue;
3447 }
3448 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3449 break;
3450 }
3451 if selection.id == state.selection_id {
3452 return true;
3453 } else {
3454 i += 1;
3455 }
3456 }
3457 false
3458 });
3459 }
3460
3461 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3462 let offset = position.to_offset(buffer);
3463 let (word_range, kind) = buffer.surrounding_word(offset, true);
3464 if offset > word_range.start && kind == Some(CharKind::Word) {
3465 Some(
3466 buffer
3467 .text_for_range(word_range.start..offset)
3468 .collect::<String>(),
3469 )
3470 } else {
3471 None
3472 }
3473 }
3474
3475 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3476 self.refresh_inlay_hints(
3477 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3478 cx,
3479 );
3480 }
3481
3482 pub fn inlay_hints_enabled(&self) -> bool {
3483 self.inlay_hint_cache.enabled
3484 }
3485
3486 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3487 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3488 return;
3489 }
3490
3491 let reason_description = reason.description();
3492 let ignore_debounce = matches!(
3493 reason,
3494 InlayHintRefreshReason::SettingsChange(_)
3495 | InlayHintRefreshReason::Toggle(_)
3496 | InlayHintRefreshReason::ExcerptsRemoved(_)
3497 );
3498 let (invalidate_cache, required_languages) = match reason {
3499 InlayHintRefreshReason::Toggle(enabled) => {
3500 self.inlay_hint_cache.enabled = enabled;
3501 if enabled {
3502 (InvalidationStrategy::RefreshRequested, None)
3503 } else {
3504 self.inlay_hint_cache.clear();
3505 self.splice_inlays(
3506 self.visible_inlay_hints(cx)
3507 .iter()
3508 .map(|inlay| inlay.id)
3509 .collect(),
3510 Vec::new(),
3511 cx,
3512 );
3513 return;
3514 }
3515 }
3516 InlayHintRefreshReason::SettingsChange(new_settings) => {
3517 match self.inlay_hint_cache.update_settings(
3518 &self.buffer,
3519 new_settings,
3520 self.visible_inlay_hints(cx),
3521 cx,
3522 ) {
3523 ControlFlow::Break(Some(InlaySplice {
3524 to_remove,
3525 to_insert,
3526 })) => {
3527 self.splice_inlays(to_remove, to_insert, cx);
3528 return;
3529 }
3530 ControlFlow::Break(None) => return,
3531 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3532 }
3533 }
3534 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3535 if let Some(InlaySplice {
3536 to_remove,
3537 to_insert,
3538 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3539 {
3540 self.splice_inlays(to_remove, to_insert, cx);
3541 }
3542 return;
3543 }
3544 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3545 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3546 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3547 }
3548 InlayHintRefreshReason::RefreshRequested => {
3549 (InvalidationStrategy::RefreshRequested, None)
3550 }
3551 };
3552
3553 if let Some(InlaySplice {
3554 to_remove,
3555 to_insert,
3556 }) = self.inlay_hint_cache.spawn_hint_refresh(
3557 reason_description,
3558 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3559 invalidate_cache,
3560 ignore_debounce,
3561 cx,
3562 ) {
3563 self.splice_inlays(to_remove, to_insert, cx);
3564 }
3565 }
3566
3567 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3568 self.display_map
3569 .read(cx)
3570 .current_inlays()
3571 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3572 .cloned()
3573 .collect()
3574 }
3575
3576 pub fn excerpts_for_inlay_hints_query(
3577 &self,
3578 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3579 cx: &mut ViewContext<Editor>,
3580 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3581 let Some(project) = self.project.as_ref() else {
3582 return HashMap::default();
3583 };
3584 let project = project.read(cx);
3585 let multi_buffer = self.buffer().read(cx);
3586 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3587 let multi_buffer_visible_start = self
3588 .scroll_manager
3589 .anchor()
3590 .anchor
3591 .to_point(&multi_buffer_snapshot);
3592 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3593 multi_buffer_visible_start
3594 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3595 Bias::Left,
3596 );
3597 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3598 multi_buffer_snapshot
3599 .range_to_buffer_ranges(multi_buffer_visible_range)
3600 .into_iter()
3601 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3602 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3603 let buffer_file = project::File::from_dyn(buffer.file())?;
3604 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3605 let worktree_entry = buffer_worktree
3606 .read(cx)
3607 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3608 if worktree_entry.is_ignored {
3609 return None;
3610 }
3611
3612 let language = buffer.language()?;
3613 if let Some(restrict_to_languages) = restrict_to_languages {
3614 if !restrict_to_languages.contains(language) {
3615 return None;
3616 }
3617 }
3618 Some((
3619 excerpt_id,
3620 (
3621 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3622 buffer.version().clone(),
3623 excerpt_visible_range,
3624 ),
3625 ))
3626 })
3627 .collect()
3628 }
3629
3630 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3631 TextLayoutDetails {
3632 text_system: cx.text_system().clone(),
3633 editor_style: self.style.clone().unwrap(),
3634 rem_size: cx.rem_size(),
3635 scroll_anchor: self.scroll_manager.anchor(),
3636 visible_rows: self.visible_line_count(),
3637 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3638 }
3639 }
3640
3641 pub fn splice_inlays(
3642 &self,
3643 to_remove: Vec<InlayId>,
3644 to_insert: Vec<Inlay>,
3645 cx: &mut ViewContext<Self>,
3646 ) {
3647 self.display_map.update(cx, |display_map, cx| {
3648 display_map.splice_inlays(to_remove, to_insert, cx)
3649 });
3650 cx.notify();
3651 }
3652
3653 fn trigger_on_type_formatting(
3654 &self,
3655 input: String,
3656 cx: &mut ViewContext<Self>,
3657 ) -> Option<Task<Result<()>>> {
3658 if input.len() != 1 {
3659 return None;
3660 }
3661
3662 let project = self.project.as_ref()?;
3663 let position = self.selections.newest_anchor().head();
3664 let (buffer, buffer_position) = self
3665 .buffer
3666 .read(cx)
3667 .text_anchor_for_position(position, cx)?;
3668
3669 let settings = language_settings::language_settings(
3670 buffer
3671 .read(cx)
3672 .language_at(buffer_position)
3673 .map(|l| l.name()),
3674 buffer.read(cx).file(),
3675 cx,
3676 );
3677 if !settings.use_on_type_format {
3678 return None;
3679 }
3680
3681 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3682 // hence we do LSP request & edit on host side only — add formats to host's history.
3683 let push_to_lsp_host_history = true;
3684 // If this is not the host, append its history with new edits.
3685 let push_to_client_history = project.read(cx).is_via_collab();
3686
3687 let on_type_formatting = project.update(cx, |project, cx| {
3688 project.on_type_format(
3689 buffer.clone(),
3690 buffer_position,
3691 input,
3692 push_to_lsp_host_history,
3693 cx,
3694 )
3695 });
3696 Some(cx.spawn(|editor, mut cx| async move {
3697 if let Some(transaction) = on_type_formatting.await? {
3698 if push_to_client_history {
3699 buffer
3700 .update(&mut cx, |buffer, _| {
3701 buffer.push_transaction(transaction, Instant::now());
3702 })
3703 .ok();
3704 }
3705 editor.update(&mut cx, |editor, cx| {
3706 editor.refresh_document_highlights(cx);
3707 })?;
3708 }
3709 Ok(())
3710 }))
3711 }
3712
3713 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3714 if self.pending_rename.is_some() {
3715 return;
3716 }
3717
3718 let Some(provider) = self.completion_provider.as_ref() else {
3719 return;
3720 };
3721
3722 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3723 return;
3724 }
3725
3726 let position = self.selections.newest_anchor().head();
3727 let (buffer, buffer_position) =
3728 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3729 output
3730 } else {
3731 return;
3732 };
3733 let show_completion_documentation = buffer
3734 .read(cx)
3735 .snapshot()
3736 .settings_at(buffer_position, cx)
3737 .show_completion_documentation;
3738
3739 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3740
3741 let trigger_kind = match &options.trigger {
3742 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3743 CompletionTriggerKind::TRIGGER_CHARACTER
3744 }
3745 _ => CompletionTriggerKind::INVOKED,
3746 };
3747 let completion_context = CompletionContext {
3748 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3749 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3750 Some(String::from(trigger))
3751 } else {
3752 None
3753 }
3754 }),
3755 trigger_kind,
3756 };
3757 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3758 let sort_completions = provider.sort_completions();
3759
3760 let id = post_inc(&mut self.next_completion_id);
3761 let task = cx.spawn(|editor, mut cx| {
3762 async move {
3763 editor.update(&mut cx, |this, _| {
3764 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3765 })?;
3766 let completions = completions.await.log_err();
3767 let menu = if let Some(completions) = completions {
3768 let mut menu = CompletionsMenu::new(
3769 id,
3770 sort_completions,
3771 show_completion_documentation,
3772 position,
3773 buffer.clone(),
3774 completions.into(),
3775 );
3776
3777 menu.filter(query.as_deref(), cx.background_executor().clone())
3778 .await;
3779
3780 menu.visible().then_some(menu)
3781 } else {
3782 None
3783 };
3784
3785 editor.update(&mut cx, |editor, cx| {
3786 match editor.context_menu.borrow().as_ref() {
3787 None => {}
3788 Some(CodeContextMenu::Completions(prev_menu)) => {
3789 if prev_menu.id > id {
3790 return;
3791 }
3792 }
3793 _ => return,
3794 }
3795
3796 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3797 let mut menu = menu.unwrap();
3798 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3799
3800 if editor.show_inline_completions_in_menu(cx) {
3801 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3802 menu.show_inline_completion_hint(hint);
3803 }
3804 } else {
3805 editor.discard_inline_completion(false, cx);
3806 }
3807
3808 *editor.context_menu.borrow_mut() =
3809 Some(CodeContextMenu::Completions(menu));
3810
3811 cx.notify();
3812 } else if editor.completion_tasks.len() <= 1 {
3813 // If there are no more completion tasks and the last menu was
3814 // empty, we should hide it.
3815 let was_hidden = editor.hide_context_menu(cx).is_none();
3816 // If it was already hidden and we don't show inline
3817 // completions in the menu, we should also show the
3818 // inline-completion when available.
3819 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3820 editor.update_visible_inline_completion(cx);
3821 }
3822 }
3823 })?;
3824
3825 Ok::<_, anyhow::Error>(())
3826 }
3827 .log_err()
3828 });
3829
3830 self.completion_tasks.push((id, task));
3831 }
3832
3833 pub fn confirm_completion(
3834 &mut self,
3835 action: &ConfirmCompletion,
3836 cx: &mut ViewContext<Self>,
3837 ) -> Option<Task<Result<()>>> {
3838 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3839 }
3840
3841 pub fn compose_completion(
3842 &mut self,
3843 action: &ComposeCompletion,
3844 cx: &mut ViewContext<Self>,
3845 ) -> Option<Task<Result<()>>> {
3846 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3847 }
3848
3849 fn toggle_zed_predict_tos(&mut self, cx: &mut ViewContext<Self>) {
3850 let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
3851 return;
3852 };
3853
3854 ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), cx);
3855 }
3856
3857 fn do_completion(
3858 &mut self,
3859 item_ix: Option<usize>,
3860 intent: CompletionIntent,
3861 cx: &mut ViewContext<Editor>,
3862 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3863 use language::ToOffset as _;
3864
3865 {
3866 let context_menu = self.context_menu.borrow();
3867 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3868 let entries = menu.entries.borrow();
3869 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3870 match entry {
3871 Some(CompletionEntry::InlineCompletionHint(
3872 InlineCompletionMenuHint::Loading,
3873 )) => return Some(Task::ready(Ok(()))),
3874 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3875 drop(entries);
3876 drop(context_menu);
3877 self.context_menu_next(&Default::default(), cx);
3878 return Some(Task::ready(Ok(())));
3879 }
3880 Some(CompletionEntry::InlineCompletionHint(
3881 InlineCompletionMenuHint::PendingTermsAcceptance,
3882 )) => {
3883 drop(entries);
3884 drop(context_menu);
3885 self.toggle_zed_predict_tos(cx);
3886 return Some(Task::ready(Ok(())));
3887 }
3888 _ => {}
3889 }
3890 }
3891 }
3892
3893 let completions_menu =
3894 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3895 menu
3896 } else {
3897 return None;
3898 };
3899
3900 let entries = completions_menu.entries.borrow();
3901 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3902 let mat = match mat {
3903 CompletionEntry::InlineCompletionHint(_) => {
3904 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3905 cx.stop_propagation();
3906 return Some(Task::ready(Ok(())));
3907 }
3908 CompletionEntry::Match(mat) => {
3909 if self.show_inline_completions_in_menu(cx) {
3910 self.discard_inline_completion(true, cx);
3911 }
3912 mat
3913 }
3914 };
3915 let candidate_id = mat.candidate_id;
3916 drop(entries);
3917
3918 let buffer_handle = completions_menu.buffer;
3919 let completion = completions_menu
3920 .completions
3921 .borrow()
3922 .get(candidate_id)?
3923 .clone();
3924 cx.stop_propagation();
3925
3926 let snippet;
3927 let text;
3928
3929 if completion.is_snippet() {
3930 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3931 text = snippet.as_ref().unwrap().text.clone();
3932 } else {
3933 snippet = None;
3934 text = completion.new_text.clone();
3935 };
3936 let selections = self.selections.all::<usize>(cx);
3937 let buffer = buffer_handle.read(cx);
3938 let old_range = completion.old_range.to_offset(buffer);
3939 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3940
3941 let newest_selection = self.selections.newest_anchor();
3942 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3943 return None;
3944 }
3945
3946 let lookbehind = newest_selection
3947 .start
3948 .text_anchor
3949 .to_offset(buffer)
3950 .saturating_sub(old_range.start);
3951 let lookahead = old_range
3952 .end
3953 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3954 let mut common_prefix_len = old_text
3955 .bytes()
3956 .zip(text.bytes())
3957 .take_while(|(a, b)| a == b)
3958 .count();
3959
3960 let snapshot = self.buffer.read(cx).snapshot(cx);
3961 let mut range_to_replace: Option<Range<isize>> = None;
3962 let mut ranges = Vec::new();
3963 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3964 for selection in &selections {
3965 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3966 let start = selection.start.saturating_sub(lookbehind);
3967 let end = selection.end + lookahead;
3968 if selection.id == newest_selection.id {
3969 range_to_replace = Some(
3970 ((start + common_prefix_len) as isize - selection.start as isize)
3971 ..(end as isize - selection.start as isize),
3972 );
3973 }
3974 ranges.push(start + common_prefix_len..end);
3975 } else {
3976 common_prefix_len = 0;
3977 ranges.clear();
3978 ranges.extend(selections.iter().map(|s| {
3979 if s.id == newest_selection.id {
3980 range_to_replace = Some(
3981 old_range.start.to_offset_utf16(&snapshot).0 as isize
3982 - selection.start as isize
3983 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3984 - selection.start as isize,
3985 );
3986 old_range.clone()
3987 } else {
3988 s.start..s.end
3989 }
3990 }));
3991 break;
3992 }
3993 if !self.linked_edit_ranges.is_empty() {
3994 let start_anchor = snapshot.anchor_before(selection.head());
3995 let end_anchor = snapshot.anchor_after(selection.tail());
3996 if let Some(ranges) = self
3997 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3998 {
3999 for (buffer, edits) in ranges {
4000 linked_edits.entry(buffer.clone()).or_default().extend(
4001 edits
4002 .into_iter()
4003 .map(|range| (range, text[common_prefix_len..].to_owned())),
4004 );
4005 }
4006 }
4007 }
4008 }
4009 let text = &text[common_prefix_len..];
4010
4011 cx.emit(EditorEvent::InputHandled {
4012 utf16_range_to_replace: range_to_replace,
4013 text: text.into(),
4014 });
4015
4016 self.transact(cx, |this, cx| {
4017 if let Some(mut snippet) = snippet {
4018 snippet.text = text.to_string();
4019 for tabstop in snippet
4020 .tabstops
4021 .iter_mut()
4022 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4023 {
4024 tabstop.start -= common_prefix_len as isize;
4025 tabstop.end -= common_prefix_len as isize;
4026 }
4027
4028 this.insert_snippet(&ranges, snippet, cx).log_err();
4029 } else {
4030 this.buffer.update(cx, |buffer, cx| {
4031 buffer.edit(
4032 ranges.iter().map(|range| (range.clone(), text)),
4033 this.autoindent_mode.clone(),
4034 cx,
4035 );
4036 });
4037 }
4038 for (buffer, edits) in linked_edits {
4039 buffer.update(cx, |buffer, cx| {
4040 let snapshot = buffer.snapshot();
4041 let edits = edits
4042 .into_iter()
4043 .map(|(range, text)| {
4044 use text::ToPoint as TP;
4045 let end_point = TP::to_point(&range.end, &snapshot);
4046 let start_point = TP::to_point(&range.start, &snapshot);
4047 (start_point..end_point, text)
4048 })
4049 .sorted_by_key(|(range, _)| range.start)
4050 .collect::<Vec<_>>();
4051 buffer.edit(edits, None, cx);
4052 })
4053 }
4054
4055 this.refresh_inline_completion(true, false, cx);
4056 });
4057
4058 let show_new_completions_on_confirm = completion
4059 .confirm
4060 .as_ref()
4061 .map_or(false, |confirm| confirm(intent, cx));
4062 if show_new_completions_on_confirm {
4063 self.show_completions(&ShowCompletions { trigger: None }, cx);
4064 }
4065
4066 let provider = self.completion_provider.as_ref()?;
4067 drop(completion);
4068 let apply_edits = provider.apply_additional_edits_for_completion(
4069 buffer_handle,
4070 completions_menu.completions.clone(),
4071 candidate_id,
4072 true,
4073 cx,
4074 );
4075
4076 let editor_settings = EditorSettings::get_global(cx);
4077 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4078 // After the code completion is finished, users often want to know what signatures are needed.
4079 // so we should automatically call signature_help
4080 self.show_signature_help(&ShowSignatureHelp, cx);
4081 }
4082
4083 Some(cx.foreground_executor().spawn(async move {
4084 apply_edits.await?;
4085 Ok(())
4086 }))
4087 }
4088
4089 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4090 let mut context_menu = self.context_menu.borrow_mut();
4091 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4092 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4093 // Toggle if we're selecting the same one
4094 *context_menu = None;
4095 cx.notify();
4096 return;
4097 } else {
4098 // Otherwise, clear it and start a new one
4099 *context_menu = None;
4100 cx.notify();
4101 }
4102 }
4103 drop(context_menu);
4104 let snapshot = self.snapshot(cx);
4105 let deployed_from_indicator = action.deployed_from_indicator;
4106 let mut task = self.code_actions_task.take();
4107 let action = action.clone();
4108 cx.spawn(|editor, mut cx| async move {
4109 while let Some(prev_task) = task {
4110 prev_task.await.log_err();
4111 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4112 }
4113
4114 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4115 if editor.focus_handle.is_focused(cx) {
4116 let multibuffer_point = action
4117 .deployed_from_indicator
4118 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4119 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4120 let (buffer, buffer_row) = snapshot
4121 .buffer_snapshot
4122 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4123 .and_then(|(buffer_snapshot, range)| {
4124 editor
4125 .buffer
4126 .read(cx)
4127 .buffer(buffer_snapshot.remote_id())
4128 .map(|buffer| (buffer, range.start.row))
4129 })?;
4130 let (_, code_actions) = editor
4131 .available_code_actions
4132 .clone()
4133 .and_then(|(location, code_actions)| {
4134 let snapshot = location.buffer.read(cx).snapshot();
4135 let point_range = location.range.to_point(&snapshot);
4136 let point_range = point_range.start.row..=point_range.end.row;
4137 if point_range.contains(&buffer_row) {
4138 Some((location, code_actions))
4139 } else {
4140 None
4141 }
4142 })
4143 .unzip();
4144 let buffer_id = buffer.read(cx).remote_id();
4145 let tasks = editor
4146 .tasks
4147 .get(&(buffer_id, buffer_row))
4148 .map(|t| Arc::new(t.to_owned()));
4149 if tasks.is_none() && code_actions.is_none() {
4150 return None;
4151 }
4152
4153 editor.completion_tasks.clear();
4154 editor.discard_inline_completion(false, cx);
4155 let task_context =
4156 tasks
4157 .as_ref()
4158 .zip(editor.project.clone())
4159 .map(|(tasks, project)| {
4160 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4161 });
4162
4163 Some(cx.spawn(|editor, mut cx| async move {
4164 let task_context = match task_context {
4165 Some(task_context) => task_context.await,
4166 None => None,
4167 };
4168 let resolved_tasks =
4169 tasks.zip(task_context).map(|(tasks, task_context)| {
4170 Rc::new(ResolvedTasks {
4171 templates: tasks.resolve(&task_context).collect(),
4172 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4173 multibuffer_point.row,
4174 tasks.column,
4175 )),
4176 })
4177 });
4178 let spawn_straight_away = resolved_tasks
4179 .as_ref()
4180 .map_or(false, |tasks| tasks.templates.len() == 1)
4181 && code_actions
4182 .as_ref()
4183 .map_or(true, |actions| actions.is_empty());
4184 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4185 *editor.context_menu.borrow_mut() =
4186 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4187 buffer,
4188 actions: CodeActionContents {
4189 tasks: resolved_tasks,
4190 actions: code_actions,
4191 },
4192 selected_item: Default::default(),
4193 scroll_handle: UniformListScrollHandle::default(),
4194 deployed_from_indicator,
4195 }));
4196 if spawn_straight_away {
4197 if let Some(task) = editor.confirm_code_action(
4198 &ConfirmCodeAction { item_ix: Some(0) },
4199 cx,
4200 ) {
4201 cx.notify();
4202 return task;
4203 }
4204 }
4205 cx.notify();
4206 Task::ready(Ok(()))
4207 }) {
4208 task.await
4209 } else {
4210 Ok(())
4211 }
4212 }))
4213 } else {
4214 Some(Task::ready(Ok(())))
4215 }
4216 })?;
4217 if let Some(task) = spawned_test_task {
4218 task.await?;
4219 }
4220
4221 Ok::<_, anyhow::Error>(())
4222 })
4223 .detach_and_log_err(cx);
4224 }
4225
4226 pub fn confirm_code_action(
4227 &mut self,
4228 action: &ConfirmCodeAction,
4229 cx: &mut ViewContext<Self>,
4230 ) -> Option<Task<Result<()>>> {
4231 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4232 menu
4233 } else {
4234 return None;
4235 };
4236 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4237 let action = actions_menu.actions.get(action_ix)?;
4238 let title = action.label();
4239 let buffer = actions_menu.buffer;
4240 let workspace = self.workspace()?;
4241
4242 match action {
4243 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4244 workspace.update(cx, |workspace, cx| {
4245 workspace::tasks::schedule_resolved_task(
4246 workspace,
4247 task_source_kind,
4248 resolved_task,
4249 false,
4250 cx,
4251 );
4252
4253 Some(Task::ready(Ok(())))
4254 })
4255 }
4256 CodeActionsItem::CodeAction {
4257 excerpt_id,
4258 action,
4259 provider,
4260 } => {
4261 let apply_code_action =
4262 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4263 let workspace = workspace.downgrade();
4264 Some(cx.spawn(|editor, cx| async move {
4265 let project_transaction = apply_code_action.await?;
4266 Self::open_project_transaction(
4267 &editor,
4268 workspace,
4269 project_transaction,
4270 title,
4271 cx,
4272 )
4273 .await
4274 }))
4275 }
4276 }
4277 }
4278
4279 pub async fn open_project_transaction(
4280 this: &WeakView<Editor>,
4281 workspace: WeakView<Workspace>,
4282 transaction: ProjectTransaction,
4283 title: String,
4284 mut cx: AsyncWindowContext,
4285 ) -> Result<()> {
4286 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4287 cx.update(|cx| {
4288 entries.sort_unstable_by_key(|(buffer, _)| {
4289 buffer.read(cx).file().map(|f| f.path().clone())
4290 });
4291 })?;
4292
4293 // If the project transaction's edits are all contained within this editor, then
4294 // avoid opening a new editor to display them.
4295
4296 if let Some((buffer, transaction)) = entries.first() {
4297 if entries.len() == 1 {
4298 let excerpt = this.update(&mut cx, |editor, cx| {
4299 editor
4300 .buffer()
4301 .read(cx)
4302 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4303 })?;
4304 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4305 if excerpted_buffer == *buffer {
4306 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4307 let excerpt_range = excerpt_range.to_offset(buffer);
4308 buffer
4309 .edited_ranges_for_transaction::<usize>(transaction)
4310 .all(|range| {
4311 excerpt_range.start <= range.start
4312 && excerpt_range.end >= range.end
4313 })
4314 })?;
4315
4316 if all_edits_within_excerpt {
4317 return Ok(());
4318 }
4319 }
4320 }
4321 }
4322 } else {
4323 return Ok(());
4324 }
4325
4326 let mut ranges_to_highlight = Vec::new();
4327 let excerpt_buffer = cx.new_model(|cx| {
4328 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4329 for (buffer_handle, transaction) in &entries {
4330 let buffer = buffer_handle.read(cx);
4331 ranges_to_highlight.extend(
4332 multibuffer.push_excerpts_with_context_lines(
4333 buffer_handle.clone(),
4334 buffer
4335 .edited_ranges_for_transaction::<usize>(transaction)
4336 .collect(),
4337 DEFAULT_MULTIBUFFER_CONTEXT,
4338 cx,
4339 ),
4340 );
4341 }
4342 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4343 multibuffer
4344 })?;
4345
4346 workspace.update(&mut cx, |workspace, cx| {
4347 let project = workspace.project().clone();
4348 let editor =
4349 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4350 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4351 editor.update(cx, |editor, cx| {
4352 editor.highlight_background::<Self>(
4353 &ranges_to_highlight,
4354 |theme| theme.editor_highlighted_line_background,
4355 cx,
4356 );
4357 });
4358 })?;
4359
4360 Ok(())
4361 }
4362
4363 pub fn clear_code_action_providers(&mut self) {
4364 self.code_action_providers.clear();
4365 self.available_code_actions.take();
4366 }
4367
4368 pub fn add_code_action_provider(
4369 &mut self,
4370 provider: Rc<dyn CodeActionProvider>,
4371 cx: &mut ViewContext<Self>,
4372 ) {
4373 if self
4374 .code_action_providers
4375 .iter()
4376 .any(|existing_provider| existing_provider.id() == provider.id())
4377 {
4378 return;
4379 }
4380
4381 self.code_action_providers.push(provider);
4382 self.refresh_code_actions(cx);
4383 }
4384
4385 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4386 self.code_action_providers
4387 .retain(|provider| provider.id() != id);
4388 self.refresh_code_actions(cx);
4389 }
4390
4391 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4392 let buffer = self.buffer.read(cx);
4393 let newest_selection = self.selections.newest_anchor().clone();
4394 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4395 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4396 if start_buffer != end_buffer {
4397 return None;
4398 }
4399
4400 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4401 cx.background_executor()
4402 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4403 .await;
4404
4405 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4406 let providers = this.code_action_providers.clone();
4407 let tasks = this
4408 .code_action_providers
4409 .iter()
4410 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4411 .collect::<Vec<_>>();
4412 (providers, tasks)
4413 })?;
4414
4415 let mut actions = Vec::new();
4416 for (provider, provider_actions) in
4417 providers.into_iter().zip(future::join_all(tasks).await)
4418 {
4419 if let Some(provider_actions) = provider_actions.log_err() {
4420 actions.extend(provider_actions.into_iter().map(|action| {
4421 AvailableCodeAction {
4422 excerpt_id: newest_selection.start.excerpt_id,
4423 action,
4424 provider: provider.clone(),
4425 }
4426 }));
4427 }
4428 }
4429
4430 this.update(&mut cx, |this, cx| {
4431 this.available_code_actions = if actions.is_empty() {
4432 None
4433 } else {
4434 Some((
4435 Location {
4436 buffer: start_buffer,
4437 range: start..end,
4438 },
4439 actions.into(),
4440 ))
4441 };
4442 cx.notify();
4443 })
4444 }));
4445 None
4446 }
4447
4448 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4449 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4450 self.show_git_blame_inline = false;
4451
4452 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4453 cx.background_executor().timer(delay).await;
4454
4455 this.update(&mut cx, |this, cx| {
4456 this.show_git_blame_inline = true;
4457 cx.notify();
4458 })
4459 .log_err();
4460 }));
4461 }
4462 }
4463
4464 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4465 if self.pending_rename.is_some() {
4466 return None;
4467 }
4468
4469 let provider = self.semantics_provider.clone()?;
4470 let buffer = self.buffer.read(cx);
4471 let newest_selection = self.selections.newest_anchor().clone();
4472 let cursor_position = newest_selection.head();
4473 let (cursor_buffer, cursor_buffer_position) =
4474 buffer.text_anchor_for_position(cursor_position, cx)?;
4475 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4476 if cursor_buffer != tail_buffer {
4477 return None;
4478 }
4479 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4480 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4481 cx.background_executor()
4482 .timer(Duration::from_millis(debounce))
4483 .await;
4484
4485 let highlights = if let Some(highlights) = cx
4486 .update(|cx| {
4487 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4488 })
4489 .ok()
4490 .flatten()
4491 {
4492 highlights.await.log_err()
4493 } else {
4494 None
4495 };
4496
4497 if let Some(highlights) = highlights {
4498 this.update(&mut cx, |this, cx| {
4499 if this.pending_rename.is_some() {
4500 return;
4501 }
4502
4503 let buffer_id = cursor_position.buffer_id;
4504 let buffer = this.buffer.read(cx);
4505 if !buffer
4506 .text_anchor_for_position(cursor_position, cx)
4507 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4508 {
4509 return;
4510 }
4511
4512 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4513 let mut write_ranges = Vec::new();
4514 let mut read_ranges = Vec::new();
4515 for highlight in highlights {
4516 for (excerpt_id, excerpt_range) in
4517 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4518 {
4519 let start = highlight
4520 .range
4521 .start
4522 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4523 let end = highlight
4524 .range
4525 .end
4526 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4527 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4528 continue;
4529 }
4530
4531 let range = Anchor {
4532 buffer_id,
4533 excerpt_id,
4534 text_anchor: start,
4535 diff_base_anchor: None,
4536 }..Anchor {
4537 buffer_id,
4538 excerpt_id,
4539 text_anchor: end,
4540 diff_base_anchor: None,
4541 };
4542 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4543 write_ranges.push(range);
4544 } else {
4545 read_ranges.push(range);
4546 }
4547 }
4548 }
4549
4550 this.highlight_background::<DocumentHighlightRead>(
4551 &read_ranges,
4552 |theme| theme.editor_document_highlight_read_background,
4553 cx,
4554 );
4555 this.highlight_background::<DocumentHighlightWrite>(
4556 &write_ranges,
4557 |theme| theme.editor_document_highlight_write_background,
4558 cx,
4559 );
4560 cx.notify();
4561 })
4562 .log_err();
4563 }
4564 }));
4565 None
4566 }
4567
4568 pub fn refresh_inline_completion(
4569 &mut self,
4570 debounce: bool,
4571 user_requested: bool,
4572 cx: &mut ViewContext<Self>,
4573 ) -> Option<()> {
4574 let provider = self.inline_completion_provider()?;
4575 let cursor = self.selections.newest_anchor().head();
4576 let (buffer, cursor_buffer_position) =
4577 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4578
4579 if !user_requested
4580 && (!self.enable_inline_completions
4581 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4582 || !self.is_focused(cx)
4583 || buffer.read(cx).is_empty())
4584 {
4585 self.discard_inline_completion(false, cx);
4586 return None;
4587 }
4588
4589 self.update_visible_inline_completion(cx);
4590 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4591 Some(())
4592 }
4593
4594 fn cycle_inline_completion(
4595 &mut self,
4596 direction: Direction,
4597 cx: &mut ViewContext<Self>,
4598 ) -> Option<()> {
4599 let provider = self.inline_completion_provider()?;
4600 let cursor = self.selections.newest_anchor().head();
4601 let (buffer, cursor_buffer_position) =
4602 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4603 if !self.enable_inline_completions
4604 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4605 {
4606 return None;
4607 }
4608
4609 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4610 self.update_visible_inline_completion(cx);
4611
4612 Some(())
4613 }
4614
4615 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4616 if !self.has_active_inline_completion() {
4617 self.refresh_inline_completion(false, true, cx);
4618 return;
4619 }
4620
4621 self.update_visible_inline_completion(cx);
4622 }
4623
4624 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4625 self.show_cursor_names(cx);
4626 }
4627
4628 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4629 self.show_cursor_names = true;
4630 cx.notify();
4631 cx.spawn(|this, mut cx| async move {
4632 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4633 this.update(&mut cx, |this, cx| {
4634 this.show_cursor_names = false;
4635 cx.notify()
4636 })
4637 .ok()
4638 })
4639 .detach();
4640 }
4641
4642 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4643 if self.has_active_inline_completion() {
4644 self.cycle_inline_completion(Direction::Next, cx);
4645 } else {
4646 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4647 if is_copilot_disabled {
4648 cx.propagate();
4649 }
4650 }
4651 }
4652
4653 pub fn previous_inline_completion(
4654 &mut self,
4655 _: &PreviousInlineCompletion,
4656 cx: &mut ViewContext<Self>,
4657 ) {
4658 if self.has_active_inline_completion() {
4659 self.cycle_inline_completion(Direction::Prev, cx);
4660 } else {
4661 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4662 if is_copilot_disabled {
4663 cx.propagate();
4664 }
4665 }
4666 }
4667
4668 pub fn accept_inline_completion(
4669 &mut self,
4670 _: &AcceptInlineCompletion,
4671 cx: &mut ViewContext<Self>,
4672 ) {
4673 let buffer = self.buffer.read(cx);
4674 let snapshot = buffer.snapshot(cx);
4675 let selection = self.selections.newest_adjusted(cx);
4676 let cursor = selection.head();
4677 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4678 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4679 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4680 {
4681 if cursor.column < suggested_indent.len
4682 && cursor.column <= current_indent.len
4683 && current_indent.len <= suggested_indent.len
4684 {
4685 self.tab(&Default::default(), cx);
4686 return;
4687 }
4688 }
4689
4690 if self.show_inline_completions_in_menu(cx) {
4691 self.hide_context_menu(cx);
4692 }
4693
4694 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4695 return;
4696 };
4697
4698 self.report_inline_completion_event(true, cx);
4699
4700 match &active_inline_completion.completion {
4701 InlineCompletion::Move(position) => {
4702 let position = *position;
4703 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4704 selections.select_anchor_ranges([position..position]);
4705 });
4706 }
4707 InlineCompletion::Edit { edits, .. } => {
4708 if let Some(provider) = self.inline_completion_provider() {
4709 provider.accept(cx);
4710 }
4711
4712 let snapshot = self.buffer.read(cx).snapshot(cx);
4713 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4714
4715 self.buffer.update(cx, |buffer, cx| {
4716 buffer.edit(edits.iter().cloned(), None, cx)
4717 });
4718
4719 self.change_selections(None, cx, |s| {
4720 s.select_anchor_ranges([last_edit_end..last_edit_end])
4721 });
4722
4723 self.update_visible_inline_completion(cx);
4724 if self.active_inline_completion.is_none() {
4725 self.refresh_inline_completion(true, true, cx);
4726 }
4727
4728 cx.notify();
4729 }
4730 }
4731 }
4732
4733 pub fn accept_partial_inline_completion(
4734 &mut self,
4735 _: &AcceptPartialInlineCompletion,
4736 cx: &mut ViewContext<Self>,
4737 ) {
4738 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4739 return;
4740 };
4741 if self.selections.count() != 1 {
4742 return;
4743 }
4744
4745 self.report_inline_completion_event(true, cx);
4746
4747 match &active_inline_completion.completion {
4748 InlineCompletion::Move(position) => {
4749 let position = *position;
4750 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4751 selections.select_anchor_ranges([position..position]);
4752 });
4753 }
4754 InlineCompletion::Edit { edits, .. } => {
4755 // Find an insertion that starts at the cursor position.
4756 let snapshot = self.buffer.read(cx).snapshot(cx);
4757 let cursor_offset = self.selections.newest::<usize>(cx).head();
4758 let insertion = edits.iter().find_map(|(range, text)| {
4759 let range = range.to_offset(&snapshot);
4760 if range.is_empty() && range.start == cursor_offset {
4761 Some(text)
4762 } else {
4763 None
4764 }
4765 });
4766
4767 if let Some(text) = insertion {
4768 let mut partial_completion = text
4769 .chars()
4770 .by_ref()
4771 .take_while(|c| c.is_alphabetic())
4772 .collect::<String>();
4773 if partial_completion.is_empty() {
4774 partial_completion = text
4775 .chars()
4776 .by_ref()
4777 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4778 .collect::<String>();
4779 }
4780
4781 cx.emit(EditorEvent::InputHandled {
4782 utf16_range_to_replace: None,
4783 text: partial_completion.clone().into(),
4784 });
4785
4786 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4787
4788 self.refresh_inline_completion(true, true, cx);
4789 cx.notify();
4790 } else {
4791 self.accept_inline_completion(&Default::default(), cx);
4792 }
4793 }
4794 }
4795 }
4796
4797 fn discard_inline_completion(
4798 &mut self,
4799 should_report_inline_completion_event: bool,
4800 cx: &mut ViewContext<Self>,
4801 ) -> bool {
4802 if should_report_inline_completion_event {
4803 self.report_inline_completion_event(false, cx);
4804 }
4805
4806 if let Some(provider) = self.inline_completion_provider() {
4807 provider.discard(cx);
4808 }
4809
4810 self.take_active_inline_completion(cx).is_some()
4811 }
4812
4813 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4814 let Some(provider) = self.inline_completion_provider() else {
4815 return;
4816 };
4817
4818 let Some((_, buffer, _)) = self
4819 .buffer
4820 .read(cx)
4821 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4822 else {
4823 return;
4824 };
4825
4826 let extension = buffer
4827 .read(cx)
4828 .file()
4829 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4830
4831 let event_type = match accepted {
4832 true => "Inline Completion Accepted",
4833 false => "Inline Completion Discarded",
4834 };
4835 telemetry::event!(
4836 event_type,
4837 provider = provider.name(),
4838 suggestion_accepted = accepted,
4839 file_extension = extension,
4840 );
4841 }
4842
4843 pub fn has_active_inline_completion(&self) -> bool {
4844 self.active_inline_completion.is_some()
4845 }
4846
4847 fn take_active_inline_completion(
4848 &mut self,
4849 cx: &mut ViewContext<Self>,
4850 ) -> Option<InlineCompletion> {
4851 let active_inline_completion = self.active_inline_completion.take()?;
4852 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4853 self.clear_highlights::<InlineCompletionHighlight>(cx);
4854 Some(active_inline_completion.completion)
4855 }
4856
4857 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4858 let selection = self.selections.newest_anchor();
4859 let cursor = selection.head();
4860 let multibuffer = self.buffer.read(cx).snapshot(cx);
4861 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4862 let excerpt_id = cursor.excerpt_id;
4863
4864 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4865 && (self.context_menu.borrow().is_some()
4866 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4867 if completions_menu_has_precedence
4868 || !offset_selection.is_empty()
4869 || !self.enable_inline_completions
4870 || self
4871 .active_inline_completion
4872 .as_ref()
4873 .map_or(false, |completion| {
4874 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4875 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4876 !invalidation_range.contains(&offset_selection.head())
4877 })
4878 {
4879 self.discard_inline_completion(false, cx);
4880 return None;
4881 }
4882
4883 self.take_active_inline_completion(cx);
4884 let provider = self.inline_completion_provider()?;
4885
4886 let (buffer, cursor_buffer_position) =
4887 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4888
4889 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4890 let edits = inline_completion
4891 .edits
4892 .into_iter()
4893 .flat_map(|(range, new_text)| {
4894 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4895 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4896 Some((start..end, new_text))
4897 })
4898 .collect::<Vec<_>>();
4899 if edits.is_empty() {
4900 return None;
4901 }
4902
4903 let first_edit_start = edits.first().unwrap().0.start;
4904 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
4905 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
4906
4907 let last_edit_end = edits.last().unwrap().0.end;
4908 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
4909 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
4910
4911 let cursor_row = cursor.to_point(&multibuffer).row;
4912
4913 let mut inlay_ids = Vec::new();
4914 let invalidation_row_range;
4915 let completion = if cursor_row < edit_start_row {
4916 invalidation_row_range = cursor_row..edit_end_row;
4917 InlineCompletion::Move(first_edit_start)
4918 } else if cursor_row > edit_end_row {
4919 invalidation_row_range = edit_start_row..cursor_row;
4920 InlineCompletion::Move(first_edit_start)
4921 } else {
4922 if edits
4923 .iter()
4924 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4925 {
4926 let mut inlays = Vec::new();
4927 for (range, new_text) in &edits {
4928 let inlay = Inlay::inline_completion(
4929 post_inc(&mut self.next_inlay_id),
4930 range.start,
4931 new_text.as_str(),
4932 );
4933 inlay_ids.push(inlay.id);
4934 inlays.push(inlay);
4935 }
4936
4937 self.splice_inlays(vec![], inlays, cx);
4938 } else {
4939 let background_color = cx.theme().status().deleted_background;
4940 self.highlight_text::<InlineCompletionHighlight>(
4941 edits.iter().map(|(range, _)| range.clone()).collect(),
4942 HighlightStyle {
4943 background_color: Some(background_color),
4944 ..Default::default()
4945 },
4946 cx,
4947 );
4948 }
4949
4950 invalidation_row_range = edit_start_row..edit_end_row;
4951
4952 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
4953 if provider.show_tab_accept_marker()
4954 && first_edit_start_point.row == last_edit_end_point.row
4955 && !edits.iter().any(|(_, edit)| edit.contains('\n'))
4956 {
4957 EditDisplayMode::TabAccept
4958 } else {
4959 EditDisplayMode::Inline
4960 }
4961 } else {
4962 EditDisplayMode::DiffPopover
4963 };
4964
4965 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
4966
4967 InlineCompletion::Edit {
4968 edits,
4969 edit_preview: inline_completion.edit_preview,
4970 display_mode,
4971 snapshot,
4972 }
4973 };
4974
4975 let invalidation_range = multibuffer
4976 .anchor_before(Point::new(invalidation_row_range.start, 0))
4977 ..multibuffer.anchor_after(Point::new(
4978 invalidation_row_range.end,
4979 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4980 ));
4981
4982 self.active_inline_completion = Some(InlineCompletionState {
4983 inlay_ids,
4984 completion,
4985 invalidation_range,
4986 });
4987
4988 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4989 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4990 match self.context_menu.borrow_mut().as_mut() {
4991 Some(CodeContextMenu::Completions(menu)) => {
4992 menu.show_inline_completion_hint(hint);
4993 }
4994 _ => {}
4995 }
4996 }
4997 }
4998
4999 cx.notify();
5000
5001 Some(())
5002 }
5003
5004 fn inline_completion_menu_hint(
5005 &self,
5006 cx: &mut ViewContext<Self>,
5007 ) -> Option<InlineCompletionMenuHint> {
5008 let provider = self.inline_completion_provider()?;
5009 if self.has_active_inline_completion() {
5010 let editor_snapshot = self.snapshot(cx);
5011
5012 let text = match &self.active_inline_completion.as_ref()?.completion {
5013 InlineCompletion::Edit {
5014 edits,
5015 edit_preview,
5016 display_mode: _,
5017 snapshot,
5018 } => edit_preview
5019 .as_ref()
5020 .and_then(|edit_preview| {
5021 inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
5022 })
5023 .map(InlineCompletionText::Edit),
5024 InlineCompletion::Move(target) => {
5025 let target_point =
5026 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
5027 let target_line = target_point.row + 1;
5028 Some(InlineCompletionText::Move(
5029 format!("Jump to edit in line {}", target_line).into(),
5030 ))
5031 }
5032 };
5033
5034 Some(InlineCompletionMenuHint::Loaded { text: text? })
5035 } else if provider.is_refreshing(cx) {
5036 Some(InlineCompletionMenuHint::Loading)
5037 } else if provider.needs_terms_acceptance(cx) {
5038 Some(InlineCompletionMenuHint::PendingTermsAcceptance)
5039 } else {
5040 Some(InlineCompletionMenuHint::None)
5041 }
5042 }
5043
5044 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5045 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5046 }
5047
5048 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
5049 let by_provider = matches!(
5050 self.menu_inline_completions_policy,
5051 MenuInlineCompletionsPolicy::ByProvider
5052 );
5053
5054 by_provider
5055 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5056 && self
5057 .inline_completion_provider()
5058 .map_or(false, |provider| provider.show_completions_in_menu())
5059 }
5060
5061 fn render_code_actions_indicator(
5062 &self,
5063 _style: &EditorStyle,
5064 row: DisplayRow,
5065 is_active: bool,
5066 cx: &mut ViewContext<Self>,
5067 ) -> Option<IconButton> {
5068 if self.available_code_actions.is_some() {
5069 Some(
5070 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5071 .shape(ui::IconButtonShape::Square)
5072 .icon_size(IconSize::XSmall)
5073 .icon_color(Color::Muted)
5074 .toggle_state(is_active)
5075 .tooltip({
5076 let focus_handle = self.focus_handle.clone();
5077 move |cx| {
5078 Tooltip::for_action_in(
5079 "Toggle Code Actions",
5080 &ToggleCodeActions {
5081 deployed_from_indicator: None,
5082 },
5083 &focus_handle,
5084 cx,
5085 )
5086 }
5087 })
5088 .on_click(cx.listener(move |editor, _e, cx| {
5089 editor.focus(cx);
5090 editor.toggle_code_actions(
5091 &ToggleCodeActions {
5092 deployed_from_indicator: Some(row),
5093 },
5094 cx,
5095 );
5096 })),
5097 )
5098 } else {
5099 None
5100 }
5101 }
5102
5103 fn clear_tasks(&mut self) {
5104 self.tasks.clear()
5105 }
5106
5107 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5108 if self.tasks.insert(key, value).is_some() {
5109 // This case should hopefully be rare, but just in case...
5110 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5111 }
5112 }
5113
5114 fn build_tasks_context(
5115 project: &Model<Project>,
5116 buffer: &Model<Buffer>,
5117 buffer_row: u32,
5118 tasks: &Arc<RunnableTasks>,
5119 cx: &mut ViewContext<Self>,
5120 ) -> Task<Option<task::TaskContext>> {
5121 let position = Point::new(buffer_row, tasks.column);
5122 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5123 let location = Location {
5124 buffer: buffer.clone(),
5125 range: range_start..range_start,
5126 };
5127 // Fill in the environmental variables from the tree-sitter captures
5128 let mut captured_task_variables = TaskVariables::default();
5129 for (capture_name, value) in tasks.extra_variables.clone() {
5130 captured_task_variables.insert(
5131 task::VariableName::Custom(capture_name.into()),
5132 value.clone(),
5133 );
5134 }
5135 project.update(cx, |project, cx| {
5136 project.task_store().update(cx, |task_store, cx| {
5137 task_store.task_context_for_location(captured_task_variables, location, cx)
5138 })
5139 })
5140 }
5141
5142 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5143 let Some((workspace, _)) = self.workspace.clone() else {
5144 return;
5145 };
5146 let Some(project) = self.project.clone() else {
5147 return;
5148 };
5149
5150 // Try to find a closest, enclosing node using tree-sitter that has a
5151 // task
5152 let Some((buffer, buffer_row, tasks)) = self
5153 .find_enclosing_node_task(cx)
5154 // Or find the task that's closest in row-distance.
5155 .or_else(|| self.find_closest_task(cx))
5156 else {
5157 return;
5158 };
5159
5160 let reveal_strategy = action.reveal;
5161 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5162 cx.spawn(|_, mut cx| async move {
5163 let context = task_context.await?;
5164 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5165
5166 let resolved = resolved_task.resolved.as_mut()?;
5167 resolved.reveal = reveal_strategy;
5168
5169 workspace
5170 .update(&mut cx, |workspace, cx| {
5171 workspace::tasks::schedule_resolved_task(
5172 workspace,
5173 task_source_kind,
5174 resolved_task,
5175 false,
5176 cx,
5177 );
5178 })
5179 .ok()
5180 })
5181 .detach();
5182 }
5183
5184 fn find_closest_task(
5185 &mut self,
5186 cx: &mut ViewContext<Self>,
5187 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5188 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5189
5190 let ((buffer_id, row), tasks) = self
5191 .tasks
5192 .iter()
5193 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5194
5195 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5196 let tasks = Arc::new(tasks.to_owned());
5197 Some((buffer, *row, tasks))
5198 }
5199
5200 fn find_enclosing_node_task(
5201 &mut self,
5202 cx: &mut ViewContext<Self>,
5203 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5204 let snapshot = self.buffer.read(cx).snapshot(cx);
5205 let offset = self.selections.newest::<usize>(cx).head();
5206 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5207 let buffer_id = excerpt.buffer().remote_id();
5208
5209 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5210 let mut cursor = layer.node().walk();
5211
5212 while cursor.goto_first_child_for_byte(offset).is_some() {
5213 if cursor.node().end_byte() == offset {
5214 cursor.goto_next_sibling();
5215 }
5216 }
5217
5218 // Ascend to the smallest ancestor that contains the range and has a task.
5219 loop {
5220 let node = cursor.node();
5221 let node_range = node.byte_range();
5222 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5223
5224 // Check if this node contains our offset
5225 if node_range.start <= offset && node_range.end >= offset {
5226 // If it contains offset, check for task
5227 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5228 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5229 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5230 }
5231 }
5232
5233 if !cursor.goto_parent() {
5234 break;
5235 }
5236 }
5237 None
5238 }
5239
5240 fn render_run_indicator(
5241 &self,
5242 _style: &EditorStyle,
5243 is_active: bool,
5244 row: DisplayRow,
5245 cx: &mut ViewContext<Self>,
5246 ) -> IconButton {
5247 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5248 .shape(ui::IconButtonShape::Square)
5249 .icon_size(IconSize::XSmall)
5250 .icon_color(Color::Muted)
5251 .toggle_state(is_active)
5252 .on_click(cx.listener(move |editor, _e, cx| {
5253 editor.focus(cx);
5254 editor.toggle_code_actions(
5255 &ToggleCodeActions {
5256 deployed_from_indicator: Some(row),
5257 },
5258 cx,
5259 );
5260 }))
5261 }
5262
5263 #[cfg(any(test, feature = "test-support"))]
5264 pub fn context_menu_visible(&self) -> bool {
5265 self.context_menu
5266 .borrow()
5267 .as_ref()
5268 .map_or(false, |menu| menu.visible())
5269 }
5270
5271 #[cfg(feature = "test-support")]
5272 pub fn context_menu_contains_inline_completion(&self) -> bool {
5273 self.context_menu
5274 .borrow()
5275 .as_ref()
5276 .map_or(false, |menu| match menu {
5277 CodeContextMenu::Completions(menu) => {
5278 menu.entries.borrow().first().map_or(false, |entry| {
5279 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5280 })
5281 }
5282 CodeContextMenu::CodeActions(_) => false,
5283 })
5284 }
5285
5286 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5287 self.context_menu
5288 .borrow()
5289 .as_ref()
5290 .map(|menu| menu.origin(cursor_position))
5291 }
5292
5293 fn render_context_menu(
5294 &self,
5295 style: &EditorStyle,
5296 max_height_in_lines: u32,
5297 y_flipped: bool,
5298 cx: &mut ViewContext<Editor>,
5299 ) -> Option<AnyElement> {
5300 self.context_menu.borrow().as_ref().and_then(|menu| {
5301 if menu.visible() {
5302 Some(menu.render(style, max_height_in_lines, y_flipped, cx))
5303 } else {
5304 None
5305 }
5306 })
5307 }
5308
5309 fn render_context_menu_aside(
5310 &self,
5311 style: &EditorStyle,
5312 max_size: Size<Pixels>,
5313 cx: &mut ViewContext<Editor>,
5314 ) -> Option<AnyElement> {
5315 self.context_menu.borrow().as_ref().and_then(|menu| {
5316 if menu.visible() {
5317 menu.render_aside(
5318 style,
5319 max_size,
5320 self.workspace.as_ref().map(|(w, _)| w.clone()),
5321 cx,
5322 )
5323 } else {
5324 None
5325 }
5326 })
5327 }
5328
5329 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5330 cx.notify();
5331 self.completion_tasks.clear();
5332 let context_menu = self.context_menu.borrow_mut().take();
5333 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5334 self.update_visible_inline_completion(cx);
5335 }
5336 context_menu
5337 }
5338
5339 fn show_snippet_choices(
5340 &mut self,
5341 choices: &Vec<String>,
5342 selection: Range<Anchor>,
5343 cx: &mut ViewContext<Self>,
5344 ) {
5345 if selection.start.buffer_id.is_none() {
5346 return;
5347 }
5348 let buffer_id = selection.start.buffer_id.unwrap();
5349 let buffer = self.buffer().read(cx).buffer(buffer_id);
5350 let id = post_inc(&mut self.next_completion_id);
5351
5352 if let Some(buffer) = buffer {
5353 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5354 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5355 ));
5356 }
5357 }
5358
5359 pub fn insert_snippet(
5360 &mut self,
5361 insertion_ranges: &[Range<usize>],
5362 snippet: Snippet,
5363 cx: &mut ViewContext<Self>,
5364 ) -> Result<()> {
5365 struct Tabstop<T> {
5366 is_end_tabstop: bool,
5367 ranges: Vec<Range<T>>,
5368 choices: Option<Vec<String>>,
5369 }
5370
5371 let tabstops = self.buffer.update(cx, |buffer, cx| {
5372 let snippet_text: Arc<str> = snippet.text.clone().into();
5373 buffer.edit(
5374 insertion_ranges
5375 .iter()
5376 .cloned()
5377 .map(|range| (range, snippet_text.clone())),
5378 Some(AutoindentMode::EachLine),
5379 cx,
5380 );
5381
5382 let snapshot = &*buffer.read(cx);
5383 let snippet = &snippet;
5384 snippet
5385 .tabstops
5386 .iter()
5387 .map(|tabstop| {
5388 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5389 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5390 });
5391 let mut tabstop_ranges = tabstop
5392 .ranges
5393 .iter()
5394 .flat_map(|tabstop_range| {
5395 let mut delta = 0_isize;
5396 insertion_ranges.iter().map(move |insertion_range| {
5397 let insertion_start = insertion_range.start as isize + delta;
5398 delta +=
5399 snippet.text.len() as isize - insertion_range.len() as isize;
5400
5401 let start = ((insertion_start + tabstop_range.start) as usize)
5402 .min(snapshot.len());
5403 let end = ((insertion_start + tabstop_range.end) as usize)
5404 .min(snapshot.len());
5405 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5406 })
5407 })
5408 .collect::<Vec<_>>();
5409 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5410
5411 Tabstop {
5412 is_end_tabstop,
5413 ranges: tabstop_ranges,
5414 choices: tabstop.choices.clone(),
5415 }
5416 })
5417 .collect::<Vec<_>>()
5418 });
5419 if let Some(tabstop) = tabstops.first() {
5420 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5421 s.select_ranges(tabstop.ranges.iter().cloned());
5422 });
5423
5424 if let Some(choices) = &tabstop.choices {
5425 if let Some(selection) = tabstop.ranges.first() {
5426 self.show_snippet_choices(choices, selection.clone(), cx)
5427 }
5428 }
5429
5430 // If we're already at the last tabstop and it's at the end of the snippet,
5431 // we're done, we don't need to keep the state around.
5432 if !tabstop.is_end_tabstop {
5433 let choices = tabstops
5434 .iter()
5435 .map(|tabstop| tabstop.choices.clone())
5436 .collect();
5437
5438 let ranges = tabstops
5439 .into_iter()
5440 .map(|tabstop| tabstop.ranges)
5441 .collect::<Vec<_>>();
5442
5443 self.snippet_stack.push(SnippetState {
5444 active_index: 0,
5445 ranges,
5446 choices,
5447 });
5448 }
5449
5450 // Check whether the just-entered snippet ends with an auto-closable bracket.
5451 if self.autoclose_regions.is_empty() {
5452 let snapshot = self.buffer.read(cx).snapshot(cx);
5453 for selection in &mut self.selections.all::<Point>(cx) {
5454 let selection_head = selection.head();
5455 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5456 continue;
5457 };
5458
5459 let mut bracket_pair = None;
5460 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5461 let prev_chars = snapshot
5462 .reversed_chars_at(selection_head)
5463 .collect::<String>();
5464 for (pair, enabled) in scope.brackets() {
5465 if enabled
5466 && pair.close
5467 && prev_chars.starts_with(pair.start.as_str())
5468 && next_chars.starts_with(pair.end.as_str())
5469 {
5470 bracket_pair = Some(pair.clone());
5471 break;
5472 }
5473 }
5474 if let Some(pair) = bracket_pair {
5475 let start = snapshot.anchor_after(selection_head);
5476 let end = snapshot.anchor_after(selection_head);
5477 self.autoclose_regions.push(AutocloseRegion {
5478 selection_id: selection.id,
5479 range: start..end,
5480 pair,
5481 });
5482 }
5483 }
5484 }
5485 }
5486 Ok(())
5487 }
5488
5489 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5490 self.move_to_snippet_tabstop(Bias::Right, cx)
5491 }
5492
5493 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5494 self.move_to_snippet_tabstop(Bias::Left, cx)
5495 }
5496
5497 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5498 if let Some(mut snippet) = self.snippet_stack.pop() {
5499 match bias {
5500 Bias::Left => {
5501 if snippet.active_index > 0 {
5502 snippet.active_index -= 1;
5503 } else {
5504 self.snippet_stack.push(snippet);
5505 return false;
5506 }
5507 }
5508 Bias::Right => {
5509 if snippet.active_index + 1 < snippet.ranges.len() {
5510 snippet.active_index += 1;
5511 } else {
5512 self.snippet_stack.push(snippet);
5513 return false;
5514 }
5515 }
5516 }
5517 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5518 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5519 s.select_anchor_ranges(current_ranges.iter().cloned())
5520 });
5521
5522 if let Some(choices) = &snippet.choices[snippet.active_index] {
5523 if let Some(selection) = current_ranges.first() {
5524 self.show_snippet_choices(&choices, selection.clone(), cx);
5525 }
5526 }
5527
5528 // If snippet state is not at the last tabstop, push it back on the stack
5529 if snippet.active_index + 1 < snippet.ranges.len() {
5530 self.snippet_stack.push(snippet);
5531 }
5532 return true;
5533 }
5534 }
5535
5536 false
5537 }
5538
5539 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5540 self.transact(cx, |this, cx| {
5541 this.select_all(&SelectAll, cx);
5542 this.insert("", cx);
5543 });
5544 }
5545
5546 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5547 self.transact(cx, |this, cx| {
5548 this.select_autoclose_pair(cx);
5549 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5550 if !this.linked_edit_ranges.is_empty() {
5551 let selections = this.selections.all::<MultiBufferPoint>(cx);
5552 let snapshot = this.buffer.read(cx).snapshot(cx);
5553
5554 for selection in selections.iter() {
5555 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5556 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5557 if selection_start.buffer_id != selection_end.buffer_id {
5558 continue;
5559 }
5560 if let Some(ranges) =
5561 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5562 {
5563 for (buffer, entries) in ranges {
5564 linked_ranges.entry(buffer).or_default().extend(entries);
5565 }
5566 }
5567 }
5568 }
5569
5570 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5571 if !this.selections.line_mode {
5572 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5573 for selection in &mut selections {
5574 if selection.is_empty() {
5575 let old_head = selection.head();
5576 let mut new_head =
5577 movement::left(&display_map, old_head.to_display_point(&display_map))
5578 .to_point(&display_map);
5579 if let Some((buffer, line_buffer_range)) = display_map
5580 .buffer_snapshot
5581 .buffer_line_for_row(MultiBufferRow(old_head.row))
5582 {
5583 let indent_size =
5584 buffer.indent_size_for_line(line_buffer_range.start.row);
5585 let indent_len = match indent_size.kind {
5586 IndentKind::Space => {
5587 buffer.settings_at(line_buffer_range.start, cx).tab_size
5588 }
5589 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5590 };
5591 if old_head.column <= indent_size.len && old_head.column > 0 {
5592 let indent_len = indent_len.get();
5593 new_head = cmp::min(
5594 new_head,
5595 MultiBufferPoint::new(
5596 old_head.row,
5597 ((old_head.column - 1) / indent_len) * indent_len,
5598 ),
5599 );
5600 }
5601 }
5602
5603 selection.set_head(new_head, SelectionGoal::None);
5604 }
5605 }
5606 }
5607
5608 this.signature_help_state.set_backspace_pressed(true);
5609 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5610 this.insert("", cx);
5611 let empty_str: Arc<str> = Arc::from("");
5612 for (buffer, edits) in linked_ranges {
5613 let snapshot = buffer.read(cx).snapshot();
5614 use text::ToPoint as TP;
5615
5616 let edits = edits
5617 .into_iter()
5618 .map(|range| {
5619 let end_point = TP::to_point(&range.end, &snapshot);
5620 let mut start_point = TP::to_point(&range.start, &snapshot);
5621
5622 if end_point == start_point {
5623 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5624 .saturating_sub(1);
5625 start_point =
5626 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5627 };
5628
5629 (start_point..end_point, empty_str.clone())
5630 })
5631 .sorted_by_key(|(range, _)| range.start)
5632 .collect::<Vec<_>>();
5633 buffer.update(cx, |this, cx| {
5634 this.edit(edits, None, cx);
5635 })
5636 }
5637 this.refresh_inline_completion(true, false, cx);
5638 linked_editing_ranges::refresh_linked_ranges(this, cx);
5639 });
5640 }
5641
5642 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5643 self.transact(cx, |this, cx| {
5644 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5645 let line_mode = s.line_mode;
5646 s.move_with(|map, selection| {
5647 if selection.is_empty() && !line_mode {
5648 let cursor = movement::right(map, selection.head());
5649 selection.end = cursor;
5650 selection.reversed = true;
5651 selection.goal = SelectionGoal::None;
5652 }
5653 })
5654 });
5655 this.insert("", cx);
5656 this.refresh_inline_completion(true, false, cx);
5657 });
5658 }
5659
5660 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5661 if self.move_to_prev_snippet_tabstop(cx) {
5662 return;
5663 }
5664
5665 self.outdent(&Outdent, cx);
5666 }
5667
5668 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5669 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5670 return;
5671 }
5672
5673 let mut selections = self.selections.all_adjusted(cx);
5674 let buffer = self.buffer.read(cx);
5675 let snapshot = buffer.snapshot(cx);
5676 let rows_iter = selections.iter().map(|s| s.head().row);
5677 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5678
5679 let mut edits = Vec::new();
5680 let mut prev_edited_row = 0;
5681 let mut row_delta = 0;
5682 for selection in &mut selections {
5683 if selection.start.row != prev_edited_row {
5684 row_delta = 0;
5685 }
5686 prev_edited_row = selection.end.row;
5687
5688 // If the selection is non-empty, then increase the indentation of the selected lines.
5689 if !selection.is_empty() {
5690 row_delta =
5691 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5692 continue;
5693 }
5694
5695 // If the selection is empty and the cursor is in the leading whitespace before the
5696 // suggested indentation, then auto-indent the line.
5697 let cursor = selection.head();
5698 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5699 if let Some(suggested_indent) =
5700 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5701 {
5702 if cursor.column < suggested_indent.len
5703 && cursor.column <= current_indent.len
5704 && current_indent.len <= suggested_indent.len
5705 {
5706 selection.start = Point::new(cursor.row, suggested_indent.len);
5707 selection.end = selection.start;
5708 if row_delta == 0 {
5709 edits.extend(Buffer::edit_for_indent_size_adjustment(
5710 cursor.row,
5711 current_indent,
5712 suggested_indent,
5713 ));
5714 row_delta = suggested_indent.len - current_indent.len;
5715 }
5716 continue;
5717 }
5718 }
5719
5720 // Otherwise, insert a hard or soft tab.
5721 let settings = buffer.settings_at(cursor, cx);
5722 let tab_size = if settings.hard_tabs {
5723 IndentSize::tab()
5724 } else {
5725 let tab_size = settings.tab_size.get();
5726 let char_column = snapshot
5727 .text_for_range(Point::new(cursor.row, 0)..cursor)
5728 .flat_map(str::chars)
5729 .count()
5730 + row_delta as usize;
5731 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5732 IndentSize::spaces(chars_to_next_tab_stop)
5733 };
5734 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5735 selection.end = selection.start;
5736 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5737 row_delta += tab_size.len;
5738 }
5739
5740 self.transact(cx, |this, cx| {
5741 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5742 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5743 this.refresh_inline_completion(true, false, cx);
5744 });
5745 }
5746
5747 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5748 if self.read_only(cx) {
5749 return;
5750 }
5751 let mut selections = self.selections.all::<Point>(cx);
5752 let mut prev_edited_row = 0;
5753 let mut row_delta = 0;
5754 let mut edits = Vec::new();
5755 let buffer = self.buffer.read(cx);
5756 let snapshot = buffer.snapshot(cx);
5757 for selection in &mut selections {
5758 if selection.start.row != prev_edited_row {
5759 row_delta = 0;
5760 }
5761 prev_edited_row = selection.end.row;
5762
5763 row_delta =
5764 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5765 }
5766
5767 self.transact(cx, |this, cx| {
5768 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5769 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5770 });
5771 }
5772
5773 fn indent_selection(
5774 buffer: &MultiBuffer,
5775 snapshot: &MultiBufferSnapshot,
5776 selection: &mut Selection<Point>,
5777 edits: &mut Vec<(Range<Point>, String)>,
5778 delta_for_start_row: u32,
5779 cx: &AppContext,
5780 ) -> u32 {
5781 let settings = buffer.settings_at(selection.start, cx);
5782 let tab_size = settings.tab_size.get();
5783 let indent_kind = if settings.hard_tabs {
5784 IndentKind::Tab
5785 } else {
5786 IndentKind::Space
5787 };
5788 let mut start_row = selection.start.row;
5789 let mut end_row = selection.end.row + 1;
5790
5791 // If a selection ends at the beginning of a line, don't indent
5792 // that last line.
5793 if selection.end.column == 0 && selection.end.row > selection.start.row {
5794 end_row -= 1;
5795 }
5796
5797 // Avoid re-indenting a row that has already been indented by a
5798 // previous selection, but still update this selection's column
5799 // to reflect that indentation.
5800 if delta_for_start_row > 0 {
5801 start_row += 1;
5802 selection.start.column += delta_for_start_row;
5803 if selection.end.row == selection.start.row {
5804 selection.end.column += delta_for_start_row;
5805 }
5806 }
5807
5808 let mut delta_for_end_row = 0;
5809 let has_multiple_rows = start_row + 1 != end_row;
5810 for row in start_row..end_row {
5811 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5812 let indent_delta = match (current_indent.kind, indent_kind) {
5813 (IndentKind::Space, IndentKind::Space) => {
5814 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5815 IndentSize::spaces(columns_to_next_tab_stop)
5816 }
5817 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5818 (_, IndentKind::Tab) => IndentSize::tab(),
5819 };
5820
5821 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5822 0
5823 } else {
5824 selection.start.column
5825 };
5826 let row_start = Point::new(row, start);
5827 edits.push((
5828 row_start..row_start,
5829 indent_delta.chars().collect::<String>(),
5830 ));
5831
5832 // Update this selection's endpoints to reflect the indentation.
5833 if row == selection.start.row {
5834 selection.start.column += indent_delta.len;
5835 }
5836 if row == selection.end.row {
5837 selection.end.column += indent_delta.len;
5838 delta_for_end_row = indent_delta.len;
5839 }
5840 }
5841
5842 if selection.start.row == selection.end.row {
5843 delta_for_start_row + delta_for_end_row
5844 } else {
5845 delta_for_end_row
5846 }
5847 }
5848
5849 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5850 if self.read_only(cx) {
5851 return;
5852 }
5853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5854 let selections = self.selections.all::<Point>(cx);
5855 let mut deletion_ranges = Vec::new();
5856 let mut last_outdent = None;
5857 {
5858 let buffer = self.buffer.read(cx);
5859 let snapshot = buffer.snapshot(cx);
5860 for selection in &selections {
5861 let settings = buffer.settings_at(selection.start, cx);
5862 let tab_size = settings.tab_size.get();
5863 let mut rows = selection.spanned_rows(false, &display_map);
5864
5865 // Avoid re-outdenting a row that has already been outdented by a
5866 // previous selection.
5867 if let Some(last_row) = last_outdent {
5868 if last_row == rows.start {
5869 rows.start = rows.start.next_row();
5870 }
5871 }
5872 let has_multiple_rows = rows.len() > 1;
5873 for row in rows.iter_rows() {
5874 let indent_size = snapshot.indent_size_for_line(row);
5875 if indent_size.len > 0 {
5876 let deletion_len = match indent_size.kind {
5877 IndentKind::Space => {
5878 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5879 if columns_to_prev_tab_stop == 0 {
5880 tab_size
5881 } else {
5882 columns_to_prev_tab_stop
5883 }
5884 }
5885 IndentKind::Tab => 1,
5886 };
5887 let start = if has_multiple_rows
5888 || deletion_len > selection.start.column
5889 || indent_size.len < selection.start.column
5890 {
5891 0
5892 } else {
5893 selection.start.column - deletion_len
5894 };
5895 deletion_ranges.push(
5896 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5897 );
5898 last_outdent = Some(row);
5899 }
5900 }
5901 }
5902 }
5903
5904 self.transact(cx, |this, cx| {
5905 this.buffer.update(cx, |buffer, cx| {
5906 let empty_str: Arc<str> = Arc::default();
5907 buffer.edit(
5908 deletion_ranges
5909 .into_iter()
5910 .map(|range| (range, empty_str.clone())),
5911 None,
5912 cx,
5913 );
5914 });
5915 let selections = this.selections.all::<usize>(cx);
5916 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5917 });
5918 }
5919
5920 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5921 if self.read_only(cx) {
5922 return;
5923 }
5924 let selections = self
5925 .selections
5926 .all::<usize>(cx)
5927 .into_iter()
5928 .map(|s| s.range());
5929
5930 self.transact(cx, |this, cx| {
5931 this.buffer.update(cx, |buffer, cx| {
5932 buffer.autoindent_ranges(selections, cx);
5933 });
5934 let selections = this.selections.all::<usize>(cx);
5935 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5936 });
5937 }
5938
5939 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5940 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5941 let selections = self.selections.all::<Point>(cx);
5942
5943 let mut new_cursors = Vec::new();
5944 let mut edit_ranges = Vec::new();
5945 let mut selections = selections.iter().peekable();
5946 while let Some(selection) = selections.next() {
5947 let mut rows = selection.spanned_rows(false, &display_map);
5948 let goal_display_column = selection.head().to_display_point(&display_map).column();
5949
5950 // Accumulate contiguous regions of rows that we want to delete.
5951 while let Some(next_selection) = selections.peek() {
5952 let next_rows = next_selection.spanned_rows(false, &display_map);
5953 if next_rows.start <= rows.end {
5954 rows.end = next_rows.end;
5955 selections.next().unwrap();
5956 } else {
5957 break;
5958 }
5959 }
5960
5961 let buffer = &display_map.buffer_snapshot;
5962 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5963 let edit_end;
5964 let cursor_buffer_row;
5965 if buffer.max_point().row >= rows.end.0 {
5966 // If there's a line after the range, delete the \n from the end of the row range
5967 // and position the cursor on the next line.
5968 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5969 cursor_buffer_row = rows.end;
5970 } else {
5971 // If there isn't a line after the range, delete the \n from the line before the
5972 // start of the row range and position the cursor there.
5973 edit_start = edit_start.saturating_sub(1);
5974 edit_end = buffer.len();
5975 cursor_buffer_row = rows.start.previous_row();
5976 }
5977
5978 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5979 *cursor.column_mut() =
5980 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5981
5982 new_cursors.push((
5983 selection.id,
5984 buffer.anchor_after(cursor.to_point(&display_map)),
5985 ));
5986 edit_ranges.push(edit_start..edit_end);
5987 }
5988
5989 self.transact(cx, |this, cx| {
5990 let buffer = this.buffer.update(cx, |buffer, cx| {
5991 let empty_str: Arc<str> = Arc::default();
5992 buffer.edit(
5993 edit_ranges
5994 .into_iter()
5995 .map(|range| (range, empty_str.clone())),
5996 None,
5997 cx,
5998 );
5999 buffer.snapshot(cx)
6000 });
6001 let new_selections = new_cursors
6002 .into_iter()
6003 .map(|(id, cursor)| {
6004 let cursor = cursor.to_point(&buffer);
6005 Selection {
6006 id,
6007 start: cursor,
6008 end: cursor,
6009 reversed: false,
6010 goal: SelectionGoal::None,
6011 }
6012 })
6013 .collect();
6014
6015 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6016 s.select(new_selections);
6017 });
6018 });
6019 }
6020
6021 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
6022 if self.read_only(cx) {
6023 return;
6024 }
6025 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6026 for selection in self.selections.all::<Point>(cx) {
6027 let start = MultiBufferRow(selection.start.row);
6028 // Treat single line selections as if they include the next line. Otherwise this action
6029 // would do nothing for single line selections individual cursors.
6030 let end = if selection.start.row == selection.end.row {
6031 MultiBufferRow(selection.start.row + 1)
6032 } else {
6033 MultiBufferRow(selection.end.row)
6034 };
6035
6036 if let Some(last_row_range) = row_ranges.last_mut() {
6037 if start <= last_row_range.end {
6038 last_row_range.end = end;
6039 continue;
6040 }
6041 }
6042 row_ranges.push(start..end);
6043 }
6044
6045 let snapshot = self.buffer.read(cx).snapshot(cx);
6046 let mut cursor_positions = Vec::new();
6047 for row_range in &row_ranges {
6048 let anchor = snapshot.anchor_before(Point::new(
6049 row_range.end.previous_row().0,
6050 snapshot.line_len(row_range.end.previous_row()),
6051 ));
6052 cursor_positions.push(anchor..anchor);
6053 }
6054
6055 self.transact(cx, |this, cx| {
6056 for row_range in row_ranges.into_iter().rev() {
6057 for row in row_range.iter_rows().rev() {
6058 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6059 let next_line_row = row.next_row();
6060 let indent = snapshot.indent_size_for_line(next_line_row);
6061 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6062
6063 let replace =
6064 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6065 " "
6066 } else {
6067 ""
6068 };
6069
6070 this.buffer.update(cx, |buffer, cx| {
6071 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6072 });
6073 }
6074 }
6075
6076 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6077 s.select_anchor_ranges(cursor_positions)
6078 });
6079 });
6080 }
6081
6082 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6083 self.join_lines_impl(true, cx);
6084 }
6085
6086 pub fn sort_lines_case_sensitive(
6087 &mut self,
6088 _: &SortLinesCaseSensitive,
6089 cx: &mut ViewContext<Self>,
6090 ) {
6091 self.manipulate_lines(cx, |lines| lines.sort())
6092 }
6093
6094 pub fn sort_lines_case_insensitive(
6095 &mut self,
6096 _: &SortLinesCaseInsensitive,
6097 cx: &mut ViewContext<Self>,
6098 ) {
6099 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6100 }
6101
6102 pub fn unique_lines_case_insensitive(
6103 &mut self,
6104 _: &UniqueLinesCaseInsensitive,
6105 cx: &mut ViewContext<Self>,
6106 ) {
6107 self.manipulate_lines(cx, |lines| {
6108 let mut seen = HashSet::default();
6109 lines.retain(|line| seen.insert(line.to_lowercase()));
6110 })
6111 }
6112
6113 pub fn unique_lines_case_sensitive(
6114 &mut self,
6115 _: &UniqueLinesCaseSensitive,
6116 cx: &mut ViewContext<Self>,
6117 ) {
6118 self.manipulate_lines(cx, |lines| {
6119 let mut seen = HashSet::default();
6120 lines.retain(|line| seen.insert(*line));
6121 })
6122 }
6123
6124 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6125 let mut revert_changes = HashMap::default();
6126 let snapshot = self.snapshot(cx);
6127 for hunk in snapshot
6128 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6129 {
6130 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6131 }
6132 if !revert_changes.is_empty() {
6133 self.transact(cx, |editor, cx| {
6134 editor.revert(revert_changes, cx);
6135 });
6136 }
6137 }
6138
6139 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6140 let Some(project) = self.project.clone() else {
6141 return;
6142 };
6143 self.reload(project, cx).detach_and_notify_err(cx);
6144 }
6145
6146 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6147 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6148 self.revert_hunks_in_ranges(selections, cx);
6149 }
6150
6151 fn revert_hunks_in_ranges(
6152 &mut self,
6153 ranges: impl Iterator<Item = Range<Point>>,
6154 cx: &mut ViewContext<Editor>,
6155 ) {
6156 let mut revert_changes = HashMap::default();
6157 let snapshot = self.snapshot(cx);
6158 for hunk in &snapshot.hunks_for_ranges(ranges) {
6159 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6160 }
6161 if !revert_changes.is_empty() {
6162 self.transact(cx, |editor, cx| {
6163 editor.revert(revert_changes, cx);
6164 });
6165 }
6166 }
6167
6168 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6169 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6170 let project_path = buffer.read(cx).project_path(cx)?;
6171 let project = self.project.as_ref()?.read(cx);
6172 let entry = project.entry_for_path(&project_path, cx)?;
6173 let parent = match &entry.canonical_path {
6174 Some(canonical_path) => canonical_path.to_path_buf(),
6175 None => project.absolute_path(&project_path, cx)?,
6176 }
6177 .parent()?
6178 .to_path_buf();
6179 Some(parent)
6180 }) {
6181 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6182 }
6183 }
6184
6185 pub fn prepare_revert_change(
6186 &self,
6187 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6188 hunk: &MultiBufferDiffHunk,
6189 cx: &mut WindowContext,
6190 ) -> Option<()> {
6191 let buffer = self.buffer.read(cx);
6192 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6193 let buffer = buffer.buffer(hunk.buffer_id)?;
6194 let buffer = buffer.read(cx);
6195 let original_text = change_set
6196 .read(cx)
6197 .base_text
6198 .as_ref()?
6199 .as_rope()
6200 .slice(hunk.diff_base_byte_range.clone());
6201 let buffer_snapshot = buffer.snapshot();
6202 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6203 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6204 probe
6205 .0
6206 .start
6207 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6208 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6209 }) {
6210 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6211 Some(())
6212 } else {
6213 None
6214 }
6215 }
6216
6217 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6218 self.manipulate_lines(cx, |lines| lines.reverse())
6219 }
6220
6221 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6222 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6223 }
6224
6225 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6226 where
6227 Fn: FnMut(&mut Vec<&str>),
6228 {
6229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6230 let buffer = self.buffer.read(cx).snapshot(cx);
6231
6232 let mut edits = Vec::new();
6233
6234 let selections = self.selections.all::<Point>(cx);
6235 let mut selections = selections.iter().peekable();
6236 let mut contiguous_row_selections = Vec::new();
6237 let mut new_selections = Vec::new();
6238 let mut added_lines = 0;
6239 let mut removed_lines = 0;
6240
6241 while let Some(selection) = selections.next() {
6242 let (start_row, end_row) = consume_contiguous_rows(
6243 &mut contiguous_row_selections,
6244 selection,
6245 &display_map,
6246 &mut selections,
6247 );
6248
6249 let start_point = Point::new(start_row.0, 0);
6250 let end_point = Point::new(
6251 end_row.previous_row().0,
6252 buffer.line_len(end_row.previous_row()),
6253 );
6254 let text = buffer
6255 .text_for_range(start_point..end_point)
6256 .collect::<String>();
6257
6258 let mut lines = text.split('\n').collect_vec();
6259
6260 let lines_before = lines.len();
6261 callback(&mut lines);
6262 let lines_after = lines.len();
6263
6264 edits.push((start_point..end_point, lines.join("\n")));
6265
6266 // Selections must change based on added and removed line count
6267 let start_row =
6268 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6269 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6270 new_selections.push(Selection {
6271 id: selection.id,
6272 start: start_row,
6273 end: end_row,
6274 goal: SelectionGoal::None,
6275 reversed: selection.reversed,
6276 });
6277
6278 if lines_after > lines_before {
6279 added_lines += lines_after - lines_before;
6280 } else if lines_before > lines_after {
6281 removed_lines += lines_before - lines_after;
6282 }
6283 }
6284
6285 self.transact(cx, |this, cx| {
6286 let buffer = this.buffer.update(cx, |buffer, cx| {
6287 buffer.edit(edits, None, cx);
6288 buffer.snapshot(cx)
6289 });
6290
6291 // Recalculate offsets on newly edited buffer
6292 let new_selections = new_selections
6293 .iter()
6294 .map(|s| {
6295 let start_point = Point::new(s.start.0, 0);
6296 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6297 Selection {
6298 id: s.id,
6299 start: buffer.point_to_offset(start_point),
6300 end: buffer.point_to_offset(end_point),
6301 goal: s.goal,
6302 reversed: s.reversed,
6303 }
6304 })
6305 .collect();
6306
6307 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6308 s.select(new_selections);
6309 });
6310
6311 this.request_autoscroll(Autoscroll::fit(), cx);
6312 });
6313 }
6314
6315 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6316 self.manipulate_text(cx, |text| text.to_uppercase())
6317 }
6318
6319 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6320 self.manipulate_text(cx, |text| text.to_lowercase())
6321 }
6322
6323 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6324 self.manipulate_text(cx, |text| {
6325 text.split('\n')
6326 .map(|line| line.to_case(Case::Title))
6327 .join("\n")
6328 })
6329 }
6330
6331 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6332 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6333 }
6334
6335 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6336 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6337 }
6338
6339 pub fn convert_to_upper_camel_case(
6340 &mut self,
6341 _: &ConvertToUpperCamelCase,
6342 cx: &mut ViewContext<Self>,
6343 ) {
6344 self.manipulate_text(cx, |text| {
6345 text.split('\n')
6346 .map(|line| line.to_case(Case::UpperCamel))
6347 .join("\n")
6348 })
6349 }
6350
6351 pub fn convert_to_lower_camel_case(
6352 &mut self,
6353 _: &ConvertToLowerCamelCase,
6354 cx: &mut ViewContext<Self>,
6355 ) {
6356 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6357 }
6358
6359 pub fn convert_to_opposite_case(
6360 &mut self,
6361 _: &ConvertToOppositeCase,
6362 cx: &mut ViewContext<Self>,
6363 ) {
6364 self.manipulate_text(cx, |text| {
6365 text.chars()
6366 .fold(String::with_capacity(text.len()), |mut t, c| {
6367 if c.is_uppercase() {
6368 t.extend(c.to_lowercase());
6369 } else {
6370 t.extend(c.to_uppercase());
6371 }
6372 t
6373 })
6374 })
6375 }
6376
6377 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6378 where
6379 Fn: FnMut(&str) -> String,
6380 {
6381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6382 let buffer = self.buffer.read(cx).snapshot(cx);
6383
6384 let mut new_selections = Vec::new();
6385 let mut edits = Vec::new();
6386 let mut selection_adjustment = 0i32;
6387
6388 for selection in self.selections.all::<usize>(cx) {
6389 let selection_is_empty = selection.is_empty();
6390
6391 let (start, end) = if selection_is_empty {
6392 let word_range = movement::surrounding_word(
6393 &display_map,
6394 selection.start.to_display_point(&display_map),
6395 );
6396 let start = word_range.start.to_offset(&display_map, Bias::Left);
6397 let end = word_range.end.to_offset(&display_map, Bias::Left);
6398 (start, end)
6399 } else {
6400 (selection.start, selection.end)
6401 };
6402
6403 let text = buffer.text_for_range(start..end).collect::<String>();
6404 let old_length = text.len() as i32;
6405 let text = callback(&text);
6406
6407 new_selections.push(Selection {
6408 start: (start as i32 - selection_adjustment) as usize,
6409 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6410 goal: SelectionGoal::None,
6411 ..selection
6412 });
6413
6414 selection_adjustment += old_length - text.len() as i32;
6415
6416 edits.push((start..end, text));
6417 }
6418
6419 self.transact(cx, |this, cx| {
6420 this.buffer.update(cx, |buffer, cx| {
6421 buffer.edit(edits, None, cx);
6422 });
6423
6424 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6425 s.select(new_selections);
6426 });
6427
6428 this.request_autoscroll(Autoscroll::fit(), cx);
6429 });
6430 }
6431
6432 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6434 let buffer = &display_map.buffer_snapshot;
6435 let selections = self.selections.all::<Point>(cx);
6436
6437 let mut edits = Vec::new();
6438 let mut selections_iter = selections.iter().peekable();
6439 while let Some(selection) = selections_iter.next() {
6440 let mut rows = selection.spanned_rows(false, &display_map);
6441 // duplicate line-wise
6442 if whole_lines || selection.start == selection.end {
6443 // Avoid duplicating the same lines twice.
6444 while let Some(next_selection) = selections_iter.peek() {
6445 let next_rows = next_selection.spanned_rows(false, &display_map);
6446 if next_rows.start < rows.end {
6447 rows.end = next_rows.end;
6448 selections_iter.next().unwrap();
6449 } else {
6450 break;
6451 }
6452 }
6453
6454 // Copy the text from the selected row region and splice it either at the start
6455 // or end of the region.
6456 let start = Point::new(rows.start.0, 0);
6457 let end = Point::new(
6458 rows.end.previous_row().0,
6459 buffer.line_len(rows.end.previous_row()),
6460 );
6461 let text = buffer
6462 .text_for_range(start..end)
6463 .chain(Some("\n"))
6464 .collect::<String>();
6465 let insert_location = if upwards {
6466 Point::new(rows.end.0, 0)
6467 } else {
6468 start
6469 };
6470 edits.push((insert_location..insert_location, text));
6471 } else {
6472 // duplicate character-wise
6473 let start = selection.start;
6474 let end = selection.end;
6475 let text = buffer.text_for_range(start..end).collect::<String>();
6476 edits.push((selection.end..selection.end, text));
6477 }
6478 }
6479
6480 self.transact(cx, |this, cx| {
6481 this.buffer.update(cx, |buffer, cx| {
6482 buffer.edit(edits, None, cx);
6483 });
6484
6485 this.request_autoscroll(Autoscroll::fit(), cx);
6486 });
6487 }
6488
6489 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6490 self.duplicate(true, true, cx);
6491 }
6492
6493 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6494 self.duplicate(false, true, cx);
6495 }
6496
6497 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6498 self.duplicate(false, false, cx);
6499 }
6500
6501 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6502 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6503 let buffer = self.buffer.read(cx).snapshot(cx);
6504
6505 let mut edits = Vec::new();
6506 let mut unfold_ranges = Vec::new();
6507 let mut refold_creases = Vec::new();
6508
6509 let selections = self.selections.all::<Point>(cx);
6510 let mut selections = selections.iter().peekable();
6511 let mut contiguous_row_selections = Vec::new();
6512 let mut new_selections = Vec::new();
6513
6514 while let Some(selection) = selections.next() {
6515 // Find all the selections that span a contiguous row range
6516 let (start_row, end_row) = consume_contiguous_rows(
6517 &mut contiguous_row_selections,
6518 selection,
6519 &display_map,
6520 &mut selections,
6521 );
6522
6523 // Move the text spanned by the row range to be before the line preceding the row range
6524 if start_row.0 > 0 {
6525 let range_to_move = Point::new(
6526 start_row.previous_row().0,
6527 buffer.line_len(start_row.previous_row()),
6528 )
6529 ..Point::new(
6530 end_row.previous_row().0,
6531 buffer.line_len(end_row.previous_row()),
6532 );
6533 let insertion_point = display_map
6534 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6535 .0;
6536
6537 // Don't move lines across excerpts
6538 if buffer
6539 .excerpt_containing(insertion_point..range_to_move.end)
6540 .is_some()
6541 {
6542 let text = buffer
6543 .text_for_range(range_to_move.clone())
6544 .flat_map(|s| s.chars())
6545 .skip(1)
6546 .chain(['\n'])
6547 .collect::<String>();
6548
6549 edits.push((
6550 buffer.anchor_after(range_to_move.start)
6551 ..buffer.anchor_before(range_to_move.end),
6552 String::new(),
6553 ));
6554 let insertion_anchor = buffer.anchor_after(insertion_point);
6555 edits.push((insertion_anchor..insertion_anchor, text));
6556
6557 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6558
6559 // Move selections up
6560 new_selections.extend(contiguous_row_selections.drain(..).map(
6561 |mut selection| {
6562 selection.start.row -= row_delta;
6563 selection.end.row -= row_delta;
6564 selection
6565 },
6566 ));
6567
6568 // Move folds up
6569 unfold_ranges.push(range_to_move.clone());
6570 for fold in display_map.folds_in_range(
6571 buffer.anchor_before(range_to_move.start)
6572 ..buffer.anchor_after(range_to_move.end),
6573 ) {
6574 let mut start = fold.range.start.to_point(&buffer);
6575 let mut end = fold.range.end.to_point(&buffer);
6576 start.row -= row_delta;
6577 end.row -= row_delta;
6578 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6579 }
6580 }
6581 }
6582
6583 // If we didn't move line(s), preserve the existing selections
6584 new_selections.append(&mut contiguous_row_selections);
6585 }
6586
6587 self.transact(cx, |this, cx| {
6588 this.unfold_ranges(&unfold_ranges, true, true, cx);
6589 this.buffer.update(cx, |buffer, cx| {
6590 for (range, text) in edits {
6591 buffer.edit([(range, text)], None, cx);
6592 }
6593 });
6594 this.fold_creases(refold_creases, true, cx);
6595 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6596 s.select(new_selections);
6597 })
6598 });
6599 }
6600
6601 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6603 let buffer = self.buffer.read(cx).snapshot(cx);
6604
6605 let mut edits = Vec::new();
6606 let mut unfold_ranges = Vec::new();
6607 let mut refold_creases = Vec::new();
6608
6609 let selections = self.selections.all::<Point>(cx);
6610 let mut selections = selections.iter().peekable();
6611 let mut contiguous_row_selections = Vec::new();
6612 let mut new_selections = Vec::new();
6613
6614 while let Some(selection) = selections.next() {
6615 // Find all the selections that span a contiguous row range
6616 let (start_row, end_row) = consume_contiguous_rows(
6617 &mut contiguous_row_selections,
6618 selection,
6619 &display_map,
6620 &mut selections,
6621 );
6622
6623 // Move the text spanned by the row range to be after the last line of the row range
6624 if end_row.0 <= buffer.max_point().row {
6625 let range_to_move =
6626 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6627 let insertion_point = display_map
6628 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6629 .0;
6630
6631 // Don't move lines across excerpt boundaries
6632 if buffer
6633 .excerpt_containing(range_to_move.start..insertion_point)
6634 .is_some()
6635 {
6636 let mut text = String::from("\n");
6637 text.extend(buffer.text_for_range(range_to_move.clone()));
6638 text.pop(); // Drop trailing newline
6639 edits.push((
6640 buffer.anchor_after(range_to_move.start)
6641 ..buffer.anchor_before(range_to_move.end),
6642 String::new(),
6643 ));
6644 let insertion_anchor = buffer.anchor_after(insertion_point);
6645 edits.push((insertion_anchor..insertion_anchor, text));
6646
6647 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6648
6649 // Move selections down
6650 new_selections.extend(contiguous_row_selections.drain(..).map(
6651 |mut selection| {
6652 selection.start.row += row_delta;
6653 selection.end.row += row_delta;
6654 selection
6655 },
6656 ));
6657
6658 // Move folds down
6659 unfold_ranges.push(range_to_move.clone());
6660 for fold in display_map.folds_in_range(
6661 buffer.anchor_before(range_to_move.start)
6662 ..buffer.anchor_after(range_to_move.end),
6663 ) {
6664 let mut start = fold.range.start.to_point(&buffer);
6665 let mut end = fold.range.end.to_point(&buffer);
6666 start.row += row_delta;
6667 end.row += row_delta;
6668 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6669 }
6670 }
6671 }
6672
6673 // If we didn't move line(s), preserve the existing selections
6674 new_selections.append(&mut contiguous_row_selections);
6675 }
6676
6677 self.transact(cx, |this, cx| {
6678 this.unfold_ranges(&unfold_ranges, true, true, cx);
6679 this.buffer.update(cx, |buffer, cx| {
6680 for (range, text) in edits {
6681 buffer.edit([(range, text)], None, cx);
6682 }
6683 });
6684 this.fold_creases(refold_creases, true, cx);
6685 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6686 });
6687 }
6688
6689 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6690 let text_layout_details = &self.text_layout_details(cx);
6691 self.transact(cx, |this, cx| {
6692 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6693 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6694 let line_mode = s.line_mode;
6695 s.move_with(|display_map, selection| {
6696 if !selection.is_empty() || line_mode {
6697 return;
6698 }
6699
6700 let mut head = selection.head();
6701 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6702 if head.column() == display_map.line_len(head.row()) {
6703 transpose_offset = display_map
6704 .buffer_snapshot
6705 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6706 }
6707
6708 if transpose_offset == 0 {
6709 return;
6710 }
6711
6712 *head.column_mut() += 1;
6713 head = display_map.clip_point(head, Bias::Right);
6714 let goal = SelectionGoal::HorizontalPosition(
6715 display_map
6716 .x_for_display_point(head, text_layout_details)
6717 .into(),
6718 );
6719 selection.collapse_to(head, goal);
6720
6721 let transpose_start = display_map
6722 .buffer_snapshot
6723 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6724 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6725 let transpose_end = display_map
6726 .buffer_snapshot
6727 .clip_offset(transpose_offset + 1, Bias::Right);
6728 if let Some(ch) =
6729 display_map.buffer_snapshot.chars_at(transpose_start).next()
6730 {
6731 edits.push((transpose_start..transpose_offset, String::new()));
6732 edits.push((transpose_end..transpose_end, ch.to_string()));
6733 }
6734 }
6735 });
6736 edits
6737 });
6738 this.buffer
6739 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6740 let selections = this.selections.all::<usize>(cx);
6741 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6742 s.select(selections);
6743 });
6744 });
6745 }
6746
6747 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6748 self.rewrap_impl(IsVimMode::No, cx)
6749 }
6750
6751 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6752 let buffer = self.buffer.read(cx).snapshot(cx);
6753 let selections = self.selections.all::<Point>(cx);
6754 let mut selections = selections.iter().peekable();
6755
6756 let mut edits = Vec::new();
6757 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6758
6759 while let Some(selection) = selections.next() {
6760 let mut start_row = selection.start.row;
6761 let mut end_row = selection.end.row;
6762
6763 // Skip selections that overlap with a range that has already been rewrapped.
6764 let selection_range = start_row..end_row;
6765 if rewrapped_row_ranges
6766 .iter()
6767 .any(|range| range.overlaps(&selection_range))
6768 {
6769 continue;
6770 }
6771
6772 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6773
6774 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6775 match language_scope.language_name().0.as_ref() {
6776 "Markdown" | "Plain Text" => {
6777 should_rewrap = true;
6778 }
6779 _ => {}
6780 }
6781 }
6782
6783 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6784
6785 // Since not all lines in the selection may be at the same indent
6786 // level, choose the indent size that is the most common between all
6787 // of the lines.
6788 //
6789 // If there is a tie, we use the deepest indent.
6790 let (indent_size, indent_end) = {
6791 let mut indent_size_occurrences = HashMap::default();
6792 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6793
6794 for row in start_row..=end_row {
6795 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6796 rows_by_indent_size.entry(indent).or_default().push(row);
6797 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6798 }
6799
6800 let indent_size = indent_size_occurrences
6801 .into_iter()
6802 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6803 .map(|(indent, _)| indent)
6804 .unwrap_or_default();
6805 let row = rows_by_indent_size[&indent_size][0];
6806 let indent_end = Point::new(row, indent_size.len);
6807
6808 (indent_size, indent_end)
6809 };
6810
6811 let mut line_prefix = indent_size.chars().collect::<String>();
6812
6813 if let Some(comment_prefix) =
6814 buffer
6815 .language_scope_at(selection.head())
6816 .and_then(|language| {
6817 language
6818 .line_comment_prefixes()
6819 .iter()
6820 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6821 .cloned()
6822 })
6823 {
6824 line_prefix.push_str(&comment_prefix);
6825 should_rewrap = true;
6826 }
6827
6828 if !should_rewrap {
6829 continue;
6830 }
6831
6832 if selection.is_empty() {
6833 'expand_upwards: while start_row > 0 {
6834 let prev_row = start_row - 1;
6835 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6836 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6837 {
6838 start_row = prev_row;
6839 } else {
6840 break 'expand_upwards;
6841 }
6842 }
6843
6844 'expand_downwards: while end_row < buffer.max_point().row {
6845 let next_row = end_row + 1;
6846 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6847 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6848 {
6849 end_row = next_row;
6850 } else {
6851 break 'expand_downwards;
6852 }
6853 }
6854 }
6855
6856 let start = Point::new(start_row, 0);
6857 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6858 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6859 let Some(lines_without_prefixes) = selection_text
6860 .lines()
6861 .map(|line| {
6862 line.strip_prefix(&line_prefix)
6863 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6864 .ok_or_else(|| {
6865 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6866 })
6867 })
6868 .collect::<Result<Vec<_>, _>>()
6869 .log_err()
6870 else {
6871 continue;
6872 };
6873
6874 let wrap_column = buffer
6875 .settings_at(Point::new(start_row, 0), cx)
6876 .preferred_line_length as usize;
6877 let wrapped_text = wrap_with_prefix(
6878 line_prefix,
6879 lines_without_prefixes.join(" "),
6880 wrap_column,
6881 tab_size,
6882 );
6883
6884 // TODO: should always use char-based diff while still supporting cursor behavior that
6885 // matches vim.
6886 let diff = match is_vim_mode {
6887 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6888 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6889 };
6890 let mut offset = start.to_offset(&buffer);
6891 let mut moved_since_edit = true;
6892
6893 for change in diff.iter_all_changes() {
6894 let value = change.value();
6895 match change.tag() {
6896 ChangeTag::Equal => {
6897 offset += value.len();
6898 moved_since_edit = true;
6899 }
6900 ChangeTag::Delete => {
6901 let start = buffer.anchor_after(offset);
6902 let end = buffer.anchor_before(offset + value.len());
6903
6904 if moved_since_edit {
6905 edits.push((start..end, String::new()));
6906 } else {
6907 edits.last_mut().unwrap().0.end = end;
6908 }
6909
6910 offset += value.len();
6911 moved_since_edit = false;
6912 }
6913 ChangeTag::Insert => {
6914 if moved_since_edit {
6915 let anchor = buffer.anchor_after(offset);
6916 edits.push((anchor..anchor, value.to_string()));
6917 } else {
6918 edits.last_mut().unwrap().1.push_str(value);
6919 }
6920
6921 moved_since_edit = false;
6922 }
6923 }
6924 }
6925
6926 rewrapped_row_ranges.push(start_row..=end_row);
6927 }
6928
6929 self.buffer
6930 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6931 }
6932
6933 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6934 let mut text = String::new();
6935 let buffer = self.buffer.read(cx).snapshot(cx);
6936 let mut selections = self.selections.all::<Point>(cx);
6937 let mut clipboard_selections = Vec::with_capacity(selections.len());
6938 {
6939 let max_point = buffer.max_point();
6940 let mut is_first = true;
6941 for selection in &mut selections {
6942 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6943 if is_entire_line {
6944 selection.start = Point::new(selection.start.row, 0);
6945 if !selection.is_empty() && selection.end.column == 0 {
6946 selection.end = cmp::min(max_point, selection.end);
6947 } else {
6948 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6949 }
6950 selection.goal = SelectionGoal::None;
6951 }
6952 if is_first {
6953 is_first = false;
6954 } else {
6955 text += "\n";
6956 }
6957 let mut len = 0;
6958 for chunk in buffer.text_for_range(selection.start..selection.end) {
6959 text.push_str(chunk);
6960 len += chunk.len();
6961 }
6962 clipboard_selections.push(ClipboardSelection {
6963 len,
6964 is_entire_line,
6965 first_line_indent: buffer
6966 .indent_size_for_line(MultiBufferRow(selection.start.row))
6967 .len,
6968 });
6969 }
6970 }
6971
6972 self.transact(cx, |this, cx| {
6973 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6974 s.select(selections);
6975 });
6976 this.insert("", cx);
6977 });
6978 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6979 }
6980
6981 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6982 let item = self.cut_common(cx);
6983 cx.write_to_clipboard(item);
6984 }
6985
6986 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6987 self.change_selections(None, cx, |s| {
6988 s.move_with(|snapshot, sel| {
6989 if sel.is_empty() {
6990 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6991 }
6992 });
6993 });
6994 let item = self.cut_common(cx);
6995 cx.set_global(KillRing(item))
6996 }
6997
6998 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6999 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7000 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7001 (kill_ring.text().to_string(), kill_ring.metadata_json())
7002 } else {
7003 return;
7004 }
7005 } else {
7006 return;
7007 };
7008 self.do_paste(&text, metadata, false, cx);
7009 }
7010
7011 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7012 let selections = self.selections.all::<Point>(cx);
7013 let buffer = self.buffer.read(cx).read(cx);
7014 let mut text = String::new();
7015
7016 let mut clipboard_selections = Vec::with_capacity(selections.len());
7017 {
7018 let max_point = buffer.max_point();
7019 let mut is_first = true;
7020 for selection in selections.iter() {
7021 let mut start = selection.start;
7022 let mut end = selection.end;
7023 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7024 if is_entire_line {
7025 start = Point::new(start.row, 0);
7026 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7027 }
7028 if is_first {
7029 is_first = false;
7030 } else {
7031 text += "\n";
7032 }
7033 let mut len = 0;
7034 for chunk in buffer.text_for_range(start..end) {
7035 text.push_str(chunk);
7036 len += chunk.len();
7037 }
7038 clipboard_selections.push(ClipboardSelection {
7039 len,
7040 is_entire_line,
7041 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7042 });
7043 }
7044 }
7045
7046 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7047 text,
7048 clipboard_selections,
7049 ));
7050 }
7051
7052 pub fn do_paste(
7053 &mut self,
7054 text: &String,
7055 clipboard_selections: Option<Vec<ClipboardSelection>>,
7056 handle_entire_lines: bool,
7057 cx: &mut ViewContext<Self>,
7058 ) {
7059 if self.read_only(cx) {
7060 return;
7061 }
7062
7063 let clipboard_text = Cow::Borrowed(text);
7064
7065 self.transact(cx, |this, cx| {
7066 if let Some(mut clipboard_selections) = clipboard_selections {
7067 let old_selections = this.selections.all::<usize>(cx);
7068 let all_selections_were_entire_line =
7069 clipboard_selections.iter().all(|s| s.is_entire_line);
7070 let first_selection_indent_column =
7071 clipboard_selections.first().map(|s| s.first_line_indent);
7072 if clipboard_selections.len() != old_selections.len() {
7073 clipboard_selections.drain(..);
7074 }
7075 let cursor_offset = this.selections.last::<usize>(cx).head();
7076 let mut auto_indent_on_paste = true;
7077
7078 this.buffer.update(cx, |buffer, cx| {
7079 let snapshot = buffer.read(cx);
7080 auto_indent_on_paste =
7081 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7082
7083 let mut start_offset = 0;
7084 let mut edits = Vec::new();
7085 let mut original_indent_columns = Vec::new();
7086 for (ix, selection) in old_selections.iter().enumerate() {
7087 let to_insert;
7088 let entire_line;
7089 let original_indent_column;
7090 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7091 let end_offset = start_offset + clipboard_selection.len;
7092 to_insert = &clipboard_text[start_offset..end_offset];
7093 entire_line = clipboard_selection.is_entire_line;
7094 start_offset = end_offset + 1;
7095 original_indent_column = Some(clipboard_selection.first_line_indent);
7096 } else {
7097 to_insert = clipboard_text.as_str();
7098 entire_line = all_selections_were_entire_line;
7099 original_indent_column = first_selection_indent_column
7100 }
7101
7102 // If the corresponding selection was empty when this slice of the
7103 // clipboard text was written, then the entire line containing the
7104 // selection was copied. If this selection is also currently empty,
7105 // then paste the line before the current line of the buffer.
7106 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7107 let column = selection.start.to_point(&snapshot).column as usize;
7108 let line_start = selection.start - column;
7109 line_start..line_start
7110 } else {
7111 selection.range()
7112 };
7113
7114 edits.push((range, to_insert));
7115 original_indent_columns.extend(original_indent_column);
7116 }
7117 drop(snapshot);
7118
7119 buffer.edit(
7120 edits,
7121 if auto_indent_on_paste {
7122 Some(AutoindentMode::Block {
7123 original_indent_columns,
7124 })
7125 } else {
7126 None
7127 },
7128 cx,
7129 );
7130 });
7131
7132 let selections = this.selections.all::<usize>(cx);
7133 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7134 } else {
7135 this.insert(&clipboard_text, cx);
7136 }
7137 });
7138 }
7139
7140 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7141 if let Some(item) = cx.read_from_clipboard() {
7142 let entries = item.entries();
7143
7144 match entries.first() {
7145 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7146 // of all the pasted entries.
7147 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7148 .do_paste(
7149 clipboard_string.text(),
7150 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7151 true,
7152 cx,
7153 ),
7154 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7155 }
7156 }
7157 }
7158
7159 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7160 if self.read_only(cx) {
7161 return;
7162 }
7163
7164 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7165 if let Some((selections, _)) =
7166 self.selection_history.transaction(transaction_id).cloned()
7167 {
7168 self.change_selections(None, cx, |s| {
7169 s.select_anchors(selections.to_vec());
7170 });
7171 }
7172 self.request_autoscroll(Autoscroll::fit(), cx);
7173 self.unmark_text(cx);
7174 self.refresh_inline_completion(true, false, cx);
7175 cx.emit(EditorEvent::Edited { transaction_id });
7176 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7177 }
7178 }
7179
7180 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7181 if self.read_only(cx) {
7182 return;
7183 }
7184
7185 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7186 if let Some((_, Some(selections))) =
7187 self.selection_history.transaction(transaction_id).cloned()
7188 {
7189 self.change_selections(None, cx, |s| {
7190 s.select_anchors(selections.to_vec());
7191 });
7192 }
7193 self.request_autoscroll(Autoscroll::fit(), cx);
7194 self.unmark_text(cx);
7195 self.refresh_inline_completion(true, false, cx);
7196 cx.emit(EditorEvent::Edited { transaction_id });
7197 }
7198 }
7199
7200 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7201 self.buffer
7202 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7203 }
7204
7205 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7206 self.buffer
7207 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7208 }
7209
7210 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7212 let line_mode = s.line_mode;
7213 s.move_with(|map, selection| {
7214 let cursor = if selection.is_empty() && !line_mode {
7215 movement::left(map, selection.start)
7216 } else {
7217 selection.start
7218 };
7219 selection.collapse_to(cursor, SelectionGoal::None);
7220 });
7221 })
7222 }
7223
7224 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7225 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7226 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7227 })
7228 }
7229
7230 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7231 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7232 let line_mode = s.line_mode;
7233 s.move_with(|map, selection| {
7234 let cursor = if selection.is_empty() && !line_mode {
7235 movement::right(map, selection.end)
7236 } else {
7237 selection.end
7238 };
7239 selection.collapse_to(cursor, SelectionGoal::None)
7240 });
7241 })
7242 }
7243
7244 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7245 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7246 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7247 })
7248 }
7249
7250 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7251 if self.take_rename(true, cx).is_some() {
7252 return;
7253 }
7254
7255 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7256 cx.propagate();
7257 return;
7258 }
7259
7260 let text_layout_details = &self.text_layout_details(cx);
7261 let selection_count = self.selections.count();
7262 let first_selection = self.selections.first_anchor();
7263
7264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7265 let line_mode = s.line_mode;
7266 s.move_with(|map, selection| {
7267 if !selection.is_empty() && !line_mode {
7268 selection.goal = SelectionGoal::None;
7269 }
7270 let (cursor, goal) = movement::up(
7271 map,
7272 selection.start,
7273 selection.goal,
7274 false,
7275 text_layout_details,
7276 );
7277 selection.collapse_to(cursor, goal);
7278 });
7279 });
7280
7281 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7282 {
7283 cx.propagate();
7284 }
7285 }
7286
7287 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7288 if self.take_rename(true, cx).is_some() {
7289 return;
7290 }
7291
7292 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7293 cx.propagate();
7294 return;
7295 }
7296
7297 let text_layout_details = &self.text_layout_details(cx);
7298
7299 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7300 let line_mode = s.line_mode;
7301 s.move_with(|map, selection| {
7302 if !selection.is_empty() && !line_mode {
7303 selection.goal = SelectionGoal::None;
7304 }
7305 let (cursor, goal) = movement::up_by_rows(
7306 map,
7307 selection.start,
7308 action.lines,
7309 selection.goal,
7310 false,
7311 text_layout_details,
7312 );
7313 selection.collapse_to(cursor, goal);
7314 });
7315 })
7316 }
7317
7318 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7319 if self.take_rename(true, cx).is_some() {
7320 return;
7321 }
7322
7323 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7324 cx.propagate();
7325 return;
7326 }
7327
7328 let text_layout_details = &self.text_layout_details(cx);
7329
7330 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7331 let line_mode = s.line_mode;
7332 s.move_with(|map, selection| {
7333 if !selection.is_empty() && !line_mode {
7334 selection.goal = SelectionGoal::None;
7335 }
7336 let (cursor, goal) = movement::down_by_rows(
7337 map,
7338 selection.start,
7339 action.lines,
7340 selection.goal,
7341 false,
7342 text_layout_details,
7343 );
7344 selection.collapse_to(cursor, goal);
7345 });
7346 })
7347 }
7348
7349 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7350 let text_layout_details = &self.text_layout_details(cx);
7351 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7352 s.move_heads_with(|map, head, goal| {
7353 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7354 })
7355 })
7356 }
7357
7358 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7359 let text_layout_details = &self.text_layout_details(cx);
7360 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7361 s.move_heads_with(|map, head, goal| {
7362 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7363 })
7364 })
7365 }
7366
7367 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7368 let Some(row_count) = self.visible_row_count() else {
7369 return;
7370 };
7371
7372 let text_layout_details = &self.text_layout_details(cx);
7373
7374 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7375 s.move_heads_with(|map, head, goal| {
7376 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7377 })
7378 })
7379 }
7380
7381 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7382 if self.take_rename(true, cx).is_some() {
7383 return;
7384 }
7385
7386 if self
7387 .context_menu
7388 .borrow_mut()
7389 .as_mut()
7390 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7391 .unwrap_or(false)
7392 {
7393 return;
7394 }
7395
7396 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7397 cx.propagate();
7398 return;
7399 }
7400
7401 let Some(row_count) = self.visible_row_count() else {
7402 return;
7403 };
7404
7405 let autoscroll = if action.center_cursor {
7406 Autoscroll::center()
7407 } else {
7408 Autoscroll::fit()
7409 };
7410
7411 let text_layout_details = &self.text_layout_details(cx);
7412
7413 self.change_selections(Some(autoscroll), cx, |s| {
7414 let line_mode = s.line_mode;
7415 s.move_with(|map, selection| {
7416 if !selection.is_empty() && !line_mode {
7417 selection.goal = SelectionGoal::None;
7418 }
7419 let (cursor, goal) = movement::up_by_rows(
7420 map,
7421 selection.end,
7422 row_count,
7423 selection.goal,
7424 false,
7425 text_layout_details,
7426 );
7427 selection.collapse_to(cursor, goal);
7428 });
7429 });
7430 }
7431
7432 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7433 let text_layout_details = &self.text_layout_details(cx);
7434 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7435 s.move_heads_with(|map, head, goal| {
7436 movement::up(map, head, goal, false, text_layout_details)
7437 })
7438 })
7439 }
7440
7441 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7442 self.take_rename(true, cx);
7443
7444 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7445 cx.propagate();
7446 return;
7447 }
7448
7449 let text_layout_details = &self.text_layout_details(cx);
7450 let selection_count = self.selections.count();
7451 let first_selection = self.selections.first_anchor();
7452
7453 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7454 let line_mode = s.line_mode;
7455 s.move_with(|map, selection| {
7456 if !selection.is_empty() && !line_mode {
7457 selection.goal = SelectionGoal::None;
7458 }
7459 let (cursor, goal) = movement::down(
7460 map,
7461 selection.end,
7462 selection.goal,
7463 false,
7464 text_layout_details,
7465 );
7466 selection.collapse_to(cursor, goal);
7467 });
7468 });
7469
7470 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7471 {
7472 cx.propagate();
7473 }
7474 }
7475
7476 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7477 let Some(row_count) = self.visible_row_count() else {
7478 return;
7479 };
7480
7481 let text_layout_details = &self.text_layout_details(cx);
7482
7483 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7484 s.move_heads_with(|map, head, goal| {
7485 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7486 })
7487 })
7488 }
7489
7490 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7491 if self.take_rename(true, cx).is_some() {
7492 return;
7493 }
7494
7495 if self
7496 .context_menu
7497 .borrow_mut()
7498 .as_mut()
7499 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7500 .unwrap_or(false)
7501 {
7502 return;
7503 }
7504
7505 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7506 cx.propagate();
7507 return;
7508 }
7509
7510 let Some(row_count) = self.visible_row_count() else {
7511 return;
7512 };
7513
7514 let autoscroll = if action.center_cursor {
7515 Autoscroll::center()
7516 } else {
7517 Autoscroll::fit()
7518 };
7519
7520 let text_layout_details = &self.text_layout_details(cx);
7521 self.change_selections(Some(autoscroll), cx, |s| {
7522 let line_mode = s.line_mode;
7523 s.move_with(|map, selection| {
7524 if !selection.is_empty() && !line_mode {
7525 selection.goal = SelectionGoal::None;
7526 }
7527 let (cursor, goal) = movement::down_by_rows(
7528 map,
7529 selection.end,
7530 row_count,
7531 selection.goal,
7532 false,
7533 text_layout_details,
7534 );
7535 selection.collapse_to(cursor, goal);
7536 });
7537 });
7538 }
7539
7540 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7541 let text_layout_details = &self.text_layout_details(cx);
7542 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7543 s.move_heads_with(|map, head, goal| {
7544 movement::down(map, head, goal, false, text_layout_details)
7545 })
7546 });
7547 }
7548
7549 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7550 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7551 context_menu.select_first(self.completion_provider.as_deref(), cx);
7552 }
7553 }
7554
7555 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7556 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7557 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7558 }
7559 }
7560
7561 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7562 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7563 context_menu.select_next(self.completion_provider.as_deref(), cx);
7564 }
7565 }
7566
7567 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7568 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7569 context_menu.select_last(self.completion_provider.as_deref(), cx);
7570 }
7571 }
7572
7573 pub fn move_to_previous_word_start(
7574 &mut self,
7575 _: &MoveToPreviousWordStart,
7576 cx: &mut ViewContext<Self>,
7577 ) {
7578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7579 s.move_cursors_with(|map, head, _| {
7580 (
7581 movement::previous_word_start(map, head),
7582 SelectionGoal::None,
7583 )
7584 });
7585 })
7586 }
7587
7588 pub fn move_to_previous_subword_start(
7589 &mut self,
7590 _: &MoveToPreviousSubwordStart,
7591 cx: &mut ViewContext<Self>,
7592 ) {
7593 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7594 s.move_cursors_with(|map, head, _| {
7595 (
7596 movement::previous_subword_start(map, head),
7597 SelectionGoal::None,
7598 )
7599 });
7600 })
7601 }
7602
7603 pub fn select_to_previous_word_start(
7604 &mut self,
7605 _: &SelectToPreviousWordStart,
7606 cx: &mut ViewContext<Self>,
7607 ) {
7608 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7609 s.move_heads_with(|map, head, _| {
7610 (
7611 movement::previous_word_start(map, head),
7612 SelectionGoal::None,
7613 )
7614 });
7615 })
7616 }
7617
7618 pub fn select_to_previous_subword_start(
7619 &mut self,
7620 _: &SelectToPreviousSubwordStart,
7621 cx: &mut ViewContext<Self>,
7622 ) {
7623 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 s.move_heads_with(|map, head, _| {
7625 (
7626 movement::previous_subword_start(map, head),
7627 SelectionGoal::None,
7628 )
7629 });
7630 })
7631 }
7632
7633 pub fn delete_to_previous_word_start(
7634 &mut self,
7635 action: &DeleteToPreviousWordStart,
7636 cx: &mut ViewContext<Self>,
7637 ) {
7638 self.transact(cx, |this, cx| {
7639 this.select_autoclose_pair(cx);
7640 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7641 let line_mode = s.line_mode;
7642 s.move_with(|map, selection| {
7643 if selection.is_empty() && !line_mode {
7644 let cursor = if action.ignore_newlines {
7645 movement::previous_word_start(map, selection.head())
7646 } else {
7647 movement::previous_word_start_or_newline(map, selection.head())
7648 };
7649 selection.set_head(cursor, SelectionGoal::None);
7650 }
7651 });
7652 });
7653 this.insert("", cx);
7654 });
7655 }
7656
7657 pub fn delete_to_previous_subword_start(
7658 &mut self,
7659 _: &DeleteToPreviousSubwordStart,
7660 cx: &mut ViewContext<Self>,
7661 ) {
7662 self.transact(cx, |this, cx| {
7663 this.select_autoclose_pair(cx);
7664 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7665 let line_mode = s.line_mode;
7666 s.move_with(|map, selection| {
7667 if selection.is_empty() && !line_mode {
7668 let cursor = movement::previous_subword_start(map, selection.head());
7669 selection.set_head(cursor, SelectionGoal::None);
7670 }
7671 });
7672 });
7673 this.insert("", cx);
7674 });
7675 }
7676
7677 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7678 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7679 s.move_cursors_with(|map, head, _| {
7680 (movement::next_word_end(map, head), SelectionGoal::None)
7681 });
7682 })
7683 }
7684
7685 pub fn move_to_next_subword_end(
7686 &mut self,
7687 _: &MoveToNextSubwordEnd,
7688 cx: &mut ViewContext<Self>,
7689 ) {
7690 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7691 s.move_cursors_with(|map, head, _| {
7692 (movement::next_subword_end(map, head), SelectionGoal::None)
7693 });
7694 })
7695 }
7696
7697 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7699 s.move_heads_with(|map, head, _| {
7700 (movement::next_word_end(map, head), SelectionGoal::None)
7701 });
7702 })
7703 }
7704
7705 pub fn select_to_next_subword_end(
7706 &mut self,
7707 _: &SelectToNextSubwordEnd,
7708 cx: &mut ViewContext<Self>,
7709 ) {
7710 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7711 s.move_heads_with(|map, head, _| {
7712 (movement::next_subword_end(map, head), SelectionGoal::None)
7713 });
7714 })
7715 }
7716
7717 pub fn delete_to_next_word_end(
7718 &mut self,
7719 action: &DeleteToNextWordEnd,
7720 cx: &mut ViewContext<Self>,
7721 ) {
7722 self.transact(cx, |this, cx| {
7723 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7724 let line_mode = s.line_mode;
7725 s.move_with(|map, selection| {
7726 if selection.is_empty() && !line_mode {
7727 let cursor = if action.ignore_newlines {
7728 movement::next_word_end(map, selection.head())
7729 } else {
7730 movement::next_word_end_or_newline(map, selection.head())
7731 };
7732 selection.set_head(cursor, SelectionGoal::None);
7733 }
7734 });
7735 });
7736 this.insert("", cx);
7737 });
7738 }
7739
7740 pub fn delete_to_next_subword_end(
7741 &mut self,
7742 _: &DeleteToNextSubwordEnd,
7743 cx: &mut ViewContext<Self>,
7744 ) {
7745 self.transact(cx, |this, cx| {
7746 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7747 s.move_with(|map, selection| {
7748 if selection.is_empty() {
7749 let cursor = movement::next_subword_end(map, selection.head());
7750 selection.set_head(cursor, SelectionGoal::None);
7751 }
7752 });
7753 });
7754 this.insert("", cx);
7755 });
7756 }
7757
7758 pub fn move_to_beginning_of_line(
7759 &mut self,
7760 action: &MoveToBeginningOfLine,
7761 cx: &mut ViewContext<Self>,
7762 ) {
7763 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7764 s.move_cursors_with(|map, head, _| {
7765 (
7766 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7767 SelectionGoal::None,
7768 )
7769 });
7770 })
7771 }
7772
7773 pub fn select_to_beginning_of_line(
7774 &mut self,
7775 action: &SelectToBeginningOfLine,
7776 cx: &mut ViewContext<Self>,
7777 ) {
7778 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7779 s.move_heads_with(|map, head, _| {
7780 (
7781 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7782 SelectionGoal::None,
7783 )
7784 });
7785 });
7786 }
7787
7788 pub fn delete_to_beginning_of_line(
7789 &mut self,
7790 _: &DeleteToBeginningOfLine,
7791 cx: &mut ViewContext<Self>,
7792 ) {
7793 self.transact(cx, |this, cx| {
7794 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7795 s.move_with(|_, selection| {
7796 selection.reversed = true;
7797 });
7798 });
7799
7800 this.select_to_beginning_of_line(
7801 &SelectToBeginningOfLine {
7802 stop_at_soft_wraps: false,
7803 },
7804 cx,
7805 );
7806 this.backspace(&Backspace, cx);
7807 });
7808 }
7809
7810 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7811 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7812 s.move_cursors_with(|map, head, _| {
7813 (
7814 movement::line_end(map, head, action.stop_at_soft_wraps),
7815 SelectionGoal::None,
7816 )
7817 });
7818 })
7819 }
7820
7821 pub fn select_to_end_of_line(
7822 &mut self,
7823 action: &SelectToEndOfLine,
7824 cx: &mut ViewContext<Self>,
7825 ) {
7826 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7827 s.move_heads_with(|map, head, _| {
7828 (
7829 movement::line_end(map, head, action.stop_at_soft_wraps),
7830 SelectionGoal::None,
7831 )
7832 });
7833 })
7834 }
7835
7836 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7837 self.transact(cx, |this, cx| {
7838 this.select_to_end_of_line(
7839 &SelectToEndOfLine {
7840 stop_at_soft_wraps: false,
7841 },
7842 cx,
7843 );
7844 this.delete(&Delete, cx);
7845 });
7846 }
7847
7848 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7849 self.transact(cx, |this, cx| {
7850 this.select_to_end_of_line(
7851 &SelectToEndOfLine {
7852 stop_at_soft_wraps: false,
7853 },
7854 cx,
7855 );
7856 this.cut(&Cut, cx);
7857 });
7858 }
7859
7860 pub fn move_to_start_of_paragraph(
7861 &mut self,
7862 _: &MoveToStartOfParagraph,
7863 cx: &mut ViewContext<Self>,
7864 ) {
7865 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7866 cx.propagate();
7867 return;
7868 }
7869
7870 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7871 s.move_with(|map, selection| {
7872 selection.collapse_to(
7873 movement::start_of_paragraph(map, selection.head(), 1),
7874 SelectionGoal::None,
7875 )
7876 });
7877 })
7878 }
7879
7880 pub fn move_to_end_of_paragraph(
7881 &mut self,
7882 _: &MoveToEndOfParagraph,
7883 cx: &mut ViewContext<Self>,
7884 ) {
7885 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7886 cx.propagate();
7887 return;
7888 }
7889
7890 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7891 s.move_with(|map, selection| {
7892 selection.collapse_to(
7893 movement::end_of_paragraph(map, selection.head(), 1),
7894 SelectionGoal::None,
7895 )
7896 });
7897 })
7898 }
7899
7900 pub fn select_to_start_of_paragraph(
7901 &mut self,
7902 _: &SelectToStartOfParagraph,
7903 cx: &mut ViewContext<Self>,
7904 ) {
7905 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7906 cx.propagate();
7907 return;
7908 }
7909
7910 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7911 s.move_heads_with(|map, head, _| {
7912 (
7913 movement::start_of_paragraph(map, head, 1),
7914 SelectionGoal::None,
7915 )
7916 });
7917 })
7918 }
7919
7920 pub fn select_to_end_of_paragraph(
7921 &mut self,
7922 _: &SelectToEndOfParagraph,
7923 cx: &mut ViewContext<Self>,
7924 ) {
7925 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7926 cx.propagate();
7927 return;
7928 }
7929
7930 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7931 s.move_heads_with(|map, head, _| {
7932 (
7933 movement::end_of_paragraph(map, head, 1),
7934 SelectionGoal::None,
7935 )
7936 });
7937 })
7938 }
7939
7940 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7941 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7942 cx.propagate();
7943 return;
7944 }
7945
7946 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7947 s.select_ranges(vec![0..0]);
7948 });
7949 }
7950
7951 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7952 let mut selection = self.selections.last::<Point>(cx);
7953 selection.set_head(Point::zero(), SelectionGoal::None);
7954
7955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7956 s.select(vec![selection]);
7957 });
7958 }
7959
7960 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7961 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7962 cx.propagate();
7963 return;
7964 }
7965
7966 let cursor = self.buffer.read(cx).read(cx).len();
7967 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7968 s.select_ranges(vec![cursor..cursor])
7969 });
7970 }
7971
7972 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7973 self.nav_history = nav_history;
7974 }
7975
7976 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7977 self.nav_history.as_ref()
7978 }
7979
7980 fn push_to_nav_history(
7981 &mut self,
7982 cursor_anchor: Anchor,
7983 new_position: Option<Point>,
7984 cx: &mut ViewContext<Self>,
7985 ) {
7986 if let Some(nav_history) = self.nav_history.as_mut() {
7987 let buffer = self.buffer.read(cx).read(cx);
7988 let cursor_position = cursor_anchor.to_point(&buffer);
7989 let scroll_state = self.scroll_manager.anchor();
7990 let scroll_top_row = scroll_state.top_row(&buffer);
7991 drop(buffer);
7992
7993 if let Some(new_position) = new_position {
7994 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7995 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7996 return;
7997 }
7998 }
7999
8000 nav_history.push(
8001 Some(NavigationData {
8002 cursor_anchor,
8003 cursor_position,
8004 scroll_anchor: scroll_state,
8005 scroll_top_row,
8006 }),
8007 cx,
8008 );
8009 }
8010 }
8011
8012 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8013 let buffer = self.buffer.read(cx).snapshot(cx);
8014 let mut selection = self.selections.first::<usize>(cx);
8015 selection.set_head(buffer.len(), SelectionGoal::None);
8016 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8017 s.select(vec![selection]);
8018 });
8019 }
8020
8021 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8022 let end = self.buffer.read(cx).read(cx).len();
8023 self.change_selections(None, cx, |s| {
8024 s.select_ranges(vec![0..end]);
8025 });
8026 }
8027
8028 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8029 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8030 let mut selections = self.selections.all::<Point>(cx);
8031 let max_point = display_map.buffer_snapshot.max_point();
8032 for selection in &mut selections {
8033 let rows = selection.spanned_rows(true, &display_map);
8034 selection.start = Point::new(rows.start.0, 0);
8035 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8036 selection.reversed = false;
8037 }
8038 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8039 s.select(selections);
8040 });
8041 }
8042
8043 pub fn split_selection_into_lines(
8044 &mut self,
8045 _: &SplitSelectionIntoLines,
8046 cx: &mut ViewContext<Self>,
8047 ) {
8048 let mut to_unfold = Vec::new();
8049 let mut new_selection_ranges = Vec::new();
8050 {
8051 let selections = self.selections.all::<Point>(cx);
8052 let buffer = self.buffer.read(cx).read(cx);
8053 for selection in selections {
8054 for row in selection.start.row..selection.end.row {
8055 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8056 new_selection_ranges.push(cursor..cursor);
8057 }
8058 new_selection_ranges.push(selection.end..selection.end);
8059 to_unfold.push(selection.start..selection.end);
8060 }
8061 }
8062 self.unfold_ranges(&to_unfold, true, true, cx);
8063 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8064 s.select_ranges(new_selection_ranges);
8065 });
8066 }
8067
8068 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8069 self.add_selection(true, cx);
8070 }
8071
8072 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8073 self.add_selection(false, cx);
8074 }
8075
8076 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8077 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8078 let mut selections = self.selections.all::<Point>(cx);
8079 let text_layout_details = self.text_layout_details(cx);
8080 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8081 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8082 let range = oldest_selection.display_range(&display_map).sorted();
8083
8084 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8085 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8086 let positions = start_x.min(end_x)..start_x.max(end_x);
8087
8088 selections.clear();
8089 let mut stack = Vec::new();
8090 for row in range.start.row().0..=range.end.row().0 {
8091 if let Some(selection) = self.selections.build_columnar_selection(
8092 &display_map,
8093 DisplayRow(row),
8094 &positions,
8095 oldest_selection.reversed,
8096 &text_layout_details,
8097 ) {
8098 stack.push(selection.id);
8099 selections.push(selection);
8100 }
8101 }
8102
8103 if above {
8104 stack.reverse();
8105 }
8106
8107 AddSelectionsState { above, stack }
8108 });
8109
8110 let last_added_selection = *state.stack.last().unwrap();
8111 let mut new_selections = Vec::new();
8112 if above == state.above {
8113 let end_row = if above {
8114 DisplayRow(0)
8115 } else {
8116 display_map.max_point().row()
8117 };
8118
8119 'outer: for selection in selections {
8120 if selection.id == last_added_selection {
8121 let range = selection.display_range(&display_map).sorted();
8122 debug_assert_eq!(range.start.row(), range.end.row());
8123 let mut row = range.start.row();
8124 let positions =
8125 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8126 px(start)..px(end)
8127 } else {
8128 let start_x =
8129 display_map.x_for_display_point(range.start, &text_layout_details);
8130 let end_x =
8131 display_map.x_for_display_point(range.end, &text_layout_details);
8132 start_x.min(end_x)..start_x.max(end_x)
8133 };
8134
8135 while row != end_row {
8136 if above {
8137 row.0 -= 1;
8138 } else {
8139 row.0 += 1;
8140 }
8141
8142 if let Some(new_selection) = self.selections.build_columnar_selection(
8143 &display_map,
8144 row,
8145 &positions,
8146 selection.reversed,
8147 &text_layout_details,
8148 ) {
8149 state.stack.push(new_selection.id);
8150 if above {
8151 new_selections.push(new_selection);
8152 new_selections.push(selection);
8153 } else {
8154 new_selections.push(selection);
8155 new_selections.push(new_selection);
8156 }
8157
8158 continue 'outer;
8159 }
8160 }
8161 }
8162
8163 new_selections.push(selection);
8164 }
8165 } else {
8166 new_selections = selections;
8167 new_selections.retain(|s| s.id != last_added_selection);
8168 state.stack.pop();
8169 }
8170
8171 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8172 s.select(new_selections);
8173 });
8174 if state.stack.len() > 1 {
8175 self.add_selections_state = Some(state);
8176 }
8177 }
8178
8179 pub fn select_next_match_internal(
8180 &mut self,
8181 display_map: &DisplaySnapshot,
8182 replace_newest: bool,
8183 autoscroll: Option<Autoscroll>,
8184 cx: &mut ViewContext<Self>,
8185 ) -> Result<()> {
8186 fn select_next_match_ranges(
8187 this: &mut Editor,
8188 range: Range<usize>,
8189 replace_newest: bool,
8190 auto_scroll: Option<Autoscroll>,
8191 cx: &mut ViewContext<Editor>,
8192 ) {
8193 this.unfold_ranges(&[range.clone()], false, true, cx);
8194 this.change_selections(auto_scroll, cx, |s| {
8195 if replace_newest {
8196 s.delete(s.newest_anchor().id);
8197 }
8198 s.insert_range(range.clone());
8199 });
8200 }
8201
8202 let buffer = &display_map.buffer_snapshot;
8203 let mut selections = self.selections.all::<usize>(cx);
8204 if let Some(mut select_next_state) = self.select_next_state.take() {
8205 let query = &select_next_state.query;
8206 if !select_next_state.done {
8207 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8208 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8209 let mut next_selected_range = None;
8210
8211 let bytes_after_last_selection =
8212 buffer.bytes_in_range(last_selection.end..buffer.len());
8213 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8214 let query_matches = query
8215 .stream_find_iter(bytes_after_last_selection)
8216 .map(|result| (last_selection.end, result))
8217 .chain(
8218 query
8219 .stream_find_iter(bytes_before_first_selection)
8220 .map(|result| (0, result)),
8221 );
8222
8223 for (start_offset, query_match) in query_matches {
8224 let query_match = query_match.unwrap(); // can only fail due to I/O
8225 let offset_range =
8226 start_offset + query_match.start()..start_offset + query_match.end();
8227 let display_range = offset_range.start.to_display_point(display_map)
8228 ..offset_range.end.to_display_point(display_map);
8229
8230 if !select_next_state.wordwise
8231 || (!movement::is_inside_word(display_map, display_range.start)
8232 && !movement::is_inside_word(display_map, display_range.end))
8233 {
8234 // TODO: This is n^2, because we might check all the selections
8235 if !selections
8236 .iter()
8237 .any(|selection| selection.range().overlaps(&offset_range))
8238 {
8239 next_selected_range = Some(offset_range);
8240 break;
8241 }
8242 }
8243 }
8244
8245 if let Some(next_selected_range) = next_selected_range {
8246 select_next_match_ranges(
8247 self,
8248 next_selected_range,
8249 replace_newest,
8250 autoscroll,
8251 cx,
8252 );
8253 } else {
8254 select_next_state.done = true;
8255 }
8256 }
8257
8258 self.select_next_state = Some(select_next_state);
8259 } else {
8260 let mut only_carets = true;
8261 let mut same_text_selected = true;
8262 let mut selected_text = None;
8263
8264 let mut selections_iter = selections.iter().peekable();
8265 while let Some(selection) = selections_iter.next() {
8266 if selection.start != selection.end {
8267 only_carets = false;
8268 }
8269
8270 if same_text_selected {
8271 if selected_text.is_none() {
8272 selected_text =
8273 Some(buffer.text_for_range(selection.range()).collect::<String>());
8274 }
8275
8276 if let Some(next_selection) = selections_iter.peek() {
8277 if next_selection.range().len() == selection.range().len() {
8278 let next_selected_text = buffer
8279 .text_for_range(next_selection.range())
8280 .collect::<String>();
8281 if Some(next_selected_text) != selected_text {
8282 same_text_selected = false;
8283 selected_text = None;
8284 }
8285 } else {
8286 same_text_selected = false;
8287 selected_text = None;
8288 }
8289 }
8290 }
8291 }
8292
8293 if only_carets {
8294 for selection in &mut selections {
8295 let word_range = movement::surrounding_word(
8296 display_map,
8297 selection.start.to_display_point(display_map),
8298 );
8299 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8300 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8301 selection.goal = SelectionGoal::None;
8302 selection.reversed = false;
8303 select_next_match_ranges(
8304 self,
8305 selection.start..selection.end,
8306 replace_newest,
8307 autoscroll,
8308 cx,
8309 );
8310 }
8311
8312 if selections.len() == 1 {
8313 let selection = selections
8314 .last()
8315 .expect("ensured that there's only one selection");
8316 let query = buffer
8317 .text_for_range(selection.start..selection.end)
8318 .collect::<String>();
8319 let is_empty = query.is_empty();
8320 let select_state = SelectNextState {
8321 query: AhoCorasick::new(&[query])?,
8322 wordwise: true,
8323 done: is_empty,
8324 };
8325 self.select_next_state = Some(select_state);
8326 } else {
8327 self.select_next_state = None;
8328 }
8329 } else if let Some(selected_text) = selected_text {
8330 self.select_next_state = Some(SelectNextState {
8331 query: AhoCorasick::new(&[selected_text])?,
8332 wordwise: false,
8333 done: false,
8334 });
8335 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8336 }
8337 }
8338 Ok(())
8339 }
8340
8341 pub fn select_all_matches(
8342 &mut self,
8343 _action: &SelectAllMatches,
8344 cx: &mut ViewContext<Self>,
8345 ) -> Result<()> {
8346 self.push_to_selection_history();
8347 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8348
8349 self.select_next_match_internal(&display_map, false, None, cx)?;
8350 let Some(select_next_state) = self.select_next_state.as_mut() else {
8351 return Ok(());
8352 };
8353 if select_next_state.done {
8354 return Ok(());
8355 }
8356
8357 let mut new_selections = self.selections.all::<usize>(cx);
8358
8359 let buffer = &display_map.buffer_snapshot;
8360 let query_matches = select_next_state
8361 .query
8362 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8363
8364 for query_match in query_matches {
8365 let query_match = query_match.unwrap(); // can only fail due to I/O
8366 let offset_range = query_match.start()..query_match.end();
8367 let display_range = offset_range.start.to_display_point(&display_map)
8368 ..offset_range.end.to_display_point(&display_map);
8369
8370 if !select_next_state.wordwise
8371 || (!movement::is_inside_word(&display_map, display_range.start)
8372 && !movement::is_inside_word(&display_map, display_range.end))
8373 {
8374 self.selections.change_with(cx, |selections| {
8375 new_selections.push(Selection {
8376 id: selections.new_selection_id(),
8377 start: offset_range.start,
8378 end: offset_range.end,
8379 reversed: false,
8380 goal: SelectionGoal::None,
8381 });
8382 });
8383 }
8384 }
8385
8386 new_selections.sort_by_key(|selection| selection.start);
8387 let mut ix = 0;
8388 while ix + 1 < new_selections.len() {
8389 let current_selection = &new_selections[ix];
8390 let next_selection = &new_selections[ix + 1];
8391 if current_selection.range().overlaps(&next_selection.range()) {
8392 if current_selection.id < next_selection.id {
8393 new_selections.remove(ix + 1);
8394 } else {
8395 new_selections.remove(ix);
8396 }
8397 } else {
8398 ix += 1;
8399 }
8400 }
8401
8402 select_next_state.done = true;
8403 self.unfold_ranges(
8404 &new_selections
8405 .iter()
8406 .map(|selection| selection.range())
8407 .collect::<Vec<_>>(),
8408 false,
8409 false,
8410 cx,
8411 );
8412 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8413 selections.select(new_selections)
8414 });
8415
8416 Ok(())
8417 }
8418
8419 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8420 self.push_to_selection_history();
8421 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8422 self.select_next_match_internal(
8423 &display_map,
8424 action.replace_newest,
8425 Some(Autoscroll::newest()),
8426 cx,
8427 )?;
8428 Ok(())
8429 }
8430
8431 pub fn select_previous(
8432 &mut self,
8433 action: &SelectPrevious,
8434 cx: &mut ViewContext<Self>,
8435 ) -> Result<()> {
8436 self.push_to_selection_history();
8437 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8438 let buffer = &display_map.buffer_snapshot;
8439 let mut selections = self.selections.all::<usize>(cx);
8440 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8441 let query = &select_prev_state.query;
8442 if !select_prev_state.done {
8443 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8444 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8445 let mut next_selected_range = None;
8446 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8447 let bytes_before_last_selection =
8448 buffer.reversed_bytes_in_range(0..last_selection.start);
8449 let bytes_after_first_selection =
8450 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8451 let query_matches = query
8452 .stream_find_iter(bytes_before_last_selection)
8453 .map(|result| (last_selection.start, result))
8454 .chain(
8455 query
8456 .stream_find_iter(bytes_after_first_selection)
8457 .map(|result| (buffer.len(), result)),
8458 );
8459 for (end_offset, query_match) in query_matches {
8460 let query_match = query_match.unwrap(); // can only fail due to I/O
8461 let offset_range =
8462 end_offset - query_match.end()..end_offset - query_match.start();
8463 let display_range = offset_range.start.to_display_point(&display_map)
8464 ..offset_range.end.to_display_point(&display_map);
8465
8466 if !select_prev_state.wordwise
8467 || (!movement::is_inside_word(&display_map, display_range.start)
8468 && !movement::is_inside_word(&display_map, display_range.end))
8469 {
8470 next_selected_range = Some(offset_range);
8471 break;
8472 }
8473 }
8474
8475 if let Some(next_selected_range) = next_selected_range {
8476 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8477 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8478 if action.replace_newest {
8479 s.delete(s.newest_anchor().id);
8480 }
8481 s.insert_range(next_selected_range);
8482 });
8483 } else {
8484 select_prev_state.done = true;
8485 }
8486 }
8487
8488 self.select_prev_state = Some(select_prev_state);
8489 } else {
8490 let mut only_carets = true;
8491 let mut same_text_selected = true;
8492 let mut selected_text = None;
8493
8494 let mut selections_iter = selections.iter().peekable();
8495 while let Some(selection) = selections_iter.next() {
8496 if selection.start != selection.end {
8497 only_carets = false;
8498 }
8499
8500 if same_text_selected {
8501 if selected_text.is_none() {
8502 selected_text =
8503 Some(buffer.text_for_range(selection.range()).collect::<String>());
8504 }
8505
8506 if let Some(next_selection) = selections_iter.peek() {
8507 if next_selection.range().len() == selection.range().len() {
8508 let next_selected_text = buffer
8509 .text_for_range(next_selection.range())
8510 .collect::<String>();
8511 if Some(next_selected_text) != selected_text {
8512 same_text_selected = false;
8513 selected_text = None;
8514 }
8515 } else {
8516 same_text_selected = false;
8517 selected_text = None;
8518 }
8519 }
8520 }
8521 }
8522
8523 if only_carets {
8524 for selection in &mut selections {
8525 let word_range = movement::surrounding_word(
8526 &display_map,
8527 selection.start.to_display_point(&display_map),
8528 );
8529 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8530 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8531 selection.goal = SelectionGoal::None;
8532 selection.reversed = false;
8533 }
8534 if selections.len() == 1 {
8535 let selection = selections
8536 .last()
8537 .expect("ensured that there's only one selection");
8538 let query = buffer
8539 .text_for_range(selection.start..selection.end)
8540 .collect::<String>();
8541 let is_empty = query.is_empty();
8542 let select_state = SelectNextState {
8543 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8544 wordwise: true,
8545 done: is_empty,
8546 };
8547 self.select_prev_state = Some(select_state);
8548 } else {
8549 self.select_prev_state = None;
8550 }
8551
8552 self.unfold_ranges(
8553 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8554 false,
8555 true,
8556 cx,
8557 );
8558 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8559 s.select(selections);
8560 });
8561 } else if let Some(selected_text) = selected_text {
8562 self.select_prev_state = Some(SelectNextState {
8563 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8564 wordwise: false,
8565 done: false,
8566 });
8567 self.select_previous(action, cx)?;
8568 }
8569 }
8570 Ok(())
8571 }
8572
8573 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8574 if self.read_only(cx) {
8575 return;
8576 }
8577 let text_layout_details = &self.text_layout_details(cx);
8578 self.transact(cx, |this, cx| {
8579 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8580 let mut edits = Vec::new();
8581 let mut selection_edit_ranges = Vec::new();
8582 let mut last_toggled_row = None;
8583 let snapshot = this.buffer.read(cx).read(cx);
8584 let empty_str: Arc<str> = Arc::default();
8585 let mut suffixes_inserted = Vec::new();
8586 let ignore_indent = action.ignore_indent;
8587
8588 fn comment_prefix_range(
8589 snapshot: &MultiBufferSnapshot,
8590 row: MultiBufferRow,
8591 comment_prefix: &str,
8592 comment_prefix_whitespace: &str,
8593 ignore_indent: bool,
8594 ) -> Range<Point> {
8595 let indent_size = if ignore_indent {
8596 0
8597 } else {
8598 snapshot.indent_size_for_line(row).len
8599 };
8600
8601 let start = Point::new(row.0, indent_size);
8602
8603 let mut line_bytes = snapshot
8604 .bytes_in_range(start..snapshot.max_point())
8605 .flatten()
8606 .copied();
8607
8608 // If this line currently begins with the line comment prefix, then record
8609 // the range containing the prefix.
8610 if line_bytes
8611 .by_ref()
8612 .take(comment_prefix.len())
8613 .eq(comment_prefix.bytes())
8614 {
8615 // Include any whitespace that matches the comment prefix.
8616 let matching_whitespace_len = line_bytes
8617 .zip(comment_prefix_whitespace.bytes())
8618 .take_while(|(a, b)| a == b)
8619 .count() as u32;
8620 let end = Point::new(
8621 start.row,
8622 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8623 );
8624 start..end
8625 } else {
8626 start..start
8627 }
8628 }
8629
8630 fn comment_suffix_range(
8631 snapshot: &MultiBufferSnapshot,
8632 row: MultiBufferRow,
8633 comment_suffix: &str,
8634 comment_suffix_has_leading_space: bool,
8635 ) -> Range<Point> {
8636 let end = Point::new(row.0, snapshot.line_len(row));
8637 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8638
8639 let mut line_end_bytes = snapshot
8640 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8641 .flatten()
8642 .copied();
8643
8644 let leading_space_len = if suffix_start_column > 0
8645 && line_end_bytes.next() == Some(b' ')
8646 && comment_suffix_has_leading_space
8647 {
8648 1
8649 } else {
8650 0
8651 };
8652
8653 // If this line currently begins with the line comment prefix, then record
8654 // the range containing the prefix.
8655 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8656 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8657 start..end
8658 } else {
8659 end..end
8660 }
8661 }
8662
8663 // TODO: Handle selections that cross excerpts
8664 for selection in &mut selections {
8665 let start_column = snapshot
8666 .indent_size_for_line(MultiBufferRow(selection.start.row))
8667 .len;
8668 let language = if let Some(language) =
8669 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8670 {
8671 language
8672 } else {
8673 continue;
8674 };
8675
8676 selection_edit_ranges.clear();
8677
8678 // If multiple selections contain a given row, avoid processing that
8679 // row more than once.
8680 let mut start_row = MultiBufferRow(selection.start.row);
8681 if last_toggled_row == Some(start_row) {
8682 start_row = start_row.next_row();
8683 }
8684 let end_row =
8685 if selection.end.row > selection.start.row && selection.end.column == 0 {
8686 MultiBufferRow(selection.end.row - 1)
8687 } else {
8688 MultiBufferRow(selection.end.row)
8689 };
8690 last_toggled_row = Some(end_row);
8691
8692 if start_row > end_row {
8693 continue;
8694 }
8695
8696 // If the language has line comments, toggle those.
8697 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8698
8699 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8700 if ignore_indent {
8701 full_comment_prefixes = full_comment_prefixes
8702 .into_iter()
8703 .map(|s| Arc::from(s.trim_end()))
8704 .collect();
8705 }
8706
8707 if !full_comment_prefixes.is_empty() {
8708 let first_prefix = full_comment_prefixes
8709 .first()
8710 .expect("prefixes is non-empty");
8711 let prefix_trimmed_lengths = full_comment_prefixes
8712 .iter()
8713 .map(|p| p.trim_end_matches(' ').len())
8714 .collect::<SmallVec<[usize; 4]>>();
8715
8716 let mut all_selection_lines_are_comments = true;
8717
8718 for row in start_row.0..=end_row.0 {
8719 let row = MultiBufferRow(row);
8720 if start_row < end_row && snapshot.is_line_blank(row) {
8721 continue;
8722 }
8723
8724 let prefix_range = full_comment_prefixes
8725 .iter()
8726 .zip(prefix_trimmed_lengths.iter().copied())
8727 .map(|(prefix, trimmed_prefix_len)| {
8728 comment_prefix_range(
8729 snapshot.deref(),
8730 row,
8731 &prefix[..trimmed_prefix_len],
8732 &prefix[trimmed_prefix_len..],
8733 ignore_indent,
8734 )
8735 })
8736 .max_by_key(|range| range.end.column - range.start.column)
8737 .expect("prefixes is non-empty");
8738
8739 if prefix_range.is_empty() {
8740 all_selection_lines_are_comments = false;
8741 }
8742
8743 selection_edit_ranges.push(prefix_range);
8744 }
8745
8746 if all_selection_lines_are_comments {
8747 edits.extend(
8748 selection_edit_ranges
8749 .iter()
8750 .cloned()
8751 .map(|range| (range, empty_str.clone())),
8752 );
8753 } else {
8754 let min_column = selection_edit_ranges
8755 .iter()
8756 .map(|range| range.start.column)
8757 .min()
8758 .unwrap_or(0);
8759 edits.extend(selection_edit_ranges.iter().map(|range| {
8760 let position = Point::new(range.start.row, min_column);
8761 (position..position, first_prefix.clone())
8762 }));
8763 }
8764 } else if let Some((full_comment_prefix, comment_suffix)) =
8765 language.block_comment_delimiters()
8766 {
8767 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8768 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8769 let prefix_range = comment_prefix_range(
8770 snapshot.deref(),
8771 start_row,
8772 comment_prefix,
8773 comment_prefix_whitespace,
8774 ignore_indent,
8775 );
8776 let suffix_range = comment_suffix_range(
8777 snapshot.deref(),
8778 end_row,
8779 comment_suffix.trim_start_matches(' '),
8780 comment_suffix.starts_with(' '),
8781 );
8782
8783 if prefix_range.is_empty() || suffix_range.is_empty() {
8784 edits.push((
8785 prefix_range.start..prefix_range.start,
8786 full_comment_prefix.clone(),
8787 ));
8788 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8789 suffixes_inserted.push((end_row, comment_suffix.len()));
8790 } else {
8791 edits.push((prefix_range, empty_str.clone()));
8792 edits.push((suffix_range, empty_str.clone()));
8793 }
8794 } else {
8795 continue;
8796 }
8797 }
8798
8799 drop(snapshot);
8800 this.buffer.update(cx, |buffer, cx| {
8801 buffer.edit(edits, None, cx);
8802 });
8803
8804 // Adjust selections so that they end before any comment suffixes that
8805 // were inserted.
8806 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8807 let mut selections = this.selections.all::<Point>(cx);
8808 let snapshot = this.buffer.read(cx).read(cx);
8809 for selection in &mut selections {
8810 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8811 match row.cmp(&MultiBufferRow(selection.end.row)) {
8812 Ordering::Less => {
8813 suffixes_inserted.next();
8814 continue;
8815 }
8816 Ordering::Greater => break,
8817 Ordering::Equal => {
8818 if selection.end.column == snapshot.line_len(row) {
8819 if selection.is_empty() {
8820 selection.start.column -= suffix_len as u32;
8821 }
8822 selection.end.column -= suffix_len as u32;
8823 }
8824 break;
8825 }
8826 }
8827 }
8828 }
8829
8830 drop(snapshot);
8831 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8832
8833 let selections = this.selections.all::<Point>(cx);
8834 let selections_on_single_row = selections.windows(2).all(|selections| {
8835 selections[0].start.row == selections[1].start.row
8836 && selections[0].end.row == selections[1].end.row
8837 && selections[0].start.row == selections[0].end.row
8838 });
8839 let selections_selecting = selections
8840 .iter()
8841 .any(|selection| selection.start != selection.end);
8842 let advance_downwards = action.advance_downwards
8843 && selections_on_single_row
8844 && !selections_selecting
8845 && !matches!(this.mode, EditorMode::SingleLine { .. });
8846
8847 if advance_downwards {
8848 let snapshot = this.buffer.read(cx).snapshot(cx);
8849
8850 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8851 s.move_cursors_with(|display_snapshot, display_point, _| {
8852 let mut point = display_point.to_point(display_snapshot);
8853 point.row += 1;
8854 point = snapshot.clip_point(point, Bias::Left);
8855 let display_point = point.to_display_point(display_snapshot);
8856 let goal = SelectionGoal::HorizontalPosition(
8857 display_snapshot
8858 .x_for_display_point(display_point, text_layout_details)
8859 .into(),
8860 );
8861 (display_point, goal)
8862 })
8863 });
8864 }
8865 });
8866 }
8867
8868 pub fn select_enclosing_symbol(
8869 &mut self,
8870 _: &SelectEnclosingSymbol,
8871 cx: &mut ViewContext<Self>,
8872 ) {
8873 let buffer = self.buffer.read(cx).snapshot(cx);
8874 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8875
8876 fn update_selection(
8877 selection: &Selection<usize>,
8878 buffer_snap: &MultiBufferSnapshot,
8879 ) -> Option<Selection<usize>> {
8880 let cursor = selection.head();
8881 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8882 for symbol in symbols.iter().rev() {
8883 let start = symbol.range.start.to_offset(buffer_snap);
8884 let end = symbol.range.end.to_offset(buffer_snap);
8885 let new_range = start..end;
8886 if start < selection.start || end > selection.end {
8887 return Some(Selection {
8888 id: selection.id,
8889 start: new_range.start,
8890 end: new_range.end,
8891 goal: SelectionGoal::None,
8892 reversed: selection.reversed,
8893 });
8894 }
8895 }
8896 None
8897 }
8898
8899 let mut selected_larger_symbol = false;
8900 let new_selections = old_selections
8901 .iter()
8902 .map(|selection| match update_selection(selection, &buffer) {
8903 Some(new_selection) => {
8904 if new_selection.range() != selection.range() {
8905 selected_larger_symbol = true;
8906 }
8907 new_selection
8908 }
8909 None => selection.clone(),
8910 })
8911 .collect::<Vec<_>>();
8912
8913 if selected_larger_symbol {
8914 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8915 s.select(new_selections);
8916 });
8917 }
8918 }
8919
8920 pub fn select_larger_syntax_node(
8921 &mut self,
8922 _: &SelectLargerSyntaxNode,
8923 cx: &mut ViewContext<Self>,
8924 ) {
8925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8926 let buffer = self.buffer.read(cx).snapshot(cx);
8927 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8928
8929 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8930 let mut selected_larger_node = false;
8931 let new_selections = old_selections
8932 .iter()
8933 .map(|selection| {
8934 let old_range = selection.start..selection.end;
8935 let mut new_range = old_range.clone();
8936 let mut new_node = None;
8937 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8938 {
8939 new_node = Some(node);
8940 new_range = containing_range;
8941 if !display_map.intersects_fold(new_range.start)
8942 && !display_map.intersects_fold(new_range.end)
8943 {
8944 break;
8945 }
8946 }
8947
8948 if let Some(node) = new_node {
8949 // Log the ancestor, to support using this action as a way to explore TreeSitter
8950 // nodes. Parent and grandparent are also logged because this operation will not
8951 // visit nodes that have the same range as their parent.
8952 log::info!("Node: {node:?}");
8953 let parent = node.parent();
8954 log::info!("Parent: {parent:?}");
8955 let grandparent = parent.and_then(|x| x.parent());
8956 log::info!("Grandparent: {grandparent:?}");
8957 }
8958
8959 selected_larger_node |= new_range != old_range;
8960 Selection {
8961 id: selection.id,
8962 start: new_range.start,
8963 end: new_range.end,
8964 goal: SelectionGoal::None,
8965 reversed: selection.reversed,
8966 }
8967 })
8968 .collect::<Vec<_>>();
8969
8970 if selected_larger_node {
8971 stack.push(old_selections);
8972 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8973 s.select(new_selections);
8974 });
8975 }
8976 self.select_larger_syntax_node_stack = stack;
8977 }
8978
8979 pub fn select_smaller_syntax_node(
8980 &mut self,
8981 _: &SelectSmallerSyntaxNode,
8982 cx: &mut ViewContext<Self>,
8983 ) {
8984 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8985 if let Some(selections) = stack.pop() {
8986 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8987 s.select(selections.to_vec());
8988 });
8989 }
8990 self.select_larger_syntax_node_stack = stack;
8991 }
8992
8993 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8994 if !EditorSettings::get_global(cx).gutter.runnables {
8995 self.clear_tasks();
8996 return Task::ready(());
8997 }
8998 let project = self.project.as_ref().map(Model::downgrade);
8999 cx.spawn(|this, mut cx| async move {
9000 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9001 let Some(project) = project.and_then(|p| p.upgrade()) else {
9002 return;
9003 };
9004 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9005 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9006 }) else {
9007 return;
9008 };
9009
9010 let hide_runnables = project
9011 .update(&mut cx, |project, cx| {
9012 // Do not display any test indicators in non-dev server remote projects.
9013 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9014 })
9015 .unwrap_or(true);
9016 if hide_runnables {
9017 return;
9018 }
9019 let new_rows =
9020 cx.background_executor()
9021 .spawn({
9022 let snapshot = display_snapshot.clone();
9023 async move {
9024 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9025 }
9026 })
9027 .await;
9028 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9029
9030 this.update(&mut cx, |this, _| {
9031 this.clear_tasks();
9032 for (key, value) in rows {
9033 this.insert_tasks(key, value);
9034 }
9035 })
9036 .ok();
9037 })
9038 }
9039 fn fetch_runnable_ranges(
9040 snapshot: &DisplaySnapshot,
9041 range: Range<Anchor>,
9042 ) -> Vec<language::RunnableRange> {
9043 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9044 }
9045
9046 fn runnable_rows(
9047 project: Model<Project>,
9048 snapshot: DisplaySnapshot,
9049 runnable_ranges: Vec<RunnableRange>,
9050 mut cx: AsyncWindowContext,
9051 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9052 runnable_ranges
9053 .into_iter()
9054 .filter_map(|mut runnable| {
9055 let tasks = cx
9056 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9057 .ok()?;
9058 if tasks.is_empty() {
9059 return None;
9060 }
9061
9062 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9063
9064 let row = snapshot
9065 .buffer_snapshot
9066 .buffer_line_for_row(MultiBufferRow(point.row))?
9067 .1
9068 .start
9069 .row;
9070
9071 let context_range =
9072 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9073 Some((
9074 (runnable.buffer_id, row),
9075 RunnableTasks {
9076 templates: tasks,
9077 offset: MultiBufferOffset(runnable.run_range.start),
9078 context_range,
9079 column: point.column,
9080 extra_variables: runnable.extra_captures,
9081 },
9082 ))
9083 })
9084 .collect()
9085 }
9086
9087 fn templates_with_tags(
9088 project: &Model<Project>,
9089 runnable: &mut Runnable,
9090 cx: &WindowContext,
9091 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9092 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9093 let (worktree_id, file) = project
9094 .buffer_for_id(runnable.buffer, cx)
9095 .and_then(|buffer| buffer.read(cx).file())
9096 .map(|file| (file.worktree_id(cx), file.clone()))
9097 .unzip();
9098
9099 (
9100 project.task_store().read(cx).task_inventory().cloned(),
9101 worktree_id,
9102 file,
9103 )
9104 });
9105
9106 let tags = mem::take(&mut runnable.tags);
9107 let mut tags: Vec<_> = tags
9108 .into_iter()
9109 .flat_map(|tag| {
9110 let tag = tag.0.clone();
9111 inventory
9112 .as_ref()
9113 .into_iter()
9114 .flat_map(|inventory| {
9115 inventory.read(cx).list_tasks(
9116 file.clone(),
9117 Some(runnable.language.clone()),
9118 worktree_id,
9119 cx,
9120 )
9121 })
9122 .filter(move |(_, template)| {
9123 template.tags.iter().any(|source_tag| source_tag == &tag)
9124 })
9125 })
9126 .sorted_by_key(|(kind, _)| kind.to_owned())
9127 .collect();
9128 if let Some((leading_tag_source, _)) = tags.first() {
9129 // Strongest source wins; if we have worktree tag binding, prefer that to
9130 // global and language bindings;
9131 // if we have a global binding, prefer that to language binding.
9132 let first_mismatch = tags
9133 .iter()
9134 .position(|(tag_source, _)| tag_source != leading_tag_source);
9135 if let Some(index) = first_mismatch {
9136 tags.truncate(index);
9137 }
9138 }
9139
9140 tags
9141 }
9142
9143 pub fn move_to_enclosing_bracket(
9144 &mut self,
9145 _: &MoveToEnclosingBracket,
9146 cx: &mut ViewContext<Self>,
9147 ) {
9148 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9149 s.move_offsets_with(|snapshot, selection| {
9150 let Some(enclosing_bracket_ranges) =
9151 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9152 else {
9153 return;
9154 };
9155
9156 let mut best_length = usize::MAX;
9157 let mut best_inside = false;
9158 let mut best_in_bracket_range = false;
9159 let mut best_destination = None;
9160 for (open, close) in enclosing_bracket_ranges {
9161 let close = close.to_inclusive();
9162 let length = close.end() - open.start;
9163 let inside = selection.start >= open.end && selection.end <= *close.start();
9164 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9165 || close.contains(&selection.head());
9166
9167 // If best is next to a bracket and current isn't, skip
9168 if !in_bracket_range && best_in_bracket_range {
9169 continue;
9170 }
9171
9172 // Prefer smaller lengths unless best is inside and current isn't
9173 if length > best_length && (best_inside || !inside) {
9174 continue;
9175 }
9176
9177 best_length = length;
9178 best_inside = inside;
9179 best_in_bracket_range = in_bracket_range;
9180 best_destination = Some(
9181 if close.contains(&selection.start) && close.contains(&selection.end) {
9182 if inside {
9183 open.end
9184 } else {
9185 open.start
9186 }
9187 } else if inside {
9188 *close.start()
9189 } else {
9190 *close.end()
9191 },
9192 );
9193 }
9194
9195 if let Some(destination) = best_destination {
9196 selection.collapse_to(destination, SelectionGoal::None);
9197 }
9198 })
9199 });
9200 }
9201
9202 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9203 self.end_selection(cx);
9204 self.selection_history.mode = SelectionHistoryMode::Undoing;
9205 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9206 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9207 self.select_next_state = entry.select_next_state;
9208 self.select_prev_state = entry.select_prev_state;
9209 self.add_selections_state = entry.add_selections_state;
9210 self.request_autoscroll(Autoscroll::newest(), cx);
9211 }
9212 self.selection_history.mode = SelectionHistoryMode::Normal;
9213 }
9214
9215 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9216 self.end_selection(cx);
9217 self.selection_history.mode = SelectionHistoryMode::Redoing;
9218 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9219 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9220 self.select_next_state = entry.select_next_state;
9221 self.select_prev_state = entry.select_prev_state;
9222 self.add_selections_state = entry.add_selections_state;
9223 self.request_autoscroll(Autoscroll::newest(), cx);
9224 }
9225 self.selection_history.mode = SelectionHistoryMode::Normal;
9226 }
9227
9228 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9229 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9230 }
9231
9232 pub fn expand_excerpts_down(
9233 &mut self,
9234 action: &ExpandExcerptsDown,
9235 cx: &mut ViewContext<Self>,
9236 ) {
9237 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9238 }
9239
9240 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9241 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9242 }
9243
9244 pub fn expand_excerpts_for_direction(
9245 &mut self,
9246 lines: u32,
9247 direction: ExpandExcerptDirection,
9248 cx: &mut ViewContext<Self>,
9249 ) {
9250 let selections = self.selections.disjoint_anchors();
9251
9252 let lines = if lines == 0 {
9253 EditorSettings::get_global(cx).expand_excerpt_lines
9254 } else {
9255 lines
9256 };
9257
9258 self.buffer.update(cx, |buffer, cx| {
9259 let snapshot = buffer.snapshot(cx);
9260 let mut excerpt_ids = selections
9261 .iter()
9262 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
9263 .collect::<Vec<_>>();
9264 excerpt_ids.sort();
9265 excerpt_ids.dedup();
9266 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9267 })
9268 }
9269
9270 pub fn expand_excerpt(
9271 &mut self,
9272 excerpt: ExcerptId,
9273 direction: ExpandExcerptDirection,
9274 cx: &mut ViewContext<Self>,
9275 ) {
9276 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9277 self.buffer.update(cx, |buffer, cx| {
9278 buffer.expand_excerpts([excerpt], lines, direction, cx)
9279 })
9280 }
9281
9282 pub fn go_to_singleton_buffer_point(&mut self, point: Point, cx: &mut ViewContext<Self>) {
9283 self.go_to_singleton_buffer_range(point..point, cx);
9284 }
9285
9286 pub fn go_to_singleton_buffer_range(
9287 &mut self,
9288 range: Range<Point>,
9289 cx: &mut ViewContext<Self>,
9290 ) {
9291 let multibuffer = self.buffer().read(cx);
9292 let Some(buffer) = multibuffer.as_singleton() else {
9293 return;
9294 };
9295 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
9296 return;
9297 };
9298 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
9299 return;
9300 };
9301 self.change_selections(Some(Autoscroll::center()), cx, |s| {
9302 s.select_anchor_ranges([start..end])
9303 });
9304 }
9305
9306 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9307 self.go_to_diagnostic_impl(Direction::Next, cx)
9308 }
9309
9310 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9311 self.go_to_diagnostic_impl(Direction::Prev, cx)
9312 }
9313
9314 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9315 let buffer = self.buffer.read(cx).snapshot(cx);
9316 let selection = self.selections.newest::<usize>(cx);
9317
9318 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9319 if direction == Direction::Next {
9320 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9321 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
9322 return;
9323 };
9324 self.activate_diagnostics(
9325 buffer_id,
9326 popover.local_diagnostic.diagnostic.group_id,
9327 cx,
9328 );
9329 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9330 let primary_range_start = active_diagnostics.primary_range.start;
9331 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9332 let mut new_selection = s.newest_anchor().clone();
9333 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9334 s.select_anchors(vec![new_selection.clone()]);
9335 });
9336 self.refresh_inline_completion(false, true, cx);
9337 }
9338 return;
9339 }
9340 }
9341
9342 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9343 active_diagnostics
9344 .primary_range
9345 .to_offset(&buffer)
9346 .to_inclusive()
9347 });
9348 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9349 if active_primary_range.contains(&selection.head()) {
9350 *active_primary_range.start()
9351 } else {
9352 selection.head()
9353 }
9354 } else {
9355 selection.head()
9356 };
9357 let snapshot = self.snapshot(cx);
9358 loop {
9359 let mut diagnostics;
9360 if direction == Direction::Prev {
9361 diagnostics = buffer
9362 .diagnostics_in_range::<_, usize>(0..search_start)
9363 .collect::<Vec<_>>();
9364 diagnostics.reverse();
9365 } else {
9366 diagnostics = buffer
9367 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
9368 .collect::<Vec<_>>();
9369 };
9370 let group = diagnostics
9371 .into_iter()
9372 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
9373 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9374 // be sorted in a stable way
9375 // skip until we are at current active diagnostic, if it exists
9376 .skip_while(|entry| {
9377 let is_in_range = match direction {
9378 Direction::Prev => entry.range.end > search_start,
9379 Direction::Next => entry.range.start < search_start,
9380 };
9381 is_in_range
9382 && self
9383 .active_diagnostics
9384 .as_ref()
9385 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9386 })
9387 .find_map(|entry| {
9388 if entry.diagnostic.is_primary
9389 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9390 && entry.range.start != entry.range.end
9391 // if we match with the active diagnostic, skip it
9392 && Some(entry.diagnostic.group_id)
9393 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9394 {
9395 Some((entry.range, entry.diagnostic.group_id))
9396 } else {
9397 None
9398 }
9399 });
9400
9401 if let Some((primary_range, group_id)) = group {
9402 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
9403 return;
9404 };
9405 self.activate_diagnostics(buffer_id, group_id, cx);
9406 if self.active_diagnostics.is_some() {
9407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9408 s.select(vec![Selection {
9409 id: selection.id,
9410 start: primary_range.start,
9411 end: primary_range.start,
9412 reversed: false,
9413 goal: SelectionGoal::None,
9414 }]);
9415 });
9416 self.refresh_inline_completion(false, true, cx);
9417 }
9418 break;
9419 } else {
9420 // Cycle around to the start of the buffer, potentially moving back to the start of
9421 // the currently active diagnostic.
9422 active_primary_range.take();
9423 if direction == Direction::Prev {
9424 if search_start == buffer.len() {
9425 break;
9426 } else {
9427 search_start = buffer.len();
9428 }
9429 } else if search_start == 0 {
9430 break;
9431 } else {
9432 search_start = 0;
9433 }
9434 }
9435 }
9436 }
9437
9438 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9439 let snapshot = self.snapshot(cx);
9440 let selection = self.selections.newest::<Point>(cx);
9441 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9442 }
9443
9444 fn go_to_hunk_after_position(
9445 &mut self,
9446 snapshot: &EditorSnapshot,
9447 position: Point,
9448 cx: &mut ViewContext<Editor>,
9449 ) -> Option<MultiBufferDiffHunk> {
9450 let mut hunk = snapshot
9451 .buffer_snapshot
9452 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
9453 .find(|hunk| hunk.row_range.start.0 > position.row);
9454 if hunk.is_none() {
9455 hunk = snapshot
9456 .buffer_snapshot
9457 .diff_hunks_in_range(Point::zero()..position)
9458 .find(|hunk| hunk.row_range.end.0 < position.row)
9459 }
9460 if let Some(hunk) = &hunk {
9461 let destination = Point::new(hunk.row_range.start.0, 0);
9462 self.unfold_ranges(&[destination..destination], false, false, cx);
9463 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9464 s.select_ranges(vec![destination..destination]);
9465 });
9466 }
9467
9468 hunk
9469 }
9470
9471 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9472 let snapshot = self.snapshot(cx);
9473 let selection = self.selections.newest::<Point>(cx);
9474 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9475 }
9476
9477 fn go_to_hunk_before_position(
9478 &mut self,
9479 snapshot: &EditorSnapshot,
9480 position: Point,
9481 cx: &mut ViewContext<Editor>,
9482 ) -> Option<MultiBufferDiffHunk> {
9483 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
9484 if hunk.is_none() {
9485 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
9486 }
9487 if let Some(hunk) = &hunk {
9488 let destination = Point::new(hunk.row_range.start.0, 0);
9489 self.unfold_ranges(&[destination..destination], false, false, cx);
9490 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9491 s.select_ranges(vec![destination..destination]);
9492 });
9493 }
9494
9495 hunk
9496 }
9497
9498 pub fn go_to_definition(
9499 &mut self,
9500 _: &GoToDefinition,
9501 cx: &mut ViewContext<Self>,
9502 ) -> Task<Result<Navigated>> {
9503 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9504 cx.spawn(|editor, mut cx| async move {
9505 if definition.await? == Navigated::Yes {
9506 return Ok(Navigated::Yes);
9507 }
9508 match editor.update(&mut cx, |editor, cx| {
9509 editor.find_all_references(&FindAllReferences, cx)
9510 })? {
9511 Some(references) => references.await,
9512 None => Ok(Navigated::No),
9513 }
9514 })
9515 }
9516
9517 pub fn go_to_declaration(
9518 &mut self,
9519 _: &GoToDeclaration,
9520 cx: &mut ViewContext<Self>,
9521 ) -> Task<Result<Navigated>> {
9522 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9523 }
9524
9525 pub fn go_to_declaration_split(
9526 &mut self,
9527 _: &GoToDeclaration,
9528 cx: &mut ViewContext<Self>,
9529 ) -> Task<Result<Navigated>> {
9530 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9531 }
9532
9533 pub fn go_to_implementation(
9534 &mut self,
9535 _: &GoToImplementation,
9536 cx: &mut ViewContext<Self>,
9537 ) -> Task<Result<Navigated>> {
9538 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9539 }
9540
9541 pub fn go_to_implementation_split(
9542 &mut self,
9543 _: &GoToImplementationSplit,
9544 cx: &mut ViewContext<Self>,
9545 ) -> Task<Result<Navigated>> {
9546 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9547 }
9548
9549 pub fn go_to_type_definition(
9550 &mut self,
9551 _: &GoToTypeDefinition,
9552 cx: &mut ViewContext<Self>,
9553 ) -> Task<Result<Navigated>> {
9554 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9555 }
9556
9557 pub fn go_to_definition_split(
9558 &mut self,
9559 _: &GoToDefinitionSplit,
9560 cx: &mut ViewContext<Self>,
9561 ) -> Task<Result<Navigated>> {
9562 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9563 }
9564
9565 pub fn go_to_type_definition_split(
9566 &mut self,
9567 _: &GoToTypeDefinitionSplit,
9568 cx: &mut ViewContext<Self>,
9569 ) -> Task<Result<Navigated>> {
9570 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9571 }
9572
9573 fn go_to_definition_of_kind(
9574 &mut self,
9575 kind: GotoDefinitionKind,
9576 split: bool,
9577 cx: &mut ViewContext<Self>,
9578 ) -> Task<Result<Navigated>> {
9579 let Some(provider) = self.semantics_provider.clone() else {
9580 return Task::ready(Ok(Navigated::No));
9581 };
9582 let head = self.selections.newest::<usize>(cx).head();
9583 let buffer = self.buffer.read(cx);
9584 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9585 text_anchor
9586 } else {
9587 return Task::ready(Ok(Navigated::No));
9588 };
9589
9590 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9591 return Task::ready(Ok(Navigated::No));
9592 };
9593
9594 cx.spawn(|editor, mut cx| async move {
9595 let definitions = definitions.await?;
9596 let navigated = editor
9597 .update(&mut cx, |editor, cx| {
9598 editor.navigate_to_hover_links(
9599 Some(kind),
9600 definitions
9601 .into_iter()
9602 .filter(|location| {
9603 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9604 })
9605 .map(HoverLink::Text)
9606 .collect::<Vec<_>>(),
9607 split,
9608 cx,
9609 )
9610 })?
9611 .await?;
9612 anyhow::Ok(navigated)
9613 })
9614 }
9615
9616 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9617 let selection = self.selections.newest_anchor();
9618 let head = selection.head();
9619 let tail = selection.tail();
9620
9621 let Some((buffer, start_position)) =
9622 self.buffer.read(cx).text_anchor_for_position(head, cx)
9623 else {
9624 return;
9625 };
9626
9627 let end_position = if head != tail {
9628 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9629 return;
9630 };
9631 Some(pos)
9632 } else {
9633 None
9634 };
9635
9636 let url_finder = cx.spawn(|editor, mut cx| async move {
9637 let url = if let Some(end_pos) = end_position {
9638 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9639 } else {
9640 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9641 };
9642
9643 if let Some(url) = url {
9644 editor.update(&mut cx, |_, cx| {
9645 cx.open_url(&url);
9646 })
9647 } else {
9648 Ok(())
9649 }
9650 });
9651
9652 url_finder.detach();
9653 }
9654
9655 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9656 let Some(workspace) = self.workspace() else {
9657 return;
9658 };
9659
9660 let position = self.selections.newest_anchor().head();
9661
9662 let Some((buffer, buffer_position)) =
9663 self.buffer.read(cx).text_anchor_for_position(position, cx)
9664 else {
9665 return;
9666 };
9667
9668 let project = self.project.clone();
9669
9670 cx.spawn(|_, mut cx| async move {
9671 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9672
9673 if let Some((_, path)) = result {
9674 workspace
9675 .update(&mut cx, |workspace, cx| {
9676 workspace.open_resolved_path(path, cx)
9677 })?
9678 .await?;
9679 }
9680 anyhow::Ok(())
9681 })
9682 .detach();
9683 }
9684
9685 pub(crate) fn navigate_to_hover_links(
9686 &mut self,
9687 kind: Option<GotoDefinitionKind>,
9688 mut definitions: Vec<HoverLink>,
9689 split: bool,
9690 cx: &mut ViewContext<Editor>,
9691 ) -> Task<Result<Navigated>> {
9692 // If there is one definition, just open it directly
9693 if definitions.len() == 1 {
9694 let definition = definitions.pop().unwrap();
9695
9696 enum TargetTaskResult {
9697 Location(Option<Location>),
9698 AlreadyNavigated,
9699 }
9700
9701 let target_task = match definition {
9702 HoverLink::Text(link) => {
9703 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9704 }
9705 HoverLink::InlayHint(lsp_location, server_id) => {
9706 let computation = self.compute_target_location(lsp_location, server_id, cx);
9707 cx.background_executor().spawn(async move {
9708 let location = computation.await?;
9709 Ok(TargetTaskResult::Location(location))
9710 })
9711 }
9712 HoverLink::Url(url) => {
9713 cx.open_url(&url);
9714 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9715 }
9716 HoverLink::File(path) => {
9717 if let Some(workspace) = self.workspace() {
9718 cx.spawn(|_, mut cx| async move {
9719 workspace
9720 .update(&mut cx, |workspace, cx| {
9721 workspace.open_resolved_path(path, cx)
9722 })?
9723 .await
9724 .map(|_| TargetTaskResult::AlreadyNavigated)
9725 })
9726 } else {
9727 Task::ready(Ok(TargetTaskResult::Location(None)))
9728 }
9729 }
9730 };
9731 cx.spawn(|editor, mut cx| async move {
9732 let target = match target_task.await.context("target resolution task")? {
9733 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9734 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9735 TargetTaskResult::Location(Some(target)) => target,
9736 };
9737
9738 editor.update(&mut cx, |editor, cx| {
9739 let Some(workspace) = editor.workspace() else {
9740 return Navigated::No;
9741 };
9742 let pane = workspace.read(cx).active_pane().clone();
9743
9744 let range = target.range.to_point(target.buffer.read(cx));
9745 let range = editor.range_for_match(&range);
9746 let range = collapse_multiline_range(range);
9747
9748 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9749 editor.go_to_singleton_buffer_range(range.clone(), cx);
9750 } else {
9751 cx.window_context().defer(move |cx| {
9752 let target_editor: View<Self> =
9753 workspace.update(cx, |workspace, cx| {
9754 let pane = if split {
9755 workspace.adjacent_pane(cx)
9756 } else {
9757 workspace.active_pane().clone()
9758 };
9759
9760 workspace.open_project_item(
9761 pane,
9762 target.buffer.clone(),
9763 true,
9764 true,
9765 cx,
9766 )
9767 });
9768 target_editor.update(cx, |target_editor, cx| {
9769 // When selecting a definition in a different buffer, disable the nav history
9770 // to avoid creating a history entry at the previous cursor location.
9771 pane.update(cx, |pane, _| pane.disable_history());
9772 target_editor.go_to_singleton_buffer_range(range, cx);
9773 pane.update(cx, |pane, _| pane.enable_history());
9774 });
9775 });
9776 }
9777 Navigated::Yes
9778 })
9779 })
9780 } else if !definitions.is_empty() {
9781 cx.spawn(|editor, mut cx| async move {
9782 let (title, location_tasks, workspace) = editor
9783 .update(&mut cx, |editor, cx| {
9784 let tab_kind = match kind {
9785 Some(GotoDefinitionKind::Implementation) => "Implementations",
9786 _ => "Definitions",
9787 };
9788 let title = definitions
9789 .iter()
9790 .find_map(|definition| match definition {
9791 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9792 let buffer = origin.buffer.read(cx);
9793 format!(
9794 "{} for {}",
9795 tab_kind,
9796 buffer
9797 .text_for_range(origin.range.clone())
9798 .collect::<String>()
9799 )
9800 }),
9801 HoverLink::InlayHint(_, _) => None,
9802 HoverLink::Url(_) => None,
9803 HoverLink::File(_) => None,
9804 })
9805 .unwrap_or(tab_kind.to_string());
9806 let location_tasks = definitions
9807 .into_iter()
9808 .map(|definition| match definition {
9809 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9810 HoverLink::InlayHint(lsp_location, server_id) => {
9811 editor.compute_target_location(lsp_location, server_id, cx)
9812 }
9813 HoverLink::Url(_) => Task::ready(Ok(None)),
9814 HoverLink::File(_) => Task::ready(Ok(None)),
9815 })
9816 .collect::<Vec<_>>();
9817 (title, location_tasks, editor.workspace().clone())
9818 })
9819 .context("location tasks preparation")?;
9820
9821 let locations = future::join_all(location_tasks)
9822 .await
9823 .into_iter()
9824 .filter_map(|location| location.transpose())
9825 .collect::<Result<_>>()
9826 .context("location tasks")?;
9827
9828 let Some(workspace) = workspace else {
9829 return Ok(Navigated::No);
9830 };
9831 let opened = workspace
9832 .update(&mut cx, |workspace, cx| {
9833 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9834 })
9835 .ok();
9836
9837 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9838 })
9839 } else {
9840 Task::ready(Ok(Navigated::No))
9841 }
9842 }
9843
9844 fn compute_target_location(
9845 &self,
9846 lsp_location: lsp::Location,
9847 server_id: LanguageServerId,
9848 cx: &mut ViewContext<Self>,
9849 ) -> Task<anyhow::Result<Option<Location>>> {
9850 let Some(project) = self.project.clone() else {
9851 return Task::ready(Ok(None));
9852 };
9853
9854 cx.spawn(move |editor, mut cx| async move {
9855 let location_task = editor.update(&mut cx, |_, cx| {
9856 project.update(cx, |project, cx| {
9857 let language_server_name = project
9858 .language_server_statuses(cx)
9859 .find(|(id, _)| server_id == *id)
9860 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9861 language_server_name.map(|language_server_name| {
9862 project.open_local_buffer_via_lsp(
9863 lsp_location.uri.clone(),
9864 server_id,
9865 language_server_name,
9866 cx,
9867 )
9868 })
9869 })
9870 })?;
9871 let location = match location_task {
9872 Some(task) => Some({
9873 let target_buffer_handle = task.await.context("open local buffer")?;
9874 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9875 let target_start = target_buffer
9876 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9877 let target_end = target_buffer
9878 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9879 target_buffer.anchor_after(target_start)
9880 ..target_buffer.anchor_before(target_end)
9881 })?;
9882 Location {
9883 buffer: target_buffer_handle,
9884 range,
9885 }
9886 }),
9887 None => None,
9888 };
9889 Ok(location)
9890 })
9891 }
9892
9893 pub fn find_all_references(
9894 &mut self,
9895 _: &FindAllReferences,
9896 cx: &mut ViewContext<Self>,
9897 ) -> Option<Task<Result<Navigated>>> {
9898 let selection = self.selections.newest::<usize>(cx);
9899 let multi_buffer = self.buffer.read(cx);
9900 let head = selection.head();
9901
9902 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9903 let head_anchor = multi_buffer_snapshot.anchor_at(
9904 head,
9905 if head < selection.tail() {
9906 Bias::Right
9907 } else {
9908 Bias::Left
9909 },
9910 );
9911
9912 match self
9913 .find_all_references_task_sources
9914 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9915 {
9916 Ok(_) => {
9917 log::info!(
9918 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9919 );
9920 return None;
9921 }
9922 Err(i) => {
9923 self.find_all_references_task_sources.insert(i, head_anchor);
9924 }
9925 }
9926
9927 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9928 let workspace = self.workspace()?;
9929 let project = workspace.read(cx).project().clone();
9930 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9931 Some(cx.spawn(|editor, mut cx| async move {
9932 let _cleanup = defer({
9933 let mut cx = cx.clone();
9934 move || {
9935 let _ = editor.update(&mut cx, |editor, _| {
9936 if let Ok(i) =
9937 editor
9938 .find_all_references_task_sources
9939 .binary_search_by(|anchor| {
9940 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9941 })
9942 {
9943 editor.find_all_references_task_sources.remove(i);
9944 }
9945 });
9946 }
9947 });
9948
9949 let locations = references.await?;
9950 if locations.is_empty() {
9951 return anyhow::Ok(Navigated::No);
9952 }
9953
9954 workspace.update(&mut cx, |workspace, cx| {
9955 let title = locations
9956 .first()
9957 .as_ref()
9958 .map(|location| {
9959 let buffer = location.buffer.read(cx);
9960 format!(
9961 "References to `{}`",
9962 buffer
9963 .text_for_range(location.range.clone())
9964 .collect::<String>()
9965 )
9966 })
9967 .unwrap();
9968 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9969 Navigated::Yes
9970 })
9971 }))
9972 }
9973
9974 /// Opens a multibuffer with the given project locations in it
9975 pub fn open_locations_in_multibuffer(
9976 workspace: &mut Workspace,
9977 mut locations: Vec<Location>,
9978 title: String,
9979 split: bool,
9980 cx: &mut ViewContext<Workspace>,
9981 ) {
9982 // If there are multiple definitions, open them in a multibuffer
9983 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9984 let mut locations = locations.into_iter().peekable();
9985 let mut ranges_to_highlight = Vec::new();
9986 let capability = workspace.project().read(cx).capability();
9987
9988 let excerpt_buffer = cx.new_model(|cx| {
9989 let mut multibuffer = MultiBuffer::new(capability);
9990 while let Some(location) = locations.next() {
9991 let buffer = location.buffer.read(cx);
9992 let mut ranges_for_buffer = Vec::new();
9993 let range = location.range.to_offset(buffer);
9994 ranges_for_buffer.push(range.clone());
9995
9996 while let Some(next_location) = locations.peek() {
9997 if next_location.buffer == location.buffer {
9998 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9999 locations.next();
10000 } else {
10001 break;
10002 }
10003 }
10004
10005 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10006 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10007 location.buffer.clone(),
10008 ranges_for_buffer,
10009 DEFAULT_MULTIBUFFER_CONTEXT,
10010 cx,
10011 ))
10012 }
10013
10014 multibuffer.with_title(title)
10015 });
10016
10017 let editor = cx.new_view(|cx| {
10018 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10019 });
10020 editor.update(cx, |editor, cx| {
10021 if let Some(first_range) = ranges_to_highlight.first() {
10022 editor.change_selections(None, cx, |selections| {
10023 selections.clear_disjoint();
10024 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10025 });
10026 }
10027 editor.highlight_background::<Self>(
10028 &ranges_to_highlight,
10029 |theme| theme.editor_highlighted_line_background,
10030 cx,
10031 );
10032 editor.register_buffers_with_language_servers(cx);
10033 });
10034
10035 let item = Box::new(editor);
10036 let item_id = item.item_id();
10037
10038 if split {
10039 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10040 } else {
10041 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10042 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10043 pane.close_current_preview_item(cx)
10044 } else {
10045 None
10046 }
10047 });
10048 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10049 }
10050 workspace.active_pane().update(cx, |pane, cx| {
10051 pane.set_preview_item_id(Some(item_id), cx);
10052 });
10053 }
10054
10055 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10056 use language::ToOffset as _;
10057
10058 let provider = self.semantics_provider.clone()?;
10059 let selection = self.selections.newest_anchor().clone();
10060 let (cursor_buffer, cursor_buffer_position) = self
10061 .buffer
10062 .read(cx)
10063 .text_anchor_for_position(selection.head(), cx)?;
10064 let (tail_buffer, cursor_buffer_position_end) = self
10065 .buffer
10066 .read(cx)
10067 .text_anchor_for_position(selection.tail(), cx)?;
10068 if tail_buffer != cursor_buffer {
10069 return None;
10070 }
10071
10072 let snapshot = cursor_buffer.read(cx).snapshot();
10073 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10074 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10075 let prepare_rename = provider
10076 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10077 .unwrap_or_else(|| Task::ready(Ok(None)));
10078 drop(snapshot);
10079
10080 Some(cx.spawn(|this, mut cx| async move {
10081 let rename_range = if let Some(range) = prepare_rename.await? {
10082 Some(range)
10083 } else {
10084 this.update(&mut cx, |this, cx| {
10085 let buffer = this.buffer.read(cx).snapshot(cx);
10086 let mut buffer_highlights = this
10087 .document_highlights_for_position(selection.head(), &buffer)
10088 .filter(|highlight| {
10089 highlight.start.excerpt_id == selection.head().excerpt_id
10090 && highlight.end.excerpt_id == selection.head().excerpt_id
10091 });
10092 buffer_highlights
10093 .next()
10094 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10095 })?
10096 };
10097 if let Some(rename_range) = rename_range {
10098 this.update(&mut cx, |this, cx| {
10099 let snapshot = cursor_buffer.read(cx).snapshot();
10100 let rename_buffer_range = rename_range.to_offset(&snapshot);
10101 let cursor_offset_in_rename_range =
10102 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10103 let cursor_offset_in_rename_range_end =
10104 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10105
10106 this.take_rename(false, cx);
10107 let buffer = this.buffer.read(cx).read(cx);
10108 let cursor_offset = selection.head().to_offset(&buffer);
10109 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10110 let rename_end = rename_start + rename_buffer_range.len();
10111 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10112 let mut old_highlight_id = None;
10113 let old_name: Arc<str> = buffer
10114 .chunks(rename_start..rename_end, true)
10115 .map(|chunk| {
10116 if old_highlight_id.is_none() {
10117 old_highlight_id = chunk.syntax_highlight_id;
10118 }
10119 chunk.text
10120 })
10121 .collect::<String>()
10122 .into();
10123
10124 drop(buffer);
10125
10126 // Position the selection in the rename editor so that it matches the current selection.
10127 this.show_local_selections = false;
10128 let rename_editor = cx.new_view(|cx| {
10129 let mut editor = Editor::single_line(cx);
10130 editor.buffer.update(cx, |buffer, cx| {
10131 buffer.edit([(0..0, old_name.clone())], None, cx)
10132 });
10133 let rename_selection_range = match cursor_offset_in_rename_range
10134 .cmp(&cursor_offset_in_rename_range_end)
10135 {
10136 Ordering::Equal => {
10137 editor.select_all(&SelectAll, cx);
10138 return editor;
10139 }
10140 Ordering::Less => {
10141 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10142 }
10143 Ordering::Greater => {
10144 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10145 }
10146 };
10147 if rename_selection_range.end > old_name.len() {
10148 editor.select_all(&SelectAll, cx);
10149 } else {
10150 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10151 s.select_ranges([rename_selection_range]);
10152 });
10153 }
10154 editor
10155 });
10156 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10157 if e == &EditorEvent::Focused {
10158 cx.emit(EditorEvent::FocusedIn)
10159 }
10160 })
10161 .detach();
10162
10163 let write_highlights =
10164 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10165 let read_highlights =
10166 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10167 let ranges = write_highlights
10168 .iter()
10169 .flat_map(|(_, ranges)| ranges.iter())
10170 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10171 .cloned()
10172 .collect();
10173
10174 this.highlight_text::<Rename>(
10175 ranges,
10176 HighlightStyle {
10177 fade_out: Some(0.6),
10178 ..Default::default()
10179 },
10180 cx,
10181 );
10182 let rename_focus_handle = rename_editor.focus_handle(cx);
10183 cx.focus(&rename_focus_handle);
10184 let block_id = this.insert_blocks(
10185 [BlockProperties {
10186 style: BlockStyle::Flex,
10187 placement: BlockPlacement::Below(range.start),
10188 height: 1,
10189 render: Arc::new({
10190 let rename_editor = rename_editor.clone();
10191 move |cx: &mut BlockContext| {
10192 let mut text_style = cx.editor_style.text.clone();
10193 if let Some(highlight_style) = old_highlight_id
10194 .and_then(|h| h.style(&cx.editor_style.syntax))
10195 {
10196 text_style = text_style.highlight(highlight_style);
10197 }
10198 div()
10199 .block_mouse_down()
10200 .pl(cx.anchor_x)
10201 .child(EditorElement::new(
10202 &rename_editor,
10203 EditorStyle {
10204 background: cx.theme().system().transparent,
10205 local_player: cx.editor_style.local_player,
10206 text: text_style,
10207 scrollbar_width: cx.editor_style.scrollbar_width,
10208 syntax: cx.editor_style.syntax.clone(),
10209 status: cx.editor_style.status.clone(),
10210 inlay_hints_style: HighlightStyle {
10211 font_weight: Some(FontWeight::BOLD),
10212 ..make_inlay_hints_style(cx)
10213 },
10214 inline_completion_styles: make_suggestion_styles(
10215 cx,
10216 ),
10217 ..EditorStyle::default()
10218 },
10219 ))
10220 .into_any_element()
10221 }
10222 }),
10223 priority: 0,
10224 }],
10225 Some(Autoscroll::fit()),
10226 cx,
10227 )[0];
10228 this.pending_rename = Some(RenameState {
10229 range,
10230 old_name,
10231 editor: rename_editor,
10232 block_id,
10233 });
10234 })?;
10235 }
10236
10237 Ok(())
10238 }))
10239 }
10240
10241 pub fn confirm_rename(
10242 &mut self,
10243 _: &ConfirmRename,
10244 cx: &mut ViewContext<Self>,
10245 ) -> Option<Task<Result<()>>> {
10246 let rename = self.take_rename(false, cx)?;
10247 let workspace = self.workspace()?.downgrade();
10248 let (buffer, start) = self
10249 .buffer
10250 .read(cx)
10251 .text_anchor_for_position(rename.range.start, cx)?;
10252 let (end_buffer, _) = self
10253 .buffer
10254 .read(cx)
10255 .text_anchor_for_position(rename.range.end, cx)?;
10256 if buffer != end_buffer {
10257 return None;
10258 }
10259
10260 let old_name = rename.old_name;
10261 let new_name = rename.editor.read(cx).text(cx);
10262
10263 let rename = self.semantics_provider.as_ref()?.perform_rename(
10264 &buffer,
10265 start,
10266 new_name.clone(),
10267 cx,
10268 )?;
10269
10270 Some(cx.spawn(|editor, mut cx| async move {
10271 let project_transaction = rename.await?;
10272 Self::open_project_transaction(
10273 &editor,
10274 workspace,
10275 project_transaction,
10276 format!("Rename: {} → {}", old_name, new_name),
10277 cx.clone(),
10278 )
10279 .await?;
10280
10281 editor.update(&mut cx, |editor, cx| {
10282 editor.refresh_document_highlights(cx);
10283 })?;
10284 Ok(())
10285 }))
10286 }
10287
10288 fn take_rename(
10289 &mut self,
10290 moving_cursor: bool,
10291 cx: &mut ViewContext<Self>,
10292 ) -> Option<RenameState> {
10293 let rename = self.pending_rename.take()?;
10294 if rename.editor.focus_handle(cx).is_focused(cx) {
10295 cx.focus(&self.focus_handle);
10296 }
10297
10298 self.remove_blocks(
10299 [rename.block_id].into_iter().collect(),
10300 Some(Autoscroll::fit()),
10301 cx,
10302 );
10303 self.clear_highlights::<Rename>(cx);
10304 self.show_local_selections = true;
10305
10306 if moving_cursor {
10307 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10308 editor.selections.newest::<usize>(cx).head()
10309 });
10310
10311 // Update the selection to match the position of the selection inside
10312 // the rename editor.
10313 let snapshot = self.buffer.read(cx).read(cx);
10314 let rename_range = rename.range.to_offset(&snapshot);
10315 let cursor_in_editor = snapshot
10316 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10317 .min(rename_range.end);
10318 drop(snapshot);
10319
10320 self.change_selections(None, cx, |s| {
10321 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10322 });
10323 } else {
10324 self.refresh_document_highlights(cx);
10325 }
10326
10327 Some(rename)
10328 }
10329
10330 pub fn pending_rename(&self) -> Option<&RenameState> {
10331 self.pending_rename.as_ref()
10332 }
10333
10334 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10335 let project = match &self.project {
10336 Some(project) => project.clone(),
10337 None => return None,
10338 };
10339
10340 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10341 }
10342
10343 fn format_selections(
10344 &mut self,
10345 _: &FormatSelections,
10346 cx: &mut ViewContext<Self>,
10347 ) -> Option<Task<Result<()>>> {
10348 let project = match &self.project {
10349 Some(project) => project.clone(),
10350 None => return None,
10351 };
10352
10353 let ranges = self
10354 .selections
10355 .all_adjusted(cx)
10356 .into_iter()
10357 .map(|selection| selection.range())
10358 .collect_vec();
10359
10360 Some(self.perform_format(
10361 project,
10362 FormatTrigger::Manual,
10363 FormatTarget::Ranges(ranges),
10364 cx,
10365 ))
10366 }
10367
10368 fn perform_format(
10369 &mut self,
10370 project: Model<Project>,
10371 trigger: FormatTrigger,
10372 target: FormatTarget,
10373 cx: &mut ViewContext<Self>,
10374 ) -> Task<Result<()>> {
10375 let buffer = self.buffer.clone();
10376 let (buffers, target) = match target {
10377 FormatTarget::Buffers => {
10378 let mut buffers = buffer.read(cx).all_buffers();
10379 if trigger == FormatTrigger::Save {
10380 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10381 }
10382 (buffers, LspFormatTarget::Buffers)
10383 }
10384 FormatTarget::Ranges(selection_ranges) => {
10385 let multi_buffer = buffer.read(cx);
10386 let snapshot = multi_buffer.read(cx);
10387 let mut buffers = HashSet::default();
10388 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10389 BTreeMap::new();
10390 for selection_range in selection_ranges {
10391 for (buffer, buffer_range, _) in
10392 snapshot.range_to_buffer_ranges(selection_range)
10393 {
10394 let buffer_id = buffer.remote_id();
10395 let start = buffer.anchor_before(buffer_range.start);
10396 let end = buffer.anchor_after(buffer_range.end);
10397 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10398 buffer_id_to_ranges
10399 .entry(buffer_id)
10400 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10401 .or_insert_with(|| vec![start..end]);
10402 }
10403 }
10404 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10405 }
10406 };
10407
10408 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10409 let format = project.update(cx, |project, cx| {
10410 project.format(buffers, target, true, trigger, cx)
10411 });
10412
10413 cx.spawn(|_, mut cx| async move {
10414 let transaction = futures::select_biased! {
10415 () = timeout => {
10416 log::warn!("timed out waiting for formatting");
10417 None
10418 }
10419 transaction = format.log_err().fuse() => transaction,
10420 };
10421
10422 buffer
10423 .update(&mut cx, |buffer, cx| {
10424 if let Some(transaction) = transaction {
10425 if !buffer.is_singleton() {
10426 buffer.push_transaction(&transaction.0, cx);
10427 }
10428 }
10429
10430 cx.notify();
10431 })
10432 .ok();
10433
10434 Ok(())
10435 })
10436 }
10437
10438 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10439 if let Some(project) = self.project.clone() {
10440 self.buffer.update(cx, |multi_buffer, cx| {
10441 project.update(cx, |project, cx| {
10442 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10443 });
10444 })
10445 }
10446 }
10447
10448 fn cancel_language_server_work(
10449 &mut self,
10450 _: &actions::CancelLanguageServerWork,
10451 cx: &mut ViewContext<Self>,
10452 ) {
10453 if let Some(project) = self.project.clone() {
10454 self.buffer.update(cx, |multi_buffer, cx| {
10455 project.update(cx, |project, cx| {
10456 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10457 });
10458 })
10459 }
10460 }
10461
10462 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10463 cx.show_character_palette();
10464 }
10465
10466 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10467 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10468 let buffer = self.buffer.read(cx).snapshot(cx);
10469 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10470 let is_valid = buffer
10471 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
10472 .any(|entry| {
10473 entry.diagnostic.is_primary
10474 && !entry.range.is_empty()
10475 && entry.range.start == primary_range_start
10476 && entry.diagnostic.message == active_diagnostics.primary_message
10477 });
10478
10479 if is_valid != active_diagnostics.is_valid {
10480 active_diagnostics.is_valid = is_valid;
10481 let mut new_styles = HashMap::default();
10482 for (block_id, diagnostic) in &active_diagnostics.blocks {
10483 new_styles.insert(
10484 *block_id,
10485 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10486 );
10487 }
10488 self.display_map.update(cx, |display_map, _cx| {
10489 display_map.replace_blocks(new_styles)
10490 });
10491 }
10492 }
10493 }
10494
10495 fn activate_diagnostics(
10496 &mut self,
10497 buffer_id: BufferId,
10498 group_id: usize,
10499 cx: &mut ViewContext<Self>,
10500 ) {
10501 self.dismiss_diagnostics(cx);
10502 let snapshot = self.snapshot(cx);
10503 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10504 let buffer = self.buffer.read(cx).snapshot(cx);
10505
10506 let mut primary_range = None;
10507 let mut primary_message = None;
10508 let diagnostic_group = buffer
10509 .diagnostic_group(buffer_id, group_id)
10510 .filter_map(|entry| {
10511 let start = entry.range.start;
10512 let end = entry.range.end;
10513 if snapshot.is_line_folded(MultiBufferRow(start.row))
10514 && (start.row == end.row
10515 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10516 {
10517 return None;
10518 }
10519 if entry.diagnostic.is_primary {
10520 primary_range = Some(entry.range.clone());
10521 primary_message = Some(entry.diagnostic.message.clone());
10522 }
10523 Some(entry)
10524 })
10525 .collect::<Vec<_>>();
10526 let primary_range = primary_range?;
10527 let primary_message = primary_message?;
10528
10529 let blocks = display_map
10530 .insert_blocks(
10531 diagnostic_group.iter().map(|entry| {
10532 let diagnostic = entry.diagnostic.clone();
10533 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10534 BlockProperties {
10535 style: BlockStyle::Fixed,
10536 placement: BlockPlacement::Below(
10537 buffer.anchor_after(entry.range.start),
10538 ),
10539 height: message_height,
10540 render: diagnostic_block_renderer(diagnostic, None, true, true),
10541 priority: 0,
10542 }
10543 }),
10544 cx,
10545 )
10546 .into_iter()
10547 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10548 .collect();
10549
10550 Some(ActiveDiagnosticGroup {
10551 primary_range: buffer.anchor_before(primary_range.start)
10552 ..buffer.anchor_after(primary_range.end),
10553 primary_message,
10554 group_id,
10555 blocks,
10556 is_valid: true,
10557 })
10558 });
10559 }
10560
10561 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10562 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10563 self.display_map.update(cx, |display_map, cx| {
10564 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10565 });
10566 cx.notify();
10567 }
10568 }
10569
10570 pub fn set_selections_from_remote(
10571 &mut self,
10572 selections: Vec<Selection<Anchor>>,
10573 pending_selection: Option<Selection<Anchor>>,
10574 cx: &mut ViewContext<Self>,
10575 ) {
10576 let old_cursor_position = self.selections.newest_anchor().head();
10577 self.selections.change_with(cx, |s| {
10578 s.select_anchors(selections);
10579 if let Some(pending_selection) = pending_selection {
10580 s.set_pending(pending_selection, SelectMode::Character);
10581 } else {
10582 s.clear_pending();
10583 }
10584 });
10585 self.selections_did_change(false, &old_cursor_position, true, cx);
10586 }
10587
10588 fn push_to_selection_history(&mut self) {
10589 self.selection_history.push(SelectionHistoryEntry {
10590 selections: self.selections.disjoint_anchors(),
10591 select_next_state: self.select_next_state.clone(),
10592 select_prev_state: self.select_prev_state.clone(),
10593 add_selections_state: self.add_selections_state.clone(),
10594 });
10595 }
10596
10597 pub fn transact(
10598 &mut self,
10599 cx: &mut ViewContext<Self>,
10600 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10601 ) -> Option<TransactionId> {
10602 self.start_transaction_at(Instant::now(), cx);
10603 update(self, cx);
10604 self.end_transaction_at(Instant::now(), cx)
10605 }
10606
10607 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10608 self.end_selection(cx);
10609 if let Some(tx_id) = self
10610 .buffer
10611 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10612 {
10613 self.selection_history
10614 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10615 cx.emit(EditorEvent::TransactionBegun {
10616 transaction_id: tx_id,
10617 })
10618 }
10619 }
10620
10621 pub fn end_transaction_at(
10622 &mut self,
10623 now: Instant,
10624 cx: &mut ViewContext<Self>,
10625 ) -> Option<TransactionId> {
10626 if let Some(transaction_id) = self
10627 .buffer
10628 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10629 {
10630 if let Some((_, end_selections)) =
10631 self.selection_history.transaction_mut(transaction_id)
10632 {
10633 *end_selections = Some(self.selections.disjoint_anchors());
10634 } else {
10635 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10636 }
10637
10638 cx.emit(EditorEvent::Edited { transaction_id });
10639 Some(transaction_id)
10640 } else {
10641 None
10642 }
10643 }
10644
10645 pub fn set_mark(&mut self, _: &actions::SetMark, cx: &mut ViewContext<Self>) {
10646 if self.selection_mark_mode {
10647 self.change_selections(None, cx, |s| {
10648 s.move_with(|_, sel| {
10649 sel.collapse_to(sel.head(), SelectionGoal::None);
10650 });
10651 })
10652 }
10653 self.selection_mark_mode = true;
10654 cx.notify();
10655 }
10656
10657 pub fn swap_selection_ends(
10658 &mut self,
10659 _: &actions::SwapSelectionEnds,
10660 cx: &mut ViewContext<Self>,
10661 ) {
10662 self.change_selections(None, cx, |s| {
10663 s.move_with(|_, sel| {
10664 if sel.start != sel.end {
10665 sel.reversed = !sel.reversed
10666 }
10667 });
10668 });
10669 self.request_autoscroll(Autoscroll::newest(), cx);
10670 cx.notify();
10671 }
10672
10673 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10674 if self.is_singleton(cx) {
10675 let selection = self.selections.newest::<Point>(cx);
10676
10677 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10678 let range = if selection.is_empty() {
10679 let point = selection.head().to_display_point(&display_map);
10680 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10681 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10682 .to_point(&display_map);
10683 start..end
10684 } else {
10685 selection.range()
10686 };
10687 if display_map.folds_in_range(range).next().is_some() {
10688 self.unfold_lines(&Default::default(), cx)
10689 } else {
10690 self.fold(&Default::default(), cx)
10691 }
10692 } else {
10693 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10694 let buffer_ids: HashSet<_> = multi_buffer_snapshot
10695 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
10696 .map(|(snapshot, _, _)| snapshot.remote_id())
10697 .collect();
10698
10699 for buffer_id in buffer_ids {
10700 if self.is_buffer_folded(buffer_id, cx) {
10701 self.unfold_buffer(buffer_id, cx);
10702 } else {
10703 self.fold_buffer(buffer_id, cx);
10704 }
10705 }
10706 }
10707 }
10708
10709 pub fn toggle_fold_recursive(
10710 &mut self,
10711 _: &actions::ToggleFoldRecursive,
10712 cx: &mut ViewContext<Self>,
10713 ) {
10714 let selection = self.selections.newest::<Point>(cx);
10715
10716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10717 let range = if selection.is_empty() {
10718 let point = selection.head().to_display_point(&display_map);
10719 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10720 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10721 .to_point(&display_map);
10722 start..end
10723 } else {
10724 selection.range()
10725 };
10726 if display_map.folds_in_range(range).next().is_some() {
10727 self.unfold_recursive(&Default::default(), cx)
10728 } else {
10729 self.fold_recursive(&Default::default(), cx)
10730 }
10731 }
10732
10733 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10734 if self.is_singleton(cx) {
10735 let mut to_fold = Vec::new();
10736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10737 let selections = self.selections.all_adjusted(cx);
10738
10739 for selection in selections {
10740 let range = selection.range().sorted();
10741 let buffer_start_row = range.start.row;
10742
10743 if range.start.row != range.end.row {
10744 let mut found = false;
10745 let mut row = range.start.row;
10746 while row <= range.end.row {
10747 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10748 {
10749 found = true;
10750 row = crease.range().end.row + 1;
10751 to_fold.push(crease);
10752 } else {
10753 row += 1
10754 }
10755 }
10756 if found {
10757 continue;
10758 }
10759 }
10760
10761 for row in (0..=range.start.row).rev() {
10762 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10763 if crease.range().end.row >= buffer_start_row {
10764 to_fold.push(crease);
10765 if row <= range.start.row {
10766 break;
10767 }
10768 }
10769 }
10770 }
10771 }
10772
10773 self.fold_creases(to_fold, true, cx);
10774 } else {
10775 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10776
10777 let buffer_ids: HashSet<_> = multi_buffer_snapshot
10778 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
10779 .map(|(snapshot, _, _)| snapshot.remote_id())
10780 .collect();
10781 for buffer_id in buffer_ids {
10782 self.fold_buffer(buffer_id, cx);
10783 }
10784 }
10785 }
10786
10787 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10788 if !self.buffer.read(cx).is_singleton() {
10789 return;
10790 }
10791
10792 let fold_at_level = fold_at.level;
10793 let snapshot = self.buffer.read(cx).snapshot(cx);
10794 let mut to_fold = Vec::new();
10795 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10796
10797 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10798 while start_row < end_row {
10799 match self
10800 .snapshot(cx)
10801 .crease_for_buffer_row(MultiBufferRow(start_row))
10802 {
10803 Some(crease) => {
10804 let nested_start_row = crease.range().start.row + 1;
10805 let nested_end_row = crease.range().end.row;
10806
10807 if current_level < fold_at_level {
10808 stack.push((nested_start_row, nested_end_row, current_level + 1));
10809 } else if current_level == fold_at_level {
10810 to_fold.push(crease);
10811 }
10812
10813 start_row = nested_end_row + 1;
10814 }
10815 None => start_row += 1,
10816 }
10817 }
10818 }
10819
10820 self.fold_creases(to_fold, true, cx);
10821 }
10822
10823 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10824 if self.buffer.read(cx).is_singleton() {
10825 let mut fold_ranges = Vec::new();
10826 let snapshot = self.buffer.read(cx).snapshot(cx);
10827
10828 for row in 0..snapshot.max_row().0 {
10829 if let Some(foldable_range) =
10830 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10831 {
10832 fold_ranges.push(foldable_range);
10833 }
10834 }
10835
10836 self.fold_creases(fold_ranges, true, cx);
10837 } else {
10838 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10839 editor
10840 .update(&mut cx, |editor, cx| {
10841 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10842 editor.fold_buffer(buffer_id, cx);
10843 }
10844 })
10845 .ok();
10846 });
10847 }
10848 }
10849
10850 pub fn fold_function_bodies(
10851 &mut self,
10852 _: &actions::FoldFunctionBodies,
10853 cx: &mut ViewContext<Self>,
10854 ) {
10855 let snapshot = self.buffer.read(cx).snapshot(cx);
10856
10857 let ranges = snapshot
10858 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
10859 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
10860 .collect::<Vec<_>>();
10861
10862 let creases = ranges
10863 .into_iter()
10864 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10865 .collect();
10866
10867 self.fold_creases(creases, true, cx);
10868 }
10869
10870 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10871 let mut to_fold = Vec::new();
10872 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10873 let selections = self.selections.all_adjusted(cx);
10874
10875 for selection in selections {
10876 let range = selection.range().sorted();
10877 let buffer_start_row = range.start.row;
10878
10879 if range.start.row != range.end.row {
10880 let mut found = false;
10881 for row in range.start.row..=range.end.row {
10882 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10883 found = true;
10884 to_fold.push(crease);
10885 }
10886 }
10887 if found {
10888 continue;
10889 }
10890 }
10891
10892 for row in (0..=range.start.row).rev() {
10893 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10894 if crease.range().end.row >= buffer_start_row {
10895 to_fold.push(crease);
10896 } else {
10897 break;
10898 }
10899 }
10900 }
10901 }
10902
10903 self.fold_creases(to_fold, true, cx);
10904 }
10905
10906 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10907 let buffer_row = fold_at.buffer_row;
10908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10909
10910 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10911 let autoscroll = self
10912 .selections
10913 .all::<Point>(cx)
10914 .iter()
10915 .any(|selection| crease.range().overlaps(&selection.range()));
10916
10917 self.fold_creases(vec![crease], autoscroll, cx);
10918 }
10919 }
10920
10921 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10922 if self.is_singleton(cx) {
10923 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10924 let buffer = &display_map.buffer_snapshot;
10925 let selections = self.selections.all::<Point>(cx);
10926 let ranges = selections
10927 .iter()
10928 .map(|s| {
10929 let range = s.display_range(&display_map).sorted();
10930 let mut start = range.start.to_point(&display_map);
10931 let mut end = range.end.to_point(&display_map);
10932 start.column = 0;
10933 end.column = buffer.line_len(MultiBufferRow(end.row));
10934 start..end
10935 })
10936 .collect::<Vec<_>>();
10937
10938 self.unfold_ranges(&ranges, true, true, cx);
10939 } else {
10940 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10941 let buffer_ids: HashSet<_> = multi_buffer_snapshot
10942 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
10943 .map(|(snapshot, _, _)| snapshot.remote_id())
10944 .collect();
10945 for buffer_id in buffer_ids {
10946 self.unfold_buffer(buffer_id, cx);
10947 }
10948 }
10949 }
10950
10951 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10953 let selections = self.selections.all::<Point>(cx);
10954 let ranges = selections
10955 .iter()
10956 .map(|s| {
10957 let mut range = s.display_range(&display_map).sorted();
10958 *range.start.column_mut() = 0;
10959 *range.end.column_mut() = display_map.line_len(range.end.row());
10960 let start = range.start.to_point(&display_map);
10961 let end = range.end.to_point(&display_map);
10962 start..end
10963 })
10964 .collect::<Vec<_>>();
10965
10966 self.unfold_ranges(&ranges, true, true, cx);
10967 }
10968
10969 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10970 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10971
10972 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10973 ..Point::new(
10974 unfold_at.buffer_row.0,
10975 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10976 );
10977
10978 let autoscroll = self
10979 .selections
10980 .all::<Point>(cx)
10981 .iter()
10982 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10983
10984 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10985 }
10986
10987 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10988 if self.buffer.read(cx).is_singleton() {
10989 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10990 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10991 } else {
10992 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10993 editor
10994 .update(&mut cx, |editor, cx| {
10995 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10996 editor.unfold_buffer(buffer_id, cx);
10997 }
10998 })
10999 .ok();
11000 });
11001 }
11002 }
11003
11004 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11005 let selections = self.selections.all::<Point>(cx);
11006 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11007 let line_mode = self.selections.line_mode;
11008 let ranges = selections
11009 .into_iter()
11010 .map(|s| {
11011 if line_mode {
11012 let start = Point::new(s.start.row, 0);
11013 let end = Point::new(
11014 s.end.row,
11015 display_map
11016 .buffer_snapshot
11017 .line_len(MultiBufferRow(s.end.row)),
11018 );
11019 Crease::simple(start..end, display_map.fold_placeholder.clone())
11020 } else {
11021 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11022 }
11023 })
11024 .collect::<Vec<_>>();
11025 self.fold_creases(ranges, true, cx);
11026 }
11027
11028 pub fn fold_ranges<T: ToOffset + Clone>(
11029 &mut self,
11030 ranges: Vec<Range<T>>,
11031 auto_scroll: bool,
11032 cx: &mut ViewContext<Self>,
11033 ) {
11034 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11035 let ranges = ranges
11036 .into_iter()
11037 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11038 .collect::<Vec<_>>();
11039 self.fold_creases(ranges, auto_scroll, cx);
11040 }
11041
11042 pub fn fold_creases<T: ToOffset + Clone>(
11043 &mut self,
11044 creases: Vec<Crease<T>>,
11045 auto_scroll: bool,
11046 cx: &mut ViewContext<Self>,
11047 ) {
11048 if creases.is_empty() {
11049 return;
11050 }
11051
11052 let mut buffers_affected = HashSet::default();
11053 let multi_buffer = self.buffer().read(cx);
11054 for crease in &creases {
11055 if let Some((_, buffer, _)) =
11056 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11057 {
11058 buffers_affected.insert(buffer.read(cx).remote_id());
11059 };
11060 }
11061
11062 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11063
11064 if auto_scroll {
11065 self.request_autoscroll(Autoscroll::fit(), cx);
11066 }
11067
11068 cx.notify();
11069
11070 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11071 // Clear diagnostics block when folding a range that contains it.
11072 let snapshot = self.snapshot(cx);
11073 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11074 drop(snapshot);
11075 self.active_diagnostics = Some(active_diagnostics);
11076 self.dismiss_diagnostics(cx);
11077 } else {
11078 self.active_diagnostics = Some(active_diagnostics);
11079 }
11080 }
11081
11082 self.scrollbar_marker_state.dirty = true;
11083 }
11084
11085 /// Removes any folds whose ranges intersect any of the given ranges.
11086 pub fn unfold_ranges<T: ToOffset + Clone>(
11087 &mut self,
11088 ranges: &[Range<T>],
11089 inclusive: bool,
11090 auto_scroll: bool,
11091 cx: &mut ViewContext<Self>,
11092 ) {
11093 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11094 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11095 });
11096 }
11097
11098 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11099 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11100 return;
11101 }
11102 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11103 return;
11104 };
11105 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11106 self.display_map
11107 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11108 cx.emit(EditorEvent::BufferFoldToggled {
11109 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11110 folded: true,
11111 });
11112 cx.notify();
11113 }
11114
11115 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11116 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11117 return;
11118 }
11119 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11120 return;
11121 };
11122 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11123 self.display_map.update(cx, |display_map, cx| {
11124 display_map.unfold_buffer(buffer_id, cx);
11125 });
11126 cx.emit(EditorEvent::BufferFoldToggled {
11127 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11128 folded: false,
11129 });
11130 cx.notify();
11131 }
11132
11133 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11134 self.display_map.read(cx).is_buffer_folded(buffer)
11135 }
11136
11137 pub fn folded_buffers<'a>(&self, cx: &'a AppContext) -> &'a HashSet<BufferId> {
11138 self.display_map.read(cx).folded_buffers()
11139 }
11140
11141 /// Removes any folds with the given ranges.
11142 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11143 &mut self,
11144 ranges: &[Range<T>],
11145 type_id: TypeId,
11146 auto_scroll: bool,
11147 cx: &mut ViewContext<Self>,
11148 ) {
11149 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11150 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11151 });
11152 }
11153
11154 fn remove_folds_with<T: ToOffset + Clone>(
11155 &mut self,
11156 ranges: &[Range<T>],
11157 auto_scroll: bool,
11158 cx: &mut ViewContext<Self>,
11159 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11160 ) {
11161 if ranges.is_empty() {
11162 return;
11163 }
11164
11165 let mut buffers_affected = HashSet::default();
11166 let multi_buffer = self.buffer().read(cx);
11167 for range in ranges {
11168 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11169 buffers_affected.insert(buffer.read(cx).remote_id());
11170 };
11171 }
11172
11173 self.display_map.update(cx, update);
11174
11175 if auto_scroll {
11176 self.request_autoscroll(Autoscroll::fit(), cx);
11177 }
11178
11179 cx.notify();
11180 self.scrollbar_marker_state.dirty = true;
11181 self.active_indent_guides_state.dirty = true;
11182 }
11183
11184 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11185 self.display_map.read(cx).fold_placeholder.clone()
11186 }
11187
11188 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut AppContext) {
11189 self.buffer.update(cx, |buffer, cx| {
11190 buffer.set_all_diff_hunks_expanded(cx);
11191 });
11192 }
11193
11194 pub fn expand_all_diff_hunks(&mut self, _: &ExpandAllHunkDiffs, cx: &mut ViewContext<Self>) {
11195 self.buffer.update(cx, |buffer, cx| {
11196 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11197 });
11198 }
11199
11200 pub fn toggle_selected_diff_hunks(
11201 &mut self,
11202 _: &ToggleSelectedDiffHunks,
11203 cx: &mut ViewContext<Self>,
11204 ) {
11205 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11206 self.toggle_diff_hunks_in_ranges(ranges, cx);
11207 }
11208
11209 pub fn expand_selected_diff_hunks(&mut self, cx: &mut ViewContext<Self>) {
11210 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11211 self.buffer
11212 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11213 }
11214
11215 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut ViewContext<Self>) -> bool {
11216 self.buffer.update(cx, |buffer, cx| {
11217 let ranges = vec![Anchor::min()..Anchor::max()];
11218 if !buffer.all_diff_hunks_expanded()
11219 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11220 {
11221 buffer.collapse_diff_hunks(ranges, cx);
11222 true
11223 } else {
11224 false
11225 }
11226 })
11227 }
11228
11229 fn toggle_diff_hunks_in_ranges(
11230 &mut self,
11231 ranges: Vec<Range<Anchor>>,
11232 cx: &mut ViewContext<'_, Editor>,
11233 ) {
11234 self.buffer.update(cx, |buffer, cx| {
11235 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11236 buffer.collapse_diff_hunks(ranges, cx)
11237 } else {
11238 buffer.expand_diff_hunks(ranges, cx)
11239 }
11240 })
11241 }
11242
11243 pub(crate) fn apply_all_diff_hunks(
11244 &mut self,
11245 _: &ApplyAllDiffHunks,
11246 cx: &mut ViewContext<Self>,
11247 ) {
11248 let buffers = self.buffer.read(cx).all_buffers();
11249 for branch_buffer in buffers {
11250 branch_buffer.update(cx, |branch_buffer, cx| {
11251 branch_buffer.merge_into_base(Vec::new(), cx);
11252 });
11253 }
11254
11255 if let Some(project) = self.project.clone() {
11256 self.save(true, project, cx).detach_and_log_err(cx);
11257 }
11258 }
11259
11260 pub(crate) fn apply_selected_diff_hunks(
11261 &mut self,
11262 _: &ApplyDiffHunk,
11263 cx: &mut ViewContext<Self>,
11264 ) {
11265 let snapshot = self.snapshot(cx);
11266 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11267 let mut ranges_by_buffer = HashMap::default();
11268 self.transact(cx, |editor, cx| {
11269 for hunk in hunks {
11270 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11271 ranges_by_buffer
11272 .entry(buffer.clone())
11273 .or_insert_with(Vec::new)
11274 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11275 }
11276 }
11277
11278 for (buffer, ranges) in ranges_by_buffer {
11279 buffer.update(cx, |buffer, cx| {
11280 buffer.merge_into_base(ranges, cx);
11281 });
11282 }
11283 });
11284
11285 if let Some(project) = self.project.clone() {
11286 self.save(true, project, cx).detach_and_log_err(cx);
11287 }
11288 }
11289
11290 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11291 if hovered != self.gutter_hovered {
11292 self.gutter_hovered = hovered;
11293 cx.notify();
11294 }
11295 }
11296
11297 pub fn insert_blocks(
11298 &mut self,
11299 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11300 autoscroll: Option<Autoscroll>,
11301 cx: &mut ViewContext<Self>,
11302 ) -> Vec<CustomBlockId> {
11303 let blocks = self
11304 .display_map
11305 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11306 if let Some(autoscroll) = autoscroll {
11307 self.request_autoscroll(autoscroll, cx);
11308 }
11309 cx.notify();
11310 blocks
11311 }
11312
11313 pub fn resize_blocks(
11314 &mut self,
11315 heights: HashMap<CustomBlockId, u32>,
11316 autoscroll: Option<Autoscroll>,
11317 cx: &mut ViewContext<Self>,
11318 ) {
11319 self.display_map
11320 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11321 if let Some(autoscroll) = autoscroll {
11322 self.request_autoscroll(autoscroll, cx);
11323 }
11324 cx.notify();
11325 }
11326
11327 pub fn replace_blocks(
11328 &mut self,
11329 renderers: HashMap<CustomBlockId, RenderBlock>,
11330 autoscroll: Option<Autoscroll>,
11331 cx: &mut ViewContext<Self>,
11332 ) {
11333 self.display_map
11334 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11335 if let Some(autoscroll) = autoscroll {
11336 self.request_autoscroll(autoscroll, cx);
11337 }
11338 cx.notify();
11339 }
11340
11341 pub fn remove_blocks(
11342 &mut self,
11343 block_ids: HashSet<CustomBlockId>,
11344 autoscroll: Option<Autoscroll>,
11345 cx: &mut ViewContext<Self>,
11346 ) {
11347 self.display_map.update(cx, |display_map, cx| {
11348 display_map.remove_blocks(block_ids, cx)
11349 });
11350 if let Some(autoscroll) = autoscroll {
11351 self.request_autoscroll(autoscroll, cx);
11352 }
11353 cx.notify();
11354 }
11355
11356 pub fn row_for_block(
11357 &self,
11358 block_id: CustomBlockId,
11359 cx: &mut ViewContext<Self>,
11360 ) -> Option<DisplayRow> {
11361 self.display_map
11362 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11363 }
11364
11365 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11366 self.focused_block = Some(focused_block);
11367 }
11368
11369 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11370 self.focused_block.take()
11371 }
11372
11373 pub fn insert_creases(
11374 &mut self,
11375 creases: impl IntoIterator<Item = Crease<Anchor>>,
11376 cx: &mut ViewContext<Self>,
11377 ) -> Vec<CreaseId> {
11378 self.display_map
11379 .update(cx, |map, cx| map.insert_creases(creases, cx))
11380 }
11381
11382 pub fn remove_creases(
11383 &mut self,
11384 ids: impl IntoIterator<Item = CreaseId>,
11385 cx: &mut ViewContext<Self>,
11386 ) {
11387 self.display_map
11388 .update(cx, |map, cx| map.remove_creases(ids, cx));
11389 }
11390
11391 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11392 self.display_map
11393 .update(cx, |map, cx| map.snapshot(cx))
11394 .longest_row()
11395 }
11396
11397 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11398 self.display_map
11399 .update(cx, |map, cx| map.snapshot(cx))
11400 .max_point()
11401 }
11402
11403 pub fn text(&self, cx: &AppContext) -> String {
11404 self.buffer.read(cx).read(cx).text()
11405 }
11406
11407 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11408 let text = self.text(cx);
11409 let text = text.trim();
11410
11411 if text.is_empty() {
11412 return None;
11413 }
11414
11415 Some(text.to_string())
11416 }
11417
11418 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11419 self.transact(cx, |this, cx| {
11420 this.buffer
11421 .read(cx)
11422 .as_singleton()
11423 .expect("you can only call set_text on editors for singleton buffers")
11424 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11425 });
11426 }
11427
11428 pub fn display_text(&self, cx: &mut AppContext) -> String {
11429 self.display_map
11430 .update(cx, |map, cx| map.snapshot(cx))
11431 .text()
11432 }
11433
11434 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11435 let mut wrap_guides = smallvec::smallvec![];
11436
11437 if self.show_wrap_guides == Some(false) {
11438 return wrap_guides;
11439 }
11440
11441 let settings = self.buffer.read(cx).settings_at(0, cx);
11442 if settings.show_wrap_guides {
11443 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11444 wrap_guides.push((soft_wrap as usize, true));
11445 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11446 wrap_guides.push((soft_wrap as usize, true));
11447 }
11448 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11449 }
11450
11451 wrap_guides
11452 }
11453
11454 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11455 let settings = self.buffer.read(cx).settings_at(0, cx);
11456 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11457 match mode {
11458 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11459 SoftWrap::None
11460 }
11461 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11462 language_settings::SoftWrap::PreferredLineLength => {
11463 SoftWrap::Column(settings.preferred_line_length)
11464 }
11465 language_settings::SoftWrap::Bounded => {
11466 SoftWrap::Bounded(settings.preferred_line_length)
11467 }
11468 }
11469 }
11470
11471 pub fn set_soft_wrap_mode(
11472 &mut self,
11473 mode: language_settings::SoftWrap,
11474 cx: &mut ViewContext<Self>,
11475 ) {
11476 self.soft_wrap_mode_override = Some(mode);
11477 cx.notify();
11478 }
11479
11480 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11481 self.text_style_refinement = Some(style);
11482 }
11483
11484 /// called by the Element so we know what style we were most recently rendered with.
11485 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11486 let rem_size = cx.rem_size();
11487 self.display_map.update(cx, |map, cx| {
11488 map.set_font(
11489 style.text.font(),
11490 style.text.font_size.to_pixels(rem_size),
11491 cx,
11492 )
11493 });
11494 self.style = Some(style);
11495 }
11496
11497 pub fn style(&self) -> Option<&EditorStyle> {
11498 self.style.as_ref()
11499 }
11500
11501 // Called by the element. This method is not designed to be called outside of the editor
11502 // element's layout code because it does not notify when rewrapping is computed synchronously.
11503 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11504 self.display_map
11505 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11506 }
11507
11508 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11509 if self.soft_wrap_mode_override.is_some() {
11510 self.soft_wrap_mode_override.take();
11511 } else {
11512 let soft_wrap = match self.soft_wrap_mode(cx) {
11513 SoftWrap::GitDiff => return,
11514 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11515 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11516 language_settings::SoftWrap::None
11517 }
11518 };
11519 self.soft_wrap_mode_override = Some(soft_wrap);
11520 }
11521 cx.notify();
11522 }
11523
11524 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11525 let Some(workspace) = self.workspace() else {
11526 return;
11527 };
11528 let fs = workspace.read(cx).app_state().fs.clone();
11529 let current_show = TabBarSettings::get_global(cx).show;
11530 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11531 setting.show = Some(!current_show);
11532 });
11533 }
11534
11535 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11536 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11537 self.buffer
11538 .read(cx)
11539 .settings_at(0, cx)
11540 .indent_guides
11541 .enabled
11542 });
11543 self.show_indent_guides = Some(!currently_enabled);
11544 cx.notify();
11545 }
11546
11547 fn should_show_indent_guides(&self) -> Option<bool> {
11548 self.show_indent_guides
11549 }
11550
11551 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11552 let mut editor_settings = EditorSettings::get_global(cx).clone();
11553 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11554 EditorSettings::override_global(editor_settings, cx);
11555 }
11556
11557 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11558 self.use_relative_line_numbers
11559 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11560 }
11561
11562 pub fn toggle_relative_line_numbers(
11563 &mut self,
11564 _: &ToggleRelativeLineNumbers,
11565 cx: &mut ViewContext<Self>,
11566 ) {
11567 let is_relative = self.should_use_relative_line_numbers(cx);
11568 self.set_relative_line_number(Some(!is_relative), cx)
11569 }
11570
11571 pub fn set_relative_line_number(
11572 &mut self,
11573 is_relative: Option<bool>,
11574 cx: &mut ViewContext<Self>,
11575 ) {
11576 self.use_relative_line_numbers = is_relative;
11577 cx.notify();
11578 }
11579
11580 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11581 self.show_gutter = show_gutter;
11582 cx.notify();
11583 }
11584
11585 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11586 self.show_scrollbars = show_scrollbars;
11587 cx.notify();
11588 }
11589
11590 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11591 self.show_line_numbers = Some(show_line_numbers);
11592 cx.notify();
11593 }
11594
11595 pub fn set_show_git_diff_gutter(
11596 &mut self,
11597 show_git_diff_gutter: bool,
11598 cx: &mut ViewContext<Self>,
11599 ) {
11600 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11601 cx.notify();
11602 }
11603
11604 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11605 self.show_code_actions = Some(show_code_actions);
11606 cx.notify();
11607 }
11608
11609 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11610 self.show_runnables = Some(show_runnables);
11611 cx.notify();
11612 }
11613
11614 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11615 if self.display_map.read(cx).masked != masked {
11616 self.display_map.update(cx, |map, _| map.masked = masked);
11617 }
11618 cx.notify()
11619 }
11620
11621 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11622 self.show_wrap_guides = Some(show_wrap_guides);
11623 cx.notify();
11624 }
11625
11626 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11627 self.show_indent_guides = Some(show_indent_guides);
11628 cx.notify();
11629 }
11630
11631 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11632 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11633 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11634 if let Some(dir) = file.abs_path(cx).parent() {
11635 return Some(dir.to_owned());
11636 }
11637 }
11638
11639 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11640 return Some(project_path.path.to_path_buf());
11641 }
11642 }
11643
11644 None
11645 }
11646
11647 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11648 self.active_excerpt(cx)?
11649 .1
11650 .read(cx)
11651 .file()
11652 .and_then(|f| f.as_local())
11653 }
11654
11655 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11656 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11657 let project_path = buffer.read(cx).project_path(cx)?;
11658 let project = self.project.as_ref()?.read(cx);
11659 project.absolute_path(&project_path, cx)
11660 })
11661 }
11662
11663 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11664 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11665 let project_path = buffer.read(cx).project_path(cx)?;
11666 let project = self.project.as_ref()?.read(cx);
11667 let entry = project.entry_for_path(&project_path, cx)?;
11668 let path = entry.path.to_path_buf();
11669 Some(path)
11670 })
11671 }
11672
11673 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11674 if let Some(target) = self.target_file(cx) {
11675 cx.reveal_path(&target.abs_path(cx));
11676 }
11677 }
11678
11679 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11680 if let Some(path) = self.target_file_abs_path(cx) {
11681 if let Some(path) = path.to_str() {
11682 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11683 }
11684 }
11685 }
11686
11687 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11688 if let Some(path) = self.target_file_path(cx) {
11689 if let Some(path) = path.to_str() {
11690 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11691 }
11692 }
11693 }
11694
11695 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11696 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11697
11698 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11699 self.start_git_blame(true, cx);
11700 }
11701
11702 cx.notify();
11703 }
11704
11705 pub fn toggle_git_blame_inline(
11706 &mut self,
11707 _: &ToggleGitBlameInline,
11708 cx: &mut ViewContext<Self>,
11709 ) {
11710 self.toggle_git_blame_inline_internal(true, cx);
11711 cx.notify();
11712 }
11713
11714 pub fn git_blame_inline_enabled(&self) -> bool {
11715 self.git_blame_inline_enabled
11716 }
11717
11718 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11719 self.show_selection_menu = self
11720 .show_selection_menu
11721 .map(|show_selections_menu| !show_selections_menu)
11722 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11723
11724 cx.notify();
11725 }
11726
11727 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11728 self.show_selection_menu
11729 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11730 }
11731
11732 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11733 if let Some(project) = self.project.as_ref() {
11734 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11735 return;
11736 };
11737
11738 if buffer.read(cx).file().is_none() {
11739 return;
11740 }
11741
11742 let focused = self.focus_handle(cx).contains_focused(cx);
11743
11744 let project = project.clone();
11745 let blame =
11746 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11747 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11748 self.blame = Some(blame);
11749 }
11750 }
11751
11752 fn toggle_git_blame_inline_internal(
11753 &mut self,
11754 user_triggered: bool,
11755 cx: &mut ViewContext<Self>,
11756 ) {
11757 if self.git_blame_inline_enabled {
11758 self.git_blame_inline_enabled = false;
11759 self.show_git_blame_inline = false;
11760 self.show_git_blame_inline_delay_task.take();
11761 } else {
11762 self.git_blame_inline_enabled = true;
11763 self.start_git_blame_inline(user_triggered, cx);
11764 }
11765
11766 cx.notify();
11767 }
11768
11769 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11770 self.start_git_blame(user_triggered, cx);
11771
11772 if ProjectSettings::get_global(cx)
11773 .git
11774 .inline_blame_delay()
11775 .is_some()
11776 {
11777 self.start_inline_blame_timer(cx);
11778 } else {
11779 self.show_git_blame_inline = true
11780 }
11781 }
11782
11783 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11784 self.blame.as_ref()
11785 }
11786
11787 pub fn show_git_blame_gutter(&self) -> bool {
11788 self.show_git_blame_gutter
11789 }
11790
11791 pub fn render_git_blame_gutter(&self, cx: &WindowContext) -> bool {
11792 self.show_git_blame_gutter && self.has_blame_entries(cx)
11793 }
11794
11795 pub fn render_git_blame_inline(&self, cx: &WindowContext) -> bool {
11796 self.show_git_blame_inline
11797 && self.focus_handle.is_focused(cx)
11798 && !self.newest_selection_head_on_empty_line(cx)
11799 && self.has_blame_entries(cx)
11800 }
11801
11802 fn has_blame_entries(&self, cx: &WindowContext) -> bool {
11803 self.blame()
11804 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11805 }
11806
11807 fn newest_selection_head_on_empty_line(&self, cx: &WindowContext) -> bool {
11808 let cursor_anchor = self.selections.newest_anchor().head();
11809
11810 let snapshot = self.buffer.read(cx).snapshot(cx);
11811 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11812
11813 snapshot.line_len(buffer_row) == 0
11814 }
11815
11816 fn get_permalink_to_line(&self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11817 let buffer_and_selection = maybe!({
11818 let selection = self.selections.newest::<Point>(cx);
11819 let selection_range = selection.range();
11820
11821 let multi_buffer = self.buffer().read(cx);
11822 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11823 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11824
11825 let (buffer, range, _) = if selection.reversed {
11826 buffer_ranges.first()
11827 } else {
11828 buffer_ranges.last()
11829 }?;
11830
11831 let selection = text::ToPoint::to_point(&range.start, &buffer).row
11832 ..text::ToPoint::to_point(&range.end, &buffer).row;
11833 Some((
11834 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
11835 selection,
11836 ))
11837 });
11838
11839 let Some((buffer, selection)) = buffer_and_selection else {
11840 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11841 };
11842
11843 let Some(project) = self.project.as_ref() else {
11844 return Task::ready(Err(anyhow!("editor does not have project")));
11845 };
11846
11847 project.update(cx, |project, cx| {
11848 project.get_permalink_to_line(&buffer, selection, cx)
11849 })
11850 }
11851
11852 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11853 let permalink_task = self.get_permalink_to_line(cx);
11854 let workspace = self.workspace();
11855
11856 cx.spawn(|_, mut cx| async move {
11857 match permalink_task.await {
11858 Ok(permalink) => {
11859 cx.update(|cx| {
11860 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11861 })
11862 .ok();
11863 }
11864 Err(err) => {
11865 let message = format!("Failed to copy permalink: {err}");
11866
11867 Err::<(), anyhow::Error>(err).log_err();
11868
11869 if let Some(workspace) = workspace {
11870 workspace
11871 .update(&mut cx, |workspace, cx| {
11872 struct CopyPermalinkToLine;
11873
11874 workspace.show_toast(
11875 Toast::new(
11876 NotificationId::unique::<CopyPermalinkToLine>(),
11877 message,
11878 ),
11879 cx,
11880 )
11881 })
11882 .ok();
11883 }
11884 }
11885 }
11886 })
11887 .detach();
11888 }
11889
11890 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11891 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11892 if let Some(file) = self.target_file(cx) {
11893 if let Some(path) = file.path().to_str() {
11894 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11895 }
11896 }
11897 }
11898
11899 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11900 let permalink_task = self.get_permalink_to_line(cx);
11901 let workspace = self.workspace();
11902
11903 cx.spawn(|_, mut cx| async move {
11904 match permalink_task.await {
11905 Ok(permalink) => {
11906 cx.update(|cx| {
11907 cx.open_url(permalink.as_ref());
11908 })
11909 .ok();
11910 }
11911 Err(err) => {
11912 let message = format!("Failed to open permalink: {err}");
11913
11914 Err::<(), anyhow::Error>(err).log_err();
11915
11916 if let Some(workspace) = workspace {
11917 workspace
11918 .update(&mut cx, |workspace, cx| {
11919 struct OpenPermalinkToLine;
11920
11921 workspace.show_toast(
11922 Toast::new(
11923 NotificationId::unique::<OpenPermalinkToLine>(),
11924 message,
11925 ),
11926 cx,
11927 )
11928 })
11929 .ok();
11930 }
11931 }
11932 }
11933 })
11934 .detach();
11935 }
11936
11937 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11938 self.insert_uuid(UuidVersion::V4, cx);
11939 }
11940
11941 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11942 self.insert_uuid(UuidVersion::V7, cx);
11943 }
11944
11945 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11946 self.transact(cx, |this, cx| {
11947 let edits = this
11948 .selections
11949 .all::<Point>(cx)
11950 .into_iter()
11951 .map(|selection| {
11952 let uuid = match version {
11953 UuidVersion::V4 => uuid::Uuid::new_v4(),
11954 UuidVersion::V7 => uuid::Uuid::now_v7(),
11955 };
11956
11957 (selection.range(), uuid.to_string())
11958 });
11959 this.edit(edits, cx);
11960 this.refresh_inline_completion(true, false, cx);
11961 });
11962 }
11963
11964 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11965 /// last highlight added will be used.
11966 ///
11967 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11968 pub fn highlight_rows<T: 'static>(
11969 &mut self,
11970 range: Range<Anchor>,
11971 color: Hsla,
11972 should_autoscroll: bool,
11973 cx: &mut ViewContext<Self>,
11974 ) {
11975 let snapshot = self.buffer().read(cx).snapshot(cx);
11976 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11977 let ix = row_highlights.binary_search_by(|highlight| {
11978 Ordering::Equal
11979 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11980 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11981 });
11982
11983 if let Err(mut ix) = ix {
11984 let index = post_inc(&mut self.highlight_order);
11985
11986 // If this range intersects with the preceding highlight, then merge it with
11987 // the preceding highlight. Otherwise insert a new highlight.
11988 let mut merged = false;
11989 if ix > 0 {
11990 let prev_highlight = &mut row_highlights[ix - 1];
11991 if prev_highlight
11992 .range
11993 .end
11994 .cmp(&range.start, &snapshot)
11995 .is_ge()
11996 {
11997 ix -= 1;
11998 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11999 prev_highlight.range.end = range.end;
12000 }
12001 merged = true;
12002 prev_highlight.index = index;
12003 prev_highlight.color = color;
12004 prev_highlight.should_autoscroll = should_autoscroll;
12005 }
12006 }
12007
12008 if !merged {
12009 row_highlights.insert(
12010 ix,
12011 RowHighlight {
12012 range: range.clone(),
12013 index,
12014 color,
12015 should_autoscroll,
12016 },
12017 );
12018 }
12019
12020 // If any of the following highlights intersect with this one, merge them.
12021 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12022 let highlight = &row_highlights[ix];
12023 if next_highlight
12024 .range
12025 .start
12026 .cmp(&highlight.range.end, &snapshot)
12027 .is_le()
12028 {
12029 if next_highlight
12030 .range
12031 .end
12032 .cmp(&highlight.range.end, &snapshot)
12033 .is_gt()
12034 {
12035 row_highlights[ix].range.end = next_highlight.range.end;
12036 }
12037 row_highlights.remove(ix + 1);
12038 } else {
12039 break;
12040 }
12041 }
12042 }
12043 }
12044
12045 /// Remove any highlighted row ranges of the given type that intersect the
12046 /// given ranges.
12047 pub fn remove_highlighted_rows<T: 'static>(
12048 &mut self,
12049 ranges_to_remove: Vec<Range<Anchor>>,
12050 cx: &mut ViewContext<Self>,
12051 ) {
12052 let snapshot = self.buffer().read(cx).snapshot(cx);
12053 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12054 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12055 row_highlights.retain(|highlight| {
12056 while let Some(range_to_remove) = ranges_to_remove.peek() {
12057 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12058 Ordering::Less | Ordering::Equal => {
12059 ranges_to_remove.next();
12060 }
12061 Ordering::Greater => {
12062 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12063 Ordering::Less | Ordering::Equal => {
12064 return false;
12065 }
12066 Ordering::Greater => break,
12067 }
12068 }
12069 }
12070 }
12071
12072 true
12073 })
12074 }
12075
12076 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12077 pub fn clear_row_highlights<T: 'static>(&mut self) {
12078 self.highlighted_rows.remove(&TypeId::of::<T>());
12079 }
12080
12081 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12082 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12083 self.highlighted_rows
12084 .get(&TypeId::of::<T>())
12085 .map_or(&[] as &[_], |vec| vec.as_slice())
12086 .iter()
12087 .map(|highlight| (highlight.range.clone(), highlight.color))
12088 }
12089
12090 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12091 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12092 /// Allows to ignore certain kinds of highlights.
12093 pub fn highlighted_display_rows(&self, cx: &mut WindowContext) -> BTreeMap<DisplayRow, Hsla> {
12094 let snapshot = self.snapshot(cx);
12095 let mut used_highlight_orders = HashMap::default();
12096 self.highlighted_rows
12097 .iter()
12098 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12099 .fold(
12100 BTreeMap::<DisplayRow, Hsla>::new(),
12101 |mut unique_rows, highlight| {
12102 let start = highlight.range.start.to_display_point(&snapshot);
12103 let end = highlight.range.end.to_display_point(&snapshot);
12104 let start_row = start.row().0;
12105 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12106 && end.column() == 0
12107 {
12108 end.row().0.saturating_sub(1)
12109 } else {
12110 end.row().0
12111 };
12112 for row in start_row..=end_row {
12113 let used_index =
12114 used_highlight_orders.entry(row).or_insert(highlight.index);
12115 if highlight.index >= *used_index {
12116 *used_index = highlight.index;
12117 unique_rows.insert(DisplayRow(row), highlight.color);
12118 }
12119 }
12120 unique_rows
12121 },
12122 )
12123 }
12124
12125 pub fn highlighted_display_row_for_autoscroll(
12126 &self,
12127 snapshot: &DisplaySnapshot,
12128 ) -> Option<DisplayRow> {
12129 self.highlighted_rows
12130 .values()
12131 .flat_map(|highlighted_rows| highlighted_rows.iter())
12132 .filter_map(|highlight| {
12133 if highlight.should_autoscroll {
12134 Some(highlight.range.start.to_display_point(snapshot).row())
12135 } else {
12136 None
12137 }
12138 })
12139 .min()
12140 }
12141
12142 pub fn set_search_within_ranges(
12143 &mut self,
12144 ranges: &[Range<Anchor>],
12145 cx: &mut ViewContext<Self>,
12146 ) {
12147 self.highlight_background::<SearchWithinRange>(
12148 ranges,
12149 |colors| colors.editor_document_highlight_read_background,
12150 cx,
12151 )
12152 }
12153
12154 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12155 self.breadcrumb_header = Some(new_header);
12156 }
12157
12158 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12159 self.clear_background_highlights::<SearchWithinRange>(cx);
12160 }
12161
12162 pub fn highlight_background<T: 'static>(
12163 &mut self,
12164 ranges: &[Range<Anchor>],
12165 color_fetcher: fn(&ThemeColors) -> Hsla,
12166 cx: &mut ViewContext<Self>,
12167 ) {
12168 self.background_highlights
12169 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12170 self.scrollbar_marker_state.dirty = true;
12171 cx.notify();
12172 }
12173
12174 pub fn clear_background_highlights<T: 'static>(
12175 &mut self,
12176 cx: &mut ViewContext<Self>,
12177 ) -> Option<BackgroundHighlight> {
12178 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12179 if !text_highlights.1.is_empty() {
12180 self.scrollbar_marker_state.dirty = true;
12181 cx.notify();
12182 }
12183 Some(text_highlights)
12184 }
12185
12186 pub fn highlight_gutter<T: 'static>(
12187 &mut self,
12188 ranges: &[Range<Anchor>],
12189 color_fetcher: fn(&AppContext) -> Hsla,
12190 cx: &mut ViewContext<Self>,
12191 ) {
12192 self.gutter_highlights
12193 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12194 cx.notify();
12195 }
12196
12197 pub fn clear_gutter_highlights<T: 'static>(
12198 &mut self,
12199 cx: &mut ViewContext<Self>,
12200 ) -> Option<GutterHighlight> {
12201 cx.notify();
12202 self.gutter_highlights.remove(&TypeId::of::<T>())
12203 }
12204
12205 #[cfg(feature = "test-support")]
12206 pub fn all_text_background_highlights(
12207 &self,
12208 cx: &mut ViewContext<Self>,
12209 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12210 let snapshot = self.snapshot(cx);
12211 let buffer = &snapshot.buffer_snapshot;
12212 let start = buffer.anchor_before(0);
12213 let end = buffer.anchor_after(buffer.len());
12214 let theme = cx.theme().colors();
12215 self.background_highlights_in_range(start..end, &snapshot, theme)
12216 }
12217
12218 #[cfg(feature = "test-support")]
12219 pub fn search_background_highlights(
12220 &mut self,
12221 cx: &mut ViewContext<Self>,
12222 ) -> Vec<Range<Point>> {
12223 let snapshot = self.buffer().read(cx).snapshot(cx);
12224
12225 let highlights = self
12226 .background_highlights
12227 .get(&TypeId::of::<items::BufferSearchHighlights>());
12228
12229 if let Some((_color, ranges)) = highlights {
12230 ranges
12231 .iter()
12232 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12233 .collect_vec()
12234 } else {
12235 vec![]
12236 }
12237 }
12238
12239 fn document_highlights_for_position<'a>(
12240 &'a self,
12241 position: Anchor,
12242 buffer: &'a MultiBufferSnapshot,
12243 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12244 let read_highlights = self
12245 .background_highlights
12246 .get(&TypeId::of::<DocumentHighlightRead>())
12247 .map(|h| &h.1);
12248 let write_highlights = self
12249 .background_highlights
12250 .get(&TypeId::of::<DocumentHighlightWrite>())
12251 .map(|h| &h.1);
12252 let left_position = position.bias_left(buffer);
12253 let right_position = position.bias_right(buffer);
12254 read_highlights
12255 .into_iter()
12256 .chain(write_highlights)
12257 .flat_map(move |ranges| {
12258 let start_ix = match ranges.binary_search_by(|probe| {
12259 let cmp = probe.end.cmp(&left_position, buffer);
12260 if cmp.is_ge() {
12261 Ordering::Greater
12262 } else {
12263 Ordering::Less
12264 }
12265 }) {
12266 Ok(i) | Err(i) => i,
12267 };
12268
12269 ranges[start_ix..]
12270 .iter()
12271 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12272 })
12273 }
12274
12275 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12276 self.background_highlights
12277 .get(&TypeId::of::<T>())
12278 .map_or(false, |(_, highlights)| !highlights.is_empty())
12279 }
12280
12281 pub fn background_highlights_in_range(
12282 &self,
12283 search_range: Range<Anchor>,
12284 display_snapshot: &DisplaySnapshot,
12285 theme: &ThemeColors,
12286 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12287 let mut results = Vec::new();
12288 for (color_fetcher, ranges) in self.background_highlights.values() {
12289 let color = color_fetcher(theme);
12290 let start_ix = match ranges.binary_search_by(|probe| {
12291 let cmp = probe
12292 .end
12293 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12294 if cmp.is_gt() {
12295 Ordering::Greater
12296 } else {
12297 Ordering::Less
12298 }
12299 }) {
12300 Ok(i) | Err(i) => i,
12301 };
12302 for range in &ranges[start_ix..] {
12303 if range
12304 .start
12305 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12306 .is_ge()
12307 {
12308 break;
12309 }
12310
12311 let start = range.start.to_display_point(display_snapshot);
12312 let end = range.end.to_display_point(display_snapshot);
12313 results.push((start..end, color))
12314 }
12315 }
12316 results
12317 }
12318
12319 pub fn background_highlight_row_ranges<T: 'static>(
12320 &self,
12321 search_range: Range<Anchor>,
12322 display_snapshot: &DisplaySnapshot,
12323 count: usize,
12324 ) -> Vec<RangeInclusive<DisplayPoint>> {
12325 let mut results = Vec::new();
12326 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12327 return vec![];
12328 };
12329
12330 let start_ix = match ranges.binary_search_by(|probe| {
12331 let cmp = probe
12332 .end
12333 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12334 if cmp.is_gt() {
12335 Ordering::Greater
12336 } else {
12337 Ordering::Less
12338 }
12339 }) {
12340 Ok(i) | Err(i) => i,
12341 };
12342 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12343 if let (Some(start_display), Some(end_display)) = (start, end) {
12344 results.push(
12345 start_display.to_display_point(display_snapshot)
12346 ..=end_display.to_display_point(display_snapshot),
12347 );
12348 }
12349 };
12350 let mut start_row: Option<Point> = None;
12351 let mut end_row: Option<Point> = None;
12352 if ranges.len() > count {
12353 return Vec::new();
12354 }
12355 for range in &ranges[start_ix..] {
12356 if range
12357 .start
12358 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12359 .is_ge()
12360 {
12361 break;
12362 }
12363 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12364 if let Some(current_row) = &end_row {
12365 if end.row == current_row.row {
12366 continue;
12367 }
12368 }
12369 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12370 if start_row.is_none() {
12371 assert_eq!(end_row, None);
12372 start_row = Some(start);
12373 end_row = Some(end);
12374 continue;
12375 }
12376 if let Some(current_end) = end_row.as_mut() {
12377 if start.row > current_end.row + 1 {
12378 push_region(start_row, end_row);
12379 start_row = Some(start);
12380 end_row = Some(end);
12381 } else {
12382 // Merge two hunks.
12383 *current_end = end;
12384 }
12385 } else {
12386 unreachable!();
12387 }
12388 }
12389 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12390 push_region(start_row, end_row);
12391 results
12392 }
12393
12394 pub fn gutter_highlights_in_range(
12395 &self,
12396 search_range: Range<Anchor>,
12397 display_snapshot: &DisplaySnapshot,
12398 cx: &AppContext,
12399 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12400 let mut results = Vec::new();
12401 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12402 let color = color_fetcher(cx);
12403 let start_ix = match ranges.binary_search_by(|probe| {
12404 let cmp = probe
12405 .end
12406 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12407 if cmp.is_gt() {
12408 Ordering::Greater
12409 } else {
12410 Ordering::Less
12411 }
12412 }) {
12413 Ok(i) | Err(i) => i,
12414 };
12415 for range in &ranges[start_ix..] {
12416 if range
12417 .start
12418 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12419 .is_ge()
12420 {
12421 break;
12422 }
12423
12424 let start = range.start.to_display_point(display_snapshot);
12425 let end = range.end.to_display_point(display_snapshot);
12426 results.push((start..end, color))
12427 }
12428 }
12429 results
12430 }
12431
12432 /// Get the text ranges corresponding to the redaction query
12433 pub fn redacted_ranges(
12434 &self,
12435 search_range: Range<Anchor>,
12436 display_snapshot: &DisplaySnapshot,
12437 cx: &WindowContext,
12438 ) -> Vec<Range<DisplayPoint>> {
12439 display_snapshot
12440 .buffer_snapshot
12441 .redacted_ranges(search_range, |file| {
12442 if let Some(file) = file {
12443 file.is_private()
12444 && EditorSettings::get(
12445 Some(SettingsLocation {
12446 worktree_id: file.worktree_id(cx),
12447 path: file.path().as_ref(),
12448 }),
12449 cx,
12450 )
12451 .redact_private_values
12452 } else {
12453 false
12454 }
12455 })
12456 .map(|range| {
12457 range.start.to_display_point(display_snapshot)
12458 ..range.end.to_display_point(display_snapshot)
12459 })
12460 .collect()
12461 }
12462
12463 pub fn highlight_text<T: 'static>(
12464 &mut self,
12465 ranges: Vec<Range<Anchor>>,
12466 style: HighlightStyle,
12467 cx: &mut ViewContext<Self>,
12468 ) {
12469 self.display_map.update(cx, |map, _| {
12470 map.highlight_text(TypeId::of::<T>(), ranges, style)
12471 });
12472 cx.notify();
12473 }
12474
12475 pub(crate) fn highlight_inlays<T: 'static>(
12476 &mut self,
12477 highlights: Vec<InlayHighlight>,
12478 style: HighlightStyle,
12479 cx: &mut ViewContext<Self>,
12480 ) {
12481 self.display_map.update(cx, |map, _| {
12482 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12483 });
12484 cx.notify();
12485 }
12486
12487 pub fn text_highlights<'a, T: 'static>(
12488 &'a self,
12489 cx: &'a AppContext,
12490 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12491 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12492 }
12493
12494 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12495 let cleared = self
12496 .display_map
12497 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12498 if cleared {
12499 cx.notify();
12500 }
12501 }
12502
12503 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12504 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12505 && self.focus_handle.is_focused(cx)
12506 }
12507
12508 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12509 self.show_cursor_when_unfocused = is_enabled;
12510 cx.notify();
12511 }
12512
12513 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12514 self.project
12515 .as_ref()
12516 .map(|project| project.read(cx).lsp_store())
12517 }
12518
12519 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12520 cx.notify();
12521 }
12522
12523 fn on_buffer_event(
12524 &mut self,
12525 multibuffer: Model<MultiBuffer>,
12526 event: &multi_buffer::Event,
12527 cx: &mut ViewContext<Self>,
12528 ) {
12529 match event {
12530 multi_buffer::Event::Edited {
12531 singleton_buffer_edited,
12532 edited_buffer: buffer_edited,
12533 } => {
12534 self.scrollbar_marker_state.dirty = true;
12535 self.active_indent_guides_state.dirty = true;
12536 self.refresh_active_diagnostics(cx);
12537 self.refresh_code_actions(cx);
12538 if self.has_active_inline_completion() {
12539 self.update_visible_inline_completion(cx);
12540 }
12541 if let Some(buffer) = buffer_edited {
12542 let buffer_id = buffer.read(cx).remote_id();
12543 if !self.registered_buffers.contains_key(&buffer_id) {
12544 if let Some(lsp_store) = self.lsp_store(cx) {
12545 lsp_store.update(cx, |lsp_store, cx| {
12546 self.registered_buffers.insert(
12547 buffer_id,
12548 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12549 );
12550 })
12551 }
12552 }
12553 }
12554 cx.emit(EditorEvent::BufferEdited);
12555 cx.emit(SearchEvent::MatchesInvalidated);
12556 if *singleton_buffer_edited {
12557 if let Some(project) = &self.project {
12558 let project = project.read(cx);
12559 #[allow(clippy::mutable_key_type)]
12560 let languages_affected = multibuffer
12561 .read(cx)
12562 .all_buffers()
12563 .into_iter()
12564 .filter_map(|buffer| {
12565 let buffer = buffer.read(cx);
12566 let language = buffer.language()?;
12567 if project.is_local()
12568 && project
12569 .language_servers_for_local_buffer(buffer, cx)
12570 .count()
12571 == 0
12572 {
12573 None
12574 } else {
12575 Some(language)
12576 }
12577 })
12578 .cloned()
12579 .collect::<HashSet<_>>();
12580 if !languages_affected.is_empty() {
12581 self.refresh_inlay_hints(
12582 InlayHintRefreshReason::BufferEdited(languages_affected),
12583 cx,
12584 );
12585 }
12586 }
12587 }
12588
12589 let Some(project) = &self.project else { return };
12590 let (telemetry, is_via_ssh) = {
12591 let project = project.read(cx);
12592 let telemetry = project.client().telemetry().clone();
12593 let is_via_ssh = project.is_via_ssh();
12594 (telemetry, is_via_ssh)
12595 };
12596 refresh_linked_ranges(self, cx);
12597 telemetry.log_edit_event("editor", is_via_ssh);
12598 }
12599 multi_buffer::Event::ExcerptsAdded {
12600 buffer,
12601 predecessor,
12602 excerpts,
12603 } => {
12604 self.tasks_update_task = Some(self.refresh_runnables(cx));
12605 let buffer_id = buffer.read(cx).remote_id();
12606 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
12607 if let Some(project) = &self.project {
12608 get_unstaged_changes_for_buffers(
12609 project,
12610 [buffer.clone()],
12611 self.buffer.clone(),
12612 cx,
12613 );
12614 }
12615 }
12616 cx.emit(EditorEvent::ExcerptsAdded {
12617 buffer: buffer.clone(),
12618 predecessor: *predecessor,
12619 excerpts: excerpts.clone(),
12620 });
12621 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12622 }
12623 multi_buffer::Event::ExcerptsRemoved { ids } => {
12624 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12625 let buffer = self.buffer.read(cx);
12626 self.registered_buffers
12627 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12628 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12629 }
12630 multi_buffer::Event::ExcerptsEdited { ids } => {
12631 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12632 }
12633 multi_buffer::Event::ExcerptsExpanded { ids } => {
12634 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12635 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12636 }
12637 multi_buffer::Event::Reparsed(buffer_id) => {
12638 self.tasks_update_task = Some(self.refresh_runnables(cx));
12639
12640 cx.emit(EditorEvent::Reparsed(*buffer_id));
12641 }
12642 multi_buffer::Event::LanguageChanged(buffer_id) => {
12643 linked_editing_ranges::refresh_linked_ranges(self, cx);
12644 cx.emit(EditorEvent::Reparsed(*buffer_id));
12645 cx.notify();
12646 }
12647 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12648 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12649 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12650 cx.emit(EditorEvent::TitleChanged)
12651 }
12652 // multi_buffer::Event::DiffBaseChanged => {
12653 // self.scrollbar_marker_state.dirty = true;
12654 // cx.emit(EditorEvent::DiffBaseChanged);
12655 // cx.notify();
12656 // }
12657 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12658 multi_buffer::Event::DiagnosticsUpdated => {
12659 self.refresh_active_diagnostics(cx);
12660 self.scrollbar_marker_state.dirty = true;
12661 cx.notify();
12662 }
12663 _ => {}
12664 };
12665 }
12666
12667 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12668 cx.notify();
12669 }
12670
12671 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12672 self.tasks_update_task = Some(self.refresh_runnables(cx));
12673 self.refresh_inline_completion(true, false, cx);
12674 self.refresh_inlay_hints(
12675 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12676 self.selections.newest_anchor().head(),
12677 &self.buffer.read(cx).snapshot(cx),
12678 cx,
12679 )),
12680 cx,
12681 );
12682
12683 let old_cursor_shape = self.cursor_shape;
12684
12685 {
12686 let editor_settings = EditorSettings::get_global(cx);
12687 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12688 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12689 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12690 }
12691
12692 if old_cursor_shape != self.cursor_shape {
12693 cx.emit(EditorEvent::CursorShapeChanged);
12694 }
12695
12696 let project_settings = ProjectSettings::get_global(cx);
12697 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12698
12699 if self.mode == EditorMode::Full {
12700 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12701 if self.git_blame_inline_enabled != inline_blame_enabled {
12702 self.toggle_git_blame_inline_internal(false, cx);
12703 }
12704 }
12705
12706 cx.notify();
12707 }
12708
12709 pub fn set_searchable(&mut self, searchable: bool) {
12710 self.searchable = searchable;
12711 }
12712
12713 pub fn searchable(&self) -> bool {
12714 self.searchable
12715 }
12716
12717 fn open_proposed_changes_editor(
12718 &mut self,
12719 _: &OpenProposedChangesEditor,
12720 cx: &mut ViewContext<Self>,
12721 ) {
12722 let Some(workspace) = self.workspace() else {
12723 cx.propagate();
12724 return;
12725 };
12726
12727 let selections = self.selections.all::<usize>(cx);
12728 let multi_buffer = self.buffer.read(cx);
12729 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12730 let mut new_selections_by_buffer = HashMap::default();
12731 for selection in selections {
12732 for (buffer, range, _) in
12733 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12734 {
12735 let mut range = range.to_point(buffer);
12736 range.start.column = 0;
12737 range.end.column = buffer.line_len(range.end.row);
12738 new_selections_by_buffer
12739 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
12740 .or_insert(Vec::new())
12741 .push(range)
12742 }
12743 }
12744
12745 let proposed_changes_buffers = new_selections_by_buffer
12746 .into_iter()
12747 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12748 .collect::<Vec<_>>();
12749 let proposed_changes_editor = cx.new_view(|cx| {
12750 ProposedChangesEditor::new(
12751 "Proposed changes",
12752 proposed_changes_buffers,
12753 self.project.clone(),
12754 cx,
12755 )
12756 });
12757
12758 cx.window_context().defer(move |cx| {
12759 workspace.update(cx, |workspace, cx| {
12760 workspace.active_pane().update(cx, |pane, cx| {
12761 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12762 });
12763 });
12764 });
12765 }
12766
12767 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12768 self.open_excerpts_common(None, true, cx)
12769 }
12770
12771 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12772 self.open_excerpts_common(None, false, cx)
12773 }
12774
12775 fn open_excerpts_common(
12776 &mut self,
12777 jump_data: Option<JumpData>,
12778 split: bool,
12779 cx: &mut ViewContext<Self>,
12780 ) {
12781 let Some(workspace) = self.workspace() else {
12782 cx.propagate();
12783 return;
12784 };
12785
12786 if self.buffer.read(cx).is_singleton() {
12787 cx.propagate();
12788 return;
12789 }
12790
12791 let mut new_selections_by_buffer = HashMap::default();
12792 match &jump_data {
12793 Some(JumpData::MultiBufferPoint {
12794 excerpt_id,
12795 position,
12796 anchor,
12797 line_offset_from_top,
12798 }) => {
12799 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12800 if let Some(buffer) = multi_buffer_snapshot
12801 .buffer_id_for_excerpt(*excerpt_id)
12802 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12803 {
12804 let buffer_snapshot = buffer.read(cx).snapshot();
12805 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12806 language::ToPoint::to_point(anchor, &buffer_snapshot)
12807 } else {
12808 buffer_snapshot.clip_point(*position, Bias::Left)
12809 };
12810 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12811 new_selections_by_buffer.insert(
12812 buffer,
12813 (
12814 vec![jump_to_offset..jump_to_offset],
12815 Some(*line_offset_from_top),
12816 ),
12817 );
12818 }
12819 }
12820 Some(JumpData::MultiBufferRow {
12821 row,
12822 line_offset_from_top,
12823 }) => {
12824 let point = MultiBufferPoint::new(row.0, 0);
12825 if let Some((buffer, buffer_point, _)) =
12826 self.buffer.read(cx).point_to_buffer_point(point, cx)
12827 {
12828 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12829 new_selections_by_buffer
12830 .entry(buffer)
12831 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12832 .0
12833 .push(buffer_offset..buffer_offset)
12834 }
12835 }
12836 None => {
12837 let selections = self.selections.all::<usize>(cx);
12838 let multi_buffer = self.buffer.read(cx);
12839 for selection in selections {
12840 for (buffer, mut range, _) in multi_buffer
12841 .snapshot(cx)
12842 .range_to_buffer_ranges(selection.range())
12843 {
12844 // When editing branch buffers, jump to the corresponding location
12845 // in their base buffer.
12846 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
12847 let buffer = buffer_handle.read(cx);
12848 if let Some(base_buffer) = buffer.base_buffer() {
12849 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12850 buffer_handle = base_buffer;
12851 }
12852
12853 if selection.reversed {
12854 mem::swap(&mut range.start, &mut range.end);
12855 }
12856 new_selections_by_buffer
12857 .entry(buffer_handle)
12858 .or_insert((Vec::new(), None))
12859 .0
12860 .push(range)
12861 }
12862 }
12863 }
12864 }
12865
12866 if new_selections_by_buffer.is_empty() {
12867 return;
12868 }
12869
12870 // We defer the pane interaction because we ourselves are a workspace item
12871 // and activating a new item causes the pane to call a method on us reentrantly,
12872 // which panics if we're on the stack.
12873 cx.window_context().defer(move |cx| {
12874 workspace.update(cx, |workspace, cx| {
12875 let pane = if split {
12876 workspace.adjacent_pane(cx)
12877 } else {
12878 workspace.active_pane().clone()
12879 };
12880
12881 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12882 let editor = buffer
12883 .read(cx)
12884 .file()
12885 .is_none()
12886 .then(|| {
12887 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12888 // so `workspace.open_project_item` will never find them, always opening a new editor.
12889 // Instead, we try to activate the existing editor in the pane first.
12890 let (editor, pane_item_index) =
12891 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12892 let editor = item.downcast::<Editor>()?;
12893 let singleton_buffer =
12894 editor.read(cx).buffer().read(cx).as_singleton()?;
12895 if singleton_buffer == buffer {
12896 Some((editor, i))
12897 } else {
12898 None
12899 }
12900 })?;
12901 pane.update(cx, |pane, cx| {
12902 pane.activate_item(pane_item_index, true, true, cx)
12903 });
12904 Some(editor)
12905 })
12906 .flatten()
12907 .unwrap_or_else(|| {
12908 workspace.open_project_item::<Self>(
12909 pane.clone(),
12910 buffer,
12911 true,
12912 true,
12913 cx,
12914 )
12915 });
12916
12917 editor.update(cx, |editor, cx| {
12918 let autoscroll = match scroll_offset {
12919 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12920 None => Autoscroll::newest(),
12921 };
12922 let nav_history = editor.nav_history.take();
12923 editor.change_selections(Some(autoscroll), cx, |s| {
12924 s.select_ranges(ranges);
12925 });
12926 editor.nav_history = nav_history;
12927 });
12928 }
12929 })
12930 });
12931 }
12932
12933 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12934 let snapshot = self.buffer.read(cx).read(cx);
12935 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12936 Some(
12937 ranges
12938 .iter()
12939 .map(move |range| {
12940 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12941 })
12942 .collect(),
12943 )
12944 }
12945
12946 fn selection_replacement_ranges(
12947 &self,
12948 range: Range<OffsetUtf16>,
12949 cx: &mut AppContext,
12950 ) -> Vec<Range<OffsetUtf16>> {
12951 let selections = self.selections.all::<OffsetUtf16>(cx);
12952 let newest_selection = selections
12953 .iter()
12954 .max_by_key(|selection| selection.id)
12955 .unwrap();
12956 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12957 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12958 let snapshot = self.buffer.read(cx).read(cx);
12959 selections
12960 .into_iter()
12961 .map(|mut selection| {
12962 selection.start.0 =
12963 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12964 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12965 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12966 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12967 })
12968 .collect()
12969 }
12970
12971 fn report_editor_event(
12972 &self,
12973 event_type: &'static str,
12974 file_extension: Option<String>,
12975 cx: &AppContext,
12976 ) {
12977 if cfg!(any(test, feature = "test-support")) {
12978 return;
12979 }
12980
12981 let Some(project) = &self.project else { return };
12982
12983 // If None, we are in a file without an extension
12984 let file = self
12985 .buffer
12986 .read(cx)
12987 .as_singleton()
12988 .and_then(|b| b.read(cx).file());
12989 let file_extension = file_extension.or(file
12990 .as_ref()
12991 .and_then(|file| Path::new(file.file_name(cx)).extension())
12992 .and_then(|e| e.to_str())
12993 .map(|a| a.to_string()));
12994
12995 let vim_mode = cx
12996 .global::<SettingsStore>()
12997 .raw_user_settings()
12998 .get("vim_mode")
12999 == Some(&serde_json::Value::Bool(true));
13000
13001 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13002 == language::language_settings::InlineCompletionProvider::Copilot;
13003 let copilot_enabled_for_language = self
13004 .buffer
13005 .read(cx)
13006 .settings_at(0, cx)
13007 .show_inline_completions;
13008
13009 let project = project.read(cx);
13010 telemetry::event!(
13011 event_type,
13012 file_extension,
13013 vim_mode,
13014 copilot_enabled,
13015 copilot_enabled_for_language,
13016 is_via_ssh = project.is_via_ssh(),
13017 );
13018 }
13019
13020 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13021 /// with each line being an array of {text, highlight} objects.
13022 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13023 #[derive(Serialize)]
13024 struct Chunk<'a> {
13025 text: String,
13026 highlight: Option<&'a str>,
13027 }
13028
13029 let snapshot = self.buffer.read(cx).snapshot(cx);
13030 let range = self
13031 .selected_text_range(false, cx)
13032 .and_then(|selection| {
13033 if selection.range.is_empty() {
13034 None
13035 } else {
13036 Some(selection.range)
13037 }
13038 })
13039 .unwrap_or_else(|| 0..snapshot.len());
13040
13041 let chunks = snapshot.chunks(range, true);
13042 let mut lines = Vec::new();
13043 let mut line: VecDeque<Chunk> = VecDeque::new();
13044
13045 let Some(style) = self.style.as_ref() else {
13046 return;
13047 };
13048
13049 for chunk in chunks {
13050 let highlight = chunk
13051 .syntax_highlight_id
13052 .and_then(|id| id.name(&style.syntax));
13053 let mut chunk_lines = chunk.text.split('\n').peekable();
13054 while let Some(text) = chunk_lines.next() {
13055 let mut merged_with_last_token = false;
13056 if let Some(last_token) = line.back_mut() {
13057 if last_token.highlight == highlight {
13058 last_token.text.push_str(text);
13059 merged_with_last_token = true;
13060 }
13061 }
13062
13063 if !merged_with_last_token {
13064 line.push_back(Chunk {
13065 text: text.into(),
13066 highlight,
13067 });
13068 }
13069
13070 if chunk_lines.peek().is_some() {
13071 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13072 line.pop_front();
13073 }
13074 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13075 line.pop_back();
13076 }
13077
13078 lines.push(mem::take(&mut line));
13079 }
13080 }
13081 }
13082
13083 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13084 return;
13085 };
13086 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13087 }
13088
13089 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13090 self.request_autoscroll(Autoscroll::newest(), cx);
13091 let position = self.selections.newest_display(cx).start;
13092 mouse_context_menu::deploy_context_menu(self, None, position, cx);
13093 }
13094
13095 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13096 &self.inlay_hint_cache
13097 }
13098
13099 pub fn replay_insert_event(
13100 &mut self,
13101 text: &str,
13102 relative_utf16_range: Option<Range<isize>>,
13103 cx: &mut ViewContext<Self>,
13104 ) {
13105 if !self.input_enabled {
13106 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13107 return;
13108 }
13109 if let Some(relative_utf16_range) = relative_utf16_range {
13110 let selections = self.selections.all::<OffsetUtf16>(cx);
13111 self.change_selections(None, cx, |s| {
13112 let new_ranges = selections.into_iter().map(|range| {
13113 let start = OffsetUtf16(
13114 range
13115 .head()
13116 .0
13117 .saturating_add_signed(relative_utf16_range.start),
13118 );
13119 let end = OffsetUtf16(
13120 range
13121 .head()
13122 .0
13123 .saturating_add_signed(relative_utf16_range.end),
13124 );
13125 start..end
13126 });
13127 s.select_ranges(new_ranges);
13128 });
13129 }
13130
13131 self.handle_input(text, cx);
13132 }
13133
13134 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13135 let Some(provider) = self.semantics_provider.as_ref() else {
13136 return false;
13137 };
13138
13139 let mut supports = false;
13140 self.buffer().read(cx).for_each_buffer(|buffer| {
13141 supports |= provider.supports_inlay_hints(buffer, cx);
13142 });
13143 supports
13144 }
13145
13146 pub fn focus(&self, cx: &mut WindowContext) {
13147 cx.focus(&self.focus_handle)
13148 }
13149
13150 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13151 self.focus_handle.is_focused(cx)
13152 }
13153
13154 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13155 cx.emit(EditorEvent::Focused);
13156
13157 if let Some(descendant) = self
13158 .last_focused_descendant
13159 .take()
13160 .and_then(|descendant| descendant.upgrade())
13161 {
13162 cx.focus(&descendant);
13163 } else {
13164 if let Some(blame) = self.blame.as_ref() {
13165 blame.update(cx, GitBlame::focus)
13166 }
13167
13168 self.blink_manager.update(cx, BlinkManager::enable);
13169 self.show_cursor_names(cx);
13170 self.buffer.update(cx, |buffer, cx| {
13171 buffer.finalize_last_transaction(cx);
13172 if self.leader_peer_id.is_none() {
13173 buffer.set_active_selections(
13174 &self.selections.disjoint_anchors(),
13175 self.selections.line_mode,
13176 self.cursor_shape,
13177 cx,
13178 );
13179 }
13180 });
13181 }
13182 }
13183
13184 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13185 cx.emit(EditorEvent::FocusedIn)
13186 }
13187
13188 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13189 if event.blurred != self.focus_handle {
13190 self.last_focused_descendant = Some(event.blurred);
13191 }
13192 }
13193
13194 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13195 self.blink_manager.update(cx, BlinkManager::disable);
13196 self.buffer
13197 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13198
13199 if let Some(blame) = self.blame.as_ref() {
13200 blame.update(cx, GitBlame::blur)
13201 }
13202 if !self.hover_state.focused(cx) {
13203 hide_hover(self, cx);
13204 }
13205
13206 self.hide_context_menu(cx);
13207 cx.emit(EditorEvent::Blurred);
13208 cx.notify();
13209 }
13210
13211 pub fn register_action<A: Action>(
13212 &mut self,
13213 listener: impl Fn(&A, &mut WindowContext) + 'static,
13214 ) -> Subscription {
13215 let id = self.next_editor_action_id.post_inc();
13216 let listener = Arc::new(listener);
13217 self.editor_actions.borrow_mut().insert(
13218 id,
13219 Box::new(move |cx| {
13220 let cx = cx.window_context();
13221 let listener = listener.clone();
13222 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13223 let action = action.downcast_ref().unwrap();
13224 if phase == DispatchPhase::Bubble {
13225 listener(action, cx)
13226 }
13227 })
13228 }),
13229 );
13230
13231 let editor_actions = self.editor_actions.clone();
13232 Subscription::new(move || {
13233 editor_actions.borrow_mut().remove(&id);
13234 })
13235 }
13236
13237 pub fn file_header_size(&self) -> u32 {
13238 FILE_HEADER_HEIGHT
13239 }
13240
13241 pub fn revert(
13242 &mut self,
13243 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13244 cx: &mut ViewContext<Self>,
13245 ) {
13246 self.buffer().update(cx, |multi_buffer, cx| {
13247 for (buffer_id, changes) in revert_changes {
13248 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13249 buffer.update(cx, |buffer, cx| {
13250 buffer.edit(
13251 changes.into_iter().map(|(range, text)| {
13252 (range, text.to_string().map(Arc::<str>::from))
13253 }),
13254 None,
13255 cx,
13256 );
13257 });
13258 }
13259 }
13260 });
13261 self.change_selections(None, cx, |selections| selections.refresh());
13262 }
13263
13264 pub fn to_pixel_point(
13265 &self,
13266 source: multi_buffer::Anchor,
13267 editor_snapshot: &EditorSnapshot,
13268 cx: &mut ViewContext<Self>,
13269 ) -> Option<gpui::Point<Pixels>> {
13270 let source_point = source.to_display_point(editor_snapshot);
13271 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13272 }
13273
13274 pub fn display_to_pixel_point(
13275 &self,
13276 source: DisplayPoint,
13277 editor_snapshot: &EditorSnapshot,
13278 cx: &WindowContext,
13279 ) -> Option<gpui::Point<Pixels>> {
13280 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13281 let text_layout_details = self.text_layout_details(cx);
13282 let scroll_top = text_layout_details
13283 .scroll_anchor
13284 .scroll_position(editor_snapshot)
13285 .y;
13286
13287 if source.row().as_f32() < scroll_top.floor() {
13288 return None;
13289 }
13290 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13291 let source_y = line_height * (source.row().as_f32() - scroll_top);
13292 Some(gpui::Point::new(source_x, source_y))
13293 }
13294
13295 pub fn has_active_completions_menu(&self) -> bool {
13296 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13297 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13298 })
13299 }
13300
13301 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13302 self.addons
13303 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13304 }
13305
13306 pub fn unregister_addon<T: Addon>(&mut self) {
13307 self.addons.remove(&std::any::TypeId::of::<T>());
13308 }
13309
13310 pub fn addon<T: Addon>(&self) -> Option<&T> {
13311 let type_id = std::any::TypeId::of::<T>();
13312 self.addons
13313 .get(&type_id)
13314 .and_then(|item| item.to_any().downcast_ref::<T>())
13315 }
13316
13317 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13318 let text_layout_details = self.text_layout_details(cx);
13319 let style = &text_layout_details.editor_style;
13320 let font_id = cx.text_system().resolve_font(&style.text.font());
13321 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13322 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13323
13324 let em_width = cx
13325 .text_system()
13326 .typographic_bounds(font_id, font_size, 'm')
13327 .unwrap()
13328 .size
13329 .width;
13330
13331 gpui::Point::new(em_width, line_height)
13332 }
13333}
13334
13335fn get_unstaged_changes_for_buffers(
13336 project: &Model<Project>,
13337 buffers: impl IntoIterator<Item = Model<Buffer>>,
13338 buffer: Model<MultiBuffer>,
13339 cx: &mut AppContext,
13340) {
13341 let mut tasks = Vec::new();
13342 project.update(cx, |project, cx| {
13343 for buffer in buffers {
13344 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13345 }
13346 });
13347 cx.spawn(|mut cx| async move {
13348 let change_sets = futures::future::join_all(tasks).await;
13349 buffer
13350 .update(&mut cx, |buffer, cx| {
13351 for change_set in change_sets {
13352 if let Some(change_set) = change_set.log_err() {
13353 buffer.add_change_set(change_set, cx);
13354 }
13355 }
13356 })
13357 .ok();
13358 })
13359 .detach();
13360}
13361
13362fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13363 let tab_size = tab_size.get() as usize;
13364 let mut width = offset;
13365
13366 for ch in text.chars() {
13367 width += if ch == '\t' {
13368 tab_size - (width % tab_size)
13369 } else {
13370 1
13371 };
13372 }
13373
13374 width - offset
13375}
13376
13377#[cfg(test)]
13378mod tests {
13379 use super::*;
13380
13381 #[test]
13382 fn test_string_size_with_expanded_tabs() {
13383 let nz = |val| NonZeroU32::new(val).unwrap();
13384 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13385 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13386 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13387 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13388 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13389 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13390 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13391 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13392 }
13393}
13394
13395/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13396struct WordBreakingTokenizer<'a> {
13397 input: &'a str,
13398}
13399
13400impl<'a> WordBreakingTokenizer<'a> {
13401 fn new(input: &'a str) -> Self {
13402 Self { input }
13403 }
13404}
13405
13406fn is_char_ideographic(ch: char) -> bool {
13407 use unicode_script::Script::*;
13408 use unicode_script::UnicodeScript;
13409 matches!(ch.script(), Han | Tangut | Yi)
13410}
13411
13412fn is_grapheme_ideographic(text: &str) -> bool {
13413 text.chars().any(is_char_ideographic)
13414}
13415
13416fn is_grapheme_whitespace(text: &str) -> bool {
13417 text.chars().any(|x| x.is_whitespace())
13418}
13419
13420fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13421 text.chars().next().map_or(false, |ch| {
13422 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13423 })
13424}
13425
13426#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13427struct WordBreakToken<'a> {
13428 token: &'a str,
13429 grapheme_len: usize,
13430 is_whitespace: bool,
13431}
13432
13433impl<'a> Iterator for WordBreakingTokenizer<'a> {
13434 /// Yields a span, the count of graphemes in the token, and whether it was
13435 /// whitespace. Note that it also breaks at word boundaries.
13436 type Item = WordBreakToken<'a>;
13437
13438 fn next(&mut self) -> Option<Self::Item> {
13439 use unicode_segmentation::UnicodeSegmentation;
13440 if self.input.is_empty() {
13441 return None;
13442 }
13443
13444 let mut iter = self.input.graphemes(true).peekable();
13445 let mut offset = 0;
13446 let mut graphemes = 0;
13447 if let Some(first_grapheme) = iter.next() {
13448 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13449 offset += first_grapheme.len();
13450 graphemes += 1;
13451 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13452 if let Some(grapheme) = iter.peek().copied() {
13453 if should_stay_with_preceding_ideograph(grapheme) {
13454 offset += grapheme.len();
13455 graphemes += 1;
13456 }
13457 }
13458 } else {
13459 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13460 let mut next_word_bound = words.peek().copied();
13461 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13462 next_word_bound = words.next();
13463 }
13464 while let Some(grapheme) = iter.peek().copied() {
13465 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13466 break;
13467 };
13468 if is_grapheme_whitespace(grapheme) != is_whitespace {
13469 break;
13470 };
13471 offset += grapheme.len();
13472 graphemes += 1;
13473 iter.next();
13474 }
13475 }
13476 let token = &self.input[..offset];
13477 self.input = &self.input[offset..];
13478 if is_whitespace {
13479 Some(WordBreakToken {
13480 token: " ",
13481 grapheme_len: 1,
13482 is_whitespace: true,
13483 })
13484 } else {
13485 Some(WordBreakToken {
13486 token,
13487 grapheme_len: graphemes,
13488 is_whitespace: false,
13489 })
13490 }
13491 } else {
13492 None
13493 }
13494 }
13495}
13496
13497#[test]
13498fn test_word_breaking_tokenizer() {
13499 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13500 ("", &[]),
13501 (" ", &[(" ", 1, true)]),
13502 ("Ʒ", &[("Ʒ", 1, false)]),
13503 ("Ǽ", &[("Ǽ", 1, false)]),
13504 ("⋑", &[("⋑", 1, false)]),
13505 ("⋑⋑", &[("⋑⋑", 2, false)]),
13506 (
13507 "原理,进而",
13508 &[
13509 ("原", 1, false),
13510 ("理,", 2, false),
13511 ("进", 1, false),
13512 ("而", 1, false),
13513 ],
13514 ),
13515 (
13516 "hello world",
13517 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13518 ),
13519 (
13520 "hello, world",
13521 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13522 ),
13523 (
13524 " hello world",
13525 &[
13526 (" ", 1, true),
13527 ("hello", 5, false),
13528 (" ", 1, true),
13529 ("world", 5, false),
13530 ],
13531 ),
13532 (
13533 "这是什么 \n 钢笔",
13534 &[
13535 ("这", 1, false),
13536 ("是", 1, false),
13537 ("什", 1, false),
13538 ("么", 1, false),
13539 (" ", 1, true),
13540 ("钢", 1, false),
13541 ("笔", 1, false),
13542 ],
13543 ),
13544 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13545 ];
13546
13547 for (input, result) in tests {
13548 assert_eq!(
13549 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13550 result
13551 .iter()
13552 .copied()
13553 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13554 token,
13555 grapheme_len,
13556 is_whitespace,
13557 })
13558 .collect::<Vec<_>>()
13559 );
13560 }
13561}
13562
13563fn wrap_with_prefix(
13564 line_prefix: String,
13565 unwrapped_text: String,
13566 wrap_column: usize,
13567 tab_size: NonZeroU32,
13568) -> String {
13569 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13570 let mut wrapped_text = String::new();
13571 let mut current_line = line_prefix.clone();
13572
13573 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13574 let mut current_line_len = line_prefix_len;
13575 for WordBreakToken {
13576 token,
13577 grapheme_len,
13578 is_whitespace,
13579 } in tokenizer
13580 {
13581 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13582 wrapped_text.push_str(current_line.trim_end());
13583 wrapped_text.push('\n');
13584 current_line.truncate(line_prefix.len());
13585 current_line_len = line_prefix_len;
13586 if !is_whitespace {
13587 current_line.push_str(token);
13588 current_line_len += grapheme_len;
13589 }
13590 } else if !is_whitespace {
13591 current_line.push_str(token);
13592 current_line_len += grapheme_len;
13593 } else if current_line_len != line_prefix_len {
13594 current_line.push(' ');
13595 current_line_len += 1;
13596 }
13597 }
13598
13599 if !current_line.is_empty() {
13600 wrapped_text.push_str(¤t_line);
13601 }
13602 wrapped_text
13603}
13604
13605#[test]
13606fn test_wrap_with_prefix() {
13607 assert_eq!(
13608 wrap_with_prefix(
13609 "# ".to_string(),
13610 "abcdefg".to_string(),
13611 4,
13612 NonZeroU32::new(4).unwrap()
13613 ),
13614 "# abcdefg"
13615 );
13616 assert_eq!(
13617 wrap_with_prefix(
13618 "".to_string(),
13619 "\thello world".to_string(),
13620 8,
13621 NonZeroU32::new(4).unwrap()
13622 ),
13623 "hello\nworld"
13624 );
13625 assert_eq!(
13626 wrap_with_prefix(
13627 "// ".to_string(),
13628 "xx \nyy zz aa bb cc".to_string(),
13629 12,
13630 NonZeroU32::new(4).unwrap()
13631 ),
13632 "// xx yy zz\n// aa bb cc"
13633 );
13634 assert_eq!(
13635 wrap_with_prefix(
13636 String::new(),
13637 "这是什么 \n 钢笔".to_string(),
13638 3,
13639 NonZeroU32::new(4).unwrap()
13640 ),
13641 "这是什\n么 钢\n笔"
13642 );
13643}
13644
13645pub trait CollaborationHub {
13646 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13647 fn user_participant_indices<'a>(
13648 &self,
13649 cx: &'a AppContext,
13650 ) -> &'a HashMap<u64, ParticipantIndex>;
13651 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13652}
13653
13654impl CollaborationHub for Model<Project> {
13655 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13656 self.read(cx).collaborators()
13657 }
13658
13659 fn user_participant_indices<'a>(
13660 &self,
13661 cx: &'a AppContext,
13662 ) -> &'a HashMap<u64, ParticipantIndex> {
13663 self.read(cx).user_store().read(cx).participant_indices()
13664 }
13665
13666 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13667 let this = self.read(cx);
13668 let user_ids = this.collaborators().values().map(|c| c.user_id);
13669 this.user_store().read_with(cx, |user_store, cx| {
13670 user_store.participant_names(user_ids, cx)
13671 })
13672 }
13673}
13674
13675pub trait SemanticsProvider {
13676 fn hover(
13677 &self,
13678 buffer: &Model<Buffer>,
13679 position: text::Anchor,
13680 cx: &mut AppContext,
13681 ) -> Option<Task<Vec<project::Hover>>>;
13682
13683 fn inlay_hints(
13684 &self,
13685 buffer_handle: Model<Buffer>,
13686 range: Range<text::Anchor>,
13687 cx: &mut AppContext,
13688 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13689
13690 fn resolve_inlay_hint(
13691 &self,
13692 hint: InlayHint,
13693 buffer_handle: Model<Buffer>,
13694 server_id: LanguageServerId,
13695 cx: &mut AppContext,
13696 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13697
13698 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13699
13700 fn document_highlights(
13701 &self,
13702 buffer: &Model<Buffer>,
13703 position: text::Anchor,
13704 cx: &mut AppContext,
13705 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13706
13707 fn definitions(
13708 &self,
13709 buffer: &Model<Buffer>,
13710 position: text::Anchor,
13711 kind: GotoDefinitionKind,
13712 cx: &mut AppContext,
13713 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13714
13715 fn range_for_rename(
13716 &self,
13717 buffer: &Model<Buffer>,
13718 position: text::Anchor,
13719 cx: &mut AppContext,
13720 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13721
13722 fn perform_rename(
13723 &self,
13724 buffer: &Model<Buffer>,
13725 position: text::Anchor,
13726 new_name: String,
13727 cx: &mut AppContext,
13728 ) -> Option<Task<Result<ProjectTransaction>>>;
13729}
13730
13731pub trait CompletionProvider {
13732 fn completions(
13733 &self,
13734 buffer: &Model<Buffer>,
13735 buffer_position: text::Anchor,
13736 trigger: CompletionContext,
13737 cx: &mut ViewContext<Editor>,
13738 ) -> Task<Result<Vec<Completion>>>;
13739
13740 fn resolve_completions(
13741 &self,
13742 buffer: Model<Buffer>,
13743 completion_indices: Vec<usize>,
13744 completions: Rc<RefCell<Box<[Completion]>>>,
13745 cx: &mut ViewContext<Editor>,
13746 ) -> Task<Result<bool>>;
13747
13748 fn apply_additional_edits_for_completion(
13749 &self,
13750 _buffer: Model<Buffer>,
13751 _completions: Rc<RefCell<Box<[Completion]>>>,
13752 _completion_index: usize,
13753 _push_to_history: bool,
13754 _cx: &mut ViewContext<Editor>,
13755 ) -> Task<Result<Option<language::Transaction>>> {
13756 Task::ready(Ok(None))
13757 }
13758
13759 fn is_completion_trigger(
13760 &self,
13761 buffer: &Model<Buffer>,
13762 position: language::Anchor,
13763 text: &str,
13764 trigger_in_words: bool,
13765 cx: &mut ViewContext<Editor>,
13766 ) -> bool;
13767
13768 fn sort_completions(&self) -> bool {
13769 true
13770 }
13771}
13772
13773pub trait CodeActionProvider {
13774 fn id(&self) -> Arc<str>;
13775
13776 fn code_actions(
13777 &self,
13778 buffer: &Model<Buffer>,
13779 range: Range<text::Anchor>,
13780 cx: &mut WindowContext,
13781 ) -> Task<Result<Vec<CodeAction>>>;
13782
13783 fn apply_code_action(
13784 &self,
13785 buffer_handle: Model<Buffer>,
13786 action: CodeAction,
13787 excerpt_id: ExcerptId,
13788 push_to_history: bool,
13789 cx: &mut WindowContext,
13790 ) -> Task<Result<ProjectTransaction>>;
13791}
13792
13793impl CodeActionProvider for Model<Project> {
13794 fn id(&self) -> Arc<str> {
13795 "project".into()
13796 }
13797
13798 fn code_actions(
13799 &self,
13800 buffer: &Model<Buffer>,
13801 range: Range<text::Anchor>,
13802 cx: &mut WindowContext,
13803 ) -> Task<Result<Vec<CodeAction>>> {
13804 self.update(cx, |project, cx| {
13805 project.code_actions(buffer, range, None, cx)
13806 })
13807 }
13808
13809 fn apply_code_action(
13810 &self,
13811 buffer_handle: Model<Buffer>,
13812 action: CodeAction,
13813 _excerpt_id: ExcerptId,
13814 push_to_history: bool,
13815 cx: &mut WindowContext,
13816 ) -> Task<Result<ProjectTransaction>> {
13817 self.update(cx, |project, cx| {
13818 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13819 })
13820 }
13821}
13822
13823fn snippet_completions(
13824 project: &Project,
13825 buffer: &Model<Buffer>,
13826 buffer_position: text::Anchor,
13827 cx: &mut AppContext,
13828) -> Task<Result<Vec<Completion>>> {
13829 let language = buffer.read(cx).language_at(buffer_position);
13830 let language_name = language.as_ref().map(|language| language.lsp_id());
13831 let snippet_store = project.snippets().read(cx);
13832 let snippets = snippet_store.snippets_for(language_name, cx);
13833
13834 if snippets.is_empty() {
13835 return Task::ready(Ok(vec![]));
13836 }
13837 let snapshot = buffer.read(cx).text_snapshot();
13838 let chars: String = snapshot
13839 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13840 .collect();
13841
13842 let scope = language.map(|language| language.default_scope());
13843 let executor = cx.background_executor().clone();
13844
13845 cx.background_executor().spawn(async move {
13846 let classifier = CharClassifier::new(scope).for_completion(true);
13847 let mut last_word = chars
13848 .chars()
13849 .take_while(|c| classifier.is_word(*c))
13850 .collect::<String>();
13851 last_word = last_word.chars().rev().collect();
13852
13853 if last_word.is_empty() {
13854 return Ok(vec![]);
13855 }
13856
13857 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13858 let to_lsp = |point: &text::Anchor| {
13859 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13860 point_to_lsp(end)
13861 };
13862 let lsp_end = to_lsp(&buffer_position);
13863
13864 let candidates = snippets
13865 .iter()
13866 .enumerate()
13867 .flat_map(|(ix, snippet)| {
13868 snippet
13869 .prefix
13870 .iter()
13871 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13872 })
13873 .collect::<Vec<StringMatchCandidate>>();
13874
13875 let mut matches = fuzzy::match_strings(
13876 &candidates,
13877 &last_word,
13878 last_word.chars().any(|c| c.is_uppercase()),
13879 100,
13880 &Default::default(),
13881 executor,
13882 )
13883 .await;
13884
13885 // Remove all candidates where the query's start does not match the start of any word in the candidate
13886 if let Some(query_start) = last_word.chars().next() {
13887 matches.retain(|string_match| {
13888 split_words(&string_match.string).any(|word| {
13889 // Check that the first codepoint of the word as lowercase matches the first
13890 // codepoint of the query as lowercase
13891 word.chars()
13892 .flat_map(|codepoint| codepoint.to_lowercase())
13893 .zip(query_start.to_lowercase())
13894 .all(|(word_cp, query_cp)| word_cp == query_cp)
13895 })
13896 });
13897 }
13898
13899 let matched_strings = matches
13900 .into_iter()
13901 .map(|m| m.string)
13902 .collect::<HashSet<_>>();
13903
13904 let result: Vec<Completion> = snippets
13905 .into_iter()
13906 .filter_map(|snippet| {
13907 let matching_prefix = snippet
13908 .prefix
13909 .iter()
13910 .find(|prefix| matched_strings.contains(*prefix))?;
13911 let start = as_offset - last_word.len();
13912 let start = snapshot.anchor_before(start);
13913 let range = start..buffer_position;
13914 let lsp_start = to_lsp(&start);
13915 let lsp_range = lsp::Range {
13916 start: lsp_start,
13917 end: lsp_end,
13918 };
13919 Some(Completion {
13920 old_range: range,
13921 new_text: snippet.body.clone(),
13922 resolved: false,
13923 label: CodeLabel {
13924 text: matching_prefix.clone(),
13925 runs: vec![],
13926 filter_range: 0..matching_prefix.len(),
13927 },
13928 server_id: LanguageServerId(usize::MAX),
13929 documentation: snippet.description.clone().map(Documentation::SingleLine),
13930 lsp_completion: lsp::CompletionItem {
13931 label: snippet.prefix.first().unwrap().clone(),
13932 kind: Some(CompletionItemKind::SNIPPET),
13933 label_details: snippet.description.as_ref().map(|description| {
13934 lsp::CompletionItemLabelDetails {
13935 detail: Some(description.clone()),
13936 description: None,
13937 }
13938 }),
13939 insert_text_format: Some(InsertTextFormat::SNIPPET),
13940 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13941 lsp::InsertReplaceEdit {
13942 new_text: snippet.body.clone(),
13943 insert: lsp_range,
13944 replace: lsp_range,
13945 },
13946 )),
13947 filter_text: Some(snippet.body.clone()),
13948 sort_text: Some(char::MAX.to_string()),
13949 ..Default::default()
13950 },
13951 confirm: None,
13952 })
13953 })
13954 .collect();
13955
13956 Ok(result)
13957 })
13958}
13959
13960impl CompletionProvider for Model<Project> {
13961 fn completions(
13962 &self,
13963 buffer: &Model<Buffer>,
13964 buffer_position: text::Anchor,
13965 options: CompletionContext,
13966 cx: &mut ViewContext<Editor>,
13967 ) -> Task<Result<Vec<Completion>>> {
13968 self.update(cx, |project, cx| {
13969 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13970 let project_completions = project.completions(buffer, buffer_position, options, cx);
13971 cx.background_executor().spawn(async move {
13972 let mut completions = project_completions.await?;
13973 let snippets_completions = snippets.await?;
13974 completions.extend(snippets_completions);
13975 Ok(completions)
13976 })
13977 })
13978 }
13979
13980 fn resolve_completions(
13981 &self,
13982 buffer: Model<Buffer>,
13983 completion_indices: Vec<usize>,
13984 completions: Rc<RefCell<Box<[Completion]>>>,
13985 cx: &mut ViewContext<Editor>,
13986 ) -> Task<Result<bool>> {
13987 self.update(cx, |project, cx| {
13988 project.lsp_store().update(cx, |lsp_store, cx| {
13989 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13990 })
13991 })
13992 }
13993
13994 fn apply_additional_edits_for_completion(
13995 &self,
13996 buffer: Model<Buffer>,
13997 completions: Rc<RefCell<Box<[Completion]>>>,
13998 completion_index: usize,
13999 push_to_history: bool,
14000 cx: &mut ViewContext<Editor>,
14001 ) -> Task<Result<Option<language::Transaction>>> {
14002 self.update(cx, |project, cx| {
14003 project.lsp_store().update(cx, |lsp_store, cx| {
14004 lsp_store.apply_additional_edits_for_completion(
14005 buffer,
14006 completions,
14007 completion_index,
14008 push_to_history,
14009 cx,
14010 )
14011 })
14012 })
14013 }
14014
14015 fn is_completion_trigger(
14016 &self,
14017 buffer: &Model<Buffer>,
14018 position: language::Anchor,
14019 text: &str,
14020 trigger_in_words: bool,
14021 cx: &mut ViewContext<Editor>,
14022 ) -> bool {
14023 let mut chars = text.chars();
14024 let char = if let Some(char) = chars.next() {
14025 char
14026 } else {
14027 return false;
14028 };
14029 if chars.next().is_some() {
14030 return false;
14031 }
14032
14033 let buffer = buffer.read(cx);
14034 let snapshot = buffer.snapshot();
14035 if !snapshot.settings_at(position, cx).show_completions_on_input {
14036 return false;
14037 }
14038 let classifier = snapshot.char_classifier_at(position).for_completion(true);
14039 if trigger_in_words && classifier.is_word(char) {
14040 return true;
14041 }
14042
14043 buffer.completion_triggers().contains(text)
14044 }
14045}
14046
14047impl SemanticsProvider for Model<Project> {
14048 fn hover(
14049 &self,
14050 buffer: &Model<Buffer>,
14051 position: text::Anchor,
14052 cx: &mut AppContext,
14053 ) -> Option<Task<Vec<project::Hover>>> {
14054 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14055 }
14056
14057 fn document_highlights(
14058 &self,
14059 buffer: &Model<Buffer>,
14060 position: text::Anchor,
14061 cx: &mut AppContext,
14062 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14063 Some(self.update(cx, |project, cx| {
14064 project.document_highlights(buffer, position, cx)
14065 }))
14066 }
14067
14068 fn definitions(
14069 &self,
14070 buffer: &Model<Buffer>,
14071 position: text::Anchor,
14072 kind: GotoDefinitionKind,
14073 cx: &mut AppContext,
14074 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14075 Some(self.update(cx, |project, cx| match kind {
14076 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14077 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14078 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14079 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14080 }))
14081 }
14082
14083 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14084 // TODO: make this work for remote projects
14085 self.read(cx)
14086 .language_servers_for_local_buffer(buffer.read(cx), cx)
14087 .any(
14088 |(_, server)| match server.capabilities().inlay_hint_provider {
14089 Some(lsp::OneOf::Left(enabled)) => enabled,
14090 Some(lsp::OneOf::Right(_)) => true,
14091 None => false,
14092 },
14093 )
14094 }
14095
14096 fn inlay_hints(
14097 &self,
14098 buffer_handle: Model<Buffer>,
14099 range: Range<text::Anchor>,
14100 cx: &mut AppContext,
14101 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14102 Some(self.update(cx, |project, cx| {
14103 project.inlay_hints(buffer_handle, range, cx)
14104 }))
14105 }
14106
14107 fn resolve_inlay_hint(
14108 &self,
14109 hint: InlayHint,
14110 buffer_handle: Model<Buffer>,
14111 server_id: LanguageServerId,
14112 cx: &mut AppContext,
14113 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14114 Some(self.update(cx, |project, cx| {
14115 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14116 }))
14117 }
14118
14119 fn range_for_rename(
14120 &self,
14121 buffer: &Model<Buffer>,
14122 position: text::Anchor,
14123 cx: &mut AppContext,
14124 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14125 Some(self.update(cx, |project, cx| {
14126 let buffer = buffer.clone();
14127 let task = project.prepare_rename(buffer.clone(), position, cx);
14128 cx.spawn(|_, mut cx| async move {
14129 Ok(match task.await? {
14130 PrepareRenameResponse::Success(range) => Some(range),
14131 PrepareRenameResponse::InvalidPosition => None,
14132 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14133 // Fallback on using TreeSitter info to determine identifier range
14134 buffer.update(&mut cx, |buffer, _| {
14135 let snapshot = buffer.snapshot();
14136 let (range, kind) = snapshot.surrounding_word(position);
14137 if kind != Some(CharKind::Word) {
14138 return None;
14139 }
14140 Some(
14141 snapshot.anchor_before(range.start)
14142 ..snapshot.anchor_after(range.end),
14143 )
14144 })?
14145 }
14146 })
14147 })
14148 }))
14149 }
14150
14151 fn perform_rename(
14152 &self,
14153 buffer: &Model<Buffer>,
14154 position: text::Anchor,
14155 new_name: String,
14156 cx: &mut AppContext,
14157 ) -> Option<Task<Result<ProjectTransaction>>> {
14158 Some(self.update(cx, |project, cx| {
14159 project.perform_rename(buffer.clone(), position, new_name, cx)
14160 }))
14161 }
14162}
14163
14164fn inlay_hint_settings(
14165 location: Anchor,
14166 snapshot: &MultiBufferSnapshot,
14167 cx: &mut ViewContext<Editor>,
14168) -> InlayHintSettings {
14169 let file = snapshot.file_at(location);
14170 let language = snapshot.language_at(location).map(|l| l.name());
14171 language_settings(language, file, cx).inlay_hints
14172}
14173
14174fn consume_contiguous_rows(
14175 contiguous_row_selections: &mut Vec<Selection<Point>>,
14176 selection: &Selection<Point>,
14177 display_map: &DisplaySnapshot,
14178 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14179) -> (MultiBufferRow, MultiBufferRow) {
14180 contiguous_row_selections.push(selection.clone());
14181 let start_row = MultiBufferRow(selection.start.row);
14182 let mut end_row = ending_row(selection, display_map);
14183
14184 while let Some(next_selection) = selections.peek() {
14185 if next_selection.start.row <= end_row.0 {
14186 end_row = ending_row(next_selection, display_map);
14187 contiguous_row_selections.push(selections.next().unwrap().clone());
14188 } else {
14189 break;
14190 }
14191 }
14192 (start_row, end_row)
14193}
14194
14195fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14196 if next_selection.end.column > 0 || next_selection.is_empty() {
14197 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14198 } else {
14199 MultiBufferRow(next_selection.end.row)
14200 }
14201}
14202
14203impl EditorSnapshot {
14204 pub fn remote_selections_in_range<'a>(
14205 &'a self,
14206 range: &'a Range<Anchor>,
14207 collaboration_hub: &dyn CollaborationHub,
14208 cx: &'a AppContext,
14209 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14210 let participant_names = collaboration_hub.user_names(cx);
14211 let participant_indices = collaboration_hub.user_participant_indices(cx);
14212 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14213 let collaborators_by_replica_id = collaborators_by_peer_id
14214 .iter()
14215 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14216 .collect::<HashMap<_, _>>();
14217 self.buffer_snapshot
14218 .selections_in_range(range, false)
14219 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14220 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14221 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14222 let user_name = participant_names.get(&collaborator.user_id).cloned();
14223 Some(RemoteSelection {
14224 replica_id,
14225 selection,
14226 cursor_shape,
14227 line_mode,
14228 participant_index,
14229 peer_id: collaborator.peer_id,
14230 user_name,
14231 })
14232 })
14233 }
14234
14235 pub fn hunks_for_ranges(
14236 &self,
14237 ranges: impl Iterator<Item = Range<Point>>,
14238 ) -> Vec<MultiBufferDiffHunk> {
14239 let mut hunks = Vec::new();
14240 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
14241 HashMap::default();
14242 for query_range in ranges {
14243 let query_rows =
14244 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
14245 for hunk in self.buffer_snapshot.diff_hunks_in_range(
14246 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
14247 ) {
14248 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
14249 // when the caret is just above or just below the deleted hunk.
14250 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
14251 let related_to_selection = if allow_adjacent {
14252 hunk.row_range.overlaps(&query_rows)
14253 || hunk.row_range.start == query_rows.end
14254 || hunk.row_range.end == query_rows.start
14255 } else {
14256 hunk.row_range.overlaps(&query_rows)
14257 };
14258 if related_to_selection {
14259 if !processed_buffer_rows
14260 .entry(hunk.buffer_id)
14261 .or_default()
14262 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
14263 {
14264 continue;
14265 }
14266 hunks.push(hunk);
14267 }
14268 }
14269 }
14270
14271 hunks
14272 }
14273
14274 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14275 self.display_snapshot.buffer_snapshot.language_at(position)
14276 }
14277
14278 pub fn is_focused(&self) -> bool {
14279 self.is_focused
14280 }
14281
14282 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14283 self.placeholder_text.as_ref()
14284 }
14285
14286 pub fn scroll_position(&self) -> gpui::Point<f32> {
14287 self.scroll_anchor.scroll_position(&self.display_snapshot)
14288 }
14289
14290 fn gutter_dimensions(
14291 &self,
14292 font_id: FontId,
14293 font_size: Pixels,
14294 em_width: Pixels,
14295 em_advance: Pixels,
14296 max_line_number_width: Pixels,
14297 cx: &AppContext,
14298 ) -> GutterDimensions {
14299 if !self.show_gutter {
14300 return GutterDimensions::default();
14301 }
14302 let descent = cx.text_system().descent(font_id, font_size);
14303
14304 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14305 matches!(
14306 ProjectSettings::get_global(cx).git.git_gutter,
14307 Some(GitGutterSetting::TrackedFiles)
14308 )
14309 });
14310 let gutter_settings = EditorSettings::get_global(cx).gutter;
14311 let show_line_numbers = self
14312 .show_line_numbers
14313 .unwrap_or(gutter_settings.line_numbers);
14314 let line_gutter_width = if show_line_numbers {
14315 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14316 let min_width_for_number_on_gutter = em_advance * 4.0;
14317 max_line_number_width.max(min_width_for_number_on_gutter)
14318 } else {
14319 0.0.into()
14320 };
14321
14322 let show_code_actions = self
14323 .show_code_actions
14324 .unwrap_or(gutter_settings.code_actions);
14325
14326 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14327
14328 let git_blame_entries_width =
14329 self.git_blame_gutter_max_author_length
14330 .map(|max_author_length| {
14331 // Length of the author name, but also space for the commit hash,
14332 // the spacing and the timestamp.
14333 let max_char_count = max_author_length
14334 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14335 + 7 // length of commit sha
14336 + 14 // length of max relative timestamp ("60 minutes ago")
14337 + 4; // gaps and margins
14338
14339 em_advance * max_char_count
14340 });
14341
14342 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14343 left_padding += if show_code_actions || show_runnables {
14344 em_width * 3.0
14345 } else if show_git_gutter && show_line_numbers {
14346 em_width * 2.0
14347 } else if show_git_gutter || show_line_numbers {
14348 em_width
14349 } else {
14350 px(0.)
14351 };
14352
14353 let right_padding = if gutter_settings.folds && show_line_numbers {
14354 em_width * 4.0
14355 } else if gutter_settings.folds {
14356 em_width * 3.0
14357 } else if show_line_numbers {
14358 em_width
14359 } else {
14360 px(0.)
14361 };
14362
14363 GutterDimensions {
14364 left_padding,
14365 right_padding,
14366 width: line_gutter_width + left_padding + right_padding,
14367 margin: -descent,
14368 git_blame_entries_width,
14369 }
14370 }
14371
14372 pub fn render_crease_toggle(
14373 &self,
14374 buffer_row: MultiBufferRow,
14375 row_contains_cursor: bool,
14376 editor: View<Editor>,
14377 cx: &mut WindowContext,
14378 ) -> Option<AnyElement> {
14379 let folded = self.is_line_folded(buffer_row);
14380 let mut is_foldable = false;
14381
14382 if let Some(crease) = self
14383 .crease_snapshot
14384 .query_row(buffer_row, &self.buffer_snapshot)
14385 {
14386 is_foldable = true;
14387 match crease {
14388 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14389 if let Some(render_toggle) = render_toggle {
14390 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14391 if folded {
14392 editor.update(cx, |editor, cx| {
14393 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14394 });
14395 } else {
14396 editor.update(cx, |editor, cx| {
14397 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14398 });
14399 }
14400 });
14401 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14402 }
14403 }
14404 }
14405 }
14406
14407 is_foldable |= self.starts_indent(buffer_row);
14408
14409 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14410 Some(
14411 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14412 .toggle_state(folded)
14413 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14414 if folded {
14415 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14416 } else {
14417 this.fold_at(&FoldAt { buffer_row }, cx);
14418 }
14419 }))
14420 .into_any_element(),
14421 )
14422 } else {
14423 None
14424 }
14425 }
14426
14427 pub fn render_crease_trailer(
14428 &self,
14429 buffer_row: MultiBufferRow,
14430 cx: &mut WindowContext,
14431 ) -> Option<AnyElement> {
14432 let folded = self.is_line_folded(buffer_row);
14433 if let Crease::Inline { render_trailer, .. } = self
14434 .crease_snapshot
14435 .query_row(buffer_row, &self.buffer_snapshot)?
14436 {
14437 let render_trailer = render_trailer.as_ref()?;
14438 Some(render_trailer(buffer_row, folded, cx))
14439 } else {
14440 None
14441 }
14442 }
14443}
14444
14445impl Deref for EditorSnapshot {
14446 type Target = DisplaySnapshot;
14447
14448 fn deref(&self) -> &Self::Target {
14449 &self.display_snapshot
14450 }
14451}
14452
14453#[derive(Clone, Debug, PartialEq, Eq)]
14454pub enum EditorEvent {
14455 InputIgnored {
14456 text: Arc<str>,
14457 },
14458 InputHandled {
14459 utf16_range_to_replace: Option<Range<isize>>,
14460 text: Arc<str>,
14461 },
14462 ExcerptsAdded {
14463 buffer: Model<Buffer>,
14464 predecessor: ExcerptId,
14465 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14466 },
14467 ExcerptsRemoved {
14468 ids: Vec<ExcerptId>,
14469 },
14470 BufferFoldToggled {
14471 ids: Vec<ExcerptId>,
14472 folded: bool,
14473 },
14474 ExcerptsEdited {
14475 ids: Vec<ExcerptId>,
14476 },
14477 ExcerptsExpanded {
14478 ids: Vec<ExcerptId>,
14479 },
14480 BufferEdited,
14481 Edited {
14482 transaction_id: clock::Lamport,
14483 },
14484 Reparsed(BufferId),
14485 Focused,
14486 FocusedIn,
14487 Blurred,
14488 DirtyChanged,
14489 Saved,
14490 TitleChanged,
14491 DiffBaseChanged,
14492 SelectionsChanged {
14493 local: bool,
14494 },
14495 ScrollPositionChanged {
14496 local: bool,
14497 autoscroll: bool,
14498 },
14499 Closed,
14500 TransactionUndone {
14501 transaction_id: clock::Lamport,
14502 },
14503 TransactionBegun {
14504 transaction_id: clock::Lamport,
14505 },
14506 Reloaded,
14507 CursorShapeChanged,
14508}
14509
14510impl EventEmitter<EditorEvent> for Editor {}
14511
14512impl FocusableView for Editor {
14513 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14514 self.focus_handle.clone()
14515 }
14516}
14517
14518impl Render for Editor {
14519 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14520 let settings = ThemeSettings::get_global(cx);
14521
14522 let mut text_style = match self.mode {
14523 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14524 color: cx.theme().colors().editor_foreground,
14525 font_family: settings.ui_font.family.clone(),
14526 font_features: settings.ui_font.features.clone(),
14527 font_fallbacks: settings.ui_font.fallbacks.clone(),
14528 font_size: rems(0.875).into(),
14529 font_weight: settings.ui_font.weight,
14530 line_height: relative(settings.buffer_line_height.value()),
14531 ..Default::default()
14532 },
14533 EditorMode::Full => TextStyle {
14534 color: cx.theme().colors().editor_foreground,
14535 font_family: settings.buffer_font.family.clone(),
14536 font_features: settings.buffer_font.features.clone(),
14537 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14538 font_size: settings.buffer_font_size().into(),
14539 font_weight: settings.buffer_font.weight,
14540 line_height: relative(settings.buffer_line_height.value()),
14541 ..Default::default()
14542 },
14543 };
14544 if let Some(text_style_refinement) = &self.text_style_refinement {
14545 text_style.refine(text_style_refinement)
14546 }
14547
14548 let background = match self.mode {
14549 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14550 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14551 EditorMode::Full => cx.theme().colors().editor_background,
14552 };
14553
14554 EditorElement::new(
14555 cx.view(),
14556 EditorStyle {
14557 background,
14558 local_player: cx.theme().players().local(),
14559 text: text_style,
14560 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14561 syntax: cx.theme().syntax().clone(),
14562 status: cx.theme().status().clone(),
14563 inlay_hints_style: make_inlay_hints_style(cx),
14564 inline_completion_styles: make_suggestion_styles(cx),
14565 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14566 },
14567 )
14568 }
14569}
14570
14571impl ViewInputHandler for Editor {
14572 fn text_for_range(
14573 &mut self,
14574 range_utf16: Range<usize>,
14575 adjusted_range: &mut Option<Range<usize>>,
14576 cx: &mut ViewContext<Self>,
14577 ) -> Option<String> {
14578 let snapshot = self.buffer.read(cx).read(cx);
14579 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14580 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14581 if (start.0..end.0) != range_utf16 {
14582 adjusted_range.replace(start.0..end.0);
14583 }
14584 Some(snapshot.text_for_range(start..end).collect())
14585 }
14586
14587 fn selected_text_range(
14588 &mut self,
14589 ignore_disabled_input: bool,
14590 cx: &mut ViewContext<Self>,
14591 ) -> Option<UTF16Selection> {
14592 // Prevent the IME menu from appearing when holding down an alphabetic key
14593 // while input is disabled.
14594 if !ignore_disabled_input && !self.input_enabled {
14595 return None;
14596 }
14597
14598 let selection = self.selections.newest::<OffsetUtf16>(cx);
14599 let range = selection.range();
14600
14601 Some(UTF16Selection {
14602 range: range.start.0..range.end.0,
14603 reversed: selection.reversed,
14604 })
14605 }
14606
14607 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14608 let snapshot = self.buffer.read(cx).read(cx);
14609 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14610 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14611 }
14612
14613 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14614 self.clear_highlights::<InputComposition>(cx);
14615 self.ime_transaction.take();
14616 }
14617
14618 fn replace_text_in_range(
14619 &mut self,
14620 range_utf16: Option<Range<usize>>,
14621 text: &str,
14622 cx: &mut ViewContext<Self>,
14623 ) {
14624 if !self.input_enabled {
14625 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14626 return;
14627 }
14628
14629 self.transact(cx, |this, cx| {
14630 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14631 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14632 Some(this.selection_replacement_ranges(range_utf16, cx))
14633 } else {
14634 this.marked_text_ranges(cx)
14635 };
14636
14637 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14638 let newest_selection_id = this.selections.newest_anchor().id;
14639 this.selections
14640 .all::<OffsetUtf16>(cx)
14641 .iter()
14642 .zip(ranges_to_replace.iter())
14643 .find_map(|(selection, range)| {
14644 if selection.id == newest_selection_id {
14645 Some(
14646 (range.start.0 as isize - selection.head().0 as isize)
14647 ..(range.end.0 as isize - selection.head().0 as isize),
14648 )
14649 } else {
14650 None
14651 }
14652 })
14653 });
14654
14655 cx.emit(EditorEvent::InputHandled {
14656 utf16_range_to_replace: range_to_replace,
14657 text: text.into(),
14658 });
14659
14660 if let Some(new_selected_ranges) = new_selected_ranges {
14661 this.change_selections(None, cx, |selections| {
14662 selections.select_ranges(new_selected_ranges)
14663 });
14664 this.backspace(&Default::default(), cx);
14665 }
14666
14667 this.handle_input(text, cx);
14668 });
14669
14670 if let Some(transaction) = self.ime_transaction {
14671 self.buffer.update(cx, |buffer, cx| {
14672 buffer.group_until_transaction(transaction, cx);
14673 });
14674 }
14675
14676 self.unmark_text(cx);
14677 }
14678
14679 fn replace_and_mark_text_in_range(
14680 &mut self,
14681 range_utf16: Option<Range<usize>>,
14682 text: &str,
14683 new_selected_range_utf16: Option<Range<usize>>,
14684 cx: &mut ViewContext<Self>,
14685 ) {
14686 if !self.input_enabled {
14687 return;
14688 }
14689
14690 let transaction = self.transact(cx, |this, cx| {
14691 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14692 let snapshot = this.buffer.read(cx).read(cx);
14693 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14694 for marked_range in &mut marked_ranges {
14695 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14696 marked_range.start.0 += relative_range_utf16.start;
14697 marked_range.start =
14698 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14699 marked_range.end =
14700 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14701 }
14702 }
14703 Some(marked_ranges)
14704 } else if let Some(range_utf16) = range_utf16 {
14705 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14706 Some(this.selection_replacement_ranges(range_utf16, cx))
14707 } else {
14708 None
14709 };
14710
14711 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14712 let newest_selection_id = this.selections.newest_anchor().id;
14713 this.selections
14714 .all::<OffsetUtf16>(cx)
14715 .iter()
14716 .zip(ranges_to_replace.iter())
14717 .find_map(|(selection, range)| {
14718 if selection.id == newest_selection_id {
14719 Some(
14720 (range.start.0 as isize - selection.head().0 as isize)
14721 ..(range.end.0 as isize - selection.head().0 as isize),
14722 )
14723 } else {
14724 None
14725 }
14726 })
14727 });
14728
14729 cx.emit(EditorEvent::InputHandled {
14730 utf16_range_to_replace: range_to_replace,
14731 text: text.into(),
14732 });
14733
14734 if let Some(ranges) = ranges_to_replace {
14735 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14736 }
14737
14738 let marked_ranges = {
14739 let snapshot = this.buffer.read(cx).read(cx);
14740 this.selections
14741 .disjoint_anchors()
14742 .iter()
14743 .map(|selection| {
14744 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14745 })
14746 .collect::<Vec<_>>()
14747 };
14748
14749 if text.is_empty() {
14750 this.unmark_text(cx);
14751 } else {
14752 this.highlight_text::<InputComposition>(
14753 marked_ranges.clone(),
14754 HighlightStyle {
14755 underline: Some(UnderlineStyle {
14756 thickness: px(1.),
14757 color: None,
14758 wavy: false,
14759 }),
14760 ..Default::default()
14761 },
14762 cx,
14763 );
14764 }
14765
14766 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14767 let use_autoclose = this.use_autoclose;
14768 let use_auto_surround = this.use_auto_surround;
14769 this.set_use_autoclose(false);
14770 this.set_use_auto_surround(false);
14771 this.handle_input(text, cx);
14772 this.set_use_autoclose(use_autoclose);
14773 this.set_use_auto_surround(use_auto_surround);
14774
14775 if let Some(new_selected_range) = new_selected_range_utf16 {
14776 let snapshot = this.buffer.read(cx).read(cx);
14777 let new_selected_ranges = marked_ranges
14778 .into_iter()
14779 .map(|marked_range| {
14780 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14781 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14782 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14783 snapshot.clip_offset_utf16(new_start, Bias::Left)
14784 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14785 })
14786 .collect::<Vec<_>>();
14787
14788 drop(snapshot);
14789 this.change_selections(None, cx, |selections| {
14790 selections.select_ranges(new_selected_ranges)
14791 });
14792 }
14793 });
14794
14795 self.ime_transaction = self.ime_transaction.or(transaction);
14796 if let Some(transaction) = self.ime_transaction {
14797 self.buffer.update(cx, |buffer, cx| {
14798 buffer.group_until_transaction(transaction, cx);
14799 });
14800 }
14801
14802 if self.text_highlights::<InputComposition>(cx).is_none() {
14803 self.ime_transaction.take();
14804 }
14805 }
14806
14807 fn bounds_for_range(
14808 &mut self,
14809 range_utf16: Range<usize>,
14810 element_bounds: gpui::Bounds<Pixels>,
14811 cx: &mut ViewContext<Self>,
14812 ) -> Option<gpui::Bounds<Pixels>> {
14813 let text_layout_details = self.text_layout_details(cx);
14814 let gpui::Point {
14815 x: em_width,
14816 y: line_height,
14817 } = self.character_size(cx);
14818
14819 let snapshot = self.snapshot(cx);
14820 let scroll_position = snapshot.scroll_position();
14821 let scroll_left = scroll_position.x * em_width;
14822
14823 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14824 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14825 + self.gutter_dimensions.width
14826 + self.gutter_dimensions.margin;
14827 let y = line_height * (start.row().as_f32() - scroll_position.y);
14828
14829 Some(Bounds {
14830 origin: element_bounds.origin + point(x, y),
14831 size: size(em_width, line_height),
14832 })
14833 }
14834}
14835
14836trait SelectionExt {
14837 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14838 fn spanned_rows(
14839 &self,
14840 include_end_if_at_line_start: bool,
14841 map: &DisplaySnapshot,
14842 ) -> Range<MultiBufferRow>;
14843}
14844
14845impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14846 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14847 let start = self
14848 .start
14849 .to_point(&map.buffer_snapshot)
14850 .to_display_point(map);
14851 let end = self
14852 .end
14853 .to_point(&map.buffer_snapshot)
14854 .to_display_point(map);
14855 if self.reversed {
14856 end..start
14857 } else {
14858 start..end
14859 }
14860 }
14861
14862 fn spanned_rows(
14863 &self,
14864 include_end_if_at_line_start: bool,
14865 map: &DisplaySnapshot,
14866 ) -> Range<MultiBufferRow> {
14867 let start = self.start.to_point(&map.buffer_snapshot);
14868 let mut end = self.end.to_point(&map.buffer_snapshot);
14869 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14870 end.row -= 1;
14871 }
14872
14873 let buffer_start = map.prev_line_boundary(start).0;
14874 let buffer_end = map.next_line_boundary(end).0;
14875 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14876 }
14877}
14878
14879impl<T: InvalidationRegion> InvalidationStack<T> {
14880 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14881 where
14882 S: Clone + ToOffset,
14883 {
14884 while let Some(region) = self.last() {
14885 let all_selections_inside_invalidation_ranges =
14886 if selections.len() == region.ranges().len() {
14887 selections
14888 .iter()
14889 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14890 .all(|(selection, invalidation_range)| {
14891 let head = selection.head().to_offset(buffer);
14892 invalidation_range.start <= head && invalidation_range.end >= head
14893 })
14894 } else {
14895 false
14896 };
14897
14898 if all_selections_inside_invalidation_ranges {
14899 break;
14900 } else {
14901 self.pop();
14902 }
14903 }
14904 }
14905}
14906
14907impl<T> Default for InvalidationStack<T> {
14908 fn default() -> Self {
14909 Self(Default::default())
14910 }
14911}
14912
14913impl<T> Deref for InvalidationStack<T> {
14914 type Target = Vec<T>;
14915
14916 fn deref(&self) -> &Self::Target {
14917 &self.0
14918 }
14919}
14920
14921impl<T> DerefMut for InvalidationStack<T> {
14922 fn deref_mut(&mut self) -> &mut Self::Target {
14923 &mut self.0
14924 }
14925}
14926
14927impl InvalidationRegion for SnippetState {
14928 fn ranges(&self) -> &[Range<Anchor>] {
14929 &self.ranges[self.active_index]
14930 }
14931}
14932
14933pub fn diagnostic_block_renderer(
14934 diagnostic: Diagnostic,
14935 max_message_rows: Option<u8>,
14936 allow_closing: bool,
14937 _is_valid: bool,
14938) -> RenderBlock {
14939 let (text_without_backticks, code_ranges) =
14940 highlight_diagnostic_message(&diagnostic, max_message_rows);
14941
14942 Arc::new(move |cx: &mut BlockContext| {
14943 let group_id: SharedString = cx.block_id.to_string().into();
14944
14945 let mut text_style = cx.text_style().clone();
14946 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14947 let theme_settings = ThemeSettings::get_global(cx);
14948 text_style.font_family = theme_settings.buffer_font.family.clone();
14949 text_style.font_style = theme_settings.buffer_font.style;
14950 text_style.font_features = theme_settings.buffer_font.features.clone();
14951 text_style.font_weight = theme_settings.buffer_font.weight;
14952
14953 let multi_line_diagnostic = diagnostic.message.contains('\n');
14954
14955 let buttons = |diagnostic: &Diagnostic| {
14956 if multi_line_diagnostic {
14957 v_flex()
14958 } else {
14959 h_flex()
14960 }
14961 .when(allow_closing, |div| {
14962 div.children(diagnostic.is_primary.then(|| {
14963 IconButton::new("close-block", IconName::XCircle)
14964 .icon_color(Color::Muted)
14965 .size(ButtonSize::Compact)
14966 .style(ButtonStyle::Transparent)
14967 .visible_on_hover(group_id.clone())
14968 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14969 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14970 }))
14971 })
14972 .child(
14973 IconButton::new("copy-block", IconName::Copy)
14974 .icon_color(Color::Muted)
14975 .size(ButtonSize::Compact)
14976 .style(ButtonStyle::Transparent)
14977 .visible_on_hover(group_id.clone())
14978 .on_click({
14979 let message = diagnostic.message.clone();
14980 move |_click, cx| {
14981 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14982 }
14983 })
14984 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14985 )
14986 };
14987
14988 let icon_size = buttons(&diagnostic)
14989 .into_any_element()
14990 .layout_as_root(AvailableSpace::min_size(), cx);
14991
14992 h_flex()
14993 .id(cx.block_id)
14994 .group(group_id.clone())
14995 .relative()
14996 .size_full()
14997 .block_mouse_down()
14998 .pl(cx.gutter_dimensions.width)
14999 .w(cx.max_width - cx.gutter_dimensions.full_width())
15000 .child(
15001 div()
15002 .flex()
15003 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15004 .flex_shrink(),
15005 )
15006 .child(buttons(&diagnostic))
15007 .child(div().flex().flex_shrink_0().child(
15008 StyledText::new(text_without_backticks.clone()).with_highlights(
15009 &text_style,
15010 code_ranges.iter().map(|range| {
15011 (
15012 range.clone(),
15013 HighlightStyle {
15014 font_weight: Some(FontWeight::BOLD),
15015 ..Default::default()
15016 },
15017 )
15018 }),
15019 ),
15020 ))
15021 .into_any_element()
15022 })
15023}
15024
15025fn inline_completion_edit_text(
15026 current_snapshot: &BufferSnapshot,
15027 edits: &[(Range<Anchor>, String)],
15028 edit_preview: &EditPreview,
15029 include_deletions: bool,
15030 cx: &WindowContext,
15031) -> Option<HighlightedEdits> {
15032 let edits = edits
15033 .iter()
15034 .map(|(anchor, text)| {
15035 (
15036 anchor.start.text_anchor..anchor.end.text_anchor,
15037 text.clone(),
15038 )
15039 })
15040 .collect::<Vec<_>>();
15041
15042 Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15043}
15044
15045pub fn highlight_diagnostic_message(
15046 diagnostic: &Diagnostic,
15047 mut max_message_rows: Option<u8>,
15048) -> (SharedString, Vec<Range<usize>>) {
15049 let mut text_without_backticks = String::new();
15050 let mut code_ranges = Vec::new();
15051
15052 if let Some(source) = &diagnostic.source {
15053 text_without_backticks.push_str(source);
15054 code_ranges.push(0..source.len());
15055 text_without_backticks.push_str(": ");
15056 }
15057
15058 let mut prev_offset = 0;
15059 let mut in_code_block = false;
15060 let has_row_limit = max_message_rows.is_some();
15061 let mut newline_indices = diagnostic
15062 .message
15063 .match_indices('\n')
15064 .filter(|_| has_row_limit)
15065 .map(|(ix, _)| ix)
15066 .fuse()
15067 .peekable();
15068
15069 for (quote_ix, _) in diagnostic
15070 .message
15071 .match_indices('`')
15072 .chain([(diagnostic.message.len(), "")])
15073 {
15074 let mut first_newline_ix = None;
15075 let mut last_newline_ix = None;
15076 while let Some(newline_ix) = newline_indices.peek() {
15077 if *newline_ix < quote_ix {
15078 if first_newline_ix.is_none() {
15079 first_newline_ix = Some(*newline_ix);
15080 }
15081 last_newline_ix = Some(*newline_ix);
15082
15083 if let Some(rows_left) = &mut max_message_rows {
15084 if *rows_left == 0 {
15085 break;
15086 } else {
15087 *rows_left -= 1;
15088 }
15089 }
15090 let _ = newline_indices.next();
15091 } else {
15092 break;
15093 }
15094 }
15095 let prev_len = text_without_backticks.len();
15096 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15097 text_without_backticks.push_str(new_text);
15098 if in_code_block {
15099 code_ranges.push(prev_len..text_without_backticks.len());
15100 }
15101 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15102 in_code_block = !in_code_block;
15103 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15104 text_without_backticks.push_str("...");
15105 break;
15106 }
15107 }
15108
15109 (text_without_backticks.into(), code_ranges)
15110}
15111
15112fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15113 match severity {
15114 DiagnosticSeverity::ERROR => colors.error,
15115 DiagnosticSeverity::WARNING => colors.warning,
15116 DiagnosticSeverity::INFORMATION => colors.info,
15117 DiagnosticSeverity::HINT => colors.info,
15118 _ => colors.ignored,
15119 }
15120}
15121
15122pub fn styled_runs_for_code_label<'a>(
15123 label: &'a CodeLabel,
15124 syntax_theme: &'a theme::SyntaxTheme,
15125) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15126 let fade_out = HighlightStyle {
15127 fade_out: Some(0.35),
15128 ..Default::default()
15129 };
15130
15131 let mut prev_end = label.filter_range.end;
15132 label
15133 .runs
15134 .iter()
15135 .enumerate()
15136 .flat_map(move |(ix, (range, highlight_id))| {
15137 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15138 style
15139 } else {
15140 return Default::default();
15141 };
15142 let mut muted_style = style;
15143 muted_style.highlight(fade_out);
15144
15145 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15146 if range.start >= label.filter_range.end {
15147 if range.start > prev_end {
15148 runs.push((prev_end..range.start, fade_out));
15149 }
15150 runs.push((range.clone(), muted_style));
15151 } else if range.end <= label.filter_range.end {
15152 runs.push((range.clone(), style));
15153 } else {
15154 runs.push((range.start..label.filter_range.end, style));
15155 runs.push((label.filter_range.end..range.end, muted_style));
15156 }
15157 prev_end = cmp::max(prev_end, range.end);
15158
15159 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15160 runs.push((prev_end..label.text.len(), fade_out));
15161 }
15162
15163 runs
15164 })
15165}
15166
15167pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15168 let mut prev_index = 0;
15169 let mut prev_codepoint: Option<char> = None;
15170 text.char_indices()
15171 .chain([(text.len(), '\0')])
15172 .filter_map(move |(index, codepoint)| {
15173 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15174 let is_boundary = index == text.len()
15175 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15176 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15177 if is_boundary {
15178 let chunk = &text[prev_index..index];
15179 prev_index = index;
15180 Some(chunk)
15181 } else {
15182 None
15183 }
15184 })
15185}
15186
15187pub trait RangeToAnchorExt: Sized {
15188 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15189
15190 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15191 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15192 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15193 }
15194}
15195
15196impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15197 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15198 let start_offset = self.start.to_offset(snapshot);
15199 let end_offset = self.end.to_offset(snapshot);
15200 if start_offset == end_offset {
15201 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15202 } else {
15203 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15204 }
15205 }
15206}
15207
15208pub trait RowExt {
15209 fn as_f32(&self) -> f32;
15210
15211 fn next_row(&self) -> Self;
15212
15213 fn previous_row(&self) -> Self;
15214
15215 fn minus(&self, other: Self) -> u32;
15216}
15217
15218impl RowExt for DisplayRow {
15219 fn as_f32(&self) -> f32 {
15220 self.0 as f32
15221 }
15222
15223 fn next_row(&self) -> Self {
15224 Self(self.0 + 1)
15225 }
15226
15227 fn previous_row(&self) -> Self {
15228 Self(self.0.saturating_sub(1))
15229 }
15230
15231 fn minus(&self, other: Self) -> u32 {
15232 self.0 - other.0
15233 }
15234}
15235
15236impl RowExt for MultiBufferRow {
15237 fn as_f32(&self) -> f32 {
15238 self.0 as f32
15239 }
15240
15241 fn next_row(&self) -> Self {
15242 Self(self.0 + 1)
15243 }
15244
15245 fn previous_row(&self) -> Self {
15246 Self(self.0.saturating_sub(1))
15247 }
15248
15249 fn minus(&self, other: Self) -> u32 {
15250 self.0 - other.0
15251 }
15252}
15253
15254trait RowRangeExt {
15255 type Row;
15256
15257 fn len(&self) -> usize;
15258
15259 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15260}
15261
15262impl RowRangeExt for Range<MultiBufferRow> {
15263 type Row = MultiBufferRow;
15264
15265 fn len(&self) -> usize {
15266 (self.end.0 - self.start.0) as usize
15267 }
15268
15269 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15270 (self.start.0..self.end.0).map(MultiBufferRow)
15271 }
15272}
15273
15274impl RowRangeExt for Range<DisplayRow> {
15275 type Row = DisplayRow;
15276
15277 fn len(&self) -> usize {
15278 (self.end.0 - self.start.0) as usize
15279 }
15280
15281 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15282 (self.start.0..self.end.0).map(DisplayRow)
15283 }
15284}
15285
15286/// If select range has more than one line, we
15287/// just point the cursor to range.start.
15288fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
15289 if range.start.row == range.end.row {
15290 range
15291 } else {
15292 range.start..range.start
15293 }
15294}
15295pub struct KillRing(ClipboardItem);
15296impl Global for KillRing {}
15297
15298const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
15299
15300fn all_edits_insertions_or_deletions(
15301 edits: &Vec<(Range<Anchor>, String)>,
15302 snapshot: &MultiBufferSnapshot,
15303) -> bool {
15304 let mut all_insertions = true;
15305 let mut all_deletions = true;
15306
15307 for (range, new_text) in edits.iter() {
15308 let range_is_empty = range.to_offset(&snapshot).is_empty();
15309 let text_is_empty = new_text.is_empty();
15310
15311 if range_is_empty != text_is_empty {
15312 if range_is_empty {
15313 all_deletions = false;
15314 } else {
15315 all_insertions = false;
15316 }
15317 } else {
15318 return false;
15319 }
15320
15321 if !all_insertions && !all_deletions {
15322 return false;
15323 }
15324 }
15325 all_insertions || all_deletions
15326}