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 hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73use zed_predict_tos::ZedPredictTos;
74
75use code_context_menus::{
76 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
77 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
78};
79use git::blame::GitBlame;
80use gpui::{
81 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
82 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
83 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
84 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
85 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
86 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
87 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
88 WeakView, WindowContext,
89};
90use highlight_matching_bracket::refresh_matching_bracket_highlights;
91use hover_popover::{hide_hover, HoverState};
92pub(crate) use hunk_diff::HoveredHunk;
93use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
94use indent_guides::ActiveIndentGuidesState;
95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
96pub use inline_completion::Direction;
97use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
98pub use items::MAX_TAB_TITLE_LEN;
99use itertools::Itertools;
100use language::{
101 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
102 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
103 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
104 Point, Selection, SelectionGoal, TransactionId,
105};
106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
107use linked_editing_ranges::refresh_linked_ranges;
108use mouse_context_menu::MouseContextMenu;
109pub use proposed_changes_editor::{
110 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
111};
112use similar::{ChangeTag, TextDiff};
113use std::iter::Peekable;
114use task::{ResolvedTask, TaskTemplate, TaskVariables};
115
116use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
117pub use lsp::CompletionContext;
118use lsp::{
119 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
120 LanguageServerId, LanguageServerName,
121};
122
123use movement::TextLayoutDetails;
124pub use multi_buffer::{
125 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
126 ToPoint,
127};
128use multi_buffer::{
129 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
130};
131use project::{
132 buffer_store::BufferChangeSet,
133 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
134 project_settings::{GitGutterSetting, ProjectSettings},
135 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
136 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
137};
138use rand::prelude::*;
139use rpc::{proto::*, ErrorExt};
140use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
141use selections_collection::{
142 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
143};
144use serde::{Deserialize, Serialize};
145use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
146use smallvec::SmallVec;
147use snippet::Snippet;
148use std::{
149 any::TypeId,
150 borrow::Cow,
151 cell::RefCell,
152 cmp::{self, Ordering, Reverse},
153 mem,
154 num::NonZeroU32,
155 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
156 path::{Path, PathBuf},
157 rc::Rc,
158 sync::Arc,
159 time::{Duration, Instant},
160};
161pub use sum_tree::Bias;
162use sum_tree::TreeMap;
163use text::{BufferId, OffsetUtf16, Rope};
164use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
165use ui::{
166 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
167 PopoverMenuHandle, Tooltip,
168};
169use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
170use workspace::item::{ItemHandle, PreviewTabsSettings};
171use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
172use workspace::{
173 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
174};
175use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
176
177use crate::hover_links::{find_url, find_url_from_range};
178use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
179
180pub const FILE_HEADER_HEIGHT: u32 = 2;
181pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
182pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
183pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
184const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
185const MAX_LINE_LEN: usize = 1024;
186const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
187const MAX_SELECTION_HISTORY_LEN: usize = 1024;
188pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
189#[doc(hidden)]
190pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
191
192pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
193pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
194
195pub fn render_parsed_markdown(
196 element_id: impl Into<ElementId>,
197 parsed: &language::ParsedMarkdown,
198 editor_style: &EditorStyle,
199 workspace: Option<WeakView<Workspace>>,
200 cx: &mut WindowContext,
201) -> InteractiveText {
202 let code_span_background_color = cx
203 .theme()
204 .colors()
205 .editor_document_highlight_read_background;
206
207 let highlights = gpui::combine_highlights(
208 parsed.highlights.iter().filter_map(|(range, highlight)| {
209 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
210 Some((range.clone(), highlight))
211 }),
212 parsed
213 .regions
214 .iter()
215 .zip(&parsed.region_ranges)
216 .filter_map(|(region, range)| {
217 if region.code {
218 Some((
219 range.clone(),
220 HighlightStyle {
221 background_color: Some(code_span_background_color),
222 ..Default::default()
223 },
224 ))
225 } else {
226 None
227 }
228 }),
229 );
230
231 let mut links = Vec::new();
232 let mut link_ranges = Vec::new();
233 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
234 if let Some(link) = region.link.clone() {
235 links.push(link);
236 link_ranges.push(range.clone());
237 }
238 }
239
240 InteractiveText::new(
241 element_id,
242 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
243 )
244 .on_click(link_ranges, move |clicked_range_ix, cx| {
245 match &links[clicked_range_ix] {
246 markdown::Link::Web { url } => cx.open_url(url),
247 markdown::Link::Path { path } => {
248 if let Some(workspace) = &workspace {
249 _ = workspace.update(cx, |workspace, cx| {
250 workspace.open_abs_path(path.clone(), false, cx).detach();
251 });
252 }
253 }
254 }
255 })
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub enum InlayId {
260 InlineCompletion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::InlineCompletion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DiffRowHighlight {}
274enum DocumentHighlightRead {}
275enum DocumentHighlightWrite {}
276enum InputComposition {}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut AppContext) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut AppContext) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new_views(
306 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
318 Editor::new_file(workspace, &Default::default(), cx)
319 })
320 .detach();
321 }
322 });
323 cx.on_action(move |_: &workspace::NewWindow, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
327 Editor::new_file(workspace, &Default::default(), cx)
328 })
329 .detach();
330 }
331 });
332 git::project_diff::init(cx);
333}
334
335pub struct SearchWithinRange;
336
337trait InvalidationRegion {
338 fn ranges(&self) -> &[Range<Anchor>];
339}
340
341#[derive(Clone, Debug, PartialEq)]
342pub enum SelectPhase {
343 Begin {
344 position: DisplayPoint,
345 add: bool,
346 click_count: usize,
347 },
348 BeginColumnar {
349 position: DisplayPoint,
350 reset: bool,
351 goal_column: u32,
352 },
353 Extend {
354 position: DisplayPoint,
355 click_count: usize,
356 },
357 Update {
358 position: DisplayPoint,
359 goal_column: u32,
360 scroll_delta: gpui::Point<f32>,
361 },
362 End,
363}
364
365#[derive(Clone, Debug)]
366pub enum SelectMode {
367 Character,
368 Word(Range<Anchor>),
369 Line(Range<Anchor>),
370 All,
371}
372
373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
374pub enum EditorMode {
375 SingleLine { auto_width: bool },
376 AutoHeight { max_lines: usize },
377 Full,
378}
379
380#[derive(Copy, Clone, Debug)]
381pub enum SoftWrap {
382 /// Prefer not to wrap at all.
383 ///
384 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
385 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
386 GitDiff,
387 /// Prefer a single line generally, unless an overly long line is encountered.
388 None,
389 /// Soft wrap lines that exceed the editor width.
390 EditorWidth,
391 /// Soft wrap lines at the preferred line length.
392 Column(u32),
393 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
394 Bounded(u32),
395}
396
397#[derive(Clone)]
398pub struct EditorStyle {
399 pub background: Hsla,
400 pub local_player: PlayerColor,
401 pub text: TextStyle,
402 pub scrollbar_width: Pixels,
403 pub syntax: Arc<SyntaxTheme>,
404 pub status: StatusColors,
405 pub inlay_hints_style: HighlightStyle,
406 pub inline_completion_styles: InlineCompletionStyles,
407 pub unnecessary_code_fade: f32,
408}
409
410impl Default for EditorStyle {
411 fn default() -> Self {
412 Self {
413 background: Hsla::default(),
414 local_player: PlayerColor::default(),
415 text: TextStyle::default(),
416 scrollbar_width: Pixels::default(),
417 syntax: Default::default(),
418 // HACK: Status colors don't have a real default.
419 // We should look into removing the status colors from the editor
420 // style and retrieve them directly from the theme.
421 status: StatusColors::dark(),
422 inlay_hints_style: HighlightStyle::default(),
423 inline_completion_styles: InlineCompletionStyles {
424 insertion: HighlightStyle::default(),
425 whitespace: HighlightStyle::default(),
426 },
427 unnecessary_code_fade: Default::default(),
428 }
429 }
430}
431
432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
433 let show_background = language_settings::language_settings(None, None, cx)
434 .inlay_hints
435 .show_background;
436
437 HighlightStyle {
438 color: Some(cx.theme().status().hint),
439 background_color: show_background.then(|| cx.theme().status().hint_background),
440 ..HighlightStyle::default()
441 }
442}
443
444pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
445 InlineCompletionStyles {
446 insertion: HighlightStyle {
447 color: Some(cx.theme().status().predictive),
448 ..HighlightStyle::default()
449 },
450 whitespace: HighlightStyle {
451 background_color: Some(cx.theme().status().created_background),
452 ..HighlightStyle::default()
453 },
454 }
455}
456
457type CompletionId = usize;
458
459#[derive(Debug, Clone)]
460enum InlineCompletionMenuHint {
461 Loading,
462 Loaded { text: InlineCompletionText },
463 PendingTermsAcceptance,
464 None,
465}
466
467impl InlineCompletionMenuHint {
468 pub fn label(&self) -> &'static str {
469 match self {
470 InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
471 "Edit Prediction"
472 }
473 InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
474 InlineCompletionMenuHint::None => "No Prediction",
475 }
476 }
477}
478
479#[derive(Clone, Debug)]
480enum InlineCompletionText {
481 Move(SharedString),
482 Edit {
483 text: SharedString,
484 highlights: Vec<(Range<usize>, HighlightStyle)>,
485 },
486}
487
488pub(crate) enum EditDisplayMode {
489 TabAccept,
490 DiffPopover,
491 Inline,
492}
493
494enum InlineCompletion {
495 Edit {
496 edits: Vec<(Range<Anchor>, String)>,
497 display_mode: EditDisplayMode,
498 },
499 Move(Anchor),
500}
501
502struct InlineCompletionState {
503 inlay_ids: Vec<InlayId>,
504 completion: InlineCompletion,
505 invalidation_range: Range<Anchor>,
506}
507
508enum InlineCompletionHighlight {}
509
510#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
511struct EditorActionId(usize);
512
513impl EditorActionId {
514 pub fn post_inc(&mut self) -> Self {
515 let answer = self.0;
516
517 *self = Self(answer + 1);
518
519 Self(answer)
520 }
521}
522
523// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
524// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
525
526type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
527type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
528
529#[derive(Default)]
530struct ScrollbarMarkerState {
531 scrollbar_size: Size<Pixels>,
532 dirty: bool,
533 markers: Arc<[PaintQuad]>,
534 pending_refresh: Option<Task<Result<()>>>,
535}
536
537impl ScrollbarMarkerState {
538 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
539 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
540 }
541}
542
543#[derive(Clone, Debug)]
544struct RunnableTasks {
545 templates: Vec<(TaskSourceKind, TaskTemplate)>,
546 offset: MultiBufferOffset,
547 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
548 column: u32,
549 // Values of all named captures, including those starting with '_'
550 extra_variables: HashMap<String, String>,
551 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
552 context_range: Range<BufferOffset>,
553}
554
555impl RunnableTasks {
556 fn resolve<'a>(
557 &'a self,
558 cx: &'a task::TaskContext,
559 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
560 self.templates.iter().filter_map(|(kind, template)| {
561 template
562 .resolve_task(&kind.to_id_base(), cx)
563 .map(|task| (kind.clone(), task))
564 })
565 }
566}
567
568#[derive(Clone)]
569struct ResolvedTasks {
570 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
571 position: Anchor,
572}
573#[derive(Copy, Clone, Debug)]
574struct MultiBufferOffset(usize);
575#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
576struct BufferOffset(usize);
577
578// Addons allow storing per-editor state in other crates (e.g. Vim)
579pub trait Addon: 'static {
580 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
581
582 fn to_any(&self) -> &dyn std::any::Any;
583}
584
585#[derive(Debug, Copy, Clone, PartialEq, Eq)]
586pub enum IsVimMode {
587 Yes,
588 No,
589}
590
591/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
592///
593/// See the [module level documentation](self) for more information.
594pub struct Editor {
595 focus_handle: FocusHandle,
596 last_focused_descendant: Option<WeakFocusHandle>,
597 /// The text buffer being edited
598 buffer: Model<MultiBuffer>,
599 /// Map of how text in the buffer should be displayed.
600 /// Handles soft wraps, folds, fake inlay text insertions, etc.
601 pub display_map: Model<DisplayMap>,
602 pub selections: SelectionsCollection,
603 pub scroll_manager: ScrollManager,
604 /// When inline assist editors are linked, they all render cursors because
605 /// typing enters text into each of them, even the ones that aren't focused.
606 pub(crate) show_cursor_when_unfocused: bool,
607 columnar_selection_tail: Option<Anchor>,
608 add_selections_state: Option<AddSelectionsState>,
609 select_next_state: Option<SelectNextState>,
610 select_prev_state: Option<SelectNextState>,
611 selection_history: SelectionHistory,
612 autoclose_regions: Vec<AutocloseRegion>,
613 snippet_stack: InvalidationStack<SnippetState>,
614 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
615 ime_transaction: Option<TransactionId>,
616 active_diagnostics: Option<ActiveDiagnosticGroup>,
617 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
618
619 project: Option<Model<Project>>,
620 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
621 completion_provider: Option<Box<dyn CompletionProvider>>,
622 collaboration_hub: Option<Box<dyn CollaborationHub>>,
623 blink_manager: Model<BlinkManager>,
624 show_cursor_names: bool,
625 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
626 pub show_local_selections: bool,
627 mode: EditorMode,
628 show_breadcrumbs: bool,
629 show_gutter: bool,
630 show_scrollbars: bool,
631 show_line_numbers: Option<bool>,
632 use_relative_line_numbers: Option<bool>,
633 show_git_diff_gutter: Option<bool>,
634 show_code_actions: Option<bool>,
635 show_runnables: Option<bool>,
636 show_wrap_guides: Option<bool>,
637 show_indent_guides: Option<bool>,
638 placeholder_text: Option<Arc<str>>,
639 highlight_order: usize,
640 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
641 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
642 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
643 scrollbar_marker_state: ScrollbarMarkerState,
644 active_indent_guides_state: ActiveIndentGuidesState,
645 nav_history: Option<ItemNavHistory>,
646 context_menu: RefCell<Option<CodeContextMenu>>,
647 mouse_context_menu: Option<MouseContextMenu>,
648 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
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 inlay_hint_cache: InlayHintCache,
682 diff_map: DiffMap,
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 diff_map: DiffMapSnapshot,
753 is_focused: bool,
754 scroll_anchor: ScrollAnchor,
755 ongoing_scroll: OngoingScroll,
756 current_line_highlight: CurrentLineHighlight,
757 gutter_hovered: bool,
758}
759
760const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
761
762#[derive(Default, Debug, Clone, Copy)]
763pub struct GutterDimensions {
764 pub left_padding: Pixels,
765 pub right_padding: Pixels,
766 pub width: Pixels,
767 pub margin: Pixels,
768 pub git_blame_entries_width: Option<Pixels>,
769}
770
771impl GutterDimensions {
772 /// The full width of the space taken up by the gutter.
773 pub fn full_width(&self) -> Pixels {
774 self.margin + self.width
775 }
776
777 /// The width of the space reserved for the fold indicators,
778 /// use alongside 'justify_end' and `gutter_width` to
779 /// right align content with the line numbers
780 pub fn fold_area_width(&self) -> Pixels {
781 self.margin + self.right_padding
782 }
783}
784
785#[derive(Debug)]
786pub struct RemoteSelection {
787 pub replica_id: ReplicaId,
788 pub selection: Selection<Anchor>,
789 pub cursor_shape: CursorShape,
790 pub peer_id: PeerId,
791 pub line_mode: bool,
792 pub participant_index: Option<ParticipantIndex>,
793 pub user_name: Option<SharedString>,
794}
795
796#[derive(Clone, Debug)]
797struct SelectionHistoryEntry {
798 selections: Arc<[Selection<Anchor>]>,
799 select_next_state: Option<SelectNextState>,
800 select_prev_state: Option<SelectNextState>,
801 add_selections_state: Option<AddSelectionsState>,
802}
803
804enum SelectionHistoryMode {
805 Normal,
806 Undoing,
807 Redoing,
808}
809
810#[derive(Clone, PartialEq, Eq, Hash)]
811struct HoveredCursor {
812 replica_id: u16,
813 selection_id: usize,
814}
815
816impl Default for SelectionHistoryMode {
817 fn default() -> Self {
818 Self::Normal
819 }
820}
821
822#[derive(Default)]
823struct SelectionHistory {
824 #[allow(clippy::type_complexity)]
825 selections_by_transaction:
826 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
827 mode: SelectionHistoryMode,
828 undo_stack: VecDeque<SelectionHistoryEntry>,
829 redo_stack: VecDeque<SelectionHistoryEntry>,
830}
831
832impl SelectionHistory {
833 fn insert_transaction(
834 &mut self,
835 transaction_id: TransactionId,
836 selections: Arc<[Selection<Anchor>]>,
837 ) {
838 self.selections_by_transaction
839 .insert(transaction_id, (selections, None));
840 }
841
842 #[allow(clippy::type_complexity)]
843 fn transaction(
844 &self,
845 transaction_id: TransactionId,
846 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
847 self.selections_by_transaction.get(&transaction_id)
848 }
849
850 #[allow(clippy::type_complexity)]
851 fn transaction_mut(
852 &mut self,
853 transaction_id: TransactionId,
854 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
855 self.selections_by_transaction.get_mut(&transaction_id)
856 }
857
858 fn push(&mut self, entry: SelectionHistoryEntry) {
859 if !entry.selections.is_empty() {
860 match self.mode {
861 SelectionHistoryMode::Normal => {
862 self.push_undo(entry);
863 self.redo_stack.clear();
864 }
865 SelectionHistoryMode::Undoing => self.push_redo(entry),
866 SelectionHistoryMode::Redoing => self.push_undo(entry),
867 }
868 }
869 }
870
871 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
872 if self
873 .undo_stack
874 .back()
875 .map_or(true, |e| e.selections != entry.selections)
876 {
877 self.undo_stack.push_back(entry);
878 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
879 self.undo_stack.pop_front();
880 }
881 }
882 }
883
884 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
885 if self
886 .redo_stack
887 .back()
888 .map_or(true, |e| e.selections != entry.selections)
889 {
890 self.redo_stack.push_back(entry);
891 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
892 self.redo_stack.pop_front();
893 }
894 }
895 }
896}
897
898struct RowHighlight {
899 index: usize,
900 range: Range<Anchor>,
901 color: Hsla,
902 should_autoscroll: bool,
903}
904
905#[derive(Clone, Debug)]
906struct AddSelectionsState {
907 above: bool,
908 stack: Vec<usize>,
909}
910
911#[derive(Clone)]
912struct SelectNextState {
913 query: AhoCorasick,
914 wordwise: bool,
915 done: bool,
916}
917
918impl std::fmt::Debug for SelectNextState {
919 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
920 f.debug_struct(std::any::type_name::<Self>())
921 .field("wordwise", &self.wordwise)
922 .field("done", &self.done)
923 .finish()
924 }
925}
926
927#[derive(Debug)]
928struct AutocloseRegion {
929 selection_id: usize,
930 range: Range<Anchor>,
931 pair: BracketPair,
932}
933
934#[derive(Debug)]
935struct SnippetState {
936 ranges: Vec<Vec<Range<Anchor>>>,
937 active_index: usize,
938 choices: Vec<Option<Vec<String>>>,
939}
940
941#[doc(hidden)]
942pub struct RenameState {
943 pub range: Range<Anchor>,
944 pub old_name: Arc<str>,
945 pub editor: View<Editor>,
946 block_id: CustomBlockId,
947}
948
949struct InvalidationStack<T>(Vec<T>);
950
951struct RegisteredInlineCompletionProvider {
952 provider: Arc<dyn InlineCompletionProviderHandle>,
953 _subscription: Subscription,
954}
955
956#[derive(Debug)]
957struct ActiveDiagnosticGroup {
958 primary_range: Range<Anchor>,
959 primary_message: String,
960 group_id: usize,
961 blocks: HashMap<CustomBlockId, Diagnostic>,
962 is_valid: bool,
963}
964
965#[derive(Serialize, Deserialize, Clone, Debug)]
966pub struct ClipboardSelection {
967 pub len: usize,
968 pub is_entire_line: bool,
969 pub first_line_indent: u32,
970}
971
972#[derive(Debug)]
973pub(crate) struct NavigationData {
974 cursor_anchor: Anchor,
975 cursor_position: Point,
976 scroll_anchor: ScrollAnchor,
977 scroll_top_row: u32,
978}
979
980#[derive(Debug, Clone, Copy, PartialEq, Eq)]
981pub enum GotoDefinitionKind {
982 Symbol,
983 Declaration,
984 Type,
985 Implementation,
986}
987
988#[derive(Debug, Clone)]
989enum InlayHintRefreshReason {
990 Toggle(bool),
991 SettingsChange(InlayHintSettings),
992 NewLinesShown,
993 BufferEdited(HashSet<Arc<Language>>),
994 RefreshRequested,
995 ExcerptsRemoved(Vec<ExcerptId>),
996}
997
998impl InlayHintRefreshReason {
999 fn description(&self) -> &'static str {
1000 match self {
1001 Self::Toggle(_) => "toggle",
1002 Self::SettingsChange(_) => "settings change",
1003 Self::NewLinesShown => "new lines shown",
1004 Self::BufferEdited(_) => "buffer edited",
1005 Self::RefreshRequested => "refresh requested",
1006 Self::ExcerptsRemoved(_) => "excerpts removed",
1007 }
1008 }
1009}
1010
1011pub enum FormatTarget {
1012 Buffers,
1013 Ranges(Vec<Range<MultiBufferPoint>>),
1014}
1015
1016pub(crate) struct FocusedBlock {
1017 id: BlockId,
1018 focus_handle: WeakFocusHandle,
1019}
1020
1021#[derive(Clone)]
1022enum JumpData {
1023 MultiBufferRow {
1024 row: MultiBufferRow,
1025 line_offset_from_top: u32,
1026 },
1027 MultiBufferPoint {
1028 excerpt_id: ExcerptId,
1029 position: Point,
1030 anchor: text::Anchor,
1031 line_offset_from_top: u32,
1032 },
1033}
1034
1035impl Editor {
1036 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1037 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1038 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1039 Self::new(
1040 EditorMode::SingleLine { auto_width: false },
1041 buffer,
1042 None,
1043 false,
1044 cx,
1045 )
1046 }
1047
1048 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1049 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1050 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1051 Self::new(EditorMode::Full, buffer, None, false, cx)
1052 }
1053
1054 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1055 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1056 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1057 Self::new(
1058 EditorMode::SingleLine { auto_width: true },
1059 buffer,
1060 None,
1061 false,
1062 cx,
1063 )
1064 }
1065
1066 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1067 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1068 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1069 Self::new(
1070 EditorMode::AutoHeight { max_lines },
1071 buffer,
1072 None,
1073 false,
1074 cx,
1075 )
1076 }
1077
1078 pub fn for_buffer(
1079 buffer: Model<Buffer>,
1080 project: Option<Model<Project>>,
1081 cx: &mut ViewContext<Self>,
1082 ) -> Self {
1083 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1084 Self::new(EditorMode::Full, buffer, project, false, cx)
1085 }
1086
1087 pub fn for_multibuffer(
1088 buffer: Model<MultiBuffer>,
1089 project: Option<Model<Project>>,
1090 show_excerpt_controls: bool,
1091 cx: &mut ViewContext<Self>,
1092 ) -> Self {
1093 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1094 }
1095
1096 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1097 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1098 let mut clone = Self::new(
1099 self.mode,
1100 self.buffer.clone(),
1101 self.project.clone(),
1102 show_excerpt_controls,
1103 cx,
1104 );
1105 self.display_map.update(cx, |display_map, cx| {
1106 let snapshot = display_map.snapshot(cx);
1107 clone.display_map.update(cx, |display_map, cx| {
1108 display_map.set_state(&snapshot, cx);
1109 });
1110 });
1111 clone.selections.clone_state(&self.selections);
1112 clone.scroll_manager.clone_state(&self.scroll_manager);
1113 clone.searchable = self.searchable;
1114 clone
1115 }
1116
1117 pub fn new(
1118 mode: EditorMode,
1119 buffer: Model<MultiBuffer>,
1120 project: Option<Model<Project>>,
1121 show_excerpt_controls: bool,
1122 cx: &mut ViewContext<Self>,
1123 ) -> Self {
1124 let style = cx.text_style();
1125 let font_size = style.font_size.to_pixels(cx.rem_size());
1126 let editor = cx.view().downgrade();
1127 let fold_placeholder = FoldPlaceholder {
1128 constrain_width: true,
1129 render: Arc::new(move |fold_id, fold_range, cx| {
1130 let editor = editor.clone();
1131 div()
1132 .id(fold_id)
1133 .bg(cx.theme().colors().ghost_element_background)
1134 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1135 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1136 .rounded_sm()
1137 .size_full()
1138 .cursor_pointer()
1139 .child("⋯")
1140 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1141 .on_click(move |_, cx| {
1142 editor
1143 .update(cx, |editor, cx| {
1144 editor.unfold_ranges(
1145 &[fold_range.start..fold_range.end],
1146 true,
1147 false,
1148 cx,
1149 );
1150 cx.stop_propagation();
1151 })
1152 .ok();
1153 })
1154 .into_any()
1155 }),
1156 merge_adjacent: true,
1157 ..Default::default()
1158 };
1159 let display_map = cx.new_model(|cx| {
1160 DisplayMap::new(
1161 buffer.clone(),
1162 style.font(),
1163 font_size,
1164 None,
1165 show_excerpt_controls,
1166 FILE_HEADER_HEIGHT,
1167 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1168 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1169 fold_placeholder,
1170 cx,
1171 )
1172 });
1173
1174 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1175
1176 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1177
1178 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1179 .then(|| language_settings::SoftWrap::None);
1180
1181 let mut project_subscriptions = Vec::new();
1182 if mode == EditorMode::Full {
1183 if let Some(project) = project.as_ref() {
1184 if buffer.read(cx).is_singleton() {
1185 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1186 cx.emit(EditorEvent::TitleChanged);
1187 }));
1188 }
1189 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1190 if let project::Event::RefreshInlayHints = event {
1191 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1192 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1193 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1194 let focus_handle = editor.focus_handle(cx);
1195 if focus_handle.is_focused(cx) {
1196 let snapshot = buffer.read(cx).snapshot();
1197 for (range, snippet) in snippet_edits {
1198 let editor_range =
1199 language::range_from_lsp(*range).to_offset(&snapshot);
1200 editor
1201 .insert_snippet(&[editor_range], snippet.clone(), cx)
1202 .ok();
1203 }
1204 }
1205 }
1206 }
1207 }));
1208 if let Some(task_inventory) = project
1209 .read(cx)
1210 .task_store()
1211 .read(cx)
1212 .task_inventory()
1213 .cloned()
1214 {
1215 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1216 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1217 }));
1218 }
1219 }
1220 }
1221
1222 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1223
1224 let inlay_hint_settings =
1225 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1226 let focus_handle = cx.focus_handle();
1227 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1228 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1229 .detach();
1230 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1231 .detach();
1232 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1233
1234 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1235 Some(false)
1236 } else {
1237 None
1238 };
1239
1240 let mut code_action_providers = Vec::new();
1241 if let Some(project) = project.clone() {
1242 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1243 code_action_providers.push(Rc::new(project) as Rc<_>);
1244 }
1245
1246 let mut this = Self {
1247 focus_handle,
1248 show_cursor_when_unfocused: false,
1249 last_focused_descendant: None,
1250 buffer: buffer.clone(),
1251 display_map: display_map.clone(),
1252 selections,
1253 scroll_manager: ScrollManager::new(cx),
1254 columnar_selection_tail: None,
1255 add_selections_state: None,
1256 select_next_state: None,
1257 select_prev_state: None,
1258 selection_history: Default::default(),
1259 autoclose_regions: Default::default(),
1260 snippet_stack: Default::default(),
1261 select_larger_syntax_node_stack: Vec::new(),
1262 ime_transaction: Default::default(),
1263 active_diagnostics: None,
1264 soft_wrap_mode_override,
1265 completion_provider: project.clone().map(|project| Box::new(project) as _),
1266 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1267 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1268 project,
1269 blink_manager: blink_manager.clone(),
1270 show_local_selections: true,
1271 show_scrollbars: true,
1272 mode,
1273 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1274 show_gutter: mode == EditorMode::Full,
1275 show_line_numbers: None,
1276 use_relative_line_numbers: None,
1277 show_git_diff_gutter: None,
1278 show_code_actions: None,
1279 show_runnables: None,
1280 show_wrap_guides: None,
1281 show_indent_guides,
1282 placeholder_text: None,
1283 highlight_order: 0,
1284 highlighted_rows: HashMap::default(),
1285 background_highlights: Default::default(),
1286 gutter_highlights: TreeMap::default(),
1287 scrollbar_marker_state: ScrollbarMarkerState::default(),
1288 active_indent_guides_state: ActiveIndentGuidesState::default(),
1289 nav_history: None,
1290 context_menu: RefCell::new(None),
1291 mouse_context_menu: None,
1292 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1293 completion_tasks: Default::default(),
1294 signature_help_state: SignatureHelpState::default(),
1295 auto_signature_help: None,
1296 find_all_references_task_sources: Vec::new(),
1297 next_completion_id: 0,
1298 next_inlay_id: 0,
1299 code_action_providers,
1300 available_code_actions: Default::default(),
1301 code_actions_task: Default::default(),
1302 document_highlights_task: Default::default(),
1303 linked_editing_range_task: Default::default(),
1304 pending_rename: Default::default(),
1305 searchable: true,
1306 cursor_shape: EditorSettings::get_global(cx)
1307 .cursor_shape
1308 .unwrap_or_default(),
1309 current_line_highlight: None,
1310 autoindent_mode: Some(AutoindentMode::EachLine),
1311 collapse_matches: false,
1312 workspace: None,
1313 input_enabled: true,
1314 use_modal_editing: mode == EditorMode::Full,
1315 read_only: false,
1316 use_autoclose: true,
1317 use_auto_surround: true,
1318 auto_replace_emoji_shortcode: false,
1319 leader_peer_id: None,
1320 remote_id: None,
1321 hover_state: Default::default(),
1322 hovered_link_state: Default::default(),
1323 inline_completion_provider: None,
1324 active_inline_completion: None,
1325 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1326 diff_map: DiffMap::default(),
1327 gutter_hovered: false,
1328 pixel_position_of_newest_cursor: None,
1329 last_bounds: None,
1330 expect_bounds_change: None,
1331 gutter_dimensions: GutterDimensions::default(),
1332 style: None,
1333 show_cursor_names: false,
1334 hovered_cursors: Default::default(),
1335 next_editor_action_id: EditorActionId::default(),
1336 editor_actions: Rc::default(),
1337 show_inline_completions_override: None,
1338 enable_inline_completions: true,
1339 custom_context_menu: None,
1340 show_git_blame_gutter: false,
1341 show_git_blame_inline: false,
1342 show_selection_menu: None,
1343 show_git_blame_inline_delay_task: None,
1344 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1345 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1346 .session
1347 .restore_unsaved_buffers,
1348 blame: None,
1349 blame_subscription: None,
1350 tasks: Default::default(),
1351 _subscriptions: vec![
1352 cx.observe(&buffer, Self::on_buffer_changed),
1353 cx.subscribe(&buffer, Self::on_buffer_event),
1354 cx.observe(&display_map, Self::on_display_map_changed),
1355 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1356 cx.observe_global::<SettingsStore>(Self::settings_changed),
1357 cx.observe_window_activation(|editor, cx| {
1358 let active = cx.is_window_active();
1359 editor.blink_manager.update(cx, |blink_manager, cx| {
1360 if active {
1361 blink_manager.enable(cx);
1362 } else {
1363 blink_manager.disable(cx);
1364 }
1365 });
1366 }),
1367 ],
1368 tasks_update_task: None,
1369 linked_edit_ranges: Default::default(),
1370 previous_search_ranges: None,
1371 breadcrumb_header: None,
1372 focused_block: None,
1373 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1374 addons: HashMap::default(),
1375 registered_buffers: HashMap::default(),
1376 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1377 selection_mark_mode: false,
1378 toggle_fold_multiple_buffers: Task::ready(()),
1379 text_style_refinement: None,
1380 };
1381 this.tasks_update_task = Some(this.refresh_runnables(cx));
1382 this._subscriptions.extend(project_subscriptions);
1383
1384 this.end_selection(cx);
1385 this.scroll_manager.show_scrollbar(cx);
1386
1387 if mode == EditorMode::Full {
1388 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1389 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1390
1391 if this.git_blame_inline_enabled {
1392 this.git_blame_inline_enabled = true;
1393 this.start_git_blame_inline(false, cx);
1394 }
1395
1396 if let Some(buffer) = buffer.read(cx).as_singleton() {
1397 if let Some(project) = this.project.as_ref() {
1398 let lsp_store = project.read(cx).lsp_store();
1399 let handle = lsp_store.update(cx, |lsp_store, cx| {
1400 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1401 });
1402 this.registered_buffers
1403 .insert(buffer.read(cx).remote_id(), handle);
1404 }
1405 }
1406 }
1407
1408 this.report_editor_event("Editor Opened", None, cx);
1409 this
1410 }
1411
1412 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1413 self.mouse_context_menu
1414 .as_ref()
1415 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1416 }
1417
1418 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1419 let mut key_context = KeyContext::new_with_defaults();
1420 key_context.add("Editor");
1421 let mode = match self.mode {
1422 EditorMode::SingleLine { .. } => "single_line",
1423 EditorMode::AutoHeight { .. } => "auto_height",
1424 EditorMode::Full => "full",
1425 };
1426
1427 if EditorSettings::jupyter_enabled(cx) {
1428 key_context.add("jupyter");
1429 }
1430
1431 key_context.set("mode", mode);
1432 if self.pending_rename.is_some() {
1433 key_context.add("renaming");
1434 }
1435 match self.context_menu.borrow().as_ref() {
1436 Some(CodeContextMenu::Completions(_)) => {
1437 key_context.add("menu");
1438 key_context.add("showing_completions")
1439 }
1440 Some(CodeContextMenu::CodeActions(_)) => {
1441 key_context.add("menu");
1442 key_context.add("showing_code_actions")
1443 }
1444 None => {}
1445 }
1446
1447 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1448 if !self.focus_handle(cx).contains_focused(cx)
1449 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1450 {
1451 for addon in self.addons.values() {
1452 addon.extend_key_context(&mut key_context, cx)
1453 }
1454 }
1455
1456 if let Some(extension) = self
1457 .buffer
1458 .read(cx)
1459 .as_singleton()
1460 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1461 {
1462 key_context.set("extension", extension.to_string());
1463 }
1464
1465 if self.has_active_inline_completion() {
1466 key_context.add("copilot_suggestion");
1467 key_context.add("inline_completion");
1468 }
1469
1470 if self.selection_mark_mode {
1471 key_context.add("selection_mode");
1472 }
1473
1474 key_context
1475 }
1476
1477 pub fn new_file(
1478 workspace: &mut Workspace,
1479 _: &workspace::NewFile,
1480 cx: &mut ViewContext<Workspace>,
1481 ) {
1482 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1483 "Failed to create buffer",
1484 cx,
1485 |e, _| match e.error_code() {
1486 ErrorCode::RemoteUpgradeRequired => Some(format!(
1487 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1488 e.error_tag("required").unwrap_or("the latest version")
1489 )),
1490 _ => None,
1491 },
1492 );
1493 }
1494
1495 pub fn new_in_workspace(
1496 workspace: &mut Workspace,
1497 cx: &mut ViewContext<Workspace>,
1498 ) -> Task<Result<View<Editor>>> {
1499 let project = workspace.project().clone();
1500 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1501
1502 cx.spawn(|workspace, mut cx| async move {
1503 let buffer = create.await?;
1504 workspace.update(&mut cx, |workspace, cx| {
1505 let editor =
1506 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1507 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1508 editor
1509 })
1510 })
1511 }
1512
1513 fn new_file_vertical(
1514 workspace: &mut Workspace,
1515 _: &workspace::NewFileSplitVertical,
1516 cx: &mut ViewContext<Workspace>,
1517 ) {
1518 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1519 }
1520
1521 fn new_file_horizontal(
1522 workspace: &mut Workspace,
1523 _: &workspace::NewFileSplitHorizontal,
1524 cx: &mut ViewContext<Workspace>,
1525 ) {
1526 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1527 }
1528
1529 fn new_file_in_direction(
1530 workspace: &mut Workspace,
1531 direction: SplitDirection,
1532 cx: &mut ViewContext<Workspace>,
1533 ) {
1534 let project = workspace.project().clone();
1535 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1536
1537 cx.spawn(|workspace, mut cx| async move {
1538 let buffer = create.await?;
1539 workspace.update(&mut cx, move |workspace, cx| {
1540 workspace.split_item(
1541 direction,
1542 Box::new(
1543 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1544 ),
1545 cx,
1546 )
1547 })?;
1548 anyhow::Ok(())
1549 })
1550 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1551 ErrorCode::RemoteUpgradeRequired => Some(format!(
1552 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1553 e.error_tag("required").unwrap_or("the latest version")
1554 )),
1555 _ => None,
1556 });
1557 }
1558
1559 pub fn leader_peer_id(&self) -> Option<PeerId> {
1560 self.leader_peer_id
1561 }
1562
1563 pub fn buffer(&self) -> &Model<MultiBuffer> {
1564 &self.buffer
1565 }
1566
1567 pub fn workspace(&self) -> Option<View<Workspace>> {
1568 self.workspace.as_ref()?.0.upgrade()
1569 }
1570
1571 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1572 self.buffer().read(cx).title(cx)
1573 }
1574
1575 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1576 let git_blame_gutter_max_author_length = self
1577 .render_git_blame_gutter(cx)
1578 .then(|| {
1579 if let Some(blame) = self.blame.as_ref() {
1580 let max_author_length =
1581 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1582 Some(max_author_length)
1583 } else {
1584 None
1585 }
1586 })
1587 .flatten();
1588
1589 EditorSnapshot {
1590 mode: self.mode,
1591 show_gutter: self.show_gutter,
1592 show_line_numbers: self.show_line_numbers,
1593 show_git_diff_gutter: self.show_git_diff_gutter,
1594 show_code_actions: self.show_code_actions,
1595 show_runnables: self.show_runnables,
1596 git_blame_gutter_max_author_length,
1597 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1598 scroll_anchor: self.scroll_manager.anchor(),
1599 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1600 placeholder_text: self.placeholder_text.clone(),
1601 diff_map: self.diff_map.snapshot(),
1602 is_focused: self.focus_handle.is_focused(cx),
1603 current_line_highlight: self
1604 .current_line_highlight
1605 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1606 gutter_hovered: self.gutter_hovered,
1607 }
1608 }
1609
1610 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1611 self.buffer.read(cx).language_at(point, cx)
1612 }
1613
1614 pub fn file_at<T: ToOffset>(
1615 &self,
1616 point: T,
1617 cx: &AppContext,
1618 ) -> Option<Arc<dyn language::File>> {
1619 self.buffer.read(cx).read(cx).file_at(point).cloned()
1620 }
1621
1622 pub fn active_excerpt(
1623 &self,
1624 cx: &AppContext,
1625 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1626 self.buffer
1627 .read(cx)
1628 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1629 }
1630
1631 pub fn mode(&self) -> EditorMode {
1632 self.mode
1633 }
1634
1635 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1636 self.collaboration_hub.as_deref()
1637 }
1638
1639 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1640 self.collaboration_hub = Some(hub);
1641 }
1642
1643 pub fn set_custom_context_menu(
1644 &mut self,
1645 f: impl 'static
1646 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1647 ) {
1648 self.custom_context_menu = Some(Box::new(f))
1649 }
1650
1651 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1652 self.completion_provider = provider;
1653 }
1654
1655 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1656 self.semantics_provider.clone()
1657 }
1658
1659 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1660 self.semantics_provider = provider;
1661 }
1662
1663 pub fn set_inline_completion_provider<T>(
1664 &mut self,
1665 provider: Option<Model<T>>,
1666 cx: &mut ViewContext<Self>,
1667 ) where
1668 T: InlineCompletionProvider,
1669 {
1670 self.inline_completion_provider =
1671 provider.map(|provider| RegisteredInlineCompletionProvider {
1672 _subscription: cx.observe(&provider, |this, _, cx| {
1673 if this.focus_handle.is_focused(cx) {
1674 this.update_visible_inline_completion(cx);
1675 }
1676 }),
1677 provider: Arc::new(provider),
1678 });
1679 self.refresh_inline_completion(false, false, cx);
1680 }
1681
1682 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1683 self.placeholder_text.as_deref()
1684 }
1685
1686 pub fn set_placeholder_text(
1687 &mut self,
1688 placeholder_text: impl Into<Arc<str>>,
1689 cx: &mut ViewContext<Self>,
1690 ) {
1691 let placeholder_text = Some(placeholder_text.into());
1692 if self.placeholder_text != placeholder_text {
1693 self.placeholder_text = placeholder_text;
1694 cx.notify();
1695 }
1696 }
1697
1698 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1699 self.cursor_shape = cursor_shape;
1700
1701 // Disrupt blink for immediate user feedback that the cursor shape has changed
1702 self.blink_manager.update(cx, BlinkManager::show_cursor);
1703
1704 cx.notify();
1705 }
1706
1707 pub fn set_current_line_highlight(
1708 &mut self,
1709 current_line_highlight: Option<CurrentLineHighlight>,
1710 ) {
1711 self.current_line_highlight = current_line_highlight;
1712 }
1713
1714 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1715 self.collapse_matches = collapse_matches;
1716 }
1717
1718 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1719 let buffers = self.buffer.read(cx).all_buffers();
1720 let Some(lsp_store) = self.lsp_store(cx) else {
1721 return;
1722 };
1723 lsp_store.update(cx, |lsp_store, cx| {
1724 for buffer in buffers {
1725 self.registered_buffers
1726 .entry(buffer.read(cx).remote_id())
1727 .or_insert_with(|| {
1728 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1729 });
1730 }
1731 })
1732 }
1733
1734 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1735 if self.collapse_matches {
1736 return range.start..range.start;
1737 }
1738 range.clone()
1739 }
1740
1741 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1742 if self.display_map.read(cx).clip_at_line_ends != clip {
1743 self.display_map
1744 .update(cx, |map, _| map.clip_at_line_ends = clip);
1745 }
1746 }
1747
1748 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1749 self.input_enabled = input_enabled;
1750 }
1751
1752 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1753 self.enable_inline_completions = enabled;
1754 if !self.enable_inline_completions {
1755 self.take_active_inline_completion(cx);
1756 cx.notify();
1757 }
1758 }
1759
1760 pub fn set_autoindent(&mut self, autoindent: bool) {
1761 if autoindent {
1762 self.autoindent_mode = Some(AutoindentMode::EachLine);
1763 } else {
1764 self.autoindent_mode = None;
1765 }
1766 }
1767
1768 pub fn read_only(&self, cx: &AppContext) -> bool {
1769 self.read_only || self.buffer.read(cx).read_only()
1770 }
1771
1772 pub fn set_read_only(&mut self, read_only: bool) {
1773 self.read_only = read_only;
1774 }
1775
1776 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1777 self.use_autoclose = autoclose;
1778 }
1779
1780 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1781 self.use_auto_surround = auto_surround;
1782 }
1783
1784 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1785 self.auto_replace_emoji_shortcode = auto_replace;
1786 }
1787
1788 pub fn toggle_inline_completions(
1789 &mut self,
1790 _: &ToggleInlineCompletions,
1791 cx: &mut ViewContext<Self>,
1792 ) {
1793 if self.show_inline_completions_override.is_some() {
1794 self.set_show_inline_completions(None, cx);
1795 } else {
1796 let cursor = self.selections.newest_anchor().head();
1797 if let Some((buffer, cursor_buffer_position)) =
1798 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1799 {
1800 let show_inline_completions =
1801 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1802 self.set_show_inline_completions(Some(show_inline_completions), cx);
1803 }
1804 }
1805 }
1806
1807 pub fn set_show_inline_completions(
1808 &mut self,
1809 show_inline_completions: Option<bool>,
1810 cx: &mut ViewContext<Self>,
1811 ) {
1812 self.show_inline_completions_override = show_inline_completions;
1813 self.refresh_inline_completion(false, true, cx);
1814 }
1815
1816 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1817 let cursor = self.selections.newest_anchor().head();
1818 if let Some((buffer, buffer_position)) =
1819 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1820 {
1821 self.should_show_inline_completions(&buffer, buffer_position, cx)
1822 } else {
1823 false
1824 }
1825 }
1826
1827 fn should_show_inline_completions(
1828 &self,
1829 buffer: &Model<Buffer>,
1830 buffer_position: language::Anchor,
1831 cx: &AppContext,
1832 ) -> bool {
1833 if !self.snippet_stack.is_empty() {
1834 return false;
1835 }
1836
1837 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1838 return false;
1839 }
1840
1841 if let Some(provider) = self.inline_completion_provider() {
1842 if let Some(show_inline_completions) = self.show_inline_completions_override {
1843 show_inline_completions
1844 } else {
1845 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1846 }
1847 } else {
1848 false
1849 }
1850 }
1851
1852 fn inline_completions_disabled_in_scope(
1853 &self,
1854 buffer: &Model<Buffer>,
1855 buffer_position: language::Anchor,
1856 cx: &AppContext,
1857 ) -> bool {
1858 let snapshot = buffer.read(cx).snapshot();
1859 let settings = snapshot.settings_at(buffer_position, cx);
1860
1861 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1862 return false;
1863 };
1864
1865 scope.override_name().map_or(false, |scope_name| {
1866 settings
1867 .inline_completions_disabled_in
1868 .iter()
1869 .any(|s| s == scope_name)
1870 })
1871 }
1872
1873 pub fn set_use_modal_editing(&mut self, to: bool) {
1874 self.use_modal_editing = to;
1875 }
1876
1877 pub fn use_modal_editing(&self) -> bool {
1878 self.use_modal_editing
1879 }
1880
1881 fn selections_did_change(
1882 &mut self,
1883 local: bool,
1884 old_cursor_position: &Anchor,
1885 show_completions: bool,
1886 cx: &mut ViewContext<Self>,
1887 ) {
1888 cx.invalidate_character_coordinates();
1889
1890 // Copy selections to primary selection buffer
1891 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1892 if local {
1893 let selections = self.selections.all::<usize>(cx);
1894 let buffer_handle = self.buffer.read(cx).read(cx);
1895
1896 let mut text = String::new();
1897 for (index, selection) in selections.iter().enumerate() {
1898 let text_for_selection = buffer_handle
1899 .text_for_range(selection.start..selection.end)
1900 .collect::<String>();
1901
1902 text.push_str(&text_for_selection);
1903 if index != selections.len() - 1 {
1904 text.push('\n');
1905 }
1906 }
1907
1908 if !text.is_empty() {
1909 cx.write_to_primary(ClipboardItem::new_string(text));
1910 }
1911 }
1912
1913 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1914 self.buffer.update(cx, |buffer, cx| {
1915 buffer.set_active_selections(
1916 &self.selections.disjoint_anchors(),
1917 self.selections.line_mode,
1918 self.cursor_shape,
1919 cx,
1920 )
1921 });
1922 }
1923 let display_map = self
1924 .display_map
1925 .update(cx, |display_map, cx| display_map.snapshot(cx));
1926 let buffer = &display_map.buffer_snapshot;
1927 self.add_selections_state = None;
1928 self.select_next_state = None;
1929 self.select_prev_state = None;
1930 self.select_larger_syntax_node_stack.clear();
1931 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1932 self.snippet_stack
1933 .invalidate(&self.selections.disjoint_anchors(), buffer);
1934 self.take_rename(false, cx);
1935
1936 let new_cursor_position = self.selections.newest_anchor().head();
1937
1938 self.push_to_nav_history(
1939 *old_cursor_position,
1940 Some(new_cursor_position.to_point(buffer)),
1941 cx,
1942 );
1943
1944 if local {
1945 let new_cursor_position = self.selections.newest_anchor().head();
1946 let mut context_menu = self.context_menu.borrow_mut();
1947 let completion_menu = match context_menu.as_ref() {
1948 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1949 _ => {
1950 *context_menu = None;
1951 None
1952 }
1953 };
1954
1955 if let Some(completion_menu) = completion_menu {
1956 let cursor_position = new_cursor_position.to_offset(buffer);
1957 let (word_range, kind) =
1958 buffer.surrounding_word(completion_menu.initial_position, true);
1959 if kind == Some(CharKind::Word)
1960 && word_range.to_inclusive().contains(&cursor_position)
1961 {
1962 let mut completion_menu = completion_menu.clone();
1963 drop(context_menu);
1964
1965 let query = Self::completion_query(buffer, cursor_position);
1966 cx.spawn(move |this, mut cx| async move {
1967 completion_menu
1968 .filter(query.as_deref(), cx.background_executor().clone())
1969 .await;
1970
1971 this.update(&mut cx, |this, cx| {
1972 let mut context_menu = this.context_menu.borrow_mut();
1973 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1974 else {
1975 return;
1976 };
1977
1978 if menu.id > completion_menu.id {
1979 return;
1980 }
1981
1982 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1983 drop(context_menu);
1984 cx.notify();
1985 })
1986 })
1987 .detach();
1988
1989 if show_completions {
1990 self.show_completions(&ShowCompletions { trigger: None }, cx);
1991 }
1992 } else {
1993 drop(context_menu);
1994 self.hide_context_menu(cx);
1995 }
1996 } else {
1997 drop(context_menu);
1998 }
1999
2000 hide_hover(self, cx);
2001
2002 if old_cursor_position.to_display_point(&display_map).row()
2003 != new_cursor_position.to_display_point(&display_map).row()
2004 {
2005 self.available_code_actions.take();
2006 }
2007 self.refresh_code_actions(cx);
2008 self.refresh_document_highlights(cx);
2009 refresh_matching_bracket_highlights(self, cx);
2010 self.update_visible_inline_completion(cx);
2011 linked_editing_ranges::refresh_linked_ranges(self, cx);
2012 if self.git_blame_inline_enabled {
2013 self.start_inline_blame_timer(cx);
2014 }
2015 }
2016
2017 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2018 cx.emit(EditorEvent::SelectionsChanged { local });
2019
2020 if self.selections.disjoint_anchors().len() == 1 {
2021 cx.emit(SearchEvent::ActiveMatchChanged)
2022 }
2023 cx.notify();
2024 }
2025
2026 pub fn change_selections<R>(
2027 &mut self,
2028 autoscroll: Option<Autoscroll>,
2029 cx: &mut ViewContext<Self>,
2030 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2031 ) -> R {
2032 self.change_selections_inner(autoscroll, true, cx, change)
2033 }
2034
2035 pub fn change_selections_inner<R>(
2036 &mut self,
2037 autoscroll: Option<Autoscroll>,
2038 request_completions: bool,
2039 cx: &mut ViewContext<Self>,
2040 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2041 ) -> R {
2042 let old_cursor_position = self.selections.newest_anchor().head();
2043 self.push_to_selection_history();
2044
2045 let (changed, result) = self.selections.change_with(cx, change);
2046
2047 if changed {
2048 if let Some(autoscroll) = autoscroll {
2049 self.request_autoscroll(autoscroll, cx);
2050 }
2051 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2052
2053 if self.should_open_signature_help_automatically(
2054 &old_cursor_position,
2055 self.signature_help_state.backspace_pressed(),
2056 cx,
2057 ) {
2058 self.show_signature_help(&ShowSignatureHelp, cx);
2059 }
2060 self.signature_help_state.set_backspace_pressed(false);
2061 }
2062
2063 result
2064 }
2065
2066 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2067 where
2068 I: IntoIterator<Item = (Range<S>, T)>,
2069 S: ToOffset,
2070 T: Into<Arc<str>>,
2071 {
2072 if self.read_only(cx) {
2073 return;
2074 }
2075
2076 self.buffer
2077 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2078 }
2079
2080 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2081 where
2082 I: IntoIterator<Item = (Range<S>, T)>,
2083 S: ToOffset,
2084 T: Into<Arc<str>>,
2085 {
2086 if self.read_only(cx) {
2087 return;
2088 }
2089
2090 self.buffer.update(cx, |buffer, cx| {
2091 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2092 });
2093 }
2094
2095 pub fn edit_with_block_indent<I, S, T>(
2096 &mut self,
2097 edits: I,
2098 original_indent_columns: Vec<u32>,
2099 cx: &mut ViewContext<Self>,
2100 ) where
2101 I: IntoIterator<Item = (Range<S>, T)>,
2102 S: ToOffset,
2103 T: Into<Arc<str>>,
2104 {
2105 if self.read_only(cx) {
2106 return;
2107 }
2108
2109 self.buffer.update(cx, |buffer, cx| {
2110 buffer.edit(
2111 edits,
2112 Some(AutoindentMode::Block {
2113 original_indent_columns,
2114 }),
2115 cx,
2116 )
2117 });
2118 }
2119
2120 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2121 self.hide_context_menu(cx);
2122
2123 match phase {
2124 SelectPhase::Begin {
2125 position,
2126 add,
2127 click_count,
2128 } => self.begin_selection(position, add, click_count, cx),
2129 SelectPhase::BeginColumnar {
2130 position,
2131 goal_column,
2132 reset,
2133 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2134 SelectPhase::Extend {
2135 position,
2136 click_count,
2137 } => self.extend_selection(position, click_count, cx),
2138 SelectPhase::Update {
2139 position,
2140 goal_column,
2141 scroll_delta,
2142 } => self.update_selection(position, goal_column, scroll_delta, cx),
2143 SelectPhase::End => self.end_selection(cx),
2144 }
2145 }
2146
2147 fn extend_selection(
2148 &mut self,
2149 position: DisplayPoint,
2150 click_count: usize,
2151 cx: &mut ViewContext<Self>,
2152 ) {
2153 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2154 let tail = self.selections.newest::<usize>(cx).tail();
2155 self.begin_selection(position, false, click_count, cx);
2156
2157 let position = position.to_offset(&display_map, Bias::Left);
2158 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2159
2160 let mut pending_selection = self
2161 .selections
2162 .pending_anchor()
2163 .expect("extend_selection not called with pending selection");
2164 if position >= tail {
2165 pending_selection.start = tail_anchor;
2166 } else {
2167 pending_selection.end = tail_anchor;
2168 pending_selection.reversed = true;
2169 }
2170
2171 let mut pending_mode = self.selections.pending_mode().unwrap();
2172 match &mut pending_mode {
2173 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2174 _ => {}
2175 }
2176
2177 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2178 s.set_pending(pending_selection, pending_mode)
2179 });
2180 }
2181
2182 fn begin_selection(
2183 &mut self,
2184 position: DisplayPoint,
2185 add: bool,
2186 click_count: usize,
2187 cx: &mut ViewContext<Self>,
2188 ) {
2189 if !self.focus_handle.is_focused(cx) {
2190 self.last_focused_descendant = None;
2191 cx.focus(&self.focus_handle);
2192 }
2193
2194 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2195 let buffer = &display_map.buffer_snapshot;
2196 let newest_selection = self.selections.newest_anchor().clone();
2197 let position = display_map.clip_point(position, Bias::Left);
2198
2199 let start;
2200 let end;
2201 let mode;
2202 let mut auto_scroll;
2203 match click_count {
2204 1 => {
2205 start = buffer.anchor_before(position.to_point(&display_map));
2206 end = start;
2207 mode = SelectMode::Character;
2208 auto_scroll = true;
2209 }
2210 2 => {
2211 let range = movement::surrounding_word(&display_map, position);
2212 start = buffer.anchor_before(range.start.to_point(&display_map));
2213 end = buffer.anchor_before(range.end.to_point(&display_map));
2214 mode = SelectMode::Word(start..end);
2215 auto_scroll = true;
2216 }
2217 3 => {
2218 let position = display_map
2219 .clip_point(position, Bias::Left)
2220 .to_point(&display_map);
2221 let line_start = display_map.prev_line_boundary(position).0;
2222 let next_line_start = buffer.clip_point(
2223 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2224 Bias::Left,
2225 );
2226 start = buffer.anchor_before(line_start);
2227 end = buffer.anchor_before(next_line_start);
2228 mode = SelectMode::Line(start..end);
2229 auto_scroll = true;
2230 }
2231 _ => {
2232 start = buffer.anchor_before(0);
2233 end = buffer.anchor_before(buffer.len());
2234 mode = SelectMode::All;
2235 auto_scroll = false;
2236 }
2237 }
2238 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2239
2240 let point_to_delete: Option<usize> = {
2241 let selected_points: Vec<Selection<Point>> =
2242 self.selections.disjoint_in_range(start..end, cx);
2243
2244 if !add || click_count > 1 {
2245 None
2246 } else if !selected_points.is_empty() {
2247 Some(selected_points[0].id)
2248 } else {
2249 let clicked_point_already_selected =
2250 self.selections.disjoint.iter().find(|selection| {
2251 selection.start.to_point(buffer) == start.to_point(buffer)
2252 || selection.end.to_point(buffer) == end.to_point(buffer)
2253 });
2254
2255 clicked_point_already_selected.map(|selection| selection.id)
2256 }
2257 };
2258
2259 let selections_count = self.selections.count();
2260
2261 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2262 if let Some(point_to_delete) = point_to_delete {
2263 s.delete(point_to_delete);
2264
2265 if selections_count == 1 {
2266 s.set_pending_anchor_range(start..end, mode);
2267 }
2268 } else {
2269 if !add {
2270 s.clear_disjoint();
2271 } else if click_count > 1 {
2272 s.delete(newest_selection.id)
2273 }
2274
2275 s.set_pending_anchor_range(start..end, mode);
2276 }
2277 });
2278 }
2279
2280 fn begin_columnar_selection(
2281 &mut self,
2282 position: DisplayPoint,
2283 goal_column: u32,
2284 reset: bool,
2285 cx: &mut ViewContext<Self>,
2286 ) {
2287 if !self.focus_handle.is_focused(cx) {
2288 self.last_focused_descendant = None;
2289 cx.focus(&self.focus_handle);
2290 }
2291
2292 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2293
2294 if reset {
2295 let pointer_position = display_map
2296 .buffer_snapshot
2297 .anchor_before(position.to_point(&display_map));
2298
2299 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2300 s.clear_disjoint();
2301 s.set_pending_anchor_range(
2302 pointer_position..pointer_position,
2303 SelectMode::Character,
2304 );
2305 });
2306 }
2307
2308 let tail = self.selections.newest::<Point>(cx).tail();
2309 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2310
2311 if !reset {
2312 self.select_columns(
2313 tail.to_display_point(&display_map),
2314 position,
2315 goal_column,
2316 &display_map,
2317 cx,
2318 );
2319 }
2320 }
2321
2322 fn update_selection(
2323 &mut self,
2324 position: DisplayPoint,
2325 goal_column: u32,
2326 scroll_delta: gpui::Point<f32>,
2327 cx: &mut ViewContext<Self>,
2328 ) {
2329 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2330
2331 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2332 let tail = tail.to_display_point(&display_map);
2333 self.select_columns(tail, position, goal_column, &display_map, cx);
2334 } else if let Some(mut pending) = self.selections.pending_anchor() {
2335 let buffer = self.buffer.read(cx).snapshot(cx);
2336 let head;
2337 let tail;
2338 let mode = self.selections.pending_mode().unwrap();
2339 match &mode {
2340 SelectMode::Character => {
2341 head = position.to_point(&display_map);
2342 tail = pending.tail().to_point(&buffer);
2343 }
2344 SelectMode::Word(original_range) => {
2345 let original_display_range = original_range.start.to_display_point(&display_map)
2346 ..original_range.end.to_display_point(&display_map);
2347 let original_buffer_range = original_display_range.start.to_point(&display_map)
2348 ..original_display_range.end.to_point(&display_map);
2349 if movement::is_inside_word(&display_map, position)
2350 || original_display_range.contains(&position)
2351 {
2352 let word_range = movement::surrounding_word(&display_map, position);
2353 if word_range.start < original_display_range.start {
2354 head = word_range.start.to_point(&display_map);
2355 } else {
2356 head = word_range.end.to_point(&display_map);
2357 }
2358 } else {
2359 head = position.to_point(&display_map);
2360 }
2361
2362 if head <= original_buffer_range.start {
2363 tail = original_buffer_range.end;
2364 } else {
2365 tail = original_buffer_range.start;
2366 }
2367 }
2368 SelectMode::Line(original_range) => {
2369 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2370
2371 let position = display_map
2372 .clip_point(position, Bias::Left)
2373 .to_point(&display_map);
2374 let line_start = display_map.prev_line_boundary(position).0;
2375 let next_line_start = buffer.clip_point(
2376 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2377 Bias::Left,
2378 );
2379
2380 if line_start < original_range.start {
2381 head = line_start
2382 } else {
2383 head = next_line_start
2384 }
2385
2386 if head <= original_range.start {
2387 tail = original_range.end;
2388 } else {
2389 tail = original_range.start;
2390 }
2391 }
2392 SelectMode::All => {
2393 return;
2394 }
2395 };
2396
2397 if head < tail {
2398 pending.start = buffer.anchor_before(head);
2399 pending.end = buffer.anchor_before(tail);
2400 pending.reversed = true;
2401 } else {
2402 pending.start = buffer.anchor_before(tail);
2403 pending.end = buffer.anchor_before(head);
2404 pending.reversed = false;
2405 }
2406
2407 self.change_selections(None, cx, |s| {
2408 s.set_pending(pending, mode);
2409 });
2410 } else {
2411 log::error!("update_selection dispatched with no pending selection");
2412 return;
2413 }
2414
2415 self.apply_scroll_delta(scroll_delta, cx);
2416 cx.notify();
2417 }
2418
2419 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2420 self.columnar_selection_tail.take();
2421 if self.selections.pending_anchor().is_some() {
2422 let selections = self.selections.all::<usize>(cx);
2423 self.change_selections(None, cx, |s| {
2424 s.select(selections);
2425 s.clear_pending();
2426 });
2427 }
2428 }
2429
2430 fn select_columns(
2431 &mut self,
2432 tail: DisplayPoint,
2433 head: DisplayPoint,
2434 goal_column: u32,
2435 display_map: &DisplaySnapshot,
2436 cx: &mut ViewContext<Self>,
2437 ) {
2438 let start_row = cmp::min(tail.row(), head.row());
2439 let end_row = cmp::max(tail.row(), head.row());
2440 let start_column = cmp::min(tail.column(), goal_column);
2441 let end_column = cmp::max(tail.column(), goal_column);
2442 let reversed = start_column < tail.column();
2443
2444 let selection_ranges = (start_row.0..=end_row.0)
2445 .map(DisplayRow)
2446 .filter_map(|row| {
2447 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2448 let start = display_map
2449 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2450 .to_point(display_map);
2451 let end = display_map
2452 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2453 .to_point(display_map);
2454 if reversed {
2455 Some(end..start)
2456 } else {
2457 Some(start..end)
2458 }
2459 } else {
2460 None
2461 }
2462 })
2463 .collect::<Vec<_>>();
2464
2465 self.change_selections(None, cx, |s| {
2466 s.select_ranges(selection_ranges);
2467 });
2468 cx.notify();
2469 }
2470
2471 pub fn has_pending_nonempty_selection(&self) -> bool {
2472 let pending_nonempty_selection = match self.selections.pending_anchor() {
2473 Some(Selection { start, end, .. }) => start != end,
2474 None => false,
2475 };
2476
2477 pending_nonempty_selection
2478 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2479 }
2480
2481 pub fn has_pending_selection(&self) -> bool {
2482 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2483 }
2484
2485 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2486 self.selection_mark_mode = false;
2487
2488 if self.clear_expanded_diff_hunks(cx) {
2489 cx.notify();
2490 return;
2491 }
2492 if self.dismiss_menus_and_popups(true, cx) {
2493 return;
2494 }
2495
2496 if self.mode == EditorMode::Full
2497 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2498 {
2499 return;
2500 }
2501
2502 cx.propagate();
2503 }
2504
2505 pub fn dismiss_menus_and_popups(
2506 &mut self,
2507 should_report_inline_completion_event: bool,
2508 cx: &mut ViewContext<Self>,
2509 ) -> bool {
2510 if self.take_rename(false, cx).is_some() {
2511 return true;
2512 }
2513
2514 if hide_hover(self, cx) {
2515 return true;
2516 }
2517
2518 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2519 return true;
2520 }
2521
2522 if self.hide_context_menu(cx).is_some() {
2523 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2524 self.update_visible_inline_completion(cx);
2525 }
2526 return true;
2527 }
2528
2529 if self.mouse_context_menu.take().is_some() {
2530 return true;
2531 }
2532
2533 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2534 return true;
2535 }
2536
2537 if self.snippet_stack.pop().is_some() {
2538 return true;
2539 }
2540
2541 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2542 self.dismiss_diagnostics(cx);
2543 return true;
2544 }
2545
2546 false
2547 }
2548
2549 fn linked_editing_ranges_for(
2550 &self,
2551 selection: Range<text::Anchor>,
2552 cx: &AppContext,
2553 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2554 if self.linked_edit_ranges.is_empty() {
2555 return None;
2556 }
2557 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2558 selection.end.buffer_id.and_then(|end_buffer_id| {
2559 if selection.start.buffer_id != Some(end_buffer_id) {
2560 return None;
2561 }
2562 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2563 let snapshot = buffer.read(cx).snapshot();
2564 self.linked_edit_ranges
2565 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2566 .map(|ranges| (ranges, snapshot, buffer))
2567 })?;
2568 use text::ToOffset as TO;
2569 // find offset from the start of current range to current cursor position
2570 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2571
2572 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2573 let start_difference = start_offset - start_byte_offset;
2574 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2575 let end_difference = end_offset - start_byte_offset;
2576 // Current range has associated linked ranges.
2577 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2578 for range in linked_ranges.iter() {
2579 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2580 let end_offset = start_offset + end_difference;
2581 let start_offset = start_offset + start_difference;
2582 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2583 continue;
2584 }
2585 if self.selections.disjoint_anchor_ranges().any(|s| {
2586 if s.start.buffer_id != selection.start.buffer_id
2587 || s.end.buffer_id != selection.end.buffer_id
2588 {
2589 return false;
2590 }
2591 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2592 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2593 }) {
2594 continue;
2595 }
2596 let start = buffer_snapshot.anchor_after(start_offset);
2597 let end = buffer_snapshot.anchor_after(end_offset);
2598 linked_edits
2599 .entry(buffer.clone())
2600 .or_default()
2601 .push(start..end);
2602 }
2603 Some(linked_edits)
2604 }
2605
2606 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2607 let text: Arc<str> = text.into();
2608
2609 if self.read_only(cx) {
2610 return;
2611 }
2612
2613 let selections = self.selections.all_adjusted(cx);
2614 let mut bracket_inserted = false;
2615 let mut edits = Vec::new();
2616 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2617 let mut new_selections = Vec::with_capacity(selections.len());
2618 let mut new_autoclose_regions = Vec::new();
2619 let snapshot = self.buffer.read(cx).read(cx);
2620
2621 for (selection, autoclose_region) in
2622 self.selections_with_autoclose_regions(selections, &snapshot)
2623 {
2624 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2625 // Determine if the inserted text matches the opening or closing
2626 // bracket of any of this language's bracket pairs.
2627 let mut bracket_pair = None;
2628 let mut is_bracket_pair_start = false;
2629 let mut is_bracket_pair_end = false;
2630 if !text.is_empty() {
2631 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2632 // and they are removing the character that triggered IME popup.
2633 for (pair, enabled) in scope.brackets() {
2634 if !pair.close && !pair.surround {
2635 continue;
2636 }
2637
2638 if enabled && pair.start.ends_with(text.as_ref()) {
2639 let prefix_len = pair.start.len() - text.len();
2640 let preceding_text_matches_prefix = prefix_len == 0
2641 || (selection.start.column >= (prefix_len as u32)
2642 && snapshot.contains_str_at(
2643 Point::new(
2644 selection.start.row,
2645 selection.start.column - (prefix_len as u32),
2646 ),
2647 &pair.start[..prefix_len],
2648 ));
2649 if preceding_text_matches_prefix {
2650 bracket_pair = Some(pair.clone());
2651 is_bracket_pair_start = true;
2652 break;
2653 }
2654 }
2655 if pair.end.as_str() == text.as_ref() {
2656 bracket_pair = Some(pair.clone());
2657 is_bracket_pair_end = true;
2658 break;
2659 }
2660 }
2661 }
2662
2663 if let Some(bracket_pair) = bracket_pair {
2664 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2665 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2666 let auto_surround =
2667 self.use_auto_surround && snapshot_settings.use_auto_surround;
2668 if selection.is_empty() {
2669 if is_bracket_pair_start {
2670 // If the inserted text is a suffix of an opening bracket and the
2671 // selection is preceded by the rest of the opening bracket, then
2672 // insert the closing bracket.
2673 let following_text_allows_autoclose = snapshot
2674 .chars_at(selection.start)
2675 .next()
2676 .map_or(true, |c| scope.should_autoclose_before(c));
2677
2678 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2679 && bracket_pair.start.len() == 1
2680 {
2681 let target = bracket_pair.start.chars().next().unwrap();
2682 let current_line_count = snapshot
2683 .reversed_chars_at(selection.start)
2684 .take_while(|&c| c != '\n')
2685 .filter(|&c| c == target)
2686 .count();
2687 current_line_count % 2 == 1
2688 } else {
2689 false
2690 };
2691
2692 if autoclose
2693 && bracket_pair.close
2694 && following_text_allows_autoclose
2695 && !is_closing_quote
2696 {
2697 let anchor = snapshot.anchor_before(selection.end);
2698 new_selections.push((selection.map(|_| anchor), text.len()));
2699 new_autoclose_regions.push((
2700 anchor,
2701 text.len(),
2702 selection.id,
2703 bracket_pair.clone(),
2704 ));
2705 edits.push((
2706 selection.range(),
2707 format!("{}{}", text, bracket_pair.end).into(),
2708 ));
2709 bracket_inserted = true;
2710 continue;
2711 }
2712 }
2713
2714 if let Some(region) = autoclose_region {
2715 // If the selection is followed by an auto-inserted closing bracket,
2716 // then don't insert that closing bracket again; just move the selection
2717 // past the closing bracket.
2718 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2719 && text.as_ref() == region.pair.end.as_str();
2720 if should_skip {
2721 let anchor = snapshot.anchor_after(selection.end);
2722 new_selections
2723 .push((selection.map(|_| anchor), region.pair.end.len()));
2724 continue;
2725 }
2726 }
2727
2728 let always_treat_brackets_as_autoclosed = snapshot
2729 .settings_at(selection.start, cx)
2730 .always_treat_brackets_as_autoclosed;
2731 if always_treat_brackets_as_autoclosed
2732 && is_bracket_pair_end
2733 && snapshot.contains_str_at(selection.end, text.as_ref())
2734 {
2735 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2736 // and the inserted text is a closing bracket and the selection is followed
2737 // by the closing bracket then move the selection past the closing bracket.
2738 let anchor = snapshot.anchor_after(selection.end);
2739 new_selections.push((selection.map(|_| anchor), text.len()));
2740 continue;
2741 }
2742 }
2743 // If an opening bracket is 1 character long and is typed while
2744 // text is selected, then surround that text with the bracket pair.
2745 else if auto_surround
2746 && bracket_pair.surround
2747 && is_bracket_pair_start
2748 && bracket_pair.start.chars().count() == 1
2749 {
2750 edits.push((selection.start..selection.start, text.clone()));
2751 edits.push((
2752 selection.end..selection.end,
2753 bracket_pair.end.as_str().into(),
2754 ));
2755 bracket_inserted = true;
2756 new_selections.push((
2757 Selection {
2758 id: selection.id,
2759 start: snapshot.anchor_after(selection.start),
2760 end: snapshot.anchor_before(selection.end),
2761 reversed: selection.reversed,
2762 goal: selection.goal,
2763 },
2764 0,
2765 ));
2766 continue;
2767 }
2768 }
2769 }
2770
2771 if self.auto_replace_emoji_shortcode
2772 && selection.is_empty()
2773 && text.as_ref().ends_with(':')
2774 {
2775 if let Some(possible_emoji_short_code) =
2776 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2777 {
2778 if !possible_emoji_short_code.is_empty() {
2779 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2780 let emoji_shortcode_start = Point::new(
2781 selection.start.row,
2782 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2783 );
2784
2785 // Remove shortcode from buffer
2786 edits.push((
2787 emoji_shortcode_start..selection.start,
2788 "".to_string().into(),
2789 ));
2790 new_selections.push((
2791 Selection {
2792 id: selection.id,
2793 start: snapshot.anchor_after(emoji_shortcode_start),
2794 end: snapshot.anchor_before(selection.start),
2795 reversed: selection.reversed,
2796 goal: selection.goal,
2797 },
2798 0,
2799 ));
2800
2801 // Insert emoji
2802 let selection_start_anchor = snapshot.anchor_after(selection.start);
2803 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2804 edits.push((selection.start..selection.end, emoji.to_string().into()));
2805
2806 continue;
2807 }
2808 }
2809 }
2810 }
2811
2812 // If not handling any auto-close operation, then just replace the selected
2813 // text with the given input and move the selection to the end of the
2814 // newly inserted text.
2815 let anchor = snapshot.anchor_after(selection.end);
2816 if !self.linked_edit_ranges.is_empty() {
2817 let start_anchor = snapshot.anchor_before(selection.start);
2818
2819 let is_word_char = text.chars().next().map_or(true, |char| {
2820 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2821 classifier.is_word(char)
2822 });
2823
2824 if is_word_char {
2825 if let Some(ranges) = self
2826 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2827 {
2828 for (buffer, edits) in ranges {
2829 linked_edits
2830 .entry(buffer.clone())
2831 .or_default()
2832 .extend(edits.into_iter().map(|range| (range, text.clone())));
2833 }
2834 }
2835 }
2836 }
2837
2838 new_selections.push((selection.map(|_| anchor), 0));
2839 edits.push((selection.start..selection.end, text.clone()));
2840 }
2841
2842 drop(snapshot);
2843
2844 self.transact(cx, |this, cx| {
2845 this.buffer.update(cx, |buffer, cx| {
2846 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2847 });
2848 for (buffer, edits) in linked_edits {
2849 buffer.update(cx, |buffer, cx| {
2850 let snapshot = buffer.snapshot();
2851 let edits = edits
2852 .into_iter()
2853 .map(|(range, text)| {
2854 use text::ToPoint as TP;
2855 let end_point = TP::to_point(&range.end, &snapshot);
2856 let start_point = TP::to_point(&range.start, &snapshot);
2857 (start_point..end_point, text)
2858 })
2859 .sorted_by_key(|(range, _)| range.start)
2860 .collect::<Vec<_>>();
2861 buffer.edit(edits, None, cx);
2862 })
2863 }
2864 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2865 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2866 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2867 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2868 .zip(new_selection_deltas)
2869 .map(|(selection, delta)| Selection {
2870 id: selection.id,
2871 start: selection.start + delta,
2872 end: selection.end + delta,
2873 reversed: selection.reversed,
2874 goal: SelectionGoal::None,
2875 })
2876 .collect::<Vec<_>>();
2877
2878 let mut i = 0;
2879 for (position, delta, selection_id, pair) in new_autoclose_regions {
2880 let position = position.to_offset(&map.buffer_snapshot) + delta;
2881 let start = map.buffer_snapshot.anchor_before(position);
2882 let end = map.buffer_snapshot.anchor_after(position);
2883 while let Some(existing_state) = this.autoclose_regions.get(i) {
2884 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2885 Ordering::Less => i += 1,
2886 Ordering::Greater => break,
2887 Ordering::Equal => {
2888 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2889 Ordering::Less => i += 1,
2890 Ordering::Equal => break,
2891 Ordering::Greater => break,
2892 }
2893 }
2894 }
2895 }
2896 this.autoclose_regions.insert(
2897 i,
2898 AutocloseRegion {
2899 selection_id,
2900 range: start..end,
2901 pair,
2902 },
2903 );
2904 }
2905
2906 let had_active_inline_completion = this.has_active_inline_completion();
2907 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2908 s.select(new_selections)
2909 });
2910
2911 if !bracket_inserted {
2912 if let Some(on_type_format_task) =
2913 this.trigger_on_type_formatting(text.to_string(), cx)
2914 {
2915 on_type_format_task.detach_and_log_err(cx);
2916 }
2917 }
2918
2919 let editor_settings = EditorSettings::get_global(cx);
2920 if bracket_inserted
2921 && (editor_settings.auto_signature_help
2922 || editor_settings.show_signature_help_after_edits)
2923 {
2924 this.show_signature_help(&ShowSignatureHelp, cx);
2925 }
2926
2927 let trigger_in_words =
2928 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2929 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2930 linked_editing_ranges::refresh_linked_ranges(this, cx);
2931 this.refresh_inline_completion(true, false, cx);
2932 });
2933 }
2934
2935 fn find_possible_emoji_shortcode_at_position(
2936 snapshot: &MultiBufferSnapshot,
2937 position: Point,
2938 ) -> Option<String> {
2939 let mut chars = Vec::new();
2940 let mut found_colon = false;
2941 for char in snapshot.reversed_chars_at(position).take(100) {
2942 // Found a possible emoji shortcode in the middle of the buffer
2943 if found_colon {
2944 if char.is_whitespace() {
2945 chars.reverse();
2946 return Some(chars.iter().collect());
2947 }
2948 // If the previous character is not a whitespace, we are in the middle of a word
2949 // and we only want to complete the shortcode if the word is made up of other emojis
2950 let mut containing_word = String::new();
2951 for ch in snapshot
2952 .reversed_chars_at(position)
2953 .skip(chars.len() + 1)
2954 .take(100)
2955 {
2956 if ch.is_whitespace() {
2957 break;
2958 }
2959 containing_word.push(ch);
2960 }
2961 let containing_word = containing_word.chars().rev().collect::<String>();
2962 if util::word_consists_of_emojis(containing_word.as_str()) {
2963 chars.reverse();
2964 return Some(chars.iter().collect());
2965 }
2966 }
2967
2968 if char.is_whitespace() || !char.is_ascii() {
2969 return None;
2970 }
2971 if char == ':' {
2972 found_colon = true;
2973 } else {
2974 chars.push(char);
2975 }
2976 }
2977 // Found a possible emoji shortcode at the beginning of the buffer
2978 chars.reverse();
2979 Some(chars.iter().collect())
2980 }
2981
2982 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2983 self.transact(cx, |this, cx| {
2984 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2985 let selections = this.selections.all::<usize>(cx);
2986 let multi_buffer = this.buffer.read(cx);
2987 let buffer = multi_buffer.snapshot(cx);
2988 selections
2989 .iter()
2990 .map(|selection| {
2991 let start_point = selection.start.to_point(&buffer);
2992 let mut indent =
2993 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2994 indent.len = cmp::min(indent.len, start_point.column);
2995 let start = selection.start;
2996 let end = selection.end;
2997 let selection_is_empty = start == end;
2998 let language_scope = buffer.language_scope_at(start);
2999 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3000 &language_scope
3001 {
3002 let leading_whitespace_len = buffer
3003 .reversed_chars_at(start)
3004 .take_while(|c| c.is_whitespace() && *c != '\n')
3005 .map(|c| c.len_utf8())
3006 .sum::<usize>();
3007
3008 let trailing_whitespace_len = buffer
3009 .chars_at(end)
3010 .take_while(|c| c.is_whitespace() && *c != '\n')
3011 .map(|c| c.len_utf8())
3012 .sum::<usize>();
3013
3014 let insert_extra_newline =
3015 language.brackets().any(|(pair, enabled)| {
3016 let pair_start = pair.start.trim_end();
3017 let pair_end = pair.end.trim_start();
3018
3019 enabled
3020 && pair.newline
3021 && buffer.contains_str_at(
3022 end + trailing_whitespace_len,
3023 pair_end,
3024 )
3025 && buffer.contains_str_at(
3026 (start - leading_whitespace_len)
3027 .saturating_sub(pair_start.len()),
3028 pair_start,
3029 )
3030 });
3031
3032 // Comment extension on newline is allowed only for cursor selections
3033 let comment_delimiter = maybe!({
3034 if !selection_is_empty {
3035 return None;
3036 }
3037
3038 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3039 return None;
3040 }
3041
3042 let delimiters = language.line_comment_prefixes();
3043 let max_len_of_delimiter =
3044 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3045 let (snapshot, range) =
3046 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3047
3048 let mut index_of_first_non_whitespace = 0;
3049 let comment_candidate = snapshot
3050 .chars_for_range(range)
3051 .skip_while(|c| {
3052 let should_skip = c.is_whitespace();
3053 if should_skip {
3054 index_of_first_non_whitespace += 1;
3055 }
3056 should_skip
3057 })
3058 .take(max_len_of_delimiter)
3059 .collect::<String>();
3060 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3061 comment_candidate.starts_with(comment_prefix.as_ref())
3062 })?;
3063 let cursor_is_placed_after_comment_marker =
3064 index_of_first_non_whitespace + comment_prefix.len()
3065 <= start_point.column as usize;
3066 if cursor_is_placed_after_comment_marker {
3067 Some(comment_prefix.clone())
3068 } else {
3069 None
3070 }
3071 });
3072 (comment_delimiter, insert_extra_newline)
3073 } else {
3074 (None, false)
3075 };
3076
3077 let capacity_for_delimiter = comment_delimiter
3078 .as_deref()
3079 .map(str::len)
3080 .unwrap_or_default();
3081 let mut new_text =
3082 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3083 new_text.push('\n');
3084 new_text.extend(indent.chars());
3085 if let Some(delimiter) = &comment_delimiter {
3086 new_text.push_str(delimiter);
3087 }
3088 if insert_extra_newline {
3089 new_text = new_text.repeat(2);
3090 }
3091
3092 let anchor = buffer.anchor_after(end);
3093 let new_selection = selection.map(|_| anchor);
3094 (
3095 (start..end, new_text),
3096 (insert_extra_newline, new_selection),
3097 )
3098 })
3099 .unzip()
3100 };
3101
3102 this.edit_with_autoindent(edits, cx);
3103 let buffer = this.buffer.read(cx).snapshot(cx);
3104 let new_selections = selection_fixup_info
3105 .into_iter()
3106 .map(|(extra_newline_inserted, new_selection)| {
3107 let mut cursor = new_selection.end.to_point(&buffer);
3108 if extra_newline_inserted {
3109 cursor.row -= 1;
3110 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3111 }
3112 new_selection.map(|_| cursor)
3113 })
3114 .collect();
3115
3116 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3117 this.refresh_inline_completion(true, false, cx);
3118 });
3119 }
3120
3121 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3122 let buffer = self.buffer.read(cx);
3123 let snapshot = buffer.snapshot(cx);
3124
3125 let mut edits = Vec::new();
3126 let mut rows = Vec::new();
3127
3128 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3129 let cursor = selection.head();
3130 let row = cursor.row;
3131
3132 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3133
3134 let newline = "\n".to_string();
3135 edits.push((start_of_line..start_of_line, newline));
3136
3137 rows.push(row + rows_inserted as u32);
3138 }
3139
3140 self.transact(cx, |editor, cx| {
3141 editor.edit(edits, cx);
3142
3143 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3144 let mut index = 0;
3145 s.move_cursors_with(|map, _, _| {
3146 let row = rows[index];
3147 index += 1;
3148
3149 let point = Point::new(row, 0);
3150 let boundary = map.next_line_boundary(point).1;
3151 let clipped = map.clip_point(boundary, Bias::Left);
3152
3153 (clipped, SelectionGoal::None)
3154 });
3155 });
3156
3157 let mut indent_edits = Vec::new();
3158 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3159 for row in rows {
3160 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3161 for (row, indent) in indents {
3162 if indent.len == 0 {
3163 continue;
3164 }
3165
3166 let text = match indent.kind {
3167 IndentKind::Space => " ".repeat(indent.len as usize),
3168 IndentKind::Tab => "\t".repeat(indent.len as usize),
3169 };
3170 let point = Point::new(row.0, 0);
3171 indent_edits.push((point..point, text));
3172 }
3173 }
3174 editor.edit(indent_edits, cx);
3175 });
3176 }
3177
3178 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3179 let buffer = self.buffer.read(cx);
3180 let snapshot = buffer.snapshot(cx);
3181
3182 let mut edits = Vec::new();
3183 let mut rows = Vec::new();
3184 let mut rows_inserted = 0;
3185
3186 for selection in self.selections.all_adjusted(cx) {
3187 let cursor = selection.head();
3188 let row = cursor.row;
3189
3190 let point = Point::new(row + 1, 0);
3191 let start_of_line = snapshot.clip_point(point, Bias::Left);
3192
3193 let newline = "\n".to_string();
3194 edits.push((start_of_line..start_of_line, newline));
3195
3196 rows_inserted += 1;
3197 rows.push(row + rows_inserted);
3198 }
3199
3200 self.transact(cx, |editor, cx| {
3201 editor.edit(edits, cx);
3202
3203 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3204 let mut index = 0;
3205 s.move_cursors_with(|map, _, _| {
3206 let row = rows[index];
3207 index += 1;
3208
3209 let point = Point::new(row, 0);
3210 let boundary = map.next_line_boundary(point).1;
3211 let clipped = map.clip_point(boundary, Bias::Left);
3212
3213 (clipped, SelectionGoal::None)
3214 });
3215 });
3216
3217 let mut indent_edits = Vec::new();
3218 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3219 for row in rows {
3220 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3221 for (row, indent) in indents {
3222 if indent.len == 0 {
3223 continue;
3224 }
3225
3226 let text = match indent.kind {
3227 IndentKind::Space => " ".repeat(indent.len as usize),
3228 IndentKind::Tab => "\t".repeat(indent.len as usize),
3229 };
3230 let point = Point::new(row.0, 0);
3231 indent_edits.push((point..point, text));
3232 }
3233 }
3234 editor.edit(indent_edits, cx);
3235 });
3236 }
3237
3238 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3239 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3240 original_indent_columns: Vec::new(),
3241 });
3242 self.insert_with_autoindent_mode(text, autoindent, cx);
3243 }
3244
3245 fn insert_with_autoindent_mode(
3246 &mut self,
3247 text: &str,
3248 autoindent_mode: Option<AutoindentMode>,
3249 cx: &mut ViewContext<Self>,
3250 ) {
3251 if self.read_only(cx) {
3252 return;
3253 }
3254
3255 let text: Arc<str> = text.into();
3256 self.transact(cx, |this, cx| {
3257 let old_selections = this.selections.all_adjusted(cx);
3258 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3259 let anchors = {
3260 let snapshot = buffer.read(cx);
3261 old_selections
3262 .iter()
3263 .map(|s| {
3264 let anchor = snapshot.anchor_after(s.head());
3265 s.map(|_| anchor)
3266 })
3267 .collect::<Vec<_>>()
3268 };
3269 buffer.edit(
3270 old_selections
3271 .iter()
3272 .map(|s| (s.start..s.end, text.clone())),
3273 autoindent_mode,
3274 cx,
3275 );
3276 anchors
3277 });
3278
3279 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3280 s.select_anchors(selection_anchors);
3281 })
3282 });
3283 }
3284
3285 fn trigger_completion_on_input(
3286 &mut self,
3287 text: &str,
3288 trigger_in_words: bool,
3289 cx: &mut ViewContext<Self>,
3290 ) {
3291 if self.is_completion_trigger(text, trigger_in_words, cx) {
3292 self.show_completions(
3293 &ShowCompletions {
3294 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3295 },
3296 cx,
3297 );
3298 } else {
3299 self.hide_context_menu(cx);
3300 }
3301 }
3302
3303 fn is_completion_trigger(
3304 &self,
3305 text: &str,
3306 trigger_in_words: bool,
3307 cx: &mut ViewContext<Self>,
3308 ) -> bool {
3309 let position = self.selections.newest_anchor().head();
3310 let multibuffer = self.buffer.read(cx);
3311 let Some(buffer) = position
3312 .buffer_id
3313 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3314 else {
3315 return false;
3316 };
3317
3318 if let Some(completion_provider) = &self.completion_provider {
3319 completion_provider.is_completion_trigger(
3320 &buffer,
3321 position.text_anchor,
3322 text,
3323 trigger_in_words,
3324 cx,
3325 )
3326 } else {
3327 false
3328 }
3329 }
3330
3331 /// If any empty selections is touching the start of its innermost containing autoclose
3332 /// region, expand it to select the brackets.
3333 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3334 let selections = self.selections.all::<usize>(cx);
3335 let buffer = self.buffer.read(cx).read(cx);
3336 let new_selections = self
3337 .selections_with_autoclose_regions(selections, &buffer)
3338 .map(|(mut selection, region)| {
3339 if !selection.is_empty() {
3340 return selection;
3341 }
3342
3343 if let Some(region) = region {
3344 let mut range = region.range.to_offset(&buffer);
3345 if selection.start == range.start && range.start >= region.pair.start.len() {
3346 range.start -= region.pair.start.len();
3347 if buffer.contains_str_at(range.start, ®ion.pair.start)
3348 && buffer.contains_str_at(range.end, ®ion.pair.end)
3349 {
3350 range.end += region.pair.end.len();
3351 selection.start = range.start;
3352 selection.end = range.end;
3353
3354 return selection;
3355 }
3356 }
3357 }
3358
3359 let always_treat_brackets_as_autoclosed = buffer
3360 .settings_at(selection.start, cx)
3361 .always_treat_brackets_as_autoclosed;
3362
3363 if !always_treat_brackets_as_autoclosed {
3364 return selection;
3365 }
3366
3367 if let Some(scope) = buffer.language_scope_at(selection.start) {
3368 for (pair, enabled) in scope.brackets() {
3369 if !enabled || !pair.close {
3370 continue;
3371 }
3372
3373 if buffer.contains_str_at(selection.start, &pair.end) {
3374 let pair_start_len = pair.start.len();
3375 if buffer.contains_str_at(
3376 selection.start.saturating_sub(pair_start_len),
3377 &pair.start,
3378 ) {
3379 selection.start -= pair_start_len;
3380 selection.end += pair.end.len();
3381
3382 return selection;
3383 }
3384 }
3385 }
3386 }
3387
3388 selection
3389 })
3390 .collect();
3391
3392 drop(buffer);
3393 self.change_selections(None, cx, |selections| selections.select(new_selections));
3394 }
3395
3396 /// Iterate the given selections, and for each one, find the smallest surrounding
3397 /// autoclose region. This uses the ordering of the selections and the autoclose
3398 /// regions to avoid repeated comparisons.
3399 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3400 &'a self,
3401 selections: impl IntoIterator<Item = Selection<D>>,
3402 buffer: &'a MultiBufferSnapshot,
3403 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3404 let mut i = 0;
3405 let mut regions = self.autoclose_regions.as_slice();
3406 selections.into_iter().map(move |selection| {
3407 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3408
3409 let mut enclosing = None;
3410 while let Some(pair_state) = regions.get(i) {
3411 if pair_state.range.end.to_offset(buffer) < range.start {
3412 regions = ®ions[i + 1..];
3413 i = 0;
3414 } else if pair_state.range.start.to_offset(buffer) > range.end {
3415 break;
3416 } else {
3417 if pair_state.selection_id == selection.id {
3418 enclosing = Some(pair_state);
3419 }
3420 i += 1;
3421 }
3422 }
3423
3424 (selection, enclosing)
3425 })
3426 }
3427
3428 /// Remove any autoclose regions that no longer contain their selection.
3429 fn invalidate_autoclose_regions(
3430 &mut self,
3431 mut selections: &[Selection<Anchor>],
3432 buffer: &MultiBufferSnapshot,
3433 ) {
3434 self.autoclose_regions.retain(|state| {
3435 let mut i = 0;
3436 while let Some(selection) = selections.get(i) {
3437 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3438 selections = &selections[1..];
3439 continue;
3440 }
3441 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3442 break;
3443 }
3444 if selection.id == state.selection_id {
3445 return true;
3446 } else {
3447 i += 1;
3448 }
3449 }
3450 false
3451 });
3452 }
3453
3454 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3455 let offset = position.to_offset(buffer);
3456 let (word_range, kind) = buffer.surrounding_word(offset, true);
3457 if offset > word_range.start && kind == Some(CharKind::Word) {
3458 Some(
3459 buffer
3460 .text_for_range(word_range.start..offset)
3461 .collect::<String>(),
3462 )
3463 } else {
3464 None
3465 }
3466 }
3467
3468 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3469 self.refresh_inlay_hints(
3470 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3471 cx,
3472 );
3473 }
3474
3475 pub fn inlay_hints_enabled(&self) -> bool {
3476 self.inlay_hint_cache.enabled
3477 }
3478
3479 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3480 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3481 return;
3482 }
3483
3484 let reason_description = reason.description();
3485 let ignore_debounce = matches!(
3486 reason,
3487 InlayHintRefreshReason::SettingsChange(_)
3488 | InlayHintRefreshReason::Toggle(_)
3489 | InlayHintRefreshReason::ExcerptsRemoved(_)
3490 );
3491 let (invalidate_cache, required_languages) = match reason {
3492 InlayHintRefreshReason::Toggle(enabled) => {
3493 self.inlay_hint_cache.enabled = enabled;
3494 if enabled {
3495 (InvalidationStrategy::RefreshRequested, None)
3496 } else {
3497 self.inlay_hint_cache.clear();
3498 self.splice_inlays(
3499 self.visible_inlay_hints(cx)
3500 .iter()
3501 .map(|inlay| inlay.id)
3502 .collect(),
3503 Vec::new(),
3504 cx,
3505 );
3506 return;
3507 }
3508 }
3509 InlayHintRefreshReason::SettingsChange(new_settings) => {
3510 match self.inlay_hint_cache.update_settings(
3511 &self.buffer,
3512 new_settings,
3513 self.visible_inlay_hints(cx),
3514 cx,
3515 ) {
3516 ControlFlow::Break(Some(InlaySplice {
3517 to_remove,
3518 to_insert,
3519 })) => {
3520 self.splice_inlays(to_remove, to_insert, cx);
3521 return;
3522 }
3523 ControlFlow::Break(None) => return,
3524 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3525 }
3526 }
3527 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3528 if let Some(InlaySplice {
3529 to_remove,
3530 to_insert,
3531 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3532 {
3533 self.splice_inlays(to_remove, to_insert, cx);
3534 }
3535 return;
3536 }
3537 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3538 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3539 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3540 }
3541 InlayHintRefreshReason::RefreshRequested => {
3542 (InvalidationStrategy::RefreshRequested, None)
3543 }
3544 };
3545
3546 if let Some(InlaySplice {
3547 to_remove,
3548 to_insert,
3549 }) = self.inlay_hint_cache.spawn_hint_refresh(
3550 reason_description,
3551 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3552 invalidate_cache,
3553 ignore_debounce,
3554 cx,
3555 ) {
3556 self.splice_inlays(to_remove, to_insert, cx);
3557 }
3558 }
3559
3560 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3561 self.display_map
3562 .read(cx)
3563 .current_inlays()
3564 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3565 .cloned()
3566 .collect()
3567 }
3568
3569 pub fn excerpts_for_inlay_hints_query(
3570 &self,
3571 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3572 cx: &mut ViewContext<Editor>,
3573 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3574 let Some(project) = self.project.as_ref() else {
3575 return HashMap::default();
3576 };
3577 let project = project.read(cx);
3578 let multi_buffer = self.buffer().read(cx);
3579 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3580 let multi_buffer_visible_start = self
3581 .scroll_manager
3582 .anchor()
3583 .anchor
3584 .to_point(&multi_buffer_snapshot);
3585 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3586 multi_buffer_visible_start
3587 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3588 Bias::Left,
3589 );
3590 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3591 multi_buffer_snapshot
3592 .range_to_buffer_ranges(multi_buffer_visible_range)
3593 .into_iter()
3594 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3595 .filter_map(|(excerpt, excerpt_visible_range)| {
3596 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3597 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3598 let worktree_entry = buffer_worktree
3599 .read(cx)
3600 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3601 if worktree_entry.is_ignored {
3602 return None;
3603 }
3604
3605 let language = excerpt.buffer().language()?;
3606 if let Some(restrict_to_languages) = restrict_to_languages {
3607 if !restrict_to_languages.contains(language) {
3608 return None;
3609 }
3610 }
3611 Some((
3612 excerpt.id(),
3613 (
3614 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3615 excerpt.buffer().version().clone(),
3616 excerpt_visible_range,
3617 ),
3618 ))
3619 })
3620 .collect()
3621 }
3622
3623 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3624 TextLayoutDetails {
3625 text_system: cx.text_system().clone(),
3626 editor_style: self.style.clone().unwrap(),
3627 rem_size: cx.rem_size(),
3628 scroll_anchor: self.scroll_manager.anchor(),
3629 visible_rows: self.visible_line_count(),
3630 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3631 }
3632 }
3633
3634 pub fn splice_inlays(
3635 &self,
3636 to_remove: Vec<InlayId>,
3637 to_insert: Vec<Inlay>,
3638 cx: &mut ViewContext<Self>,
3639 ) {
3640 self.display_map.update(cx, |display_map, cx| {
3641 display_map.splice_inlays(to_remove, to_insert, cx)
3642 });
3643 cx.notify();
3644 }
3645
3646 fn trigger_on_type_formatting(
3647 &self,
3648 input: String,
3649 cx: &mut ViewContext<Self>,
3650 ) -> Option<Task<Result<()>>> {
3651 if input.len() != 1 {
3652 return None;
3653 }
3654
3655 let project = self.project.as_ref()?;
3656 let position = self.selections.newest_anchor().head();
3657 let (buffer, buffer_position) = self
3658 .buffer
3659 .read(cx)
3660 .text_anchor_for_position(position, cx)?;
3661
3662 let settings = language_settings::language_settings(
3663 buffer
3664 .read(cx)
3665 .language_at(buffer_position)
3666 .map(|l| l.name()),
3667 buffer.read(cx).file(),
3668 cx,
3669 );
3670 if !settings.use_on_type_format {
3671 return None;
3672 }
3673
3674 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3675 // hence we do LSP request & edit on host side only — add formats to host's history.
3676 let push_to_lsp_host_history = true;
3677 // If this is not the host, append its history with new edits.
3678 let push_to_client_history = project.read(cx).is_via_collab();
3679
3680 let on_type_formatting = project.update(cx, |project, cx| {
3681 project.on_type_format(
3682 buffer.clone(),
3683 buffer_position,
3684 input,
3685 push_to_lsp_host_history,
3686 cx,
3687 )
3688 });
3689 Some(cx.spawn(|editor, mut cx| async move {
3690 if let Some(transaction) = on_type_formatting.await? {
3691 if push_to_client_history {
3692 buffer
3693 .update(&mut cx, |buffer, _| {
3694 buffer.push_transaction(transaction, Instant::now());
3695 })
3696 .ok();
3697 }
3698 editor.update(&mut cx, |editor, cx| {
3699 editor.refresh_document_highlights(cx);
3700 })?;
3701 }
3702 Ok(())
3703 }))
3704 }
3705
3706 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3707 if self.pending_rename.is_some() {
3708 return;
3709 }
3710
3711 let Some(provider) = self.completion_provider.as_ref() else {
3712 return;
3713 };
3714
3715 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3716 return;
3717 }
3718
3719 let position = self.selections.newest_anchor().head();
3720 let (buffer, buffer_position) =
3721 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3722 output
3723 } else {
3724 return;
3725 };
3726 let show_completion_documentation = buffer
3727 .read(cx)
3728 .snapshot()
3729 .settings_at(buffer_position, cx)
3730 .show_completion_documentation;
3731
3732 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3733
3734 let trigger_kind = match &options.trigger {
3735 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3736 CompletionTriggerKind::TRIGGER_CHARACTER
3737 }
3738 _ => CompletionTriggerKind::INVOKED,
3739 };
3740 let completion_context = CompletionContext {
3741 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3742 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3743 Some(String::from(trigger))
3744 } else {
3745 None
3746 }
3747 }),
3748 trigger_kind,
3749 };
3750 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3751 let sort_completions = provider.sort_completions();
3752
3753 let id = post_inc(&mut self.next_completion_id);
3754 let task = cx.spawn(|editor, mut cx| {
3755 async move {
3756 editor.update(&mut cx, |this, _| {
3757 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3758 })?;
3759 let completions = completions.await.log_err();
3760 let menu = if let Some(completions) = completions {
3761 let mut menu = CompletionsMenu::new(
3762 id,
3763 sort_completions,
3764 show_completion_documentation,
3765 position,
3766 buffer.clone(),
3767 completions.into(),
3768 );
3769
3770 menu.filter(query.as_deref(), cx.background_executor().clone())
3771 .await;
3772
3773 menu.visible().then_some(menu)
3774 } else {
3775 None
3776 };
3777
3778 editor.update(&mut cx, |editor, cx| {
3779 match editor.context_menu.borrow().as_ref() {
3780 None => {}
3781 Some(CodeContextMenu::Completions(prev_menu)) => {
3782 if prev_menu.id > id {
3783 return;
3784 }
3785 }
3786 _ => return,
3787 }
3788
3789 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3790 let mut menu = menu.unwrap();
3791 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3792
3793 if editor.show_inline_completions_in_menu(cx) {
3794 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3795 menu.show_inline_completion_hint(hint);
3796 }
3797 } else {
3798 editor.discard_inline_completion(false, cx);
3799 }
3800
3801 *editor.context_menu.borrow_mut() =
3802 Some(CodeContextMenu::Completions(menu));
3803
3804 cx.notify();
3805 } else if editor.completion_tasks.len() <= 1 {
3806 // If there are no more completion tasks and the last menu was
3807 // empty, we should hide it.
3808 let was_hidden = editor.hide_context_menu(cx).is_none();
3809 // If it was already hidden and we don't show inline
3810 // completions in the menu, we should also show the
3811 // inline-completion when available.
3812 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3813 editor.update_visible_inline_completion(cx);
3814 }
3815 }
3816 })?;
3817
3818 Ok::<_, anyhow::Error>(())
3819 }
3820 .log_err()
3821 });
3822
3823 self.completion_tasks.push((id, task));
3824 }
3825
3826 pub fn confirm_completion(
3827 &mut self,
3828 action: &ConfirmCompletion,
3829 cx: &mut ViewContext<Self>,
3830 ) -> Option<Task<Result<()>>> {
3831 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3832 }
3833
3834 pub fn compose_completion(
3835 &mut self,
3836 action: &ComposeCompletion,
3837 cx: &mut ViewContext<Self>,
3838 ) -> Option<Task<Result<()>>> {
3839 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3840 }
3841
3842 fn toggle_zed_predict_tos(&mut self, cx: &mut ViewContext<Self>) {
3843 let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
3844 return;
3845 };
3846
3847 ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), cx);
3848 }
3849
3850 fn do_completion(
3851 &mut self,
3852 item_ix: Option<usize>,
3853 intent: CompletionIntent,
3854 cx: &mut ViewContext<Editor>,
3855 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3856 use language::ToOffset as _;
3857
3858 {
3859 let context_menu = self.context_menu.borrow();
3860 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3861 let entries = menu.entries.borrow();
3862 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3863 match entry {
3864 Some(CompletionEntry::InlineCompletionHint(
3865 InlineCompletionMenuHint::Loading,
3866 )) => return Some(Task::ready(Ok(()))),
3867 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3868 drop(entries);
3869 drop(context_menu);
3870 self.context_menu_next(&Default::default(), cx);
3871 return Some(Task::ready(Ok(())));
3872 }
3873 Some(CompletionEntry::InlineCompletionHint(
3874 InlineCompletionMenuHint::PendingTermsAcceptance,
3875 )) => {
3876 drop(entries);
3877 drop(context_menu);
3878 self.toggle_zed_predict_tos(cx);
3879 return Some(Task::ready(Ok(())));
3880 }
3881 _ => {}
3882 }
3883 }
3884 }
3885
3886 let completions_menu =
3887 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3888 menu
3889 } else {
3890 return None;
3891 };
3892
3893 let entries = completions_menu.entries.borrow();
3894 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3895 let mat = match mat {
3896 CompletionEntry::InlineCompletionHint(_) => {
3897 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3898 cx.stop_propagation();
3899 return Some(Task::ready(Ok(())));
3900 }
3901 CompletionEntry::Match(mat) => {
3902 if self.show_inline_completions_in_menu(cx) {
3903 self.discard_inline_completion(true, cx);
3904 }
3905 mat
3906 }
3907 };
3908 let candidate_id = mat.candidate_id;
3909 drop(entries);
3910
3911 let buffer_handle = completions_menu.buffer;
3912 let completion = completions_menu
3913 .completions
3914 .borrow()
3915 .get(candidate_id)?
3916 .clone();
3917 cx.stop_propagation();
3918
3919 let snippet;
3920 let text;
3921
3922 if completion.is_snippet() {
3923 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3924 text = snippet.as_ref().unwrap().text.clone();
3925 } else {
3926 snippet = None;
3927 text = completion.new_text.clone();
3928 };
3929 let selections = self.selections.all::<usize>(cx);
3930 let buffer = buffer_handle.read(cx);
3931 let old_range = completion.old_range.to_offset(buffer);
3932 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3933
3934 let newest_selection = self.selections.newest_anchor();
3935 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3936 return None;
3937 }
3938
3939 let lookbehind = newest_selection
3940 .start
3941 .text_anchor
3942 .to_offset(buffer)
3943 .saturating_sub(old_range.start);
3944 let lookahead = old_range
3945 .end
3946 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3947 let mut common_prefix_len = old_text
3948 .bytes()
3949 .zip(text.bytes())
3950 .take_while(|(a, b)| a == b)
3951 .count();
3952
3953 let snapshot = self.buffer.read(cx).snapshot(cx);
3954 let mut range_to_replace: Option<Range<isize>> = None;
3955 let mut ranges = Vec::new();
3956 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3957 for selection in &selections {
3958 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3959 let start = selection.start.saturating_sub(lookbehind);
3960 let end = selection.end + lookahead;
3961 if selection.id == newest_selection.id {
3962 range_to_replace = Some(
3963 ((start + common_prefix_len) as isize - selection.start as isize)
3964 ..(end as isize - selection.start as isize),
3965 );
3966 }
3967 ranges.push(start + common_prefix_len..end);
3968 } else {
3969 common_prefix_len = 0;
3970 ranges.clear();
3971 ranges.extend(selections.iter().map(|s| {
3972 if s.id == newest_selection.id {
3973 range_to_replace = Some(
3974 old_range.start.to_offset_utf16(&snapshot).0 as isize
3975 - selection.start as isize
3976 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3977 - selection.start as isize,
3978 );
3979 old_range.clone()
3980 } else {
3981 s.start..s.end
3982 }
3983 }));
3984 break;
3985 }
3986 if !self.linked_edit_ranges.is_empty() {
3987 let start_anchor = snapshot.anchor_before(selection.head());
3988 let end_anchor = snapshot.anchor_after(selection.tail());
3989 if let Some(ranges) = self
3990 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3991 {
3992 for (buffer, edits) in ranges {
3993 linked_edits.entry(buffer.clone()).or_default().extend(
3994 edits
3995 .into_iter()
3996 .map(|range| (range, text[common_prefix_len..].to_owned())),
3997 );
3998 }
3999 }
4000 }
4001 }
4002 let text = &text[common_prefix_len..];
4003
4004 cx.emit(EditorEvent::InputHandled {
4005 utf16_range_to_replace: range_to_replace,
4006 text: text.into(),
4007 });
4008
4009 self.transact(cx, |this, cx| {
4010 if let Some(mut snippet) = snippet {
4011 snippet.text = text.to_string();
4012 for tabstop in snippet
4013 .tabstops
4014 .iter_mut()
4015 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4016 {
4017 tabstop.start -= common_prefix_len as isize;
4018 tabstop.end -= common_prefix_len as isize;
4019 }
4020
4021 this.insert_snippet(&ranges, snippet, cx).log_err();
4022 } else {
4023 this.buffer.update(cx, |buffer, cx| {
4024 buffer.edit(
4025 ranges.iter().map(|range| (range.clone(), text)),
4026 this.autoindent_mode.clone(),
4027 cx,
4028 );
4029 });
4030 }
4031 for (buffer, edits) in linked_edits {
4032 buffer.update(cx, |buffer, cx| {
4033 let snapshot = buffer.snapshot();
4034 let edits = edits
4035 .into_iter()
4036 .map(|(range, text)| {
4037 use text::ToPoint as TP;
4038 let end_point = TP::to_point(&range.end, &snapshot);
4039 let start_point = TP::to_point(&range.start, &snapshot);
4040 (start_point..end_point, text)
4041 })
4042 .sorted_by_key(|(range, _)| range.start)
4043 .collect::<Vec<_>>();
4044 buffer.edit(edits, None, cx);
4045 })
4046 }
4047
4048 this.refresh_inline_completion(true, false, cx);
4049 });
4050
4051 let show_new_completions_on_confirm = completion
4052 .confirm
4053 .as_ref()
4054 .map_or(false, |confirm| confirm(intent, cx));
4055 if show_new_completions_on_confirm {
4056 self.show_completions(&ShowCompletions { trigger: None }, cx);
4057 }
4058
4059 let provider = self.completion_provider.as_ref()?;
4060 drop(completion);
4061 let apply_edits = provider.apply_additional_edits_for_completion(
4062 buffer_handle,
4063 completions_menu.completions.clone(),
4064 candidate_id,
4065 true,
4066 cx,
4067 );
4068
4069 let editor_settings = EditorSettings::get_global(cx);
4070 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4071 // After the code completion is finished, users often want to know what signatures are needed.
4072 // so we should automatically call signature_help
4073 self.show_signature_help(&ShowSignatureHelp, cx);
4074 }
4075
4076 Some(cx.foreground_executor().spawn(async move {
4077 apply_edits.await?;
4078 Ok(())
4079 }))
4080 }
4081
4082 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4083 let mut context_menu = self.context_menu.borrow_mut();
4084 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4085 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4086 // Toggle if we're selecting the same one
4087 *context_menu = None;
4088 cx.notify();
4089 return;
4090 } else {
4091 // Otherwise, clear it and start a new one
4092 *context_menu = None;
4093 cx.notify();
4094 }
4095 }
4096 drop(context_menu);
4097 let snapshot = self.snapshot(cx);
4098 let deployed_from_indicator = action.deployed_from_indicator;
4099 let mut task = self.code_actions_task.take();
4100 let action = action.clone();
4101 cx.spawn(|editor, mut cx| async move {
4102 while let Some(prev_task) = task {
4103 prev_task.await.log_err();
4104 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4105 }
4106
4107 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4108 if editor.focus_handle.is_focused(cx) {
4109 let multibuffer_point = action
4110 .deployed_from_indicator
4111 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4112 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4113 let (buffer, buffer_row) = snapshot
4114 .buffer_snapshot
4115 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4116 .and_then(|(buffer_snapshot, range)| {
4117 editor
4118 .buffer
4119 .read(cx)
4120 .buffer(buffer_snapshot.remote_id())
4121 .map(|buffer| (buffer, range.start.row))
4122 })?;
4123 let (_, code_actions) = editor
4124 .available_code_actions
4125 .clone()
4126 .and_then(|(location, code_actions)| {
4127 let snapshot = location.buffer.read(cx).snapshot();
4128 let point_range = location.range.to_point(&snapshot);
4129 let point_range = point_range.start.row..=point_range.end.row;
4130 if point_range.contains(&buffer_row) {
4131 Some((location, code_actions))
4132 } else {
4133 None
4134 }
4135 })
4136 .unzip();
4137 let buffer_id = buffer.read(cx).remote_id();
4138 let tasks = editor
4139 .tasks
4140 .get(&(buffer_id, buffer_row))
4141 .map(|t| Arc::new(t.to_owned()));
4142 if tasks.is_none() && code_actions.is_none() {
4143 return None;
4144 }
4145
4146 editor.completion_tasks.clear();
4147 editor.discard_inline_completion(false, cx);
4148 let task_context =
4149 tasks
4150 .as_ref()
4151 .zip(editor.project.clone())
4152 .map(|(tasks, project)| {
4153 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4154 });
4155
4156 Some(cx.spawn(|editor, mut cx| async move {
4157 let task_context = match task_context {
4158 Some(task_context) => task_context.await,
4159 None => None,
4160 };
4161 let resolved_tasks =
4162 tasks.zip(task_context).map(|(tasks, task_context)| {
4163 Rc::new(ResolvedTasks {
4164 templates: tasks.resolve(&task_context).collect(),
4165 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4166 multibuffer_point.row,
4167 tasks.column,
4168 )),
4169 })
4170 });
4171 let spawn_straight_away = resolved_tasks
4172 .as_ref()
4173 .map_or(false, |tasks| tasks.templates.len() == 1)
4174 && code_actions
4175 .as_ref()
4176 .map_or(true, |actions| actions.is_empty());
4177 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4178 *editor.context_menu.borrow_mut() =
4179 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4180 buffer,
4181 actions: CodeActionContents {
4182 tasks: resolved_tasks,
4183 actions: code_actions,
4184 },
4185 selected_item: Default::default(),
4186 scroll_handle: UniformListScrollHandle::default(),
4187 deployed_from_indicator,
4188 }));
4189 if spawn_straight_away {
4190 if let Some(task) = editor.confirm_code_action(
4191 &ConfirmCodeAction { item_ix: Some(0) },
4192 cx,
4193 ) {
4194 cx.notify();
4195 return task;
4196 }
4197 }
4198 cx.notify();
4199 Task::ready(Ok(()))
4200 }) {
4201 task.await
4202 } else {
4203 Ok(())
4204 }
4205 }))
4206 } else {
4207 Some(Task::ready(Ok(())))
4208 }
4209 })?;
4210 if let Some(task) = spawned_test_task {
4211 task.await?;
4212 }
4213
4214 Ok::<_, anyhow::Error>(())
4215 })
4216 .detach_and_log_err(cx);
4217 }
4218
4219 pub fn confirm_code_action(
4220 &mut self,
4221 action: &ConfirmCodeAction,
4222 cx: &mut ViewContext<Self>,
4223 ) -> Option<Task<Result<()>>> {
4224 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4225 menu
4226 } else {
4227 return None;
4228 };
4229 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4230 let action = actions_menu.actions.get(action_ix)?;
4231 let title = action.label();
4232 let buffer = actions_menu.buffer;
4233 let workspace = self.workspace()?;
4234
4235 match action {
4236 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4237 workspace.update(cx, |workspace, cx| {
4238 workspace::tasks::schedule_resolved_task(
4239 workspace,
4240 task_source_kind,
4241 resolved_task,
4242 false,
4243 cx,
4244 );
4245
4246 Some(Task::ready(Ok(())))
4247 })
4248 }
4249 CodeActionsItem::CodeAction {
4250 excerpt_id,
4251 action,
4252 provider,
4253 } => {
4254 let apply_code_action =
4255 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4256 let workspace = workspace.downgrade();
4257 Some(cx.spawn(|editor, cx| async move {
4258 let project_transaction = apply_code_action.await?;
4259 Self::open_project_transaction(
4260 &editor,
4261 workspace,
4262 project_transaction,
4263 title,
4264 cx,
4265 )
4266 .await
4267 }))
4268 }
4269 }
4270 }
4271
4272 pub async fn open_project_transaction(
4273 this: &WeakView<Editor>,
4274 workspace: WeakView<Workspace>,
4275 transaction: ProjectTransaction,
4276 title: String,
4277 mut cx: AsyncWindowContext,
4278 ) -> Result<()> {
4279 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4280 cx.update(|cx| {
4281 entries.sort_unstable_by_key(|(buffer, _)| {
4282 buffer.read(cx).file().map(|f| f.path().clone())
4283 });
4284 })?;
4285
4286 // If the project transaction's edits are all contained within this editor, then
4287 // avoid opening a new editor to display them.
4288
4289 if let Some((buffer, transaction)) = entries.first() {
4290 if entries.len() == 1 {
4291 let excerpt = this.update(&mut cx, |editor, cx| {
4292 editor
4293 .buffer()
4294 .read(cx)
4295 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4296 })?;
4297 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4298 if excerpted_buffer == *buffer {
4299 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4300 let excerpt_range = excerpt_range.to_offset(buffer);
4301 buffer
4302 .edited_ranges_for_transaction::<usize>(transaction)
4303 .all(|range| {
4304 excerpt_range.start <= range.start
4305 && excerpt_range.end >= range.end
4306 })
4307 })?;
4308
4309 if all_edits_within_excerpt {
4310 return Ok(());
4311 }
4312 }
4313 }
4314 }
4315 } else {
4316 return Ok(());
4317 }
4318
4319 let mut ranges_to_highlight = Vec::new();
4320 let excerpt_buffer = cx.new_model(|cx| {
4321 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4322 for (buffer_handle, transaction) in &entries {
4323 let buffer = buffer_handle.read(cx);
4324 ranges_to_highlight.extend(
4325 multibuffer.push_excerpts_with_context_lines(
4326 buffer_handle.clone(),
4327 buffer
4328 .edited_ranges_for_transaction::<usize>(transaction)
4329 .collect(),
4330 DEFAULT_MULTIBUFFER_CONTEXT,
4331 cx,
4332 ),
4333 );
4334 }
4335 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4336 multibuffer
4337 })?;
4338
4339 workspace.update(&mut cx, |workspace, cx| {
4340 let project = workspace.project().clone();
4341 let editor =
4342 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4343 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4344 editor.update(cx, |editor, cx| {
4345 editor.highlight_background::<Self>(
4346 &ranges_to_highlight,
4347 |theme| theme.editor_highlighted_line_background,
4348 cx,
4349 );
4350 });
4351 })?;
4352
4353 Ok(())
4354 }
4355
4356 pub fn clear_code_action_providers(&mut self) {
4357 self.code_action_providers.clear();
4358 self.available_code_actions.take();
4359 }
4360
4361 pub fn add_code_action_provider(
4362 &mut self,
4363 provider: Rc<dyn CodeActionProvider>,
4364 cx: &mut ViewContext<Self>,
4365 ) {
4366 if self
4367 .code_action_providers
4368 .iter()
4369 .any(|existing_provider| existing_provider.id() == provider.id())
4370 {
4371 return;
4372 }
4373
4374 self.code_action_providers.push(provider);
4375 self.refresh_code_actions(cx);
4376 }
4377
4378 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4379 self.code_action_providers
4380 .retain(|provider| provider.id() != id);
4381 self.refresh_code_actions(cx);
4382 }
4383
4384 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4385 let buffer = self.buffer.read(cx);
4386 let newest_selection = self.selections.newest_anchor().clone();
4387 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4388 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4389 if start_buffer != end_buffer {
4390 return None;
4391 }
4392
4393 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4394 cx.background_executor()
4395 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4396 .await;
4397
4398 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4399 let providers = this.code_action_providers.clone();
4400 let tasks = this
4401 .code_action_providers
4402 .iter()
4403 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4404 .collect::<Vec<_>>();
4405 (providers, tasks)
4406 })?;
4407
4408 let mut actions = Vec::new();
4409 for (provider, provider_actions) in
4410 providers.into_iter().zip(future::join_all(tasks).await)
4411 {
4412 if let Some(provider_actions) = provider_actions.log_err() {
4413 actions.extend(provider_actions.into_iter().map(|action| {
4414 AvailableCodeAction {
4415 excerpt_id: newest_selection.start.excerpt_id,
4416 action,
4417 provider: provider.clone(),
4418 }
4419 }));
4420 }
4421 }
4422
4423 this.update(&mut cx, |this, cx| {
4424 this.available_code_actions = if actions.is_empty() {
4425 None
4426 } else {
4427 Some((
4428 Location {
4429 buffer: start_buffer,
4430 range: start..end,
4431 },
4432 actions.into(),
4433 ))
4434 };
4435 cx.notify();
4436 })
4437 }));
4438 None
4439 }
4440
4441 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4442 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4443 self.show_git_blame_inline = false;
4444
4445 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4446 cx.background_executor().timer(delay).await;
4447
4448 this.update(&mut cx, |this, cx| {
4449 this.show_git_blame_inline = true;
4450 cx.notify();
4451 })
4452 .log_err();
4453 }));
4454 }
4455 }
4456
4457 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4458 if self.pending_rename.is_some() {
4459 return None;
4460 }
4461
4462 let provider = self.semantics_provider.clone()?;
4463 let buffer = self.buffer.read(cx);
4464 let newest_selection = self.selections.newest_anchor().clone();
4465 let cursor_position = newest_selection.head();
4466 let (cursor_buffer, cursor_buffer_position) =
4467 buffer.text_anchor_for_position(cursor_position, cx)?;
4468 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4469 if cursor_buffer != tail_buffer {
4470 return None;
4471 }
4472 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4473 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4474 cx.background_executor()
4475 .timer(Duration::from_millis(debounce))
4476 .await;
4477
4478 let highlights = if let Some(highlights) = cx
4479 .update(|cx| {
4480 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4481 })
4482 .ok()
4483 .flatten()
4484 {
4485 highlights.await.log_err()
4486 } else {
4487 None
4488 };
4489
4490 if let Some(highlights) = highlights {
4491 this.update(&mut cx, |this, cx| {
4492 if this.pending_rename.is_some() {
4493 return;
4494 }
4495
4496 let buffer_id = cursor_position.buffer_id;
4497 let buffer = this.buffer.read(cx);
4498 if !buffer
4499 .text_anchor_for_position(cursor_position, cx)
4500 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4501 {
4502 return;
4503 }
4504
4505 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4506 let mut write_ranges = Vec::new();
4507 let mut read_ranges = Vec::new();
4508 for highlight in highlights {
4509 for (excerpt_id, excerpt_range) in
4510 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4511 {
4512 let start = highlight
4513 .range
4514 .start
4515 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4516 let end = highlight
4517 .range
4518 .end
4519 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4520 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4521 continue;
4522 }
4523
4524 let range = Anchor {
4525 buffer_id,
4526 excerpt_id,
4527 text_anchor: start,
4528 }..Anchor {
4529 buffer_id,
4530 excerpt_id,
4531 text_anchor: end,
4532 };
4533 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4534 write_ranges.push(range);
4535 } else {
4536 read_ranges.push(range);
4537 }
4538 }
4539 }
4540
4541 this.highlight_background::<DocumentHighlightRead>(
4542 &read_ranges,
4543 |theme| theme.editor_document_highlight_read_background,
4544 cx,
4545 );
4546 this.highlight_background::<DocumentHighlightWrite>(
4547 &write_ranges,
4548 |theme| theme.editor_document_highlight_write_background,
4549 cx,
4550 );
4551 cx.notify();
4552 })
4553 .log_err();
4554 }
4555 }));
4556 None
4557 }
4558
4559 pub fn refresh_inline_completion(
4560 &mut self,
4561 debounce: bool,
4562 user_requested: bool,
4563 cx: &mut ViewContext<Self>,
4564 ) -> Option<()> {
4565 let provider = self.inline_completion_provider()?;
4566 let cursor = self.selections.newest_anchor().head();
4567 let (buffer, cursor_buffer_position) =
4568 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4569
4570 if !user_requested
4571 && (!self.enable_inline_completions
4572 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4573 || !self.is_focused(cx)
4574 || buffer.read(cx).is_empty())
4575 {
4576 self.discard_inline_completion(false, cx);
4577 return None;
4578 }
4579
4580 self.update_visible_inline_completion(cx);
4581 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4582 Some(())
4583 }
4584
4585 fn cycle_inline_completion(
4586 &mut self,
4587 direction: Direction,
4588 cx: &mut ViewContext<Self>,
4589 ) -> Option<()> {
4590 let provider = self.inline_completion_provider()?;
4591 let cursor = self.selections.newest_anchor().head();
4592 let (buffer, cursor_buffer_position) =
4593 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4594 if !self.enable_inline_completions
4595 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4596 {
4597 return None;
4598 }
4599
4600 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4601 self.update_visible_inline_completion(cx);
4602
4603 Some(())
4604 }
4605
4606 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4607 if !self.has_active_inline_completion() {
4608 self.refresh_inline_completion(false, true, cx);
4609 return;
4610 }
4611
4612 self.update_visible_inline_completion(cx);
4613 }
4614
4615 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4616 self.show_cursor_names(cx);
4617 }
4618
4619 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4620 self.show_cursor_names = true;
4621 cx.notify();
4622 cx.spawn(|this, mut cx| async move {
4623 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4624 this.update(&mut cx, |this, cx| {
4625 this.show_cursor_names = false;
4626 cx.notify()
4627 })
4628 .ok()
4629 })
4630 .detach();
4631 }
4632
4633 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4634 if self.has_active_inline_completion() {
4635 self.cycle_inline_completion(Direction::Next, cx);
4636 } else {
4637 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4638 if is_copilot_disabled {
4639 cx.propagate();
4640 }
4641 }
4642 }
4643
4644 pub fn previous_inline_completion(
4645 &mut self,
4646 _: &PreviousInlineCompletion,
4647 cx: &mut ViewContext<Self>,
4648 ) {
4649 if self.has_active_inline_completion() {
4650 self.cycle_inline_completion(Direction::Prev, cx);
4651 } else {
4652 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4653 if is_copilot_disabled {
4654 cx.propagate();
4655 }
4656 }
4657 }
4658
4659 pub fn accept_inline_completion(
4660 &mut self,
4661 _: &AcceptInlineCompletion,
4662 cx: &mut ViewContext<Self>,
4663 ) {
4664 let buffer = self.buffer.read(cx);
4665 let snapshot = buffer.snapshot(cx);
4666 let selection = self.selections.newest_adjusted(cx);
4667 let cursor = selection.head();
4668 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4669 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4670 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4671 {
4672 if cursor.column < suggested_indent.len
4673 && cursor.column <= current_indent.len
4674 && current_indent.len <= suggested_indent.len
4675 {
4676 self.tab(&Default::default(), cx);
4677 return;
4678 }
4679 }
4680
4681 if self.show_inline_completions_in_menu(cx) {
4682 self.hide_context_menu(cx);
4683 }
4684
4685 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4686 return;
4687 };
4688
4689 self.report_inline_completion_event(true, cx);
4690
4691 match &active_inline_completion.completion {
4692 InlineCompletion::Move(position) => {
4693 let position = *position;
4694 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4695 selections.select_anchor_ranges([position..position]);
4696 });
4697 }
4698 InlineCompletion::Edit {
4699 edits,
4700 display_mode: _,
4701 } => {
4702 if let Some(provider) = self.inline_completion_provider() {
4703 provider.accept(cx);
4704 }
4705
4706 let snapshot = self.buffer.read(cx).snapshot(cx);
4707 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4708
4709 self.buffer.update(cx, |buffer, cx| {
4710 buffer.edit(edits.iter().cloned(), None, cx)
4711 });
4712
4713 self.change_selections(None, cx, |s| {
4714 s.select_anchor_ranges([last_edit_end..last_edit_end])
4715 });
4716
4717 self.update_visible_inline_completion(cx);
4718 if self.active_inline_completion.is_none() {
4719 self.refresh_inline_completion(true, true, cx);
4720 }
4721
4722 cx.notify();
4723 }
4724 }
4725 }
4726
4727 pub fn accept_partial_inline_completion(
4728 &mut self,
4729 _: &AcceptPartialInlineCompletion,
4730 cx: &mut ViewContext<Self>,
4731 ) {
4732 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4733 return;
4734 };
4735 if self.selections.count() != 1 {
4736 return;
4737 }
4738
4739 self.report_inline_completion_event(true, cx);
4740
4741 match &active_inline_completion.completion {
4742 InlineCompletion::Move(position) => {
4743 let position = *position;
4744 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4745 selections.select_anchor_ranges([position..position]);
4746 });
4747 }
4748 InlineCompletion::Edit {
4749 edits,
4750 display_mode: _,
4751 } => {
4752 // Find an insertion that starts at the cursor position.
4753 let snapshot = self.buffer.read(cx).snapshot(cx);
4754 let cursor_offset = self.selections.newest::<usize>(cx).head();
4755 let insertion = edits.iter().find_map(|(range, text)| {
4756 let range = range.to_offset(&snapshot);
4757 if range.is_empty() && range.start == cursor_offset {
4758 Some(text)
4759 } else {
4760 None
4761 }
4762 });
4763
4764 if let Some(text) = insertion {
4765 let mut partial_completion = text
4766 .chars()
4767 .by_ref()
4768 .take_while(|c| c.is_alphabetic())
4769 .collect::<String>();
4770 if partial_completion.is_empty() {
4771 partial_completion = text
4772 .chars()
4773 .by_ref()
4774 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4775 .collect::<String>();
4776 }
4777
4778 cx.emit(EditorEvent::InputHandled {
4779 utf16_range_to_replace: None,
4780 text: partial_completion.clone().into(),
4781 });
4782
4783 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4784
4785 self.refresh_inline_completion(true, true, cx);
4786 cx.notify();
4787 } else {
4788 self.accept_inline_completion(&Default::default(), cx);
4789 }
4790 }
4791 }
4792 }
4793
4794 fn discard_inline_completion(
4795 &mut self,
4796 should_report_inline_completion_event: bool,
4797 cx: &mut ViewContext<Self>,
4798 ) -> bool {
4799 if should_report_inline_completion_event {
4800 self.report_inline_completion_event(false, cx);
4801 }
4802
4803 if let Some(provider) = self.inline_completion_provider() {
4804 provider.discard(cx);
4805 }
4806
4807 self.take_active_inline_completion(cx).is_some()
4808 }
4809
4810 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4811 let Some(provider) = self.inline_completion_provider() else {
4812 return;
4813 };
4814
4815 let Some((_, buffer, _)) = self
4816 .buffer
4817 .read(cx)
4818 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4819 else {
4820 return;
4821 };
4822
4823 let extension = buffer
4824 .read(cx)
4825 .file()
4826 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4827
4828 let event_type = match accepted {
4829 true => "Inline Completion Accepted",
4830 false => "Inline Completion Discarded",
4831 };
4832 telemetry::event!(
4833 event_type,
4834 provider = provider.name(),
4835 suggestion_accepted = accepted,
4836 file_extension = extension,
4837 );
4838 }
4839
4840 pub fn has_active_inline_completion(&self) -> bool {
4841 self.active_inline_completion.is_some()
4842 }
4843
4844 fn take_active_inline_completion(
4845 &mut self,
4846 cx: &mut ViewContext<Self>,
4847 ) -> Option<InlineCompletion> {
4848 let active_inline_completion = self.active_inline_completion.take()?;
4849 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4850 self.clear_highlights::<InlineCompletionHighlight>(cx);
4851 Some(active_inline_completion.completion)
4852 }
4853
4854 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4855 let selection = self.selections.newest_anchor();
4856 let cursor = selection.head();
4857 let multibuffer = self.buffer.read(cx).snapshot(cx);
4858 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4859 let excerpt_id = cursor.excerpt_id;
4860
4861 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4862 && (self.context_menu.borrow().is_some()
4863 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4864 if completions_menu_has_precedence
4865 || !offset_selection.is_empty()
4866 || !self.enable_inline_completions
4867 || self
4868 .active_inline_completion
4869 .as_ref()
4870 .map_or(false, |completion| {
4871 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4872 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4873 !invalidation_range.contains(&offset_selection.head())
4874 })
4875 {
4876 self.discard_inline_completion(false, cx);
4877 return None;
4878 }
4879
4880 self.take_active_inline_completion(cx);
4881 let provider = self.inline_completion_provider()?;
4882
4883 let (buffer, cursor_buffer_position) =
4884 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4885
4886 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4887 let edits = completion
4888 .edits
4889 .into_iter()
4890 .flat_map(|(range, new_text)| {
4891 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4892 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4893 Some((start..end, new_text))
4894 })
4895 .collect::<Vec<_>>();
4896 if edits.is_empty() {
4897 return None;
4898 }
4899
4900 let first_edit_start = edits.first().unwrap().0.start;
4901 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
4902 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
4903
4904 let last_edit_end = edits.last().unwrap().0.end;
4905 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
4906 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
4907
4908 let cursor_row = cursor.to_point(&multibuffer).row;
4909
4910 let mut inlay_ids = Vec::new();
4911 let invalidation_row_range;
4912 let completion;
4913 if cursor_row < edit_start_row {
4914 invalidation_row_range = cursor_row..edit_end_row;
4915 completion = InlineCompletion::Move(first_edit_start);
4916 } else if cursor_row > edit_end_row {
4917 invalidation_row_range = edit_start_row..cursor_row;
4918 completion = InlineCompletion::Move(first_edit_start);
4919 } else {
4920 if edits
4921 .iter()
4922 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4923 {
4924 let mut inlays = Vec::new();
4925 for (range, new_text) in &edits {
4926 let inlay = Inlay::inline_completion(
4927 post_inc(&mut self.next_inlay_id),
4928 range.start,
4929 new_text.as_str(),
4930 );
4931 inlay_ids.push(inlay.id);
4932 inlays.push(inlay);
4933 }
4934
4935 self.splice_inlays(vec![], inlays, cx);
4936 } else {
4937 let background_color = cx.theme().status().deleted_background;
4938 self.highlight_text::<InlineCompletionHighlight>(
4939 edits.iter().map(|(range, _)| range.clone()).collect(),
4940 HighlightStyle {
4941 background_color: Some(background_color),
4942 ..Default::default()
4943 },
4944 cx,
4945 );
4946 }
4947
4948 invalidation_row_range = edit_start_row..edit_end_row;
4949
4950 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
4951 if provider.show_tab_accept_marker()
4952 && first_edit_start_point.row == last_edit_end_point.row
4953 && !edits.iter().any(|(_, edit)| edit.contains('\n'))
4954 {
4955 EditDisplayMode::TabAccept
4956 } else {
4957 EditDisplayMode::Inline
4958 }
4959 } else {
4960 EditDisplayMode::DiffPopover
4961 };
4962
4963 completion = InlineCompletion::Edit {
4964 edits,
4965 display_mode,
4966 };
4967 };
4968
4969 let invalidation_range = multibuffer
4970 .anchor_before(Point::new(invalidation_row_range.start, 0))
4971 ..multibuffer.anchor_after(Point::new(
4972 invalidation_row_range.end,
4973 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4974 ));
4975
4976 self.active_inline_completion = Some(InlineCompletionState {
4977 inlay_ids,
4978 completion,
4979 invalidation_range,
4980 });
4981
4982 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4983 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4984 match self.context_menu.borrow_mut().as_mut() {
4985 Some(CodeContextMenu::Completions(menu)) => {
4986 menu.show_inline_completion_hint(hint);
4987 }
4988 _ => {}
4989 }
4990 }
4991 }
4992
4993 cx.notify();
4994
4995 Some(())
4996 }
4997
4998 fn inline_completion_menu_hint(
4999 &mut self,
5000 cx: &mut ViewContext<Self>,
5001 ) -> Option<InlineCompletionMenuHint> {
5002 let provider = self.inline_completion_provider()?;
5003 if self.has_active_inline_completion() {
5004 let editor_snapshot = self.snapshot(cx);
5005
5006 let text = match &self.active_inline_completion.as_ref()?.completion {
5007 InlineCompletion::Edit {
5008 edits,
5009 display_mode: _,
5010 } => inline_completion_edit_text(&editor_snapshot, edits, true, cx),
5011 InlineCompletion::Move(target) => {
5012 let target_point =
5013 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
5014 let target_line = target_point.row + 1;
5015 InlineCompletionText::Move(
5016 format!("Jump to edit in line {}", target_line).into(),
5017 )
5018 }
5019 };
5020
5021 Some(InlineCompletionMenuHint::Loaded { text })
5022 } else if provider.is_refreshing(cx) {
5023 Some(InlineCompletionMenuHint::Loading)
5024 } else if provider.needs_terms_acceptance(cx) {
5025 Some(InlineCompletionMenuHint::PendingTermsAcceptance)
5026 } else {
5027 Some(InlineCompletionMenuHint::None)
5028 }
5029 }
5030
5031 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5032 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5033 }
5034
5035 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
5036 EditorSettings::get_global(cx).show_inline_completions_in_menu
5037 && self
5038 .inline_completion_provider()
5039 .map_or(false, |provider| provider.show_completions_in_menu())
5040 }
5041
5042 fn render_code_actions_indicator(
5043 &self,
5044 _style: &EditorStyle,
5045 row: DisplayRow,
5046 is_active: bool,
5047 cx: &mut ViewContext<Self>,
5048 ) -> Option<IconButton> {
5049 if self.available_code_actions.is_some() {
5050 Some(
5051 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5052 .shape(ui::IconButtonShape::Square)
5053 .icon_size(IconSize::XSmall)
5054 .icon_color(Color::Muted)
5055 .toggle_state(is_active)
5056 .tooltip({
5057 let focus_handle = self.focus_handle.clone();
5058 move |cx| {
5059 Tooltip::for_action_in(
5060 "Toggle Code Actions",
5061 &ToggleCodeActions {
5062 deployed_from_indicator: None,
5063 },
5064 &focus_handle,
5065 cx,
5066 )
5067 }
5068 })
5069 .on_click(cx.listener(move |editor, _e, cx| {
5070 editor.focus(cx);
5071 editor.toggle_code_actions(
5072 &ToggleCodeActions {
5073 deployed_from_indicator: Some(row),
5074 },
5075 cx,
5076 );
5077 })),
5078 )
5079 } else {
5080 None
5081 }
5082 }
5083
5084 fn clear_tasks(&mut self) {
5085 self.tasks.clear()
5086 }
5087
5088 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5089 if self.tasks.insert(key, value).is_some() {
5090 // This case should hopefully be rare, but just in case...
5091 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5092 }
5093 }
5094
5095 fn build_tasks_context(
5096 project: &Model<Project>,
5097 buffer: &Model<Buffer>,
5098 buffer_row: u32,
5099 tasks: &Arc<RunnableTasks>,
5100 cx: &mut ViewContext<Self>,
5101 ) -> Task<Option<task::TaskContext>> {
5102 let position = Point::new(buffer_row, tasks.column);
5103 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5104 let location = Location {
5105 buffer: buffer.clone(),
5106 range: range_start..range_start,
5107 };
5108 // Fill in the environmental variables from the tree-sitter captures
5109 let mut captured_task_variables = TaskVariables::default();
5110 for (capture_name, value) in tasks.extra_variables.clone() {
5111 captured_task_variables.insert(
5112 task::VariableName::Custom(capture_name.into()),
5113 value.clone(),
5114 );
5115 }
5116 project.update(cx, |project, cx| {
5117 project.task_store().update(cx, |task_store, cx| {
5118 task_store.task_context_for_location(captured_task_variables, location, cx)
5119 })
5120 })
5121 }
5122
5123 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5124 let Some((workspace, _)) = self.workspace.clone() else {
5125 return;
5126 };
5127 let Some(project) = self.project.clone() else {
5128 return;
5129 };
5130
5131 // Try to find a closest, enclosing node using tree-sitter that has a
5132 // task
5133 let Some((buffer, buffer_row, tasks)) = self
5134 .find_enclosing_node_task(cx)
5135 // Or find the task that's closest in row-distance.
5136 .or_else(|| self.find_closest_task(cx))
5137 else {
5138 return;
5139 };
5140
5141 let reveal_strategy = action.reveal;
5142 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5143 cx.spawn(|_, mut cx| async move {
5144 let context = task_context.await?;
5145 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5146
5147 let resolved = resolved_task.resolved.as_mut()?;
5148 resolved.reveal = reveal_strategy;
5149
5150 workspace
5151 .update(&mut cx, |workspace, cx| {
5152 workspace::tasks::schedule_resolved_task(
5153 workspace,
5154 task_source_kind,
5155 resolved_task,
5156 false,
5157 cx,
5158 );
5159 })
5160 .ok()
5161 })
5162 .detach();
5163 }
5164
5165 fn find_closest_task(
5166 &mut self,
5167 cx: &mut ViewContext<Self>,
5168 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5169 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5170
5171 let ((buffer_id, row), tasks) = self
5172 .tasks
5173 .iter()
5174 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5175
5176 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5177 let tasks = Arc::new(tasks.to_owned());
5178 Some((buffer, *row, tasks))
5179 }
5180
5181 fn find_enclosing_node_task(
5182 &mut self,
5183 cx: &mut ViewContext<Self>,
5184 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5185 let snapshot = self.buffer.read(cx).snapshot(cx);
5186 let offset = self.selections.newest::<usize>(cx).head();
5187 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5188 let buffer_id = excerpt.buffer().remote_id();
5189
5190 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5191 let mut cursor = layer.node().walk();
5192
5193 while cursor.goto_first_child_for_byte(offset).is_some() {
5194 if cursor.node().end_byte() == offset {
5195 cursor.goto_next_sibling();
5196 }
5197 }
5198
5199 // Ascend to the smallest ancestor that contains the range and has a task.
5200 loop {
5201 let node = cursor.node();
5202 let node_range = node.byte_range();
5203 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5204
5205 // Check if this node contains our offset
5206 if node_range.start <= offset && node_range.end >= offset {
5207 // If it contains offset, check for task
5208 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5209 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5210 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5211 }
5212 }
5213
5214 if !cursor.goto_parent() {
5215 break;
5216 }
5217 }
5218 None
5219 }
5220
5221 fn render_run_indicator(
5222 &self,
5223 _style: &EditorStyle,
5224 is_active: bool,
5225 row: DisplayRow,
5226 cx: &mut ViewContext<Self>,
5227 ) -> IconButton {
5228 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5229 .shape(ui::IconButtonShape::Square)
5230 .icon_size(IconSize::XSmall)
5231 .icon_color(Color::Muted)
5232 .toggle_state(is_active)
5233 .on_click(cx.listener(move |editor, _e, cx| {
5234 editor.focus(cx);
5235 editor.toggle_code_actions(
5236 &ToggleCodeActions {
5237 deployed_from_indicator: Some(row),
5238 },
5239 cx,
5240 );
5241 }))
5242 }
5243
5244 #[cfg(any(feature = "test-support", test))]
5245 pub fn context_menu_visible(&self) -> bool {
5246 self.context_menu
5247 .borrow()
5248 .as_ref()
5249 .map_or(false, |menu| menu.visible())
5250 }
5251
5252 #[cfg(feature = "test-support")]
5253 pub fn context_menu_contains_inline_completion(&self) -> bool {
5254 self.context_menu
5255 .borrow()
5256 .as_ref()
5257 .map_or(false, |menu| match menu {
5258 CodeContextMenu::Completions(menu) => {
5259 menu.entries.borrow().first().map_or(false, |entry| {
5260 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5261 })
5262 }
5263 CodeContextMenu::CodeActions(_) => false,
5264 })
5265 }
5266
5267 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5268 self.context_menu
5269 .borrow()
5270 .as_ref()
5271 .map(|menu| menu.origin(cursor_position))
5272 }
5273
5274 fn render_context_menu(
5275 &self,
5276 style: &EditorStyle,
5277 max_height_in_lines: u32,
5278 y_flipped: bool,
5279 cx: &mut ViewContext<Editor>,
5280 ) -> Option<AnyElement> {
5281 self.context_menu.borrow().as_ref().and_then(|menu| {
5282 if menu.visible() {
5283 Some(menu.render(style, max_height_in_lines, y_flipped, cx))
5284 } else {
5285 None
5286 }
5287 })
5288 }
5289
5290 fn render_context_menu_aside(
5291 &self,
5292 style: &EditorStyle,
5293 max_size: Size<Pixels>,
5294 cx: &mut ViewContext<Editor>,
5295 ) -> Option<AnyElement> {
5296 self.context_menu.borrow().as_ref().and_then(|menu| {
5297 if menu.visible() {
5298 menu.render_aside(
5299 style,
5300 max_size,
5301 self.workspace.as_ref().map(|(w, _)| w.clone()),
5302 cx,
5303 )
5304 } else {
5305 None
5306 }
5307 })
5308 }
5309
5310 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5311 cx.notify();
5312 self.completion_tasks.clear();
5313 let context_menu = self.context_menu.borrow_mut().take();
5314 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5315 self.update_visible_inline_completion(cx);
5316 }
5317 context_menu
5318 }
5319
5320 fn show_snippet_choices(
5321 &mut self,
5322 choices: &Vec<String>,
5323 selection: Range<Anchor>,
5324 cx: &mut ViewContext<Self>,
5325 ) {
5326 if selection.start.buffer_id.is_none() {
5327 return;
5328 }
5329 let buffer_id = selection.start.buffer_id.unwrap();
5330 let buffer = self.buffer().read(cx).buffer(buffer_id);
5331 let id = post_inc(&mut self.next_completion_id);
5332
5333 if let Some(buffer) = buffer {
5334 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5335 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5336 ));
5337 }
5338 }
5339
5340 pub fn insert_snippet(
5341 &mut self,
5342 insertion_ranges: &[Range<usize>],
5343 snippet: Snippet,
5344 cx: &mut ViewContext<Self>,
5345 ) -> Result<()> {
5346 struct Tabstop<T> {
5347 is_end_tabstop: bool,
5348 ranges: Vec<Range<T>>,
5349 choices: Option<Vec<String>>,
5350 }
5351
5352 let tabstops = self.buffer.update(cx, |buffer, cx| {
5353 let snippet_text: Arc<str> = snippet.text.clone().into();
5354 buffer.edit(
5355 insertion_ranges
5356 .iter()
5357 .cloned()
5358 .map(|range| (range, snippet_text.clone())),
5359 Some(AutoindentMode::EachLine),
5360 cx,
5361 );
5362
5363 let snapshot = &*buffer.read(cx);
5364 let snippet = &snippet;
5365 snippet
5366 .tabstops
5367 .iter()
5368 .map(|tabstop| {
5369 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5370 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5371 });
5372 let mut tabstop_ranges = tabstop
5373 .ranges
5374 .iter()
5375 .flat_map(|tabstop_range| {
5376 let mut delta = 0_isize;
5377 insertion_ranges.iter().map(move |insertion_range| {
5378 let insertion_start = insertion_range.start as isize + delta;
5379 delta +=
5380 snippet.text.len() as isize - insertion_range.len() as isize;
5381
5382 let start = ((insertion_start + tabstop_range.start) as usize)
5383 .min(snapshot.len());
5384 let end = ((insertion_start + tabstop_range.end) as usize)
5385 .min(snapshot.len());
5386 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5387 })
5388 })
5389 .collect::<Vec<_>>();
5390 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5391
5392 Tabstop {
5393 is_end_tabstop,
5394 ranges: tabstop_ranges,
5395 choices: tabstop.choices.clone(),
5396 }
5397 })
5398 .collect::<Vec<_>>()
5399 });
5400 if let Some(tabstop) = tabstops.first() {
5401 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5402 s.select_ranges(tabstop.ranges.iter().cloned());
5403 });
5404
5405 if let Some(choices) = &tabstop.choices {
5406 if let Some(selection) = tabstop.ranges.first() {
5407 self.show_snippet_choices(choices, selection.clone(), cx)
5408 }
5409 }
5410
5411 // If we're already at the last tabstop and it's at the end of the snippet,
5412 // we're done, we don't need to keep the state around.
5413 if !tabstop.is_end_tabstop {
5414 let choices = tabstops
5415 .iter()
5416 .map(|tabstop| tabstop.choices.clone())
5417 .collect();
5418
5419 let ranges = tabstops
5420 .into_iter()
5421 .map(|tabstop| tabstop.ranges)
5422 .collect::<Vec<_>>();
5423
5424 self.snippet_stack.push(SnippetState {
5425 active_index: 0,
5426 ranges,
5427 choices,
5428 });
5429 }
5430
5431 // Check whether the just-entered snippet ends with an auto-closable bracket.
5432 if self.autoclose_regions.is_empty() {
5433 let snapshot = self.buffer.read(cx).snapshot(cx);
5434 for selection in &mut self.selections.all::<Point>(cx) {
5435 let selection_head = selection.head();
5436 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5437 continue;
5438 };
5439
5440 let mut bracket_pair = None;
5441 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5442 let prev_chars = snapshot
5443 .reversed_chars_at(selection_head)
5444 .collect::<String>();
5445 for (pair, enabled) in scope.brackets() {
5446 if enabled
5447 && pair.close
5448 && prev_chars.starts_with(pair.start.as_str())
5449 && next_chars.starts_with(pair.end.as_str())
5450 {
5451 bracket_pair = Some(pair.clone());
5452 break;
5453 }
5454 }
5455 if let Some(pair) = bracket_pair {
5456 let start = snapshot.anchor_after(selection_head);
5457 let end = snapshot.anchor_after(selection_head);
5458 self.autoclose_regions.push(AutocloseRegion {
5459 selection_id: selection.id,
5460 range: start..end,
5461 pair,
5462 });
5463 }
5464 }
5465 }
5466 }
5467 Ok(())
5468 }
5469
5470 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5471 self.move_to_snippet_tabstop(Bias::Right, cx)
5472 }
5473
5474 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5475 self.move_to_snippet_tabstop(Bias::Left, cx)
5476 }
5477
5478 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5479 if let Some(mut snippet) = self.snippet_stack.pop() {
5480 match bias {
5481 Bias::Left => {
5482 if snippet.active_index > 0 {
5483 snippet.active_index -= 1;
5484 } else {
5485 self.snippet_stack.push(snippet);
5486 return false;
5487 }
5488 }
5489 Bias::Right => {
5490 if snippet.active_index + 1 < snippet.ranges.len() {
5491 snippet.active_index += 1;
5492 } else {
5493 self.snippet_stack.push(snippet);
5494 return false;
5495 }
5496 }
5497 }
5498 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5499 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5500 s.select_anchor_ranges(current_ranges.iter().cloned())
5501 });
5502
5503 if let Some(choices) = &snippet.choices[snippet.active_index] {
5504 if let Some(selection) = current_ranges.first() {
5505 self.show_snippet_choices(&choices, selection.clone(), cx);
5506 }
5507 }
5508
5509 // If snippet state is not at the last tabstop, push it back on the stack
5510 if snippet.active_index + 1 < snippet.ranges.len() {
5511 self.snippet_stack.push(snippet);
5512 }
5513 return true;
5514 }
5515 }
5516
5517 false
5518 }
5519
5520 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5521 self.transact(cx, |this, cx| {
5522 this.select_all(&SelectAll, cx);
5523 this.insert("", cx);
5524 });
5525 }
5526
5527 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5528 self.transact(cx, |this, cx| {
5529 this.select_autoclose_pair(cx);
5530 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5531 if !this.linked_edit_ranges.is_empty() {
5532 let selections = this.selections.all::<MultiBufferPoint>(cx);
5533 let snapshot = this.buffer.read(cx).snapshot(cx);
5534
5535 for selection in selections.iter() {
5536 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5537 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5538 if selection_start.buffer_id != selection_end.buffer_id {
5539 continue;
5540 }
5541 if let Some(ranges) =
5542 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5543 {
5544 for (buffer, entries) in ranges {
5545 linked_ranges.entry(buffer).or_default().extend(entries);
5546 }
5547 }
5548 }
5549 }
5550
5551 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5552 if !this.selections.line_mode {
5553 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5554 for selection in &mut selections {
5555 if selection.is_empty() {
5556 let old_head = selection.head();
5557 let mut new_head =
5558 movement::left(&display_map, old_head.to_display_point(&display_map))
5559 .to_point(&display_map);
5560 if let Some((buffer, line_buffer_range)) = display_map
5561 .buffer_snapshot
5562 .buffer_line_for_row(MultiBufferRow(old_head.row))
5563 {
5564 let indent_size =
5565 buffer.indent_size_for_line(line_buffer_range.start.row);
5566 let indent_len = match indent_size.kind {
5567 IndentKind::Space => {
5568 buffer.settings_at(line_buffer_range.start, cx).tab_size
5569 }
5570 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5571 };
5572 if old_head.column <= indent_size.len && old_head.column > 0 {
5573 let indent_len = indent_len.get();
5574 new_head = cmp::min(
5575 new_head,
5576 MultiBufferPoint::new(
5577 old_head.row,
5578 ((old_head.column - 1) / indent_len) * indent_len,
5579 ),
5580 );
5581 }
5582 }
5583
5584 selection.set_head(new_head, SelectionGoal::None);
5585 }
5586 }
5587 }
5588
5589 this.signature_help_state.set_backspace_pressed(true);
5590 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5591 this.insert("", cx);
5592 let empty_str: Arc<str> = Arc::from("");
5593 for (buffer, edits) in linked_ranges {
5594 let snapshot = buffer.read(cx).snapshot();
5595 use text::ToPoint as TP;
5596
5597 let edits = edits
5598 .into_iter()
5599 .map(|range| {
5600 let end_point = TP::to_point(&range.end, &snapshot);
5601 let mut start_point = TP::to_point(&range.start, &snapshot);
5602
5603 if end_point == start_point {
5604 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5605 .saturating_sub(1);
5606 start_point =
5607 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5608 };
5609
5610 (start_point..end_point, empty_str.clone())
5611 })
5612 .sorted_by_key(|(range, _)| range.start)
5613 .collect::<Vec<_>>();
5614 buffer.update(cx, |this, cx| {
5615 this.edit(edits, None, cx);
5616 })
5617 }
5618 this.refresh_inline_completion(true, false, cx);
5619 linked_editing_ranges::refresh_linked_ranges(this, cx);
5620 });
5621 }
5622
5623 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5624 self.transact(cx, |this, cx| {
5625 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5626 let line_mode = s.line_mode;
5627 s.move_with(|map, selection| {
5628 if selection.is_empty() && !line_mode {
5629 let cursor = movement::right(map, selection.head());
5630 selection.end = cursor;
5631 selection.reversed = true;
5632 selection.goal = SelectionGoal::None;
5633 }
5634 })
5635 });
5636 this.insert("", cx);
5637 this.refresh_inline_completion(true, false, cx);
5638 });
5639 }
5640
5641 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5642 if self.move_to_prev_snippet_tabstop(cx) {
5643 return;
5644 }
5645
5646 self.outdent(&Outdent, cx);
5647 }
5648
5649 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5650 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5651 return;
5652 }
5653
5654 let mut selections = self.selections.all_adjusted(cx);
5655 let buffer = self.buffer.read(cx);
5656 let snapshot = buffer.snapshot(cx);
5657 let rows_iter = selections.iter().map(|s| s.head().row);
5658 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5659
5660 let mut edits = Vec::new();
5661 let mut prev_edited_row = 0;
5662 let mut row_delta = 0;
5663 for selection in &mut selections {
5664 if selection.start.row != prev_edited_row {
5665 row_delta = 0;
5666 }
5667 prev_edited_row = selection.end.row;
5668
5669 // If the selection is non-empty, then increase the indentation of the selected lines.
5670 if !selection.is_empty() {
5671 row_delta =
5672 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5673 continue;
5674 }
5675
5676 // If the selection is empty and the cursor is in the leading whitespace before the
5677 // suggested indentation, then auto-indent the line.
5678 let cursor = selection.head();
5679 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5680 if let Some(suggested_indent) =
5681 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5682 {
5683 if cursor.column < suggested_indent.len
5684 && cursor.column <= current_indent.len
5685 && current_indent.len <= suggested_indent.len
5686 {
5687 selection.start = Point::new(cursor.row, suggested_indent.len);
5688 selection.end = selection.start;
5689 if row_delta == 0 {
5690 edits.extend(Buffer::edit_for_indent_size_adjustment(
5691 cursor.row,
5692 current_indent,
5693 suggested_indent,
5694 ));
5695 row_delta = suggested_indent.len - current_indent.len;
5696 }
5697 continue;
5698 }
5699 }
5700
5701 // Otherwise, insert a hard or soft tab.
5702 let settings = buffer.settings_at(cursor, cx);
5703 let tab_size = if settings.hard_tabs {
5704 IndentSize::tab()
5705 } else {
5706 let tab_size = settings.tab_size.get();
5707 let char_column = snapshot
5708 .text_for_range(Point::new(cursor.row, 0)..cursor)
5709 .flat_map(str::chars)
5710 .count()
5711 + row_delta as usize;
5712 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5713 IndentSize::spaces(chars_to_next_tab_stop)
5714 };
5715 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5716 selection.end = selection.start;
5717 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5718 row_delta += tab_size.len;
5719 }
5720
5721 self.transact(cx, |this, cx| {
5722 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5723 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5724 this.refresh_inline_completion(true, false, cx);
5725 });
5726 }
5727
5728 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5729 if self.read_only(cx) {
5730 return;
5731 }
5732 let mut selections = self.selections.all::<Point>(cx);
5733 let mut prev_edited_row = 0;
5734 let mut row_delta = 0;
5735 let mut edits = Vec::new();
5736 let buffer = self.buffer.read(cx);
5737 let snapshot = buffer.snapshot(cx);
5738 for selection in &mut selections {
5739 if selection.start.row != prev_edited_row {
5740 row_delta = 0;
5741 }
5742 prev_edited_row = selection.end.row;
5743
5744 row_delta =
5745 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5746 }
5747
5748 self.transact(cx, |this, cx| {
5749 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5750 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5751 });
5752 }
5753
5754 fn indent_selection(
5755 buffer: &MultiBuffer,
5756 snapshot: &MultiBufferSnapshot,
5757 selection: &mut Selection<Point>,
5758 edits: &mut Vec<(Range<Point>, String)>,
5759 delta_for_start_row: u32,
5760 cx: &AppContext,
5761 ) -> u32 {
5762 let settings = buffer.settings_at(selection.start, cx);
5763 let tab_size = settings.tab_size.get();
5764 let indent_kind = if settings.hard_tabs {
5765 IndentKind::Tab
5766 } else {
5767 IndentKind::Space
5768 };
5769 let mut start_row = selection.start.row;
5770 let mut end_row = selection.end.row + 1;
5771
5772 // If a selection ends at the beginning of a line, don't indent
5773 // that last line.
5774 if selection.end.column == 0 && selection.end.row > selection.start.row {
5775 end_row -= 1;
5776 }
5777
5778 // Avoid re-indenting a row that has already been indented by a
5779 // previous selection, but still update this selection's column
5780 // to reflect that indentation.
5781 if delta_for_start_row > 0 {
5782 start_row += 1;
5783 selection.start.column += delta_for_start_row;
5784 if selection.end.row == selection.start.row {
5785 selection.end.column += delta_for_start_row;
5786 }
5787 }
5788
5789 let mut delta_for_end_row = 0;
5790 let has_multiple_rows = start_row + 1 != end_row;
5791 for row in start_row..end_row {
5792 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5793 let indent_delta = match (current_indent.kind, indent_kind) {
5794 (IndentKind::Space, IndentKind::Space) => {
5795 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5796 IndentSize::spaces(columns_to_next_tab_stop)
5797 }
5798 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5799 (_, IndentKind::Tab) => IndentSize::tab(),
5800 };
5801
5802 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5803 0
5804 } else {
5805 selection.start.column
5806 };
5807 let row_start = Point::new(row, start);
5808 edits.push((
5809 row_start..row_start,
5810 indent_delta.chars().collect::<String>(),
5811 ));
5812
5813 // Update this selection's endpoints to reflect the indentation.
5814 if row == selection.start.row {
5815 selection.start.column += indent_delta.len;
5816 }
5817 if row == selection.end.row {
5818 selection.end.column += indent_delta.len;
5819 delta_for_end_row = indent_delta.len;
5820 }
5821 }
5822
5823 if selection.start.row == selection.end.row {
5824 delta_for_start_row + delta_for_end_row
5825 } else {
5826 delta_for_end_row
5827 }
5828 }
5829
5830 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5831 if self.read_only(cx) {
5832 return;
5833 }
5834 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5835 let selections = self.selections.all::<Point>(cx);
5836 let mut deletion_ranges = Vec::new();
5837 let mut last_outdent = None;
5838 {
5839 let buffer = self.buffer.read(cx);
5840 let snapshot = buffer.snapshot(cx);
5841 for selection in &selections {
5842 let settings = buffer.settings_at(selection.start, cx);
5843 let tab_size = settings.tab_size.get();
5844 let mut rows = selection.spanned_rows(false, &display_map);
5845
5846 // Avoid re-outdenting a row that has already been outdented by a
5847 // previous selection.
5848 if let Some(last_row) = last_outdent {
5849 if last_row == rows.start {
5850 rows.start = rows.start.next_row();
5851 }
5852 }
5853 let has_multiple_rows = rows.len() > 1;
5854 for row in rows.iter_rows() {
5855 let indent_size = snapshot.indent_size_for_line(row);
5856 if indent_size.len > 0 {
5857 let deletion_len = match indent_size.kind {
5858 IndentKind::Space => {
5859 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5860 if columns_to_prev_tab_stop == 0 {
5861 tab_size
5862 } else {
5863 columns_to_prev_tab_stop
5864 }
5865 }
5866 IndentKind::Tab => 1,
5867 };
5868 let start = if has_multiple_rows
5869 || deletion_len > selection.start.column
5870 || indent_size.len < selection.start.column
5871 {
5872 0
5873 } else {
5874 selection.start.column - deletion_len
5875 };
5876 deletion_ranges.push(
5877 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5878 );
5879 last_outdent = Some(row);
5880 }
5881 }
5882 }
5883 }
5884
5885 self.transact(cx, |this, cx| {
5886 this.buffer.update(cx, |buffer, cx| {
5887 let empty_str: Arc<str> = Arc::default();
5888 buffer.edit(
5889 deletion_ranges
5890 .into_iter()
5891 .map(|range| (range, empty_str.clone())),
5892 None,
5893 cx,
5894 );
5895 });
5896 let selections = this.selections.all::<usize>(cx);
5897 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5898 });
5899 }
5900
5901 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5902 if self.read_only(cx) {
5903 return;
5904 }
5905 let selections = self
5906 .selections
5907 .all::<usize>(cx)
5908 .into_iter()
5909 .map(|s| s.range());
5910
5911 self.transact(cx, |this, cx| {
5912 this.buffer.update(cx, |buffer, cx| {
5913 buffer.autoindent_ranges(selections, cx);
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 delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5921 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5922 let selections = self.selections.all::<Point>(cx);
5923
5924 let mut new_cursors = Vec::new();
5925 let mut edit_ranges = Vec::new();
5926 let mut selections = selections.iter().peekable();
5927 while let Some(selection) = selections.next() {
5928 let mut rows = selection.spanned_rows(false, &display_map);
5929 let goal_display_column = selection.head().to_display_point(&display_map).column();
5930
5931 // Accumulate contiguous regions of rows that we want to delete.
5932 while let Some(next_selection) = selections.peek() {
5933 let next_rows = next_selection.spanned_rows(false, &display_map);
5934 if next_rows.start <= rows.end {
5935 rows.end = next_rows.end;
5936 selections.next().unwrap();
5937 } else {
5938 break;
5939 }
5940 }
5941
5942 let buffer = &display_map.buffer_snapshot;
5943 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5944 let edit_end;
5945 let cursor_buffer_row;
5946 if buffer.max_point().row >= rows.end.0 {
5947 // If there's a line after the range, delete the \n from the end of the row range
5948 // and position the cursor on the next line.
5949 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5950 cursor_buffer_row = rows.end;
5951 } else {
5952 // If there isn't a line after the range, delete the \n from the line before the
5953 // start of the row range and position the cursor there.
5954 edit_start = edit_start.saturating_sub(1);
5955 edit_end = buffer.len();
5956 cursor_buffer_row = rows.start.previous_row();
5957 }
5958
5959 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5960 *cursor.column_mut() =
5961 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5962
5963 new_cursors.push((
5964 selection.id,
5965 buffer.anchor_after(cursor.to_point(&display_map)),
5966 ));
5967 edit_ranges.push(edit_start..edit_end);
5968 }
5969
5970 self.transact(cx, |this, cx| {
5971 let buffer = this.buffer.update(cx, |buffer, cx| {
5972 let empty_str: Arc<str> = Arc::default();
5973 buffer.edit(
5974 edit_ranges
5975 .into_iter()
5976 .map(|range| (range, empty_str.clone())),
5977 None,
5978 cx,
5979 );
5980 buffer.snapshot(cx)
5981 });
5982 let new_selections = new_cursors
5983 .into_iter()
5984 .map(|(id, cursor)| {
5985 let cursor = cursor.to_point(&buffer);
5986 Selection {
5987 id,
5988 start: cursor,
5989 end: cursor,
5990 reversed: false,
5991 goal: SelectionGoal::None,
5992 }
5993 })
5994 .collect();
5995
5996 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5997 s.select(new_selections);
5998 });
5999 });
6000 }
6001
6002 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
6003 if self.read_only(cx) {
6004 return;
6005 }
6006 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6007 for selection in self.selections.all::<Point>(cx) {
6008 let start = MultiBufferRow(selection.start.row);
6009 // Treat single line selections as if they include the next line. Otherwise this action
6010 // would do nothing for single line selections individual cursors.
6011 let end = if selection.start.row == selection.end.row {
6012 MultiBufferRow(selection.start.row + 1)
6013 } else {
6014 MultiBufferRow(selection.end.row)
6015 };
6016
6017 if let Some(last_row_range) = row_ranges.last_mut() {
6018 if start <= last_row_range.end {
6019 last_row_range.end = end;
6020 continue;
6021 }
6022 }
6023 row_ranges.push(start..end);
6024 }
6025
6026 let snapshot = self.buffer.read(cx).snapshot(cx);
6027 let mut cursor_positions = Vec::new();
6028 for row_range in &row_ranges {
6029 let anchor = snapshot.anchor_before(Point::new(
6030 row_range.end.previous_row().0,
6031 snapshot.line_len(row_range.end.previous_row()),
6032 ));
6033 cursor_positions.push(anchor..anchor);
6034 }
6035
6036 self.transact(cx, |this, cx| {
6037 for row_range in row_ranges.into_iter().rev() {
6038 for row in row_range.iter_rows().rev() {
6039 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6040 let next_line_row = row.next_row();
6041 let indent = snapshot.indent_size_for_line(next_line_row);
6042 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6043
6044 let replace =
6045 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6046 " "
6047 } else {
6048 ""
6049 };
6050
6051 this.buffer.update(cx, |buffer, cx| {
6052 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6053 });
6054 }
6055 }
6056
6057 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6058 s.select_anchor_ranges(cursor_positions)
6059 });
6060 });
6061 }
6062
6063 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6064 self.join_lines_impl(true, cx);
6065 }
6066
6067 pub fn sort_lines_case_sensitive(
6068 &mut self,
6069 _: &SortLinesCaseSensitive,
6070 cx: &mut ViewContext<Self>,
6071 ) {
6072 self.manipulate_lines(cx, |lines| lines.sort())
6073 }
6074
6075 pub fn sort_lines_case_insensitive(
6076 &mut self,
6077 _: &SortLinesCaseInsensitive,
6078 cx: &mut ViewContext<Self>,
6079 ) {
6080 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6081 }
6082
6083 pub fn unique_lines_case_insensitive(
6084 &mut self,
6085 _: &UniqueLinesCaseInsensitive,
6086 cx: &mut ViewContext<Self>,
6087 ) {
6088 self.manipulate_lines(cx, |lines| {
6089 let mut seen = HashSet::default();
6090 lines.retain(|line| seen.insert(line.to_lowercase()));
6091 })
6092 }
6093
6094 pub fn unique_lines_case_sensitive(
6095 &mut self,
6096 _: &UniqueLinesCaseSensitive,
6097 cx: &mut ViewContext<Self>,
6098 ) {
6099 self.manipulate_lines(cx, |lines| {
6100 let mut seen = HashSet::default();
6101 lines.retain(|line| seen.insert(*line));
6102 })
6103 }
6104
6105 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6106 let mut revert_changes = HashMap::default();
6107 let snapshot = self.snapshot(cx);
6108 for hunk in hunks_for_ranges(
6109 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6110 &snapshot,
6111 ) {
6112 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6113 }
6114 if !revert_changes.is_empty() {
6115 self.transact(cx, |editor, cx| {
6116 editor.revert(revert_changes, cx);
6117 });
6118 }
6119 }
6120
6121 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6122 let Some(project) = self.project.clone() else {
6123 return;
6124 };
6125 self.reload(project, cx).detach_and_notify_err(cx);
6126 }
6127
6128 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6129 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6130 if !revert_changes.is_empty() {
6131 self.transact(cx, |editor, cx| {
6132 editor.revert(revert_changes, cx);
6133 });
6134 }
6135 }
6136
6137 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6138 let snapshot = self.buffer.read(cx).read(cx);
6139 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6140 drop(snapshot);
6141 let mut revert_changes = HashMap::default();
6142 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6143 if !revert_changes.is_empty() {
6144 self.revert(revert_changes, cx)
6145 }
6146 }
6147 }
6148
6149 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6150 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6151 let project_path = buffer.read(cx).project_path(cx)?;
6152 let project = self.project.as_ref()?.read(cx);
6153 let entry = project.entry_for_path(&project_path, cx)?;
6154 let parent = match &entry.canonical_path {
6155 Some(canonical_path) => canonical_path.to_path_buf(),
6156 None => project.absolute_path(&project_path, cx)?,
6157 }
6158 .parent()?
6159 .to_path_buf();
6160 Some(parent)
6161 }) {
6162 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6163 }
6164 }
6165
6166 fn gather_revert_changes(
6167 &mut self,
6168 selections: &[Selection<Point>],
6169 cx: &mut ViewContext<Editor>,
6170 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6171 let mut revert_changes = HashMap::default();
6172 let snapshot = self.snapshot(cx);
6173 for hunk in hunks_for_selections(&snapshot, selections) {
6174 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6175 }
6176 revert_changes
6177 }
6178
6179 pub fn prepare_revert_change(
6180 &mut self,
6181 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6182 hunk: &MultiBufferDiffHunk,
6183 cx: &AppContext,
6184 ) -> Option<()> {
6185 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6186 let buffer = buffer.read(cx);
6187 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6188 let original_text = change_set
6189 .read(cx)
6190 .base_text
6191 .as_ref()?
6192 .read(cx)
6193 .as_rope()
6194 .slice(hunk.diff_base_byte_range.clone());
6195 let buffer_snapshot = buffer.snapshot();
6196 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6197 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6198 probe
6199 .0
6200 .start
6201 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6202 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6203 }) {
6204 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6205 Some(())
6206 } else {
6207 None
6208 }
6209 }
6210
6211 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6212 self.manipulate_lines(cx, |lines| lines.reverse())
6213 }
6214
6215 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6216 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6217 }
6218
6219 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6220 where
6221 Fn: FnMut(&mut Vec<&str>),
6222 {
6223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6224 let buffer = self.buffer.read(cx).snapshot(cx);
6225
6226 let mut edits = Vec::new();
6227
6228 let selections = self.selections.all::<Point>(cx);
6229 let mut selections = selections.iter().peekable();
6230 let mut contiguous_row_selections = Vec::new();
6231 let mut new_selections = Vec::new();
6232 let mut added_lines = 0;
6233 let mut removed_lines = 0;
6234
6235 while let Some(selection) = selections.next() {
6236 let (start_row, end_row) = consume_contiguous_rows(
6237 &mut contiguous_row_selections,
6238 selection,
6239 &display_map,
6240 &mut selections,
6241 );
6242
6243 let start_point = Point::new(start_row.0, 0);
6244 let end_point = Point::new(
6245 end_row.previous_row().0,
6246 buffer.line_len(end_row.previous_row()),
6247 );
6248 let text = buffer
6249 .text_for_range(start_point..end_point)
6250 .collect::<String>();
6251
6252 let mut lines = text.split('\n').collect_vec();
6253
6254 let lines_before = lines.len();
6255 callback(&mut lines);
6256 let lines_after = lines.len();
6257
6258 edits.push((start_point..end_point, lines.join("\n")));
6259
6260 // Selections must change based on added and removed line count
6261 let start_row =
6262 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6263 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6264 new_selections.push(Selection {
6265 id: selection.id,
6266 start: start_row,
6267 end: end_row,
6268 goal: SelectionGoal::None,
6269 reversed: selection.reversed,
6270 });
6271
6272 if lines_after > lines_before {
6273 added_lines += lines_after - lines_before;
6274 } else if lines_before > lines_after {
6275 removed_lines += lines_before - lines_after;
6276 }
6277 }
6278
6279 self.transact(cx, |this, cx| {
6280 let buffer = this.buffer.update(cx, |buffer, cx| {
6281 buffer.edit(edits, None, cx);
6282 buffer.snapshot(cx)
6283 });
6284
6285 // Recalculate offsets on newly edited buffer
6286 let new_selections = new_selections
6287 .iter()
6288 .map(|s| {
6289 let start_point = Point::new(s.start.0, 0);
6290 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6291 Selection {
6292 id: s.id,
6293 start: buffer.point_to_offset(start_point),
6294 end: buffer.point_to_offset(end_point),
6295 goal: s.goal,
6296 reversed: s.reversed,
6297 }
6298 })
6299 .collect();
6300
6301 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6302 s.select(new_selections);
6303 });
6304
6305 this.request_autoscroll(Autoscroll::fit(), cx);
6306 });
6307 }
6308
6309 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6310 self.manipulate_text(cx, |text| text.to_uppercase())
6311 }
6312
6313 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6314 self.manipulate_text(cx, |text| text.to_lowercase())
6315 }
6316
6317 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6318 self.manipulate_text(cx, |text| {
6319 text.split('\n')
6320 .map(|line| line.to_case(Case::Title))
6321 .join("\n")
6322 })
6323 }
6324
6325 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6326 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6327 }
6328
6329 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6330 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6331 }
6332
6333 pub fn convert_to_upper_camel_case(
6334 &mut self,
6335 _: &ConvertToUpperCamelCase,
6336 cx: &mut ViewContext<Self>,
6337 ) {
6338 self.manipulate_text(cx, |text| {
6339 text.split('\n')
6340 .map(|line| line.to_case(Case::UpperCamel))
6341 .join("\n")
6342 })
6343 }
6344
6345 pub fn convert_to_lower_camel_case(
6346 &mut self,
6347 _: &ConvertToLowerCamelCase,
6348 cx: &mut ViewContext<Self>,
6349 ) {
6350 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6351 }
6352
6353 pub fn convert_to_opposite_case(
6354 &mut self,
6355 _: &ConvertToOppositeCase,
6356 cx: &mut ViewContext<Self>,
6357 ) {
6358 self.manipulate_text(cx, |text| {
6359 text.chars()
6360 .fold(String::with_capacity(text.len()), |mut t, c| {
6361 if c.is_uppercase() {
6362 t.extend(c.to_lowercase());
6363 } else {
6364 t.extend(c.to_uppercase());
6365 }
6366 t
6367 })
6368 })
6369 }
6370
6371 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6372 where
6373 Fn: FnMut(&str) -> String,
6374 {
6375 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6376 let buffer = self.buffer.read(cx).snapshot(cx);
6377
6378 let mut new_selections = Vec::new();
6379 let mut edits = Vec::new();
6380 let mut selection_adjustment = 0i32;
6381
6382 for selection in self.selections.all::<usize>(cx) {
6383 let selection_is_empty = selection.is_empty();
6384
6385 let (start, end) = if selection_is_empty {
6386 let word_range = movement::surrounding_word(
6387 &display_map,
6388 selection.start.to_display_point(&display_map),
6389 );
6390 let start = word_range.start.to_offset(&display_map, Bias::Left);
6391 let end = word_range.end.to_offset(&display_map, Bias::Left);
6392 (start, end)
6393 } else {
6394 (selection.start, selection.end)
6395 };
6396
6397 let text = buffer.text_for_range(start..end).collect::<String>();
6398 let old_length = text.len() as i32;
6399 let text = callback(&text);
6400
6401 new_selections.push(Selection {
6402 start: (start as i32 - selection_adjustment) as usize,
6403 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6404 goal: SelectionGoal::None,
6405 ..selection
6406 });
6407
6408 selection_adjustment += old_length - text.len() as i32;
6409
6410 edits.push((start..end, text));
6411 }
6412
6413 self.transact(cx, |this, cx| {
6414 this.buffer.update(cx, |buffer, cx| {
6415 buffer.edit(edits, None, cx);
6416 });
6417
6418 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6419 s.select(new_selections);
6420 });
6421
6422 this.request_autoscroll(Autoscroll::fit(), cx);
6423 });
6424 }
6425
6426 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6427 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6428 let buffer = &display_map.buffer_snapshot;
6429 let selections = self.selections.all::<Point>(cx);
6430
6431 let mut edits = Vec::new();
6432 let mut selections_iter = selections.iter().peekable();
6433 while let Some(selection) = selections_iter.next() {
6434 let mut rows = selection.spanned_rows(false, &display_map);
6435 // duplicate line-wise
6436 if whole_lines || selection.start == selection.end {
6437 // Avoid duplicating the same lines twice.
6438 while let Some(next_selection) = selections_iter.peek() {
6439 let next_rows = next_selection.spanned_rows(false, &display_map);
6440 if next_rows.start < rows.end {
6441 rows.end = next_rows.end;
6442 selections_iter.next().unwrap();
6443 } else {
6444 break;
6445 }
6446 }
6447
6448 // Copy the text from the selected row region and splice it either at the start
6449 // or end of the region.
6450 let start = Point::new(rows.start.0, 0);
6451 let end = Point::new(
6452 rows.end.previous_row().0,
6453 buffer.line_len(rows.end.previous_row()),
6454 );
6455 let text = buffer
6456 .text_for_range(start..end)
6457 .chain(Some("\n"))
6458 .collect::<String>();
6459 let insert_location = if upwards {
6460 Point::new(rows.end.0, 0)
6461 } else {
6462 start
6463 };
6464 edits.push((insert_location..insert_location, text));
6465 } else {
6466 // duplicate character-wise
6467 let start = selection.start;
6468 let end = selection.end;
6469 let text = buffer.text_for_range(start..end).collect::<String>();
6470 edits.push((selection.end..selection.end, text));
6471 }
6472 }
6473
6474 self.transact(cx, |this, cx| {
6475 this.buffer.update(cx, |buffer, cx| {
6476 buffer.edit(edits, None, cx);
6477 });
6478
6479 this.request_autoscroll(Autoscroll::fit(), cx);
6480 });
6481 }
6482
6483 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6484 self.duplicate(true, true, cx);
6485 }
6486
6487 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6488 self.duplicate(false, true, cx);
6489 }
6490
6491 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6492 self.duplicate(false, false, cx);
6493 }
6494
6495 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6496 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6497 let buffer = self.buffer.read(cx).snapshot(cx);
6498
6499 let mut edits = Vec::new();
6500 let mut unfold_ranges = Vec::new();
6501 let mut refold_creases = Vec::new();
6502
6503 let selections = self.selections.all::<Point>(cx);
6504 let mut selections = selections.iter().peekable();
6505 let mut contiguous_row_selections = Vec::new();
6506 let mut new_selections = Vec::new();
6507
6508 while let Some(selection) = selections.next() {
6509 // Find all the selections that span a contiguous row range
6510 let (start_row, end_row) = consume_contiguous_rows(
6511 &mut contiguous_row_selections,
6512 selection,
6513 &display_map,
6514 &mut selections,
6515 );
6516
6517 // Move the text spanned by the row range to be before the line preceding the row range
6518 if start_row.0 > 0 {
6519 let range_to_move = Point::new(
6520 start_row.previous_row().0,
6521 buffer.line_len(start_row.previous_row()),
6522 )
6523 ..Point::new(
6524 end_row.previous_row().0,
6525 buffer.line_len(end_row.previous_row()),
6526 );
6527 let insertion_point = display_map
6528 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6529 .0;
6530
6531 // Don't move lines across excerpts
6532 if buffer
6533 .excerpt_boundaries_in_range((
6534 Bound::Excluded(insertion_point),
6535 Bound::Included(range_to_move.end),
6536 ))
6537 .next()
6538 .is_none()
6539 {
6540 let text = buffer
6541 .text_for_range(range_to_move.clone())
6542 .flat_map(|s| s.chars())
6543 .skip(1)
6544 .chain(['\n'])
6545 .collect::<String>();
6546
6547 edits.push((
6548 buffer.anchor_after(range_to_move.start)
6549 ..buffer.anchor_before(range_to_move.end),
6550 String::new(),
6551 ));
6552 let insertion_anchor = buffer.anchor_after(insertion_point);
6553 edits.push((insertion_anchor..insertion_anchor, text));
6554
6555 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6556
6557 // Move selections up
6558 new_selections.extend(contiguous_row_selections.drain(..).map(
6559 |mut selection| {
6560 selection.start.row -= row_delta;
6561 selection.end.row -= row_delta;
6562 selection
6563 },
6564 ));
6565
6566 // Move folds up
6567 unfold_ranges.push(range_to_move.clone());
6568 for fold in display_map.folds_in_range(
6569 buffer.anchor_before(range_to_move.start)
6570 ..buffer.anchor_after(range_to_move.end),
6571 ) {
6572 let mut start = fold.range.start.to_point(&buffer);
6573 let mut end = fold.range.end.to_point(&buffer);
6574 start.row -= row_delta;
6575 end.row -= row_delta;
6576 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6577 }
6578 }
6579 }
6580
6581 // If we didn't move line(s), preserve the existing selections
6582 new_selections.append(&mut contiguous_row_selections);
6583 }
6584
6585 self.transact(cx, |this, cx| {
6586 this.unfold_ranges(&unfold_ranges, true, true, cx);
6587 this.buffer.update(cx, |buffer, cx| {
6588 for (range, text) in edits {
6589 buffer.edit([(range, text)], None, cx);
6590 }
6591 });
6592 this.fold_creases(refold_creases, true, cx);
6593 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6594 s.select(new_selections);
6595 })
6596 });
6597 }
6598
6599 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6600 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6601 let buffer = self.buffer.read(cx).snapshot(cx);
6602
6603 let mut edits = Vec::new();
6604 let mut unfold_ranges = Vec::new();
6605 let mut refold_creases = Vec::new();
6606
6607 let selections = self.selections.all::<Point>(cx);
6608 let mut selections = selections.iter().peekable();
6609 let mut contiguous_row_selections = Vec::new();
6610 let mut new_selections = Vec::new();
6611
6612 while let Some(selection) = selections.next() {
6613 // Find all the selections that span a contiguous row range
6614 let (start_row, end_row) = consume_contiguous_rows(
6615 &mut contiguous_row_selections,
6616 selection,
6617 &display_map,
6618 &mut selections,
6619 );
6620
6621 // Move the text spanned by the row range to be after the last line of the row range
6622 if end_row.0 <= buffer.max_point().row {
6623 let range_to_move =
6624 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6625 let insertion_point = display_map
6626 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6627 .0;
6628
6629 // Don't move lines across excerpt boundaries
6630 if buffer
6631 .excerpt_boundaries_in_range((
6632 Bound::Excluded(range_to_move.start),
6633 Bound::Included(insertion_point),
6634 ))
6635 .next()
6636 .is_none()
6637 {
6638 let mut text = String::from("\n");
6639 text.extend(buffer.text_for_range(range_to_move.clone()));
6640 text.pop(); // Drop trailing newline
6641 edits.push((
6642 buffer.anchor_after(range_to_move.start)
6643 ..buffer.anchor_before(range_to_move.end),
6644 String::new(),
6645 ));
6646 let insertion_anchor = buffer.anchor_after(insertion_point);
6647 edits.push((insertion_anchor..insertion_anchor, text));
6648
6649 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6650
6651 // Move selections down
6652 new_selections.extend(contiguous_row_selections.drain(..).map(
6653 |mut selection| {
6654 selection.start.row += row_delta;
6655 selection.end.row += row_delta;
6656 selection
6657 },
6658 ));
6659
6660 // Move folds down
6661 unfold_ranges.push(range_to_move.clone());
6662 for fold in display_map.folds_in_range(
6663 buffer.anchor_before(range_to_move.start)
6664 ..buffer.anchor_after(range_to_move.end),
6665 ) {
6666 let mut start = fold.range.start.to_point(&buffer);
6667 let mut end = fold.range.end.to_point(&buffer);
6668 start.row += row_delta;
6669 end.row += row_delta;
6670 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6671 }
6672 }
6673 }
6674
6675 // If we didn't move line(s), preserve the existing selections
6676 new_selections.append(&mut contiguous_row_selections);
6677 }
6678
6679 self.transact(cx, |this, cx| {
6680 this.unfold_ranges(&unfold_ranges, true, true, cx);
6681 this.buffer.update(cx, |buffer, cx| {
6682 for (range, text) in edits {
6683 buffer.edit([(range, text)], None, cx);
6684 }
6685 });
6686 this.fold_creases(refold_creases, true, cx);
6687 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6688 });
6689 }
6690
6691 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6692 let text_layout_details = &self.text_layout_details(cx);
6693 self.transact(cx, |this, cx| {
6694 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6695 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6696 let line_mode = s.line_mode;
6697 s.move_with(|display_map, selection| {
6698 if !selection.is_empty() || line_mode {
6699 return;
6700 }
6701
6702 let mut head = selection.head();
6703 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6704 if head.column() == display_map.line_len(head.row()) {
6705 transpose_offset = display_map
6706 .buffer_snapshot
6707 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6708 }
6709
6710 if transpose_offset == 0 {
6711 return;
6712 }
6713
6714 *head.column_mut() += 1;
6715 head = display_map.clip_point(head, Bias::Right);
6716 let goal = SelectionGoal::HorizontalPosition(
6717 display_map
6718 .x_for_display_point(head, text_layout_details)
6719 .into(),
6720 );
6721 selection.collapse_to(head, goal);
6722
6723 let transpose_start = display_map
6724 .buffer_snapshot
6725 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6726 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6727 let transpose_end = display_map
6728 .buffer_snapshot
6729 .clip_offset(transpose_offset + 1, Bias::Right);
6730 if let Some(ch) =
6731 display_map.buffer_snapshot.chars_at(transpose_start).next()
6732 {
6733 edits.push((transpose_start..transpose_offset, String::new()));
6734 edits.push((transpose_end..transpose_end, ch.to_string()));
6735 }
6736 }
6737 });
6738 edits
6739 });
6740 this.buffer
6741 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6742 let selections = this.selections.all::<usize>(cx);
6743 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6744 s.select(selections);
6745 });
6746 });
6747 }
6748
6749 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6750 self.rewrap_impl(IsVimMode::No, cx)
6751 }
6752
6753 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6754 let buffer = self.buffer.read(cx).snapshot(cx);
6755 let selections = self.selections.all::<Point>(cx);
6756 let mut selections = selections.iter().peekable();
6757
6758 let mut edits = Vec::new();
6759 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6760
6761 while let Some(selection) = selections.next() {
6762 let mut start_row = selection.start.row;
6763 let mut end_row = selection.end.row;
6764
6765 // Skip selections that overlap with a range that has already been rewrapped.
6766 let selection_range = start_row..end_row;
6767 if rewrapped_row_ranges
6768 .iter()
6769 .any(|range| range.overlaps(&selection_range))
6770 {
6771 continue;
6772 }
6773
6774 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6775
6776 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6777 match language_scope.language_name().0.as_ref() {
6778 "Markdown" | "Plain Text" => {
6779 should_rewrap = true;
6780 }
6781 _ => {}
6782 }
6783 }
6784
6785 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6786
6787 // Since not all lines in the selection may be at the same indent
6788 // level, choose the indent size that is the most common between all
6789 // of the lines.
6790 //
6791 // If there is a tie, we use the deepest indent.
6792 let (indent_size, indent_end) = {
6793 let mut indent_size_occurrences = HashMap::default();
6794 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6795
6796 for row in start_row..=end_row {
6797 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6798 rows_by_indent_size.entry(indent).or_default().push(row);
6799 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6800 }
6801
6802 let indent_size = indent_size_occurrences
6803 .into_iter()
6804 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6805 .map(|(indent, _)| indent)
6806 .unwrap_or_default();
6807 let row = rows_by_indent_size[&indent_size][0];
6808 let indent_end = Point::new(row, indent_size.len);
6809
6810 (indent_size, indent_end)
6811 };
6812
6813 let mut line_prefix = indent_size.chars().collect::<String>();
6814
6815 if let Some(comment_prefix) =
6816 buffer
6817 .language_scope_at(selection.head())
6818 .and_then(|language| {
6819 language
6820 .line_comment_prefixes()
6821 .iter()
6822 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6823 .cloned()
6824 })
6825 {
6826 line_prefix.push_str(&comment_prefix);
6827 should_rewrap = true;
6828 }
6829
6830 if !should_rewrap {
6831 continue;
6832 }
6833
6834 if selection.is_empty() {
6835 'expand_upwards: while start_row > 0 {
6836 let prev_row = start_row - 1;
6837 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6838 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6839 {
6840 start_row = prev_row;
6841 } else {
6842 break 'expand_upwards;
6843 }
6844 }
6845
6846 'expand_downwards: while end_row < buffer.max_point().row {
6847 let next_row = end_row + 1;
6848 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6849 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6850 {
6851 end_row = next_row;
6852 } else {
6853 break 'expand_downwards;
6854 }
6855 }
6856 }
6857
6858 let start = Point::new(start_row, 0);
6859 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6860 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6861 let Some(lines_without_prefixes) = selection_text
6862 .lines()
6863 .map(|line| {
6864 line.strip_prefix(&line_prefix)
6865 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6866 .ok_or_else(|| {
6867 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6868 })
6869 })
6870 .collect::<Result<Vec<_>, _>>()
6871 .log_err()
6872 else {
6873 continue;
6874 };
6875
6876 let wrap_column = buffer
6877 .settings_at(Point::new(start_row, 0), cx)
6878 .preferred_line_length as usize;
6879 let wrapped_text = wrap_with_prefix(
6880 line_prefix,
6881 lines_without_prefixes.join(" "),
6882 wrap_column,
6883 tab_size,
6884 );
6885
6886 // TODO: should always use char-based diff while still supporting cursor behavior that
6887 // matches vim.
6888 let diff = match is_vim_mode {
6889 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6890 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6891 };
6892 let mut offset = start.to_offset(&buffer);
6893 let mut moved_since_edit = true;
6894
6895 for change in diff.iter_all_changes() {
6896 let value = change.value();
6897 match change.tag() {
6898 ChangeTag::Equal => {
6899 offset += value.len();
6900 moved_since_edit = true;
6901 }
6902 ChangeTag::Delete => {
6903 let start = buffer.anchor_after(offset);
6904 let end = buffer.anchor_before(offset + value.len());
6905
6906 if moved_since_edit {
6907 edits.push((start..end, String::new()));
6908 } else {
6909 edits.last_mut().unwrap().0.end = end;
6910 }
6911
6912 offset += value.len();
6913 moved_since_edit = false;
6914 }
6915 ChangeTag::Insert => {
6916 if moved_since_edit {
6917 let anchor = buffer.anchor_after(offset);
6918 edits.push((anchor..anchor, value.to_string()));
6919 } else {
6920 edits.last_mut().unwrap().1.push_str(value);
6921 }
6922
6923 moved_since_edit = false;
6924 }
6925 }
6926 }
6927
6928 rewrapped_row_ranges.push(start_row..=end_row);
6929 }
6930
6931 self.buffer
6932 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6933 }
6934
6935 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6936 let mut text = String::new();
6937 let buffer = self.buffer.read(cx).snapshot(cx);
6938 let mut selections = self.selections.all::<Point>(cx);
6939 let mut clipboard_selections = Vec::with_capacity(selections.len());
6940 {
6941 let max_point = buffer.max_point();
6942 let mut is_first = true;
6943 for selection in &mut selections {
6944 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6945 if is_entire_line {
6946 selection.start = Point::new(selection.start.row, 0);
6947 if !selection.is_empty() && selection.end.column == 0 {
6948 selection.end = cmp::min(max_point, selection.end);
6949 } else {
6950 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6951 }
6952 selection.goal = SelectionGoal::None;
6953 }
6954 if is_first {
6955 is_first = false;
6956 } else {
6957 text += "\n";
6958 }
6959 let mut len = 0;
6960 for chunk in buffer.text_for_range(selection.start..selection.end) {
6961 text.push_str(chunk);
6962 len += chunk.len();
6963 }
6964 clipboard_selections.push(ClipboardSelection {
6965 len,
6966 is_entire_line,
6967 first_line_indent: buffer
6968 .indent_size_for_line(MultiBufferRow(selection.start.row))
6969 .len,
6970 });
6971 }
6972 }
6973
6974 self.transact(cx, |this, cx| {
6975 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6976 s.select(selections);
6977 });
6978 this.insert("", cx);
6979 });
6980 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6981 }
6982
6983 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6984 let item = self.cut_common(cx);
6985 cx.write_to_clipboard(item);
6986 }
6987
6988 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6989 self.change_selections(None, cx, |s| {
6990 s.move_with(|snapshot, sel| {
6991 if sel.is_empty() {
6992 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6993 }
6994 });
6995 });
6996 let item = self.cut_common(cx);
6997 cx.set_global(KillRing(item))
6998 }
6999
7000 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7001 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7002 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7003 (kill_ring.text().to_string(), kill_ring.metadata_json())
7004 } else {
7005 return;
7006 }
7007 } else {
7008 return;
7009 };
7010 self.do_paste(&text, metadata, false, cx);
7011 }
7012
7013 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7014 let selections = self.selections.all::<Point>(cx);
7015 let buffer = self.buffer.read(cx).read(cx);
7016 let mut text = String::new();
7017
7018 let mut clipboard_selections = Vec::with_capacity(selections.len());
7019 {
7020 let max_point = buffer.max_point();
7021 let mut is_first = true;
7022 for selection in selections.iter() {
7023 let mut start = selection.start;
7024 let mut end = selection.end;
7025 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7026 if is_entire_line {
7027 start = Point::new(start.row, 0);
7028 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7029 }
7030 if is_first {
7031 is_first = false;
7032 } else {
7033 text += "\n";
7034 }
7035 let mut len = 0;
7036 for chunk in buffer.text_for_range(start..end) {
7037 text.push_str(chunk);
7038 len += chunk.len();
7039 }
7040 clipboard_selections.push(ClipboardSelection {
7041 len,
7042 is_entire_line,
7043 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7044 });
7045 }
7046 }
7047
7048 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7049 text,
7050 clipboard_selections,
7051 ));
7052 }
7053
7054 pub fn do_paste(
7055 &mut self,
7056 text: &String,
7057 clipboard_selections: Option<Vec<ClipboardSelection>>,
7058 handle_entire_lines: bool,
7059 cx: &mut ViewContext<Self>,
7060 ) {
7061 if self.read_only(cx) {
7062 return;
7063 }
7064
7065 let clipboard_text = Cow::Borrowed(text);
7066
7067 self.transact(cx, |this, cx| {
7068 if let Some(mut clipboard_selections) = clipboard_selections {
7069 let old_selections = this.selections.all::<usize>(cx);
7070 let all_selections_were_entire_line =
7071 clipboard_selections.iter().all(|s| s.is_entire_line);
7072 let first_selection_indent_column =
7073 clipboard_selections.first().map(|s| s.first_line_indent);
7074 if clipboard_selections.len() != old_selections.len() {
7075 clipboard_selections.drain(..);
7076 }
7077 let cursor_offset = this.selections.last::<usize>(cx).head();
7078 let mut auto_indent_on_paste = true;
7079
7080 this.buffer.update(cx, |buffer, cx| {
7081 let snapshot = buffer.read(cx);
7082 auto_indent_on_paste =
7083 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7084
7085 let mut start_offset = 0;
7086 let mut edits = Vec::new();
7087 let mut original_indent_columns = Vec::new();
7088 for (ix, selection) in old_selections.iter().enumerate() {
7089 let to_insert;
7090 let entire_line;
7091 let original_indent_column;
7092 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7093 let end_offset = start_offset + clipboard_selection.len;
7094 to_insert = &clipboard_text[start_offset..end_offset];
7095 entire_line = clipboard_selection.is_entire_line;
7096 start_offset = end_offset + 1;
7097 original_indent_column = Some(clipboard_selection.first_line_indent);
7098 } else {
7099 to_insert = clipboard_text.as_str();
7100 entire_line = all_selections_were_entire_line;
7101 original_indent_column = first_selection_indent_column
7102 }
7103
7104 // If the corresponding selection was empty when this slice of the
7105 // clipboard text was written, then the entire line containing the
7106 // selection was copied. If this selection is also currently empty,
7107 // then paste the line before the current line of the buffer.
7108 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7109 let column = selection.start.to_point(&snapshot).column as usize;
7110 let line_start = selection.start - column;
7111 line_start..line_start
7112 } else {
7113 selection.range()
7114 };
7115
7116 edits.push((range, to_insert));
7117 original_indent_columns.extend(original_indent_column);
7118 }
7119 drop(snapshot);
7120
7121 buffer.edit(
7122 edits,
7123 if auto_indent_on_paste {
7124 Some(AutoindentMode::Block {
7125 original_indent_columns,
7126 })
7127 } else {
7128 None
7129 },
7130 cx,
7131 );
7132 });
7133
7134 let selections = this.selections.all::<usize>(cx);
7135 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7136 } else {
7137 this.insert(&clipboard_text, cx);
7138 }
7139 });
7140 }
7141
7142 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7143 if let Some(item) = cx.read_from_clipboard() {
7144 let entries = item.entries();
7145
7146 match entries.first() {
7147 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7148 // of all the pasted entries.
7149 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7150 .do_paste(
7151 clipboard_string.text(),
7152 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7153 true,
7154 cx,
7155 ),
7156 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7157 }
7158 }
7159 }
7160
7161 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7162 if self.read_only(cx) {
7163 return;
7164 }
7165
7166 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7167 if let Some((selections, _)) =
7168 self.selection_history.transaction(transaction_id).cloned()
7169 {
7170 self.change_selections(None, cx, |s| {
7171 s.select_anchors(selections.to_vec());
7172 });
7173 }
7174 self.request_autoscroll(Autoscroll::fit(), cx);
7175 self.unmark_text(cx);
7176 self.refresh_inline_completion(true, false, cx);
7177 cx.emit(EditorEvent::Edited { transaction_id });
7178 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7179 }
7180 }
7181
7182 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7183 if self.read_only(cx) {
7184 return;
7185 }
7186
7187 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7188 if let Some((_, Some(selections))) =
7189 self.selection_history.transaction(transaction_id).cloned()
7190 {
7191 self.change_selections(None, cx, |s| {
7192 s.select_anchors(selections.to_vec());
7193 });
7194 }
7195 self.request_autoscroll(Autoscroll::fit(), cx);
7196 self.unmark_text(cx);
7197 self.refresh_inline_completion(true, false, cx);
7198 cx.emit(EditorEvent::Edited { transaction_id });
7199 }
7200 }
7201
7202 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7203 self.buffer
7204 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7205 }
7206
7207 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7208 self.buffer
7209 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7210 }
7211
7212 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7213 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7214 let line_mode = s.line_mode;
7215 s.move_with(|map, selection| {
7216 let cursor = if selection.is_empty() && !line_mode {
7217 movement::left(map, selection.start)
7218 } else {
7219 selection.start
7220 };
7221 selection.collapse_to(cursor, SelectionGoal::None);
7222 });
7223 })
7224 }
7225
7226 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7227 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7228 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7229 })
7230 }
7231
7232 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7233 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7234 let line_mode = s.line_mode;
7235 s.move_with(|map, selection| {
7236 let cursor = if selection.is_empty() && !line_mode {
7237 movement::right(map, selection.end)
7238 } else {
7239 selection.end
7240 };
7241 selection.collapse_to(cursor, SelectionGoal::None)
7242 });
7243 })
7244 }
7245
7246 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7248 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7249 })
7250 }
7251
7252 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7253 if self.take_rename(true, cx).is_some() {
7254 return;
7255 }
7256
7257 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7258 cx.propagate();
7259 return;
7260 }
7261
7262 let text_layout_details = &self.text_layout_details(cx);
7263 let selection_count = self.selections.count();
7264 let first_selection = self.selections.first_anchor();
7265
7266 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7267 let line_mode = s.line_mode;
7268 s.move_with(|map, selection| {
7269 if !selection.is_empty() && !line_mode {
7270 selection.goal = SelectionGoal::None;
7271 }
7272 let (cursor, goal) = movement::up(
7273 map,
7274 selection.start,
7275 selection.goal,
7276 false,
7277 text_layout_details,
7278 );
7279 selection.collapse_to(cursor, goal);
7280 });
7281 });
7282
7283 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7284 {
7285 cx.propagate();
7286 }
7287 }
7288
7289 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7290 if self.take_rename(true, cx).is_some() {
7291 return;
7292 }
7293
7294 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7295 cx.propagate();
7296 return;
7297 }
7298
7299 let text_layout_details = &self.text_layout_details(cx);
7300
7301 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7302 let line_mode = s.line_mode;
7303 s.move_with(|map, selection| {
7304 if !selection.is_empty() && !line_mode {
7305 selection.goal = SelectionGoal::None;
7306 }
7307 let (cursor, goal) = movement::up_by_rows(
7308 map,
7309 selection.start,
7310 action.lines,
7311 selection.goal,
7312 false,
7313 text_layout_details,
7314 );
7315 selection.collapse_to(cursor, goal);
7316 });
7317 })
7318 }
7319
7320 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7321 if self.take_rename(true, cx).is_some() {
7322 return;
7323 }
7324
7325 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7326 cx.propagate();
7327 return;
7328 }
7329
7330 let text_layout_details = &self.text_layout_details(cx);
7331
7332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7333 let line_mode = s.line_mode;
7334 s.move_with(|map, selection| {
7335 if !selection.is_empty() && !line_mode {
7336 selection.goal = SelectionGoal::None;
7337 }
7338 let (cursor, goal) = movement::down_by_rows(
7339 map,
7340 selection.start,
7341 action.lines,
7342 selection.goal,
7343 false,
7344 text_layout_details,
7345 );
7346 selection.collapse_to(cursor, goal);
7347 });
7348 })
7349 }
7350
7351 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7352 let text_layout_details = &self.text_layout_details(cx);
7353 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7354 s.move_heads_with(|map, head, goal| {
7355 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7356 })
7357 })
7358 }
7359
7360 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7361 let text_layout_details = &self.text_layout_details(cx);
7362 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7363 s.move_heads_with(|map, head, goal| {
7364 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7365 })
7366 })
7367 }
7368
7369 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7370 let Some(row_count) = self.visible_row_count() else {
7371 return;
7372 };
7373
7374 let text_layout_details = &self.text_layout_details(cx);
7375
7376 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7377 s.move_heads_with(|map, head, goal| {
7378 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7379 })
7380 })
7381 }
7382
7383 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7384 if self.take_rename(true, cx).is_some() {
7385 return;
7386 }
7387
7388 if self
7389 .context_menu
7390 .borrow_mut()
7391 .as_mut()
7392 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7393 .unwrap_or(false)
7394 {
7395 return;
7396 }
7397
7398 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7399 cx.propagate();
7400 return;
7401 }
7402
7403 let Some(row_count) = self.visible_row_count() else {
7404 return;
7405 };
7406
7407 let autoscroll = if action.center_cursor {
7408 Autoscroll::center()
7409 } else {
7410 Autoscroll::fit()
7411 };
7412
7413 let text_layout_details = &self.text_layout_details(cx);
7414
7415 self.change_selections(Some(autoscroll), cx, |s| {
7416 let line_mode = s.line_mode;
7417 s.move_with(|map, selection| {
7418 if !selection.is_empty() && !line_mode {
7419 selection.goal = SelectionGoal::None;
7420 }
7421 let (cursor, goal) = movement::up_by_rows(
7422 map,
7423 selection.end,
7424 row_count,
7425 selection.goal,
7426 false,
7427 text_layout_details,
7428 );
7429 selection.collapse_to(cursor, goal);
7430 });
7431 });
7432 }
7433
7434 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7435 let text_layout_details = &self.text_layout_details(cx);
7436 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7437 s.move_heads_with(|map, head, goal| {
7438 movement::up(map, head, goal, false, text_layout_details)
7439 })
7440 })
7441 }
7442
7443 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7444 self.take_rename(true, cx);
7445
7446 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7447 cx.propagate();
7448 return;
7449 }
7450
7451 let text_layout_details = &self.text_layout_details(cx);
7452 let selection_count = self.selections.count();
7453 let first_selection = self.selections.first_anchor();
7454
7455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7456 let line_mode = s.line_mode;
7457 s.move_with(|map, selection| {
7458 if !selection.is_empty() && !line_mode {
7459 selection.goal = SelectionGoal::None;
7460 }
7461 let (cursor, goal) = movement::down(
7462 map,
7463 selection.end,
7464 selection.goal,
7465 false,
7466 text_layout_details,
7467 );
7468 selection.collapse_to(cursor, goal);
7469 });
7470 });
7471
7472 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7473 {
7474 cx.propagate();
7475 }
7476 }
7477
7478 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7479 let Some(row_count) = self.visible_row_count() else {
7480 return;
7481 };
7482
7483 let text_layout_details = &self.text_layout_details(cx);
7484
7485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7486 s.move_heads_with(|map, head, goal| {
7487 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7488 })
7489 })
7490 }
7491
7492 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7493 if self.take_rename(true, cx).is_some() {
7494 return;
7495 }
7496
7497 if self
7498 .context_menu
7499 .borrow_mut()
7500 .as_mut()
7501 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7502 .unwrap_or(false)
7503 {
7504 return;
7505 }
7506
7507 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7508 cx.propagate();
7509 return;
7510 }
7511
7512 let Some(row_count) = self.visible_row_count() else {
7513 return;
7514 };
7515
7516 let autoscroll = if action.center_cursor {
7517 Autoscroll::center()
7518 } else {
7519 Autoscroll::fit()
7520 };
7521
7522 let text_layout_details = &self.text_layout_details(cx);
7523 self.change_selections(Some(autoscroll), cx, |s| {
7524 let line_mode = s.line_mode;
7525 s.move_with(|map, selection| {
7526 if !selection.is_empty() && !line_mode {
7527 selection.goal = SelectionGoal::None;
7528 }
7529 let (cursor, goal) = movement::down_by_rows(
7530 map,
7531 selection.end,
7532 row_count,
7533 selection.goal,
7534 false,
7535 text_layout_details,
7536 );
7537 selection.collapse_to(cursor, goal);
7538 });
7539 });
7540 }
7541
7542 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7543 let text_layout_details = &self.text_layout_details(cx);
7544 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7545 s.move_heads_with(|map, head, goal| {
7546 movement::down(map, head, goal, false, text_layout_details)
7547 })
7548 });
7549 }
7550
7551 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7552 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7553 context_menu.select_first(self.completion_provider.as_deref(), cx);
7554 }
7555 }
7556
7557 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7558 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7559 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7560 }
7561 }
7562
7563 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7564 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7565 context_menu.select_next(self.completion_provider.as_deref(), cx);
7566 }
7567 }
7568
7569 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7570 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7571 context_menu.select_last(self.completion_provider.as_deref(), cx);
7572 }
7573 }
7574
7575 pub fn move_to_previous_word_start(
7576 &mut self,
7577 _: &MoveToPreviousWordStart,
7578 cx: &mut ViewContext<Self>,
7579 ) {
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 s.move_cursors_with(|map, head, _| {
7582 (
7583 movement::previous_word_start(map, head),
7584 SelectionGoal::None,
7585 )
7586 });
7587 })
7588 }
7589
7590 pub fn move_to_previous_subword_start(
7591 &mut self,
7592 _: &MoveToPreviousSubwordStart,
7593 cx: &mut ViewContext<Self>,
7594 ) {
7595 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7596 s.move_cursors_with(|map, head, _| {
7597 (
7598 movement::previous_subword_start(map, head),
7599 SelectionGoal::None,
7600 )
7601 });
7602 })
7603 }
7604
7605 pub fn select_to_previous_word_start(
7606 &mut self,
7607 _: &SelectToPreviousWordStart,
7608 cx: &mut ViewContext<Self>,
7609 ) {
7610 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7611 s.move_heads_with(|map, head, _| {
7612 (
7613 movement::previous_word_start(map, head),
7614 SelectionGoal::None,
7615 )
7616 });
7617 })
7618 }
7619
7620 pub fn select_to_previous_subword_start(
7621 &mut self,
7622 _: &SelectToPreviousSubwordStart,
7623 cx: &mut ViewContext<Self>,
7624 ) {
7625 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7626 s.move_heads_with(|map, head, _| {
7627 (
7628 movement::previous_subword_start(map, head),
7629 SelectionGoal::None,
7630 )
7631 });
7632 })
7633 }
7634
7635 pub fn delete_to_previous_word_start(
7636 &mut self,
7637 action: &DeleteToPreviousWordStart,
7638 cx: &mut ViewContext<Self>,
7639 ) {
7640 self.transact(cx, |this, cx| {
7641 this.select_autoclose_pair(cx);
7642 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7643 let line_mode = s.line_mode;
7644 s.move_with(|map, selection| {
7645 if selection.is_empty() && !line_mode {
7646 let cursor = if action.ignore_newlines {
7647 movement::previous_word_start(map, selection.head())
7648 } else {
7649 movement::previous_word_start_or_newline(map, selection.head())
7650 };
7651 selection.set_head(cursor, SelectionGoal::None);
7652 }
7653 });
7654 });
7655 this.insert("", cx);
7656 });
7657 }
7658
7659 pub fn delete_to_previous_subword_start(
7660 &mut self,
7661 _: &DeleteToPreviousSubwordStart,
7662 cx: &mut ViewContext<Self>,
7663 ) {
7664 self.transact(cx, |this, cx| {
7665 this.select_autoclose_pair(cx);
7666 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7667 let line_mode = s.line_mode;
7668 s.move_with(|map, selection| {
7669 if selection.is_empty() && !line_mode {
7670 let cursor = movement::previous_subword_start(map, selection.head());
7671 selection.set_head(cursor, SelectionGoal::None);
7672 }
7673 });
7674 });
7675 this.insert("", cx);
7676 });
7677 }
7678
7679 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7681 s.move_cursors_with(|map, head, _| {
7682 (movement::next_word_end(map, head), SelectionGoal::None)
7683 });
7684 })
7685 }
7686
7687 pub fn move_to_next_subword_end(
7688 &mut self,
7689 _: &MoveToNextSubwordEnd,
7690 cx: &mut ViewContext<Self>,
7691 ) {
7692 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7693 s.move_cursors_with(|map, head, _| {
7694 (movement::next_subword_end(map, head), SelectionGoal::None)
7695 });
7696 })
7697 }
7698
7699 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7700 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7701 s.move_heads_with(|map, head, _| {
7702 (movement::next_word_end(map, head), SelectionGoal::None)
7703 });
7704 })
7705 }
7706
7707 pub fn select_to_next_subword_end(
7708 &mut self,
7709 _: &SelectToNextSubwordEnd,
7710 cx: &mut ViewContext<Self>,
7711 ) {
7712 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7713 s.move_heads_with(|map, head, _| {
7714 (movement::next_subword_end(map, head), SelectionGoal::None)
7715 });
7716 })
7717 }
7718
7719 pub fn delete_to_next_word_end(
7720 &mut self,
7721 action: &DeleteToNextWordEnd,
7722 cx: &mut ViewContext<Self>,
7723 ) {
7724 self.transact(cx, |this, cx| {
7725 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7726 let line_mode = s.line_mode;
7727 s.move_with(|map, selection| {
7728 if selection.is_empty() && !line_mode {
7729 let cursor = if action.ignore_newlines {
7730 movement::next_word_end(map, selection.head())
7731 } else {
7732 movement::next_word_end_or_newline(map, selection.head())
7733 };
7734 selection.set_head(cursor, SelectionGoal::None);
7735 }
7736 });
7737 });
7738 this.insert("", cx);
7739 });
7740 }
7741
7742 pub fn delete_to_next_subword_end(
7743 &mut self,
7744 _: &DeleteToNextSubwordEnd,
7745 cx: &mut ViewContext<Self>,
7746 ) {
7747 self.transact(cx, |this, cx| {
7748 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7749 s.move_with(|map, selection| {
7750 if selection.is_empty() {
7751 let cursor = movement::next_subword_end(map, selection.head());
7752 selection.set_head(cursor, SelectionGoal::None);
7753 }
7754 });
7755 });
7756 this.insert("", cx);
7757 });
7758 }
7759
7760 pub fn move_to_beginning_of_line(
7761 &mut self,
7762 action: &MoveToBeginningOfLine,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7766 s.move_cursors_with(|map, head, _| {
7767 (
7768 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7769 SelectionGoal::None,
7770 )
7771 });
7772 })
7773 }
7774
7775 pub fn select_to_beginning_of_line(
7776 &mut self,
7777 action: &SelectToBeginningOfLine,
7778 cx: &mut ViewContext<Self>,
7779 ) {
7780 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7781 s.move_heads_with(|map, head, _| {
7782 (
7783 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7784 SelectionGoal::None,
7785 )
7786 });
7787 });
7788 }
7789
7790 pub fn delete_to_beginning_of_line(
7791 &mut self,
7792 _: &DeleteToBeginningOfLine,
7793 cx: &mut ViewContext<Self>,
7794 ) {
7795 self.transact(cx, |this, cx| {
7796 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7797 s.move_with(|_, selection| {
7798 selection.reversed = true;
7799 });
7800 });
7801
7802 this.select_to_beginning_of_line(
7803 &SelectToBeginningOfLine {
7804 stop_at_soft_wraps: false,
7805 },
7806 cx,
7807 );
7808 this.backspace(&Backspace, cx);
7809 });
7810 }
7811
7812 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7813 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7814 s.move_cursors_with(|map, head, _| {
7815 (
7816 movement::line_end(map, head, action.stop_at_soft_wraps),
7817 SelectionGoal::None,
7818 )
7819 });
7820 })
7821 }
7822
7823 pub fn select_to_end_of_line(
7824 &mut self,
7825 action: &SelectToEndOfLine,
7826 cx: &mut ViewContext<Self>,
7827 ) {
7828 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7829 s.move_heads_with(|map, head, _| {
7830 (
7831 movement::line_end(map, head, action.stop_at_soft_wraps),
7832 SelectionGoal::None,
7833 )
7834 });
7835 })
7836 }
7837
7838 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7839 self.transact(cx, |this, cx| {
7840 this.select_to_end_of_line(
7841 &SelectToEndOfLine {
7842 stop_at_soft_wraps: false,
7843 },
7844 cx,
7845 );
7846 this.delete(&Delete, cx);
7847 });
7848 }
7849
7850 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7851 self.transact(cx, |this, cx| {
7852 this.select_to_end_of_line(
7853 &SelectToEndOfLine {
7854 stop_at_soft_wraps: false,
7855 },
7856 cx,
7857 );
7858 this.cut(&Cut, cx);
7859 });
7860 }
7861
7862 pub fn move_to_start_of_paragraph(
7863 &mut self,
7864 _: &MoveToStartOfParagraph,
7865 cx: &mut ViewContext<Self>,
7866 ) {
7867 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7868 cx.propagate();
7869 return;
7870 }
7871
7872 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7873 s.move_with(|map, selection| {
7874 selection.collapse_to(
7875 movement::start_of_paragraph(map, selection.head(), 1),
7876 SelectionGoal::None,
7877 )
7878 });
7879 })
7880 }
7881
7882 pub fn move_to_end_of_paragraph(
7883 &mut self,
7884 _: &MoveToEndOfParagraph,
7885 cx: &mut ViewContext<Self>,
7886 ) {
7887 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7888 cx.propagate();
7889 return;
7890 }
7891
7892 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7893 s.move_with(|map, selection| {
7894 selection.collapse_to(
7895 movement::end_of_paragraph(map, selection.head(), 1),
7896 SelectionGoal::None,
7897 )
7898 });
7899 })
7900 }
7901
7902 pub fn select_to_start_of_paragraph(
7903 &mut self,
7904 _: &SelectToStartOfParagraph,
7905 cx: &mut ViewContext<Self>,
7906 ) {
7907 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7908 cx.propagate();
7909 return;
7910 }
7911
7912 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7913 s.move_heads_with(|map, head, _| {
7914 (
7915 movement::start_of_paragraph(map, head, 1),
7916 SelectionGoal::None,
7917 )
7918 });
7919 })
7920 }
7921
7922 pub fn select_to_end_of_paragraph(
7923 &mut self,
7924 _: &SelectToEndOfParagraph,
7925 cx: &mut ViewContext<Self>,
7926 ) {
7927 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7928 cx.propagate();
7929 return;
7930 }
7931
7932 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7933 s.move_heads_with(|map, head, _| {
7934 (
7935 movement::end_of_paragraph(map, head, 1),
7936 SelectionGoal::None,
7937 )
7938 });
7939 })
7940 }
7941
7942 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7943 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7944 cx.propagate();
7945 return;
7946 }
7947
7948 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7949 s.select_ranges(vec![0..0]);
7950 });
7951 }
7952
7953 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7954 let mut selection = self.selections.last::<Point>(cx);
7955 selection.set_head(Point::zero(), SelectionGoal::None);
7956
7957 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7958 s.select(vec![selection]);
7959 });
7960 }
7961
7962 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7963 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7964 cx.propagate();
7965 return;
7966 }
7967
7968 let cursor = self.buffer.read(cx).read(cx).len();
7969 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7970 s.select_ranges(vec![cursor..cursor])
7971 });
7972 }
7973
7974 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7975 self.nav_history = nav_history;
7976 }
7977
7978 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7979 self.nav_history.as_ref()
7980 }
7981
7982 fn push_to_nav_history(
7983 &mut self,
7984 cursor_anchor: Anchor,
7985 new_position: Option<Point>,
7986 cx: &mut ViewContext<Self>,
7987 ) {
7988 if let Some(nav_history) = self.nav_history.as_mut() {
7989 let buffer = self.buffer.read(cx).read(cx);
7990 let cursor_position = cursor_anchor.to_point(&buffer);
7991 let scroll_state = self.scroll_manager.anchor();
7992 let scroll_top_row = scroll_state.top_row(&buffer);
7993 drop(buffer);
7994
7995 if let Some(new_position) = new_position {
7996 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7997 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7998 return;
7999 }
8000 }
8001
8002 nav_history.push(
8003 Some(NavigationData {
8004 cursor_anchor,
8005 cursor_position,
8006 scroll_anchor: scroll_state,
8007 scroll_top_row,
8008 }),
8009 cx,
8010 );
8011 }
8012 }
8013
8014 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8015 let buffer = self.buffer.read(cx).snapshot(cx);
8016 let mut selection = self.selections.first::<usize>(cx);
8017 selection.set_head(buffer.len(), SelectionGoal::None);
8018 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8019 s.select(vec![selection]);
8020 });
8021 }
8022
8023 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8024 let end = self.buffer.read(cx).read(cx).len();
8025 self.change_selections(None, cx, |s| {
8026 s.select_ranges(vec![0..end]);
8027 });
8028 }
8029
8030 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8032 let mut selections = self.selections.all::<Point>(cx);
8033 let max_point = display_map.buffer_snapshot.max_point();
8034 for selection in &mut selections {
8035 let rows = selection.spanned_rows(true, &display_map);
8036 selection.start = Point::new(rows.start.0, 0);
8037 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8038 selection.reversed = false;
8039 }
8040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8041 s.select(selections);
8042 });
8043 }
8044
8045 pub fn split_selection_into_lines(
8046 &mut self,
8047 _: &SplitSelectionIntoLines,
8048 cx: &mut ViewContext<Self>,
8049 ) {
8050 let mut to_unfold = Vec::new();
8051 let mut new_selection_ranges = Vec::new();
8052 {
8053 let selections = self.selections.all::<Point>(cx);
8054 let buffer = self.buffer.read(cx).read(cx);
8055 for selection in selections {
8056 for row in selection.start.row..selection.end.row {
8057 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8058 new_selection_ranges.push(cursor..cursor);
8059 }
8060 new_selection_ranges.push(selection.end..selection.end);
8061 to_unfold.push(selection.start..selection.end);
8062 }
8063 }
8064 self.unfold_ranges(&to_unfold, true, true, cx);
8065 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8066 s.select_ranges(new_selection_ranges);
8067 });
8068 }
8069
8070 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8071 self.add_selection(true, cx);
8072 }
8073
8074 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8075 self.add_selection(false, cx);
8076 }
8077
8078 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8079 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8080 let mut selections = self.selections.all::<Point>(cx);
8081 let text_layout_details = self.text_layout_details(cx);
8082 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8083 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8084 let range = oldest_selection.display_range(&display_map).sorted();
8085
8086 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8087 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8088 let positions = start_x.min(end_x)..start_x.max(end_x);
8089
8090 selections.clear();
8091 let mut stack = Vec::new();
8092 for row in range.start.row().0..=range.end.row().0 {
8093 if let Some(selection) = self.selections.build_columnar_selection(
8094 &display_map,
8095 DisplayRow(row),
8096 &positions,
8097 oldest_selection.reversed,
8098 &text_layout_details,
8099 ) {
8100 stack.push(selection.id);
8101 selections.push(selection);
8102 }
8103 }
8104
8105 if above {
8106 stack.reverse();
8107 }
8108
8109 AddSelectionsState { above, stack }
8110 });
8111
8112 let last_added_selection = *state.stack.last().unwrap();
8113 let mut new_selections = Vec::new();
8114 if above == state.above {
8115 let end_row = if above {
8116 DisplayRow(0)
8117 } else {
8118 display_map.max_point().row()
8119 };
8120
8121 'outer: for selection in selections {
8122 if selection.id == last_added_selection {
8123 let range = selection.display_range(&display_map).sorted();
8124 debug_assert_eq!(range.start.row(), range.end.row());
8125 let mut row = range.start.row();
8126 let positions =
8127 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8128 px(start)..px(end)
8129 } else {
8130 let start_x =
8131 display_map.x_for_display_point(range.start, &text_layout_details);
8132 let end_x =
8133 display_map.x_for_display_point(range.end, &text_layout_details);
8134 start_x.min(end_x)..start_x.max(end_x)
8135 };
8136
8137 while row != end_row {
8138 if above {
8139 row.0 -= 1;
8140 } else {
8141 row.0 += 1;
8142 }
8143
8144 if let Some(new_selection) = self.selections.build_columnar_selection(
8145 &display_map,
8146 row,
8147 &positions,
8148 selection.reversed,
8149 &text_layout_details,
8150 ) {
8151 state.stack.push(new_selection.id);
8152 if above {
8153 new_selections.push(new_selection);
8154 new_selections.push(selection);
8155 } else {
8156 new_selections.push(selection);
8157 new_selections.push(new_selection);
8158 }
8159
8160 continue 'outer;
8161 }
8162 }
8163 }
8164
8165 new_selections.push(selection);
8166 }
8167 } else {
8168 new_selections = selections;
8169 new_selections.retain(|s| s.id != last_added_selection);
8170 state.stack.pop();
8171 }
8172
8173 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8174 s.select(new_selections);
8175 });
8176 if state.stack.len() > 1 {
8177 self.add_selections_state = Some(state);
8178 }
8179 }
8180
8181 pub fn select_next_match_internal(
8182 &mut self,
8183 display_map: &DisplaySnapshot,
8184 replace_newest: bool,
8185 autoscroll: Option<Autoscroll>,
8186 cx: &mut ViewContext<Self>,
8187 ) -> Result<()> {
8188 fn select_next_match_ranges(
8189 this: &mut Editor,
8190 range: Range<usize>,
8191 replace_newest: bool,
8192 auto_scroll: Option<Autoscroll>,
8193 cx: &mut ViewContext<Editor>,
8194 ) {
8195 this.unfold_ranges(&[range.clone()], false, true, cx);
8196 this.change_selections(auto_scroll, cx, |s| {
8197 if replace_newest {
8198 s.delete(s.newest_anchor().id);
8199 }
8200 s.insert_range(range.clone());
8201 });
8202 }
8203
8204 let buffer = &display_map.buffer_snapshot;
8205 let mut selections = self.selections.all::<usize>(cx);
8206 if let Some(mut select_next_state) = self.select_next_state.take() {
8207 let query = &select_next_state.query;
8208 if !select_next_state.done {
8209 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8210 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8211 let mut next_selected_range = None;
8212
8213 let bytes_after_last_selection =
8214 buffer.bytes_in_range(last_selection.end..buffer.len());
8215 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8216 let query_matches = query
8217 .stream_find_iter(bytes_after_last_selection)
8218 .map(|result| (last_selection.end, result))
8219 .chain(
8220 query
8221 .stream_find_iter(bytes_before_first_selection)
8222 .map(|result| (0, result)),
8223 );
8224
8225 for (start_offset, query_match) in query_matches {
8226 let query_match = query_match.unwrap(); // can only fail due to I/O
8227 let offset_range =
8228 start_offset + query_match.start()..start_offset + query_match.end();
8229 let display_range = offset_range.start.to_display_point(display_map)
8230 ..offset_range.end.to_display_point(display_map);
8231
8232 if !select_next_state.wordwise
8233 || (!movement::is_inside_word(display_map, display_range.start)
8234 && !movement::is_inside_word(display_map, display_range.end))
8235 {
8236 // TODO: This is n^2, because we might check all the selections
8237 if !selections
8238 .iter()
8239 .any(|selection| selection.range().overlaps(&offset_range))
8240 {
8241 next_selected_range = Some(offset_range);
8242 break;
8243 }
8244 }
8245 }
8246
8247 if let Some(next_selected_range) = next_selected_range {
8248 select_next_match_ranges(
8249 self,
8250 next_selected_range,
8251 replace_newest,
8252 autoscroll,
8253 cx,
8254 );
8255 } else {
8256 select_next_state.done = true;
8257 }
8258 }
8259
8260 self.select_next_state = Some(select_next_state);
8261 } else {
8262 let mut only_carets = true;
8263 let mut same_text_selected = true;
8264 let mut selected_text = None;
8265
8266 let mut selections_iter = selections.iter().peekable();
8267 while let Some(selection) = selections_iter.next() {
8268 if selection.start != selection.end {
8269 only_carets = false;
8270 }
8271
8272 if same_text_selected {
8273 if selected_text.is_none() {
8274 selected_text =
8275 Some(buffer.text_for_range(selection.range()).collect::<String>());
8276 }
8277
8278 if let Some(next_selection) = selections_iter.peek() {
8279 if next_selection.range().len() == selection.range().len() {
8280 let next_selected_text = buffer
8281 .text_for_range(next_selection.range())
8282 .collect::<String>();
8283 if Some(next_selected_text) != selected_text {
8284 same_text_selected = false;
8285 selected_text = None;
8286 }
8287 } else {
8288 same_text_selected = false;
8289 selected_text = None;
8290 }
8291 }
8292 }
8293 }
8294
8295 if only_carets {
8296 for selection in &mut selections {
8297 let word_range = movement::surrounding_word(
8298 display_map,
8299 selection.start.to_display_point(display_map),
8300 );
8301 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8302 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8303 selection.goal = SelectionGoal::None;
8304 selection.reversed = false;
8305 select_next_match_ranges(
8306 self,
8307 selection.start..selection.end,
8308 replace_newest,
8309 autoscroll,
8310 cx,
8311 );
8312 }
8313
8314 if selections.len() == 1 {
8315 let selection = selections
8316 .last()
8317 .expect("ensured that there's only one selection");
8318 let query = buffer
8319 .text_for_range(selection.start..selection.end)
8320 .collect::<String>();
8321 let is_empty = query.is_empty();
8322 let select_state = SelectNextState {
8323 query: AhoCorasick::new(&[query])?,
8324 wordwise: true,
8325 done: is_empty,
8326 };
8327 self.select_next_state = Some(select_state);
8328 } else {
8329 self.select_next_state = None;
8330 }
8331 } else if let Some(selected_text) = selected_text {
8332 self.select_next_state = Some(SelectNextState {
8333 query: AhoCorasick::new(&[selected_text])?,
8334 wordwise: false,
8335 done: false,
8336 });
8337 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8338 }
8339 }
8340 Ok(())
8341 }
8342
8343 pub fn select_all_matches(
8344 &mut self,
8345 _action: &SelectAllMatches,
8346 cx: &mut ViewContext<Self>,
8347 ) -> Result<()> {
8348 self.push_to_selection_history();
8349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8350
8351 self.select_next_match_internal(&display_map, false, None, cx)?;
8352 let Some(select_next_state) = self.select_next_state.as_mut() else {
8353 return Ok(());
8354 };
8355 if select_next_state.done {
8356 return Ok(());
8357 }
8358
8359 let mut new_selections = self.selections.all::<usize>(cx);
8360
8361 let buffer = &display_map.buffer_snapshot;
8362 let query_matches = select_next_state
8363 .query
8364 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8365
8366 for query_match in query_matches {
8367 let query_match = query_match.unwrap(); // can only fail due to I/O
8368 let offset_range = query_match.start()..query_match.end();
8369 let display_range = offset_range.start.to_display_point(&display_map)
8370 ..offset_range.end.to_display_point(&display_map);
8371
8372 if !select_next_state.wordwise
8373 || (!movement::is_inside_word(&display_map, display_range.start)
8374 && !movement::is_inside_word(&display_map, display_range.end))
8375 {
8376 self.selections.change_with(cx, |selections| {
8377 new_selections.push(Selection {
8378 id: selections.new_selection_id(),
8379 start: offset_range.start,
8380 end: offset_range.end,
8381 reversed: false,
8382 goal: SelectionGoal::None,
8383 });
8384 });
8385 }
8386 }
8387
8388 new_selections.sort_by_key(|selection| selection.start);
8389 let mut ix = 0;
8390 while ix + 1 < new_selections.len() {
8391 let current_selection = &new_selections[ix];
8392 let next_selection = &new_selections[ix + 1];
8393 if current_selection.range().overlaps(&next_selection.range()) {
8394 if current_selection.id < next_selection.id {
8395 new_selections.remove(ix + 1);
8396 } else {
8397 new_selections.remove(ix);
8398 }
8399 } else {
8400 ix += 1;
8401 }
8402 }
8403
8404 select_next_state.done = true;
8405 self.unfold_ranges(
8406 &new_selections
8407 .iter()
8408 .map(|selection| selection.range())
8409 .collect::<Vec<_>>(),
8410 false,
8411 false,
8412 cx,
8413 );
8414 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8415 selections.select(new_selections)
8416 });
8417
8418 Ok(())
8419 }
8420
8421 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8422 self.push_to_selection_history();
8423 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8424 self.select_next_match_internal(
8425 &display_map,
8426 action.replace_newest,
8427 Some(Autoscroll::newest()),
8428 cx,
8429 )?;
8430 Ok(())
8431 }
8432
8433 pub fn select_previous(
8434 &mut self,
8435 action: &SelectPrevious,
8436 cx: &mut ViewContext<Self>,
8437 ) -> Result<()> {
8438 self.push_to_selection_history();
8439 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8440 let buffer = &display_map.buffer_snapshot;
8441 let mut selections = self.selections.all::<usize>(cx);
8442 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8443 let query = &select_prev_state.query;
8444 if !select_prev_state.done {
8445 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8446 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8447 let mut next_selected_range = None;
8448 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8449 let bytes_before_last_selection =
8450 buffer.reversed_bytes_in_range(0..last_selection.start);
8451 let bytes_after_first_selection =
8452 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8453 let query_matches = query
8454 .stream_find_iter(bytes_before_last_selection)
8455 .map(|result| (last_selection.start, result))
8456 .chain(
8457 query
8458 .stream_find_iter(bytes_after_first_selection)
8459 .map(|result| (buffer.len(), result)),
8460 );
8461 for (end_offset, query_match) in query_matches {
8462 let query_match = query_match.unwrap(); // can only fail due to I/O
8463 let offset_range =
8464 end_offset - query_match.end()..end_offset - query_match.start();
8465 let display_range = offset_range.start.to_display_point(&display_map)
8466 ..offset_range.end.to_display_point(&display_map);
8467
8468 if !select_prev_state.wordwise
8469 || (!movement::is_inside_word(&display_map, display_range.start)
8470 && !movement::is_inside_word(&display_map, display_range.end))
8471 {
8472 next_selected_range = Some(offset_range);
8473 break;
8474 }
8475 }
8476
8477 if let Some(next_selected_range) = next_selected_range {
8478 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8479 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8480 if action.replace_newest {
8481 s.delete(s.newest_anchor().id);
8482 }
8483 s.insert_range(next_selected_range);
8484 });
8485 } else {
8486 select_prev_state.done = true;
8487 }
8488 }
8489
8490 self.select_prev_state = Some(select_prev_state);
8491 } else {
8492 let mut only_carets = true;
8493 let mut same_text_selected = true;
8494 let mut selected_text = None;
8495
8496 let mut selections_iter = selections.iter().peekable();
8497 while let Some(selection) = selections_iter.next() {
8498 if selection.start != selection.end {
8499 only_carets = false;
8500 }
8501
8502 if same_text_selected {
8503 if selected_text.is_none() {
8504 selected_text =
8505 Some(buffer.text_for_range(selection.range()).collect::<String>());
8506 }
8507
8508 if let Some(next_selection) = selections_iter.peek() {
8509 if next_selection.range().len() == selection.range().len() {
8510 let next_selected_text = buffer
8511 .text_for_range(next_selection.range())
8512 .collect::<String>();
8513 if Some(next_selected_text) != selected_text {
8514 same_text_selected = false;
8515 selected_text = None;
8516 }
8517 } else {
8518 same_text_selected = false;
8519 selected_text = None;
8520 }
8521 }
8522 }
8523 }
8524
8525 if only_carets {
8526 for selection in &mut selections {
8527 let word_range = movement::surrounding_word(
8528 &display_map,
8529 selection.start.to_display_point(&display_map),
8530 );
8531 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8532 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8533 selection.goal = SelectionGoal::None;
8534 selection.reversed = false;
8535 }
8536 if selections.len() == 1 {
8537 let selection = selections
8538 .last()
8539 .expect("ensured that there's only one selection");
8540 let query = buffer
8541 .text_for_range(selection.start..selection.end)
8542 .collect::<String>();
8543 let is_empty = query.is_empty();
8544 let select_state = SelectNextState {
8545 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8546 wordwise: true,
8547 done: is_empty,
8548 };
8549 self.select_prev_state = Some(select_state);
8550 } else {
8551 self.select_prev_state = None;
8552 }
8553
8554 self.unfold_ranges(
8555 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8556 false,
8557 true,
8558 cx,
8559 );
8560 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8561 s.select(selections);
8562 });
8563 } else if let Some(selected_text) = selected_text {
8564 self.select_prev_state = Some(SelectNextState {
8565 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8566 wordwise: false,
8567 done: false,
8568 });
8569 self.select_previous(action, cx)?;
8570 }
8571 }
8572 Ok(())
8573 }
8574
8575 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8576 if self.read_only(cx) {
8577 return;
8578 }
8579 let text_layout_details = &self.text_layout_details(cx);
8580 self.transact(cx, |this, cx| {
8581 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8582 let mut edits = Vec::new();
8583 let mut selection_edit_ranges = Vec::new();
8584 let mut last_toggled_row = None;
8585 let snapshot = this.buffer.read(cx).read(cx);
8586 let empty_str: Arc<str> = Arc::default();
8587 let mut suffixes_inserted = Vec::new();
8588 let ignore_indent = action.ignore_indent;
8589
8590 fn comment_prefix_range(
8591 snapshot: &MultiBufferSnapshot,
8592 row: MultiBufferRow,
8593 comment_prefix: &str,
8594 comment_prefix_whitespace: &str,
8595 ignore_indent: bool,
8596 ) -> Range<Point> {
8597 let indent_size = if ignore_indent {
8598 0
8599 } else {
8600 snapshot.indent_size_for_line(row).len
8601 };
8602
8603 let start = Point::new(row.0, indent_size);
8604
8605 let mut line_bytes = snapshot
8606 .bytes_in_range(start..snapshot.max_point())
8607 .flatten()
8608 .copied();
8609
8610 // If this line currently begins with the line comment prefix, then record
8611 // the range containing the prefix.
8612 if line_bytes
8613 .by_ref()
8614 .take(comment_prefix.len())
8615 .eq(comment_prefix.bytes())
8616 {
8617 // Include any whitespace that matches the comment prefix.
8618 let matching_whitespace_len = line_bytes
8619 .zip(comment_prefix_whitespace.bytes())
8620 .take_while(|(a, b)| a == b)
8621 .count() as u32;
8622 let end = Point::new(
8623 start.row,
8624 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8625 );
8626 start..end
8627 } else {
8628 start..start
8629 }
8630 }
8631
8632 fn comment_suffix_range(
8633 snapshot: &MultiBufferSnapshot,
8634 row: MultiBufferRow,
8635 comment_suffix: &str,
8636 comment_suffix_has_leading_space: bool,
8637 ) -> Range<Point> {
8638 let end = Point::new(row.0, snapshot.line_len(row));
8639 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8640
8641 let mut line_end_bytes = snapshot
8642 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8643 .flatten()
8644 .copied();
8645
8646 let leading_space_len = if suffix_start_column > 0
8647 && line_end_bytes.next() == Some(b' ')
8648 && comment_suffix_has_leading_space
8649 {
8650 1
8651 } else {
8652 0
8653 };
8654
8655 // If this line currently begins with the line comment prefix, then record
8656 // the range containing the prefix.
8657 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8658 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8659 start..end
8660 } else {
8661 end..end
8662 }
8663 }
8664
8665 // TODO: Handle selections that cross excerpts
8666 for selection in &mut selections {
8667 let start_column = snapshot
8668 .indent_size_for_line(MultiBufferRow(selection.start.row))
8669 .len;
8670 let language = if let Some(language) =
8671 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8672 {
8673 language
8674 } else {
8675 continue;
8676 };
8677
8678 selection_edit_ranges.clear();
8679
8680 // If multiple selections contain a given row, avoid processing that
8681 // row more than once.
8682 let mut start_row = MultiBufferRow(selection.start.row);
8683 if last_toggled_row == Some(start_row) {
8684 start_row = start_row.next_row();
8685 }
8686 let end_row =
8687 if selection.end.row > selection.start.row && selection.end.column == 0 {
8688 MultiBufferRow(selection.end.row - 1)
8689 } else {
8690 MultiBufferRow(selection.end.row)
8691 };
8692 last_toggled_row = Some(end_row);
8693
8694 if start_row > end_row {
8695 continue;
8696 }
8697
8698 // If the language has line comments, toggle those.
8699 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8700
8701 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8702 if ignore_indent {
8703 full_comment_prefixes = full_comment_prefixes
8704 .into_iter()
8705 .map(|s| Arc::from(s.trim_end()))
8706 .collect();
8707 }
8708
8709 if !full_comment_prefixes.is_empty() {
8710 let first_prefix = full_comment_prefixes
8711 .first()
8712 .expect("prefixes is non-empty");
8713 let prefix_trimmed_lengths = full_comment_prefixes
8714 .iter()
8715 .map(|p| p.trim_end_matches(' ').len())
8716 .collect::<SmallVec<[usize; 4]>>();
8717
8718 let mut all_selection_lines_are_comments = true;
8719
8720 for row in start_row.0..=end_row.0 {
8721 let row = MultiBufferRow(row);
8722 if start_row < end_row && snapshot.is_line_blank(row) {
8723 continue;
8724 }
8725
8726 let prefix_range = full_comment_prefixes
8727 .iter()
8728 .zip(prefix_trimmed_lengths.iter().copied())
8729 .map(|(prefix, trimmed_prefix_len)| {
8730 comment_prefix_range(
8731 snapshot.deref(),
8732 row,
8733 &prefix[..trimmed_prefix_len],
8734 &prefix[trimmed_prefix_len..],
8735 ignore_indent,
8736 )
8737 })
8738 .max_by_key(|range| range.end.column - range.start.column)
8739 .expect("prefixes is non-empty");
8740
8741 if prefix_range.is_empty() {
8742 all_selection_lines_are_comments = false;
8743 }
8744
8745 selection_edit_ranges.push(prefix_range);
8746 }
8747
8748 if all_selection_lines_are_comments {
8749 edits.extend(
8750 selection_edit_ranges
8751 .iter()
8752 .cloned()
8753 .map(|range| (range, empty_str.clone())),
8754 );
8755 } else {
8756 let min_column = selection_edit_ranges
8757 .iter()
8758 .map(|range| range.start.column)
8759 .min()
8760 .unwrap_or(0);
8761 edits.extend(selection_edit_ranges.iter().map(|range| {
8762 let position = Point::new(range.start.row, min_column);
8763 (position..position, first_prefix.clone())
8764 }));
8765 }
8766 } else if let Some((full_comment_prefix, comment_suffix)) =
8767 language.block_comment_delimiters()
8768 {
8769 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8770 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8771 let prefix_range = comment_prefix_range(
8772 snapshot.deref(),
8773 start_row,
8774 comment_prefix,
8775 comment_prefix_whitespace,
8776 ignore_indent,
8777 );
8778 let suffix_range = comment_suffix_range(
8779 snapshot.deref(),
8780 end_row,
8781 comment_suffix.trim_start_matches(' '),
8782 comment_suffix.starts_with(' '),
8783 );
8784
8785 if prefix_range.is_empty() || suffix_range.is_empty() {
8786 edits.push((
8787 prefix_range.start..prefix_range.start,
8788 full_comment_prefix.clone(),
8789 ));
8790 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8791 suffixes_inserted.push((end_row, comment_suffix.len()));
8792 } else {
8793 edits.push((prefix_range, empty_str.clone()));
8794 edits.push((suffix_range, empty_str.clone()));
8795 }
8796 } else {
8797 continue;
8798 }
8799 }
8800
8801 drop(snapshot);
8802 this.buffer.update(cx, |buffer, cx| {
8803 buffer.edit(edits, None, cx);
8804 });
8805
8806 // Adjust selections so that they end before any comment suffixes that
8807 // were inserted.
8808 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8809 let mut selections = this.selections.all::<Point>(cx);
8810 let snapshot = this.buffer.read(cx).read(cx);
8811 for selection in &mut selections {
8812 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8813 match row.cmp(&MultiBufferRow(selection.end.row)) {
8814 Ordering::Less => {
8815 suffixes_inserted.next();
8816 continue;
8817 }
8818 Ordering::Greater => break,
8819 Ordering::Equal => {
8820 if selection.end.column == snapshot.line_len(row) {
8821 if selection.is_empty() {
8822 selection.start.column -= suffix_len as u32;
8823 }
8824 selection.end.column -= suffix_len as u32;
8825 }
8826 break;
8827 }
8828 }
8829 }
8830 }
8831
8832 drop(snapshot);
8833 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8834
8835 let selections = this.selections.all::<Point>(cx);
8836 let selections_on_single_row = selections.windows(2).all(|selections| {
8837 selections[0].start.row == selections[1].start.row
8838 && selections[0].end.row == selections[1].end.row
8839 && selections[0].start.row == selections[0].end.row
8840 });
8841 let selections_selecting = selections
8842 .iter()
8843 .any(|selection| selection.start != selection.end);
8844 let advance_downwards = action.advance_downwards
8845 && selections_on_single_row
8846 && !selections_selecting
8847 && !matches!(this.mode, EditorMode::SingleLine { .. });
8848
8849 if advance_downwards {
8850 let snapshot = this.buffer.read(cx).snapshot(cx);
8851
8852 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8853 s.move_cursors_with(|display_snapshot, display_point, _| {
8854 let mut point = display_point.to_point(display_snapshot);
8855 point.row += 1;
8856 point = snapshot.clip_point(point, Bias::Left);
8857 let display_point = point.to_display_point(display_snapshot);
8858 let goal = SelectionGoal::HorizontalPosition(
8859 display_snapshot
8860 .x_for_display_point(display_point, text_layout_details)
8861 .into(),
8862 );
8863 (display_point, goal)
8864 })
8865 });
8866 }
8867 });
8868 }
8869
8870 pub fn select_enclosing_symbol(
8871 &mut self,
8872 _: &SelectEnclosingSymbol,
8873 cx: &mut ViewContext<Self>,
8874 ) {
8875 let buffer = self.buffer.read(cx).snapshot(cx);
8876 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8877
8878 fn update_selection(
8879 selection: &Selection<usize>,
8880 buffer_snap: &MultiBufferSnapshot,
8881 ) -> Option<Selection<usize>> {
8882 let cursor = selection.head();
8883 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8884 for symbol in symbols.iter().rev() {
8885 let start = symbol.range.start.to_offset(buffer_snap);
8886 let end = symbol.range.end.to_offset(buffer_snap);
8887 let new_range = start..end;
8888 if start < selection.start || end > selection.end {
8889 return Some(Selection {
8890 id: selection.id,
8891 start: new_range.start,
8892 end: new_range.end,
8893 goal: SelectionGoal::None,
8894 reversed: selection.reversed,
8895 });
8896 }
8897 }
8898 None
8899 }
8900
8901 let mut selected_larger_symbol = false;
8902 let new_selections = old_selections
8903 .iter()
8904 .map(|selection| match update_selection(selection, &buffer) {
8905 Some(new_selection) => {
8906 if new_selection.range() != selection.range() {
8907 selected_larger_symbol = true;
8908 }
8909 new_selection
8910 }
8911 None => selection.clone(),
8912 })
8913 .collect::<Vec<_>>();
8914
8915 if selected_larger_symbol {
8916 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8917 s.select(new_selections);
8918 });
8919 }
8920 }
8921
8922 pub fn select_larger_syntax_node(
8923 &mut self,
8924 _: &SelectLargerSyntaxNode,
8925 cx: &mut ViewContext<Self>,
8926 ) {
8927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8928 let buffer = self.buffer.read(cx).snapshot(cx);
8929 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8930
8931 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8932 let mut selected_larger_node = false;
8933 let new_selections = old_selections
8934 .iter()
8935 .map(|selection| {
8936 let old_range = selection.start..selection.end;
8937 let mut new_range = old_range.clone();
8938 let mut new_node = None;
8939 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8940 {
8941 new_node = Some(node);
8942 new_range = containing_range;
8943 if !display_map.intersects_fold(new_range.start)
8944 && !display_map.intersects_fold(new_range.end)
8945 {
8946 break;
8947 }
8948 }
8949
8950 if let Some(node) = new_node {
8951 // Log the ancestor, to support using this action as a way to explore TreeSitter
8952 // nodes. Parent and grandparent are also logged because this operation will not
8953 // visit nodes that have the same range as their parent.
8954 log::info!("Node: {node:?}");
8955 let parent = node.parent();
8956 log::info!("Parent: {parent:?}");
8957 let grandparent = parent.and_then(|x| x.parent());
8958 log::info!("Grandparent: {grandparent:?}");
8959 }
8960
8961 selected_larger_node |= new_range != old_range;
8962 Selection {
8963 id: selection.id,
8964 start: new_range.start,
8965 end: new_range.end,
8966 goal: SelectionGoal::None,
8967 reversed: selection.reversed,
8968 }
8969 })
8970 .collect::<Vec<_>>();
8971
8972 if selected_larger_node {
8973 stack.push(old_selections);
8974 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8975 s.select(new_selections);
8976 });
8977 }
8978 self.select_larger_syntax_node_stack = stack;
8979 }
8980
8981 pub fn select_smaller_syntax_node(
8982 &mut self,
8983 _: &SelectSmallerSyntaxNode,
8984 cx: &mut ViewContext<Self>,
8985 ) {
8986 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8987 if let Some(selections) = stack.pop() {
8988 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8989 s.select(selections.to_vec());
8990 });
8991 }
8992 self.select_larger_syntax_node_stack = stack;
8993 }
8994
8995 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8996 if !EditorSettings::get_global(cx).gutter.runnables {
8997 self.clear_tasks();
8998 return Task::ready(());
8999 }
9000 let project = self.project.as_ref().map(Model::downgrade);
9001 cx.spawn(|this, mut cx| async move {
9002 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9003 let Some(project) = project.and_then(|p| p.upgrade()) else {
9004 return;
9005 };
9006 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9007 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9008 }) else {
9009 return;
9010 };
9011
9012 let hide_runnables = project
9013 .update(&mut cx, |project, cx| {
9014 // Do not display any test indicators in non-dev server remote projects.
9015 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9016 })
9017 .unwrap_or(true);
9018 if hide_runnables {
9019 return;
9020 }
9021 let new_rows =
9022 cx.background_executor()
9023 .spawn({
9024 let snapshot = display_snapshot.clone();
9025 async move {
9026 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9027 }
9028 })
9029 .await;
9030 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9031
9032 this.update(&mut cx, |this, _| {
9033 this.clear_tasks();
9034 for (key, value) in rows {
9035 this.insert_tasks(key, value);
9036 }
9037 })
9038 .ok();
9039 })
9040 }
9041 fn fetch_runnable_ranges(
9042 snapshot: &DisplaySnapshot,
9043 range: Range<Anchor>,
9044 ) -> Vec<language::RunnableRange> {
9045 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9046 }
9047
9048 fn runnable_rows(
9049 project: Model<Project>,
9050 snapshot: DisplaySnapshot,
9051 runnable_ranges: Vec<RunnableRange>,
9052 mut cx: AsyncWindowContext,
9053 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9054 runnable_ranges
9055 .into_iter()
9056 .filter_map(|mut runnable| {
9057 let tasks = cx
9058 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9059 .ok()?;
9060 if tasks.is_empty() {
9061 return None;
9062 }
9063
9064 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9065
9066 let row = snapshot
9067 .buffer_snapshot
9068 .buffer_line_for_row(MultiBufferRow(point.row))?
9069 .1
9070 .start
9071 .row;
9072
9073 let context_range =
9074 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9075 Some((
9076 (runnable.buffer_id, row),
9077 RunnableTasks {
9078 templates: tasks,
9079 offset: MultiBufferOffset(runnable.run_range.start),
9080 context_range,
9081 column: point.column,
9082 extra_variables: runnable.extra_captures,
9083 },
9084 ))
9085 })
9086 .collect()
9087 }
9088
9089 fn templates_with_tags(
9090 project: &Model<Project>,
9091 runnable: &mut Runnable,
9092 cx: &WindowContext,
9093 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9094 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9095 let (worktree_id, file) = project
9096 .buffer_for_id(runnable.buffer, cx)
9097 .and_then(|buffer| buffer.read(cx).file())
9098 .map(|file| (file.worktree_id(cx), file.clone()))
9099 .unzip();
9100
9101 (
9102 project.task_store().read(cx).task_inventory().cloned(),
9103 worktree_id,
9104 file,
9105 )
9106 });
9107
9108 let tags = mem::take(&mut runnable.tags);
9109 let mut tags: Vec<_> = tags
9110 .into_iter()
9111 .flat_map(|tag| {
9112 let tag = tag.0.clone();
9113 inventory
9114 .as_ref()
9115 .into_iter()
9116 .flat_map(|inventory| {
9117 inventory.read(cx).list_tasks(
9118 file.clone(),
9119 Some(runnable.language.clone()),
9120 worktree_id,
9121 cx,
9122 )
9123 })
9124 .filter(move |(_, template)| {
9125 template.tags.iter().any(|source_tag| source_tag == &tag)
9126 })
9127 })
9128 .sorted_by_key(|(kind, _)| kind.to_owned())
9129 .collect();
9130 if let Some((leading_tag_source, _)) = tags.first() {
9131 // Strongest source wins; if we have worktree tag binding, prefer that to
9132 // global and language bindings;
9133 // if we have a global binding, prefer that to language binding.
9134 let first_mismatch = tags
9135 .iter()
9136 .position(|(tag_source, _)| tag_source != leading_tag_source);
9137 if let Some(index) = first_mismatch {
9138 tags.truncate(index);
9139 }
9140 }
9141
9142 tags
9143 }
9144
9145 pub fn move_to_enclosing_bracket(
9146 &mut self,
9147 _: &MoveToEnclosingBracket,
9148 cx: &mut ViewContext<Self>,
9149 ) {
9150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9151 s.move_offsets_with(|snapshot, selection| {
9152 let Some(enclosing_bracket_ranges) =
9153 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9154 else {
9155 return;
9156 };
9157
9158 let mut best_length = usize::MAX;
9159 let mut best_inside = false;
9160 let mut best_in_bracket_range = false;
9161 let mut best_destination = None;
9162 for (open, close) in enclosing_bracket_ranges {
9163 let close = close.to_inclusive();
9164 let length = close.end() - open.start;
9165 let inside = selection.start >= open.end && selection.end <= *close.start();
9166 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9167 || close.contains(&selection.head());
9168
9169 // If best is next to a bracket and current isn't, skip
9170 if !in_bracket_range && best_in_bracket_range {
9171 continue;
9172 }
9173
9174 // Prefer smaller lengths unless best is inside and current isn't
9175 if length > best_length && (best_inside || !inside) {
9176 continue;
9177 }
9178
9179 best_length = length;
9180 best_inside = inside;
9181 best_in_bracket_range = in_bracket_range;
9182 best_destination = Some(
9183 if close.contains(&selection.start) && close.contains(&selection.end) {
9184 if inside {
9185 open.end
9186 } else {
9187 open.start
9188 }
9189 } else if inside {
9190 *close.start()
9191 } else {
9192 *close.end()
9193 },
9194 );
9195 }
9196
9197 if let Some(destination) = best_destination {
9198 selection.collapse_to(destination, SelectionGoal::None);
9199 }
9200 })
9201 });
9202 }
9203
9204 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9205 self.end_selection(cx);
9206 self.selection_history.mode = SelectionHistoryMode::Undoing;
9207 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9208 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9209 self.select_next_state = entry.select_next_state;
9210 self.select_prev_state = entry.select_prev_state;
9211 self.add_selections_state = entry.add_selections_state;
9212 self.request_autoscroll(Autoscroll::newest(), cx);
9213 }
9214 self.selection_history.mode = SelectionHistoryMode::Normal;
9215 }
9216
9217 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9218 self.end_selection(cx);
9219 self.selection_history.mode = SelectionHistoryMode::Redoing;
9220 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9221 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9222 self.select_next_state = entry.select_next_state;
9223 self.select_prev_state = entry.select_prev_state;
9224 self.add_selections_state = entry.add_selections_state;
9225 self.request_autoscroll(Autoscroll::newest(), cx);
9226 }
9227 self.selection_history.mode = SelectionHistoryMode::Normal;
9228 }
9229
9230 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9231 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9232 }
9233
9234 pub fn expand_excerpts_down(
9235 &mut self,
9236 action: &ExpandExcerptsDown,
9237 cx: &mut ViewContext<Self>,
9238 ) {
9239 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9240 }
9241
9242 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9243 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9244 }
9245
9246 pub fn expand_excerpts_for_direction(
9247 &mut self,
9248 lines: u32,
9249 direction: ExpandExcerptDirection,
9250 cx: &mut ViewContext<Self>,
9251 ) {
9252 let selections = self.selections.disjoint_anchors();
9253
9254 let lines = if lines == 0 {
9255 EditorSettings::get_global(cx).expand_excerpt_lines
9256 } else {
9257 lines
9258 };
9259
9260 self.buffer.update(cx, |buffer, cx| {
9261 let snapshot = buffer.snapshot(cx);
9262 let mut excerpt_ids = selections
9263 .iter()
9264 .flat_map(|selection| {
9265 snapshot
9266 .excerpts_for_range(selection.range())
9267 .map(|excerpt| excerpt.id())
9268 })
9269 .collect::<Vec<_>>();
9270 excerpt_ids.sort();
9271 excerpt_ids.dedup();
9272 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9273 })
9274 }
9275
9276 pub fn expand_excerpt(
9277 &mut self,
9278 excerpt: ExcerptId,
9279 direction: ExpandExcerptDirection,
9280 cx: &mut ViewContext<Self>,
9281 ) {
9282 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9283 self.buffer.update(cx, |buffer, cx| {
9284 buffer.expand_excerpts([excerpt], lines, direction, cx)
9285 })
9286 }
9287
9288 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9289 self.go_to_diagnostic_impl(Direction::Next, cx)
9290 }
9291
9292 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9293 self.go_to_diagnostic_impl(Direction::Prev, cx)
9294 }
9295
9296 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9297 let buffer = self.buffer.read(cx).snapshot(cx);
9298 let selection = self.selections.newest::<usize>(cx);
9299
9300 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9301 if direction == Direction::Next {
9302 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9303 self.activate_diagnostics(popover.group_id(), cx);
9304 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9305 let primary_range_start = active_diagnostics.primary_range.start;
9306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9307 let mut new_selection = s.newest_anchor().clone();
9308 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9309 s.select_anchors(vec![new_selection.clone()]);
9310 });
9311 self.refresh_inline_completion(false, true, cx);
9312 }
9313 return;
9314 }
9315 }
9316
9317 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9318 active_diagnostics
9319 .primary_range
9320 .to_offset(&buffer)
9321 .to_inclusive()
9322 });
9323 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9324 if active_primary_range.contains(&selection.head()) {
9325 *active_primary_range.start()
9326 } else {
9327 selection.head()
9328 }
9329 } else {
9330 selection.head()
9331 };
9332 let snapshot = self.snapshot(cx);
9333 loop {
9334 let diagnostics = if direction == Direction::Prev {
9335 buffer.diagnostics_in_range(0..search_start, true)
9336 } else {
9337 buffer.diagnostics_in_range(search_start..buffer.len(), false)
9338 }
9339 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9340 let search_start_anchor = buffer.anchor_after(search_start);
9341 let group = diagnostics
9342 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9343 // be sorted in a stable way
9344 // skip until we are at current active diagnostic, if it exists
9345 .skip_while(|entry| {
9346 let is_in_range = match direction {
9347 Direction::Prev => {
9348 entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
9349 }
9350 Direction::Next => {
9351 entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
9352 }
9353 };
9354 is_in_range
9355 && self
9356 .active_diagnostics
9357 .as_ref()
9358 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9359 })
9360 .find_map(|entry| {
9361 if entry.diagnostic.is_primary
9362 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9363 && !(entry.range.start == entry.range.end)
9364 // if we match with the active diagnostic, skip it
9365 && Some(entry.diagnostic.group_id)
9366 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9367 {
9368 Some((entry.range, entry.diagnostic.group_id))
9369 } else {
9370 None
9371 }
9372 });
9373
9374 if let Some((primary_range, group_id)) = group {
9375 self.activate_diagnostics(group_id, cx);
9376 let primary_range = primary_range.to_offset(&buffer);
9377 if self.active_diagnostics.is_some() {
9378 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9379 s.select(vec![Selection {
9380 id: selection.id,
9381 start: primary_range.start,
9382 end: primary_range.start,
9383 reversed: false,
9384 goal: SelectionGoal::None,
9385 }]);
9386 });
9387 self.refresh_inline_completion(false, true, cx);
9388 }
9389 break;
9390 } else {
9391 // Cycle around to the start of the buffer, potentially moving back to the start of
9392 // the currently active diagnostic.
9393 active_primary_range.take();
9394 if direction == Direction::Prev {
9395 if search_start == buffer.len() {
9396 break;
9397 } else {
9398 search_start = buffer.len();
9399 }
9400 } else if search_start == 0 {
9401 break;
9402 } else {
9403 search_start = 0;
9404 }
9405 }
9406 }
9407 }
9408
9409 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9410 let snapshot = self.snapshot(cx);
9411 let selection = self.selections.newest::<Point>(cx);
9412 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9413 }
9414
9415 fn go_to_hunk_after_position(
9416 &mut self,
9417 snapshot: &EditorSnapshot,
9418 position: Point,
9419 cx: &mut ViewContext<Editor>,
9420 ) -> Option<MultiBufferDiffHunk> {
9421 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9422 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9423 snapshot,
9424 position,
9425 ix > 0,
9426 snapshot.diff_map.diff_hunks_in_range(
9427 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9428 &snapshot.buffer_snapshot,
9429 ),
9430 cx,
9431 ) {
9432 return Some(hunk);
9433 }
9434 }
9435 None
9436 }
9437
9438 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9439 let snapshot = self.snapshot(cx);
9440 let selection = self.selections.newest::<Point>(cx);
9441 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9442 }
9443
9444 fn go_to_hunk_before_position(
9445 &mut self,
9446 snapshot: &EditorSnapshot,
9447 position: Point,
9448 cx: &mut ViewContext<Editor>,
9449 ) -> Option<MultiBufferDiffHunk> {
9450 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9451 .into_iter()
9452 .enumerate()
9453 {
9454 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9455 snapshot,
9456 position,
9457 ix > 0,
9458 snapshot
9459 .diff_map
9460 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9461 cx,
9462 ) {
9463 return Some(hunk);
9464 }
9465 }
9466 None
9467 }
9468
9469 fn go_to_next_hunk_in_direction(
9470 &mut self,
9471 snapshot: &DisplaySnapshot,
9472 initial_point: Point,
9473 is_wrapped: bool,
9474 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9475 cx: &mut ViewContext<Editor>,
9476 ) -> Option<MultiBufferDiffHunk> {
9477 let display_point = initial_point.to_display_point(snapshot);
9478 let mut hunks = hunks
9479 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9480 .filter(|(display_hunk, _)| {
9481 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9482 })
9483 .dedup();
9484
9485 if let Some((display_hunk, hunk)) = hunks.next() {
9486 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9487 let row = display_hunk.start_display_row();
9488 let point = DisplayPoint::new(row, 0);
9489 s.select_display_ranges([point..point]);
9490 });
9491
9492 Some(hunk)
9493 } else {
9494 None
9495 }
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_offset(target.buffer.read(cx));
9745 let range = editor.range_for_match(&range);
9746
9747 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9748 let buffer = target.buffer.read(cx);
9749 let range = check_multiline_range(buffer, range);
9750 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9751 s.select_ranges([range]);
9752 });
9753 } else {
9754 cx.window_context().defer(move |cx| {
9755 let target_editor: View<Self> =
9756 workspace.update(cx, |workspace, cx| {
9757 let pane = if split {
9758 workspace.adjacent_pane(cx)
9759 } else {
9760 workspace.active_pane().clone()
9761 };
9762
9763 workspace.open_project_item(
9764 pane,
9765 target.buffer.clone(),
9766 true,
9767 true,
9768 cx,
9769 )
9770 });
9771 target_editor.update(cx, |target_editor, cx| {
9772 // When selecting a definition in a different buffer, disable the nav history
9773 // to avoid creating a history entry at the previous cursor location.
9774 pane.update(cx, |pane, _| pane.disable_history());
9775 let buffer = target.buffer.read(cx);
9776 let range = check_multiline_range(buffer, range);
9777 target_editor.change_selections(
9778 Some(Autoscroll::focused()),
9779 cx,
9780 |s| {
9781 s.select_ranges([range]);
9782 },
9783 );
9784 pane.update(cx, |pane, _| pane.enable_history());
9785 });
9786 });
9787 }
9788 Navigated::Yes
9789 })
9790 })
9791 } else if !definitions.is_empty() {
9792 cx.spawn(|editor, mut cx| async move {
9793 let (title, location_tasks, workspace) = editor
9794 .update(&mut cx, |editor, cx| {
9795 let tab_kind = match kind {
9796 Some(GotoDefinitionKind::Implementation) => "Implementations",
9797 _ => "Definitions",
9798 };
9799 let title = definitions
9800 .iter()
9801 .find_map(|definition| match definition {
9802 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9803 let buffer = origin.buffer.read(cx);
9804 format!(
9805 "{} for {}",
9806 tab_kind,
9807 buffer
9808 .text_for_range(origin.range.clone())
9809 .collect::<String>()
9810 )
9811 }),
9812 HoverLink::InlayHint(_, _) => None,
9813 HoverLink::Url(_) => None,
9814 HoverLink::File(_) => None,
9815 })
9816 .unwrap_or(tab_kind.to_string());
9817 let location_tasks = definitions
9818 .into_iter()
9819 .map(|definition| match definition {
9820 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9821 HoverLink::InlayHint(lsp_location, server_id) => {
9822 editor.compute_target_location(lsp_location, server_id, cx)
9823 }
9824 HoverLink::Url(_) => Task::ready(Ok(None)),
9825 HoverLink::File(_) => Task::ready(Ok(None)),
9826 })
9827 .collect::<Vec<_>>();
9828 (title, location_tasks, editor.workspace().clone())
9829 })
9830 .context("location tasks preparation")?;
9831
9832 let locations = future::join_all(location_tasks)
9833 .await
9834 .into_iter()
9835 .filter_map(|location| location.transpose())
9836 .collect::<Result<_>>()
9837 .context("location tasks")?;
9838
9839 let Some(workspace) = workspace else {
9840 return Ok(Navigated::No);
9841 };
9842 let opened = workspace
9843 .update(&mut cx, |workspace, cx| {
9844 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9845 })
9846 .ok();
9847
9848 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9849 })
9850 } else {
9851 Task::ready(Ok(Navigated::No))
9852 }
9853 }
9854
9855 fn compute_target_location(
9856 &self,
9857 lsp_location: lsp::Location,
9858 server_id: LanguageServerId,
9859 cx: &mut ViewContext<Self>,
9860 ) -> Task<anyhow::Result<Option<Location>>> {
9861 let Some(project) = self.project.clone() else {
9862 return Task::ready(Ok(None));
9863 };
9864
9865 cx.spawn(move |editor, mut cx| async move {
9866 let location_task = editor.update(&mut cx, |_, cx| {
9867 project.update(cx, |project, cx| {
9868 let language_server_name = project
9869 .language_server_statuses(cx)
9870 .find(|(id, _)| server_id == *id)
9871 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9872 language_server_name.map(|language_server_name| {
9873 project.open_local_buffer_via_lsp(
9874 lsp_location.uri.clone(),
9875 server_id,
9876 language_server_name,
9877 cx,
9878 )
9879 })
9880 })
9881 })?;
9882 let location = match location_task {
9883 Some(task) => Some({
9884 let target_buffer_handle = task.await.context("open local buffer")?;
9885 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9886 let target_start = target_buffer
9887 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9888 let target_end = target_buffer
9889 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9890 target_buffer.anchor_after(target_start)
9891 ..target_buffer.anchor_before(target_end)
9892 })?;
9893 Location {
9894 buffer: target_buffer_handle,
9895 range,
9896 }
9897 }),
9898 None => None,
9899 };
9900 Ok(location)
9901 })
9902 }
9903
9904 pub fn find_all_references(
9905 &mut self,
9906 _: &FindAllReferences,
9907 cx: &mut ViewContext<Self>,
9908 ) -> Option<Task<Result<Navigated>>> {
9909 let selection = self.selections.newest::<usize>(cx);
9910 let multi_buffer = self.buffer.read(cx);
9911 let head = selection.head();
9912
9913 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9914 let head_anchor = multi_buffer_snapshot.anchor_at(
9915 head,
9916 if head < selection.tail() {
9917 Bias::Right
9918 } else {
9919 Bias::Left
9920 },
9921 );
9922
9923 match self
9924 .find_all_references_task_sources
9925 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9926 {
9927 Ok(_) => {
9928 log::info!(
9929 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9930 );
9931 return None;
9932 }
9933 Err(i) => {
9934 self.find_all_references_task_sources.insert(i, head_anchor);
9935 }
9936 }
9937
9938 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9939 let workspace = self.workspace()?;
9940 let project = workspace.read(cx).project().clone();
9941 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9942 Some(cx.spawn(|editor, mut cx| async move {
9943 let _cleanup = defer({
9944 let mut cx = cx.clone();
9945 move || {
9946 let _ = editor.update(&mut cx, |editor, _| {
9947 if let Ok(i) =
9948 editor
9949 .find_all_references_task_sources
9950 .binary_search_by(|anchor| {
9951 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9952 })
9953 {
9954 editor.find_all_references_task_sources.remove(i);
9955 }
9956 });
9957 }
9958 });
9959
9960 let locations = references.await?;
9961 if locations.is_empty() {
9962 return anyhow::Ok(Navigated::No);
9963 }
9964
9965 workspace.update(&mut cx, |workspace, cx| {
9966 let title = locations
9967 .first()
9968 .as_ref()
9969 .map(|location| {
9970 let buffer = location.buffer.read(cx);
9971 format!(
9972 "References to `{}`",
9973 buffer
9974 .text_for_range(location.range.clone())
9975 .collect::<String>()
9976 )
9977 })
9978 .unwrap();
9979 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9980 Navigated::Yes
9981 })
9982 }))
9983 }
9984
9985 /// Opens a multibuffer with the given project locations in it
9986 pub fn open_locations_in_multibuffer(
9987 workspace: &mut Workspace,
9988 mut locations: Vec<Location>,
9989 title: String,
9990 split: bool,
9991 cx: &mut ViewContext<Workspace>,
9992 ) {
9993 // If there are multiple definitions, open them in a multibuffer
9994 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9995 let mut locations = locations.into_iter().peekable();
9996 let mut ranges_to_highlight = Vec::new();
9997 let capability = workspace.project().read(cx).capability();
9998
9999 let excerpt_buffer = cx.new_model(|cx| {
10000 let mut multibuffer = MultiBuffer::new(capability);
10001 while let Some(location) = locations.next() {
10002 let buffer = location.buffer.read(cx);
10003 let mut ranges_for_buffer = Vec::new();
10004 let range = location.range.to_offset(buffer);
10005 ranges_for_buffer.push(range.clone());
10006
10007 while let Some(next_location) = locations.peek() {
10008 if next_location.buffer == location.buffer {
10009 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10010 locations.next();
10011 } else {
10012 break;
10013 }
10014 }
10015
10016 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10017 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10018 location.buffer.clone(),
10019 ranges_for_buffer,
10020 DEFAULT_MULTIBUFFER_CONTEXT,
10021 cx,
10022 ))
10023 }
10024
10025 multibuffer.with_title(title)
10026 });
10027
10028 let editor = cx.new_view(|cx| {
10029 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10030 });
10031 editor.update(cx, |editor, cx| {
10032 if let Some(first_range) = ranges_to_highlight.first() {
10033 editor.change_selections(None, cx, |selections| {
10034 selections.clear_disjoint();
10035 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10036 });
10037 }
10038 editor.highlight_background::<Self>(
10039 &ranges_to_highlight,
10040 |theme| theme.editor_highlighted_line_background,
10041 cx,
10042 );
10043 editor.register_buffers_with_language_servers(cx);
10044 });
10045
10046 let item = Box::new(editor);
10047 let item_id = item.item_id();
10048
10049 if split {
10050 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10051 } else {
10052 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10053 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10054 pane.close_current_preview_item(cx)
10055 } else {
10056 None
10057 }
10058 });
10059 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10060 }
10061 workspace.active_pane().update(cx, |pane, cx| {
10062 pane.set_preview_item_id(Some(item_id), cx);
10063 });
10064 }
10065
10066 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10067 use language::ToOffset as _;
10068
10069 let provider = self.semantics_provider.clone()?;
10070 let selection = self.selections.newest_anchor().clone();
10071 let (cursor_buffer, cursor_buffer_position) = self
10072 .buffer
10073 .read(cx)
10074 .text_anchor_for_position(selection.head(), cx)?;
10075 let (tail_buffer, cursor_buffer_position_end) = self
10076 .buffer
10077 .read(cx)
10078 .text_anchor_for_position(selection.tail(), cx)?;
10079 if tail_buffer != cursor_buffer {
10080 return None;
10081 }
10082
10083 let snapshot = cursor_buffer.read(cx).snapshot();
10084 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10085 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10086 let prepare_rename = provider
10087 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10088 .unwrap_or_else(|| Task::ready(Ok(None)));
10089 drop(snapshot);
10090
10091 Some(cx.spawn(|this, mut cx| async move {
10092 let rename_range = if let Some(range) = prepare_rename.await? {
10093 Some(range)
10094 } else {
10095 this.update(&mut cx, |this, cx| {
10096 let buffer = this.buffer.read(cx).snapshot(cx);
10097 let mut buffer_highlights = this
10098 .document_highlights_for_position(selection.head(), &buffer)
10099 .filter(|highlight| {
10100 highlight.start.excerpt_id == selection.head().excerpt_id
10101 && highlight.end.excerpt_id == selection.head().excerpt_id
10102 });
10103 buffer_highlights
10104 .next()
10105 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10106 })?
10107 };
10108 if let Some(rename_range) = rename_range {
10109 this.update(&mut cx, |this, cx| {
10110 let snapshot = cursor_buffer.read(cx).snapshot();
10111 let rename_buffer_range = rename_range.to_offset(&snapshot);
10112 let cursor_offset_in_rename_range =
10113 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10114 let cursor_offset_in_rename_range_end =
10115 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10116
10117 this.take_rename(false, cx);
10118 let buffer = this.buffer.read(cx).read(cx);
10119 let cursor_offset = selection.head().to_offset(&buffer);
10120 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10121 let rename_end = rename_start + rename_buffer_range.len();
10122 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10123 let mut old_highlight_id = None;
10124 let old_name: Arc<str> = buffer
10125 .chunks(rename_start..rename_end, true)
10126 .map(|chunk| {
10127 if old_highlight_id.is_none() {
10128 old_highlight_id = chunk.syntax_highlight_id;
10129 }
10130 chunk.text
10131 })
10132 .collect::<String>()
10133 .into();
10134
10135 drop(buffer);
10136
10137 // Position the selection in the rename editor so that it matches the current selection.
10138 this.show_local_selections = false;
10139 let rename_editor = cx.new_view(|cx| {
10140 let mut editor = Editor::single_line(cx);
10141 editor.buffer.update(cx, |buffer, cx| {
10142 buffer.edit([(0..0, old_name.clone())], None, cx)
10143 });
10144 let rename_selection_range = match cursor_offset_in_rename_range
10145 .cmp(&cursor_offset_in_rename_range_end)
10146 {
10147 Ordering::Equal => {
10148 editor.select_all(&SelectAll, cx);
10149 return editor;
10150 }
10151 Ordering::Less => {
10152 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10153 }
10154 Ordering::Greater => {
10155 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10156 }
10157 };
10158 if rename_selection_range.end > old_name.len() {
10159 editor.select_all(&SelectAll, cx);
10160 } else {
10161 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10162 s.select_ranges([rename_selection_range]);
10163 });
10164 }
10165 editor
10166 });
10167 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10168 if e == &EditorEvent::Focused {
10169 cx.emit(EditorEvent::FocusedIn)
10170 }
10171 })
10172 .detach();
10173
10174 let write_highlights =
10175 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10176 let read_highlights =
10177 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10178 let ranges = write_highlights
10179 .iter()
10180 .flat_map(|(_, ranges)| ranges.iter())
10181 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10182 .cloned()
10183 .collect();
10184
10185 this.highlight_text::<Rename>(
10186 ranges,
10187 HighlightStyle {
10188 fade_out: Some(0.6),
10189 ..Default::default()
10190 },
10191 cx,
10192 );
10193 let rename_focus_handle = rename_editor.focus_handle(cx);
10194 cx.focus(&rename_focus_handle);
10195 let block_id = this.insert_blocks(
10196 [BlockProperties {
10197 style: BlockStyle::Flex,
10198 placement: BlockPlacement::Below(range.start),
10199 height: 1,
10200 render: Arc::new({
10201 let rename_editor = rename_editor.clone();
10202 move |cx: &mut BlockContext| {
10203 let mut text_style = cx.editor_style.text.clone();
10204 if let Some(highlight_style) = old_highlight_id
10205 .and_then(|h| h.style(&cx.editor_style.syntax))
10206 {
10207 text_style = text_style.highlight(highlight_style);
10208 }
10209 div()
10210 .block_mouse_down()
10211 .pl(cx.anchor_x)
10212 .child(EditorElement::new(
10213 &rename_editor,
10214 EditorStyle {
10215 background: cx.theme().system().transparent,
10216 local_player: cx.editor_style.local_player,
10217 text: text_style,
10218 scrollbar_width: cx.editor_style.scrollbar_width,
10219 syntax: cx.editor_style.syntax.clone(),
10220 status: cx.editor_style.status.clone(),
10221 inlay_hints_style: HighlightStyle {
10222 font_weight: Some(FontWeight::BOLD),
10223 ..make_inlay_hints_style(cx)
10224 },
10225 inline_completion_styles: make_suggestion_styles(
10226 cx,
10227 ),
10228 ..EditorStyle::default()
10229 },
10230 ))
10231 .into_any_element()
10232 }
10233 }),
10234 priority: 0,
10235 }],
10236 Some(Autoscroll::fit()),
10237 cx,
10238 )[0];
10239 this.pending_rename = Some(RenameState {
10240 range,
10241 old_name,
10242 editor: rename_editor,
10243 block_id,
10244 });
10245 })?;
10246 }
10247
10248 Ok(())
10249 }))
10250 }
10251
10252 pub fn confirm_rename(
10253 &mut self,
10254 _: &ConfirmRename,
10255 cx: &mut ViewContext<Self>,
10256 ) -> Option<Task<Result<()>>> {
10257 let rename = self.take_rename(false, cx)?;
10258 let workspace = self.workspace()?.downgrade();
10259 let (buffer, start) = self
10260 .buffer
10261 .read(cx)
10262 .text_anchor_for_position(rename.range.start, cx)?;
10263 let (end_buffer, _) = self
10264 .buffer
10265 .read(cx)
10266 .text_anchor_for_position(rename.range.end, cx)?;
10267 if buffer != end_buffer {
10268 return None;
10269 }
10270
10271 let old_name = rename.old_name;
10272 let new_name = rename.editor.read(cx).text(cx);
10273
10274 let rename = self.semantics_provider.as_ref()?.perform_rename(
10275 &buffer,
10276 start,
10277 new_name.clone(),
10278 cx,
10279 )?;
10280
10281 Some(cx.spawn(|editor, mut cx| async move {
10282 let project_transaction = rename.await?;
10283 Self::open_project_transaction(
10284 &editor,
10285 workspace,
10286 project_transaction,
10287 format!("Rename: {} → {}", old_name, new_name),
10288 cx.clone(),
10289 )
10290 .await?;
10291
10292 editor.update(&mut cx, |editor, cx| {
10293 editor.refresh_document_highlights(cx);
10294 })?;
10295 Ok(())
10296 }))
10297 }
10298
10299 fn take_rename(
10300 &mut self,
10301 moving_cursor: bool,
10302 cx: &mut ViewContext<Self>,
10303 ) -> Option<RenameState> {
10304 let rename = self.pending_rename.take()?;
10305 if rename.editor.focus_handle(cx).is_focused(cx) {
10306 cx.focus(&self.focus_handle);
10307 }
10308
10309 self.remove_blocks(
10310 [rename.block_id].into_iter().collect(),
10311 Some(Autoscroll::fit()),
10312 cx,
10313 );
10314 self.clear_highlights::<Rename>(cx);
10315 self.show_local_selections = true;
10316
10317 if moving_cursor {
10318 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10319 editor.selections.newest::<usize>(cx).head()
10320 });
10321
10322 // Update the selection to match the position of the selection inside
10323 // the rename editor.
10324 let snapshot = self.buffer.read(cx).read(cx);
10325 let rename_range = rename.range.to_offset(&snapshot);
10326 let cursor_in_editor = snapshot
10327 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10328 .min(rename_range.end);
10329 drop(snapshot);
10330
10331 self.change_selections(None, cx, |s| {
10332 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10333 });
10334 } else {
10335 self.refresh_document_highlights(cx);
10336 }
10337
10338 Some(rename)
10339 }
10340
10341 pub fn pending_rename(&self) -> Option<&RenameState> {
10342 self.pending_rename.as_ref()
10343 }
10344
10345 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10346 let project = match &self.project {
10347 Some(project) => project.clone(),
10348 None => return None,
10349 };
10350
10351 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10352 }
10353
10354 fn format_selections(
10355 &mut self,
10356 _: &FormatSelections,
10357 cx: &mut ViewContext<Self>,
10358 ) -> Option<Task<Result<()>>> {
10359 let project = match &self.project {
10360 Some(project) => project.clone(),
10361 None => return None,
10362 };
10363
10364 let ranges = self
10365 .selections
10366 .all_adjusted(cx)
10367 .into_iter()
10368 .map(|selection| selection.range())
10369 .collect_vec();
10370
10371 Some(self.perform_format(
10372 project,
10373 FormatTrigger::Manual,
10374 FormatTarget::Ranges(ranges),
10375 cx,
10376 ))
10377 }
10378
10379 fn perform_format(
10380 &mut self,
10381 project: Model<Project>,
10382 trigger: FormatTrigger,
10383 target: FormatTarget,
10384 cx: &mut ViewContext<Self>,
10385 ) -> Task<Result<()>> {
10386 let buffer = self.buffer.clone();
10387 let (buffers, target) = match target {
10388 FormatTarget::Buffers => {
10389 let mut buffers = buffer.read(cx).all_buffers();
10390 if trigger == FormatTrigger::Save {
10391 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10392 }
10393 (buffers, LspFormatTarget::Buffers)
10394 }
10395 FormatTarget::Ranges(selection_ranges) => {
10396 let multi_buffer = buffer.read(cx);
10397 let snapshot = multi_buffer.read(cx);
10398 let mut buffers = HashSet::default();
10399 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10400 BTreeMap::new();
10401 for selection_range in selection_ranges {
10402 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10403 {
10404 let buffer_id = excerpt.buffer_id();
10405 let start = excerpt.buffer().anchor_before(buffer_range.start);
10406 let end = excerpt.buffer().anchor_after(buffer_range.end);
10407 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10408 buffer_id_to_ranges
10409 .entry(buffer_id)
10410 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10411 .or_insert_with(|| vec![start..end]);
10412 }
10413 }
10414 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10415 }
10416 };
10417
10418 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10419 let format = project.update(cx, |project, cx| {
10420 project.format(buffers, target, true, trigger, cx)
10421 });
10422
10423 cx.spawn(|_, mut cx| async move {
10424 let transaction = futures::select_biased! {
10425 () = timeout => {
10426 log::warn!("timed out waiting for formatting");
10427 None
10428 }
10429 transaction = format.log_err().fuse() => transaction,
10430 };
10431
10432 buffer
10433 .update(&mut cx, |buffer, cx| {
10434 if let Some(transaction) = transaction {
10435 if !buffer.is_singleton() {
10436 buffer.push_transaction(&transaction.0, cx);
10437 }
10438 }
10439
10440 cx.notify();
10441 })
10442 .ok();
10443
10444 Ok(())
10445 })
10446 }
10447
10448 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10449 if let Some(project) = self.project.clone() {
10450 self.buffer.update(cx, |multi_buffer, cx| {
10451 project.update(cx, |project, cx| {
10452 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10453 });
10454 })
10455 }
10456 }
10457
10458 fn cancel_language_server_work(
10459 &mut self,
10460 _: &actions::CancelLanguageServerWork,
10461 cx: &mut ViewContext<Self>,
10462 ) {
10463 if let Some(project) = self.project.clone() {
10464 self.buffer.update(cx, |multi_buffer, cx| {
10465 project.update(cx, |project, cx| {
10466 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10467 });
10468 })
10469 }
10470 }
10471
10472 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10473 cx.show_character_palette();
10474 }
10475
10476 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10477 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10478 let buffer = self.buffer.read(cx).snapshot(cx);
10479 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10480 let is_valid = buffer
10481 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10482 .any(|entry| {
10483 let range = entry.range.to_offset(&buffer);
10484 entry.diagnostic.is_primary
10485 && !range.is_empty()
10486 && range.start == primary_range_start
10487 && entry.diagnostic.message == active_diagnostics.primary_message
10488 });
10489
10490 if is_valid != active_diagnostics.is_valid {
10491 active_diagnostics.is_valid = is_valid;
10492 let mut new_styles = HashMap::default();
10493 for (block_id, diagnostic) in &active_diagnostics.blocks {
10494 new_styles.insert(
10495 *block_id,
10496 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10497 );
10498 }
10499 self.display_map.update(cx, |display_map, _cx| {
10500 display_map.replace_blocks(new_styles)
10501 });
10502 }
10503 }
10504 }
10505
10506 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10507 self.dismiss_diagnostics(cx);
10508 let snapshot = self.snapshot(cx);
10509 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10510 let buffer = self.buffer.read(cx).snapshot(cx);
10511
10512 let mut primary_range = None;
10513 let mut primary_message = None;
10514 let mut group_end = Point::zero();
10515 let diagnostic_group = buffer
10516 .diagnostic_group(group_id)
10517 .filter_map(|entry| {
10518 let start = entry.range.start.to_point(&buffer);
10519 let end = entry.range.end.to_point(&buffer);
10520 if snapshot.is_line_folded(MultiBufferRow(start.row))
10521 && (start.row == end.row
10522 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10523 {
10524 return None;
10525 }
10526 if end > group_end {
10527 group_end = end;
10528 }
10529 if entry.diagnostic.is_primary {
10530 primary_range = Some(entry.range.clone());
10531 primary_message = Some(entry.diagnostic.message.clone());
10532 }
10533 Some(entry)
10534 })
10535 .collect::<Vec<_>>();
10536 let primary_range = primary_range?;
10537 let primary_message = primary_message?;
10538
10539 let blocks = display_map
10540 .insert_blocks(
10541 diagnostic_group.iter().map(|entry| {
10542 let diagnostic = entry.diagnostic.clone();
10543 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10544 BlockProperties {
10545 style: BlockStyle::Fixed,
10546 placement: BlockPlacement::Below(
10547 buffer.anchor_after(entry.range.start),
10548 ),
10549 height: message_height,
10550 render: diagnostic_block_renderer(diagnostic, None, true, true),
10551 priority: 0,
10552 }
10553 }),
10554 cx,
10555 )
10556 .into_iter()
10557 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10558 .collect();
10559
10560 Some(ActiveDiagnosticGroup {
10561 primary_range,
10562 primary_message,
10563 group_id,
10564 blocks,
10565 is_valid: true,
10566 })
10567 });
10568 }
10569
10570 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10571 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10572 self.display_map.update(cx, |display_map, cx| {
10573 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10574 });
10575 cx.notify();
10576 }
10577 }
10578
10579 pub fn set_selections_from_remote(
10580 &mut self,
10581 selections: Vec<Selection<Anchor>>,
10582 pending_selection: Option<Selection<Anchor>>,
10583 cx: &mut ViewContext<Self>,
10584 ) {
10585 let old_cursor_position = self.selections.newest_anchor().head();
10586 self.selections.change_with(cx, |s| {
10587 s.select_anchors(selections);
10588 if let Some(pending_selection) = pending_selection {
10589 s.set_pending(pending_selection, SelectMode::Character);
10590 } else {
10591 s.clear_pending();
10592 }
10593 });
10594 self.selections_did_change(false, &old_cursor_position, true, cx);
10595 }
10596
10597 fn push_to_selection_history(&mut self) {
10598 self.selection_history.push(SelectionHistoryEntry {
10599 selections: self.selections.disjoint_anchors(),
10600 select_next_state: self.select_next_state.clone(),
10601 select_prev_state: self.select_prev_state.clone(),
10602 add_selections_state: self.add_selections_state.clone(),
10603 });
10604 }
10605
10606 pub fn transact(
10607 &mut self,
10608 cx: &mut ViewContext<Self>,
10609 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10610 ) -> Option<TransactionId> {
10611 self.start_transaction_at(Instant::now(), cx);
10612 update(self, cx);
10613 self.end_transaction_at(Instant::now(), cx)
10614 }
10615
10616 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10617 self.end_selection(cx);
10618 if let Some(tx_id) = self
10619 .buffer
10620 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10621 {
10622 self.selection_history
10623 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10624 cx.emit(EditorEvent::TransactionBegun {
10625 transaction_id: tx_id,
10626 })
10627 }
10628 }
10629
10630 pub fn end_transaction_at(
10631 &mut self,
10632 now: Instant,
10633 cx: &mut ViewContext<Self>,
10634 ) -> Option<TransactionId> {
10635 if let Some(transaction_id) = self
10636 .buffer
10637 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10638 {
10639 if let Some((_, end_selections)) =
10640 self.selection_history.transaction_mut(transaction_id)
10641 {
10642 *end_selections = Some(self.selections.disjoint_anchors());
10643 } else {
10644 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10645 }
10646
10647 cx.emit(EditorEvent::Edited { transaction_id });
10648 Some(transaction_id)
10649 } else {
10650 None
10651 }
10652 }
10653
10654 pub fn set_mark(&mut self, _: &actions::SetMark, cx: &mut ViewContext<Self>) {
10655 if self.selection_mark_mode {
10656 self.change_selections(None, cx, |s| {
10657 s.move_with(|_, sel| {
10658 sel.collapse_to(sel.head(), SelectionGoal::None);
10659 });
10660 })
10661 }
10662 self.selection_mark_mode = true;
10663 cx.notify();
10664 }
10665
10666 pub fn swap_selection_ends(
10667 &mut self,
10668 _: &actions::SwapSelectionEnds,
10669 cx: &mut ViewContext<Self>,
10670 ) {
10671 self.change_selections(None, cx, |s| {
10672 s.move_with(|_, sel| {
10673 if sel.start != sel.end {
10674 sel.reversed = !sel.reversed
10675 }
10676 });
10677 });
10678 cx.notify();
10679 }
10680
10681 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10682 if self.is_singleton(cx) {
10683 let selection = self.selections.newest::<Point>(cx);
10684
10685 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10686 let range = if selection.is_empty() {
10687 let point = selection.head().to_display_point(&display_map);
10688 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10689 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10690 .to_point(&display_map);
10691 start..end
10692 } else {
10693 selection.range()
10694 };
10695 if display_map.folds_in_range(range).next().is_some() {
10696 self.unfold_lines(&Default::default(), cx)
10697 } else {
10698 self.fold(&Default::default(), cx)
10699 }
10700 } else {
10701 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10702 let mut toggled_buffers = HashSet::default();
10703 for (_, buffer_snapshot, _) in
10704 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10705 {
10706 let buffer_id = buffer_snapshot.remote_id();
10707 if toggled_buffers.insert(buffer_id) {
10708 if self.buffer_folded(buffer_id, cx) {
10709 self.unfold_buffer(buffer_id, cx);
10710 } else {
10711 self.fold_buffer(buffer_id, cx);
10712 }
10713 }
10714 }
10715 }
10716 }
10717
10718 pub fn toggle_fold_recursive(
10719 &mut self,
10720 _: &actions::ToggleFoldRecursive,
10721 cx: &mut ViewContext<Self>,
10722 ) {
10723 let selection = self.selections.newest::<Point>(cx);
10724
10725 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10726 let range = if selection.is_empty() {
10727 let point = selection.head().to_display_point(&display_map);
10728 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10729 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10730 .to_point(&display_map);
10731 start..end
10732 } else {
10733 selection.range()
10734 };
10735 if display_map.folds_in_range(range).next().is_some() {
10736 self.unfold_recursive(&Default::default(), cx)
10737 } else {
10738 self.fold_recursive(&Default::default(), cx)
10739 }
10740 }
10741
10742 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10743 if self.is_singleton(cx) {
10744 let mut to_fold = Vec::new();
10745 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10746 let selections = self.selections.all_adjusted(cx);
10747
10748 for selection in selections {
10749 let range = selection.range().sorted();
10750 let buffer_start_row = range.start.row;
10751
10752 if range.start.row != range.end.row {
10753 let mut found = false;
10754 let mut row = range.start.row;
10755 while row <= range.end.row {
10756 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10757 {
10758 found = true;
10759 row = crease.range().end.row + 1;
10760 to_fold.push(crease);
10761 } else {
10762 row += 1
10763 }
10764 }
10765 if found {
10766 continue;
10767 }
10768 }
10769
10770 for row in (0..=range.start.row).rev() {
10771 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10772 if crease.range().end.row >= buffer_start_row {
10773 to_fold.push(crease);
10774 if row <= range.start.row {
10775 break;
10776 }
10777 }
10778 }
10779 }
10780 }
10781
10782 self.fold_creases(to_fold, true, cx);
10783 } else {
10784 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10785 let mut folded_buffers = HashSet::default();
10786 for (_, buffer_snapshot, _) in
10787 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10788 {
10789 let buffer_id = buffer_snapshot.remote_id();
10790 if folded_buffers.insert(buffer_id) {
10791 self.fold_buffer(buffer_id, cx);
10792 }
10793 }
10794 }
10795 }
10796
10797 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10798 if !self.buffer.read(cx).is_singleton() {
10799 return;
10800 }
10801
10802 let fold_at_level = fold_at.level;
10803 let snapshot = self.buffer.read(cx).snapshot(cx);
10804 let mut to_fold = Vec::new();
10805 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10806
10807 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10808 while start_row < end_row {
10809 match self
10810 .snapshot(cx)
10811 .crease_for_buffer_row(MultiBufferRow(start_row))
10812 {
10813 Some(crease) => {
10814 let nested_start_row = crease.range().start.row + 1;
10815 let nested_end_row = crease.range().end.row;
10816
10817 if current_level < fold_at_level {
10818 stack.push((nested_start_row, nested_end_row, current_level + 1));
10819 } else if current_level == fold_at_level {
10820 to_fold.push(crease);
10821 }
10822
10823 start_row = nested_end_row + 1;
10824 }
10825 None => start_row += 1,
10826 }
10827 }
10828 }
10829
10830 self.fold_creases(to_fold, true, cx);
10831 }
10832
10833 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10834 if self.buffer.read(cx).is_singleton() {
10835 let mut fold_ranges = Vec::new();
10836 let snapshot = self.buffer.read(cx).snapshot(cx);
10837
10838 for row in 0..snapshot.max_row().0 {
10839 if let Some(foldable_range) =
10840 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10841 {
10842 fold_ranges.push(foldable_range);
10843 }
10844 }
10845
10846 self.fold_creases(fold_ranges, true, cx);
10847 } else {
10848 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10849 editor
10850 .update(&mut cx, |editor, cx| {
10851 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10852 editor.fold_buffer(buffer_id, cx);
10853 }
10854 })
10855 .ok();
10856 });
10857 }
10858 }
10859
10860 pub fn fold_function_bodies(
10861 &mut self,
10862 _: &actions::FoldFunctionBodies,
10863 cx: &mut ViewContext<Self>,
10864 ) {
10865 let snapshot = self.buffer.read(cx).snapshot(cx);
10866 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10867 return;
10868 };
10869 let creases = buffer
10870 .function_body_fold_ranges(0..buffer.len())
10871 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10872 .collect();
10873
10874 self.fold_creases(creases, true, cx);
10875 }
10876
10877 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10878 let mut to_fold = Vec::new();
10879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10880 let selections = self.selections.all_adjusted(cx);
10881
10882 for selection in selections {
10883 let range = selection.range().sorted();
10884 let buffer_start_row = range.start.row;
10885
10886 if range.start.row != range.end.row {
10887 let mut found = false;
10888 for row in range.start.row..=range.end.row {
10889 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10890 found = true;
10891 to_fold.push(crease);
10892 }
10893 }
10894 if found {
10895 continue;
10896 }
10897 }
10898
10899 for row in (0..=range.start.row).rev() {
10900 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10901 if crease.range().end.row >= buffer_start_row {
10902 to_fold.push(crease);
10903 } else {
10904 break;
10905 }
10906 }
10907 }
10908 }
10909
10910 self.fold_creases(to_fold, true, cx);
10911 }
10912
10913 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10914 let buffer_row = fold_at.buffer_row;
10915 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10916
10917 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10918 let autoscroll = self
10919 .selections
10920 .all::<Point>(cx)
10921 .iter()
10922 .any(|selection| crease.range().overlaps(&selection.range()));
10923
10924 self.fold_creases(vec![crease], autoscroll, cx);
10925 }
10926 }
10927
10928 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10929 if self.is_singleton(cx) {
10930 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10931 let buffer = &display_map.buffer_snapshot;
10932 let selections = self.selections.all::<Point>(cx);
10933 let ranges = selections
10934 .iter()
10935 .map(|s| {
10936 let range = s.display_range(&display_map).sorted();
10937 let mut start = range.start.to_point(&display_map);
10938 let mut end = range.end.to_point(&display_map);
10939 start.column = 0;
10940 end.column = buffer.line_len(MultiBufferRow(end.row));
10941 start..end
10942 })
10943 .collect::<Vec<_>>();
10944
10945 self.unfold_ranges(&ranges, true, true, cx);
10946 } else {
10947 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10948 let mut unfolded_buffers = HashSet::default();
10949 for (_, buffer_snapshot, _) in
10950 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10951 {
10952 let buffer_id = buffer_snapshot.remote_id();
10953 if unfolded_buffers.insert(buffer_id) {
10954 self.unfold_buffer(buffer_id, cx);
10955 }
10956 }
10957 }
10958 }
10959
10960 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10961 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10962 let selections = self.selections.all::<Point>(cx);
10963 let ranges = selections
10964 .iter()
10965 .map(|s| {
10966 let mut range = s.display_range(&display_map).sorted();
10967 *range.start.column_mut() = 0;
10968 *range.end.column_mut() = display_map.line_len(range.end.row());
10969 let start = range.start.to_point(&display_map);
10970 let end = range.end.to_point(&display_map);
10971 start..end
10972 })
10973 .collect::<Vec<_>>();
10974
10975 self.unfold_ranges(&ranges, true, true, cx);
10976 }
10977
10978 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10979 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10980
10981 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10982 ..Point::new(
10983 unfold_at.buffer_row.0,
10984 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10985 );
10986
10987 let autoscroll = self
10988 .selections
10989 .all::<Point>(cx)
10990 .iter()
10991 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10992
10993 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10994 }
10995
10996 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10997 if self.buffer.read(cx).is_singleton() {
10998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10999 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11000 } else {
11001 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11002 editor
11003 .update(&mut cx, |editor, cx| {
11004 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11005 editor.unfold_buffer(buffer_id, cx);
11006 }
11007 })
11008 .ok();
11009 });
11010 }
11011 }
11012
11013 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11014 let selections = self.selections.all::<Point>(cx);
11015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11016 let line_mode = self.selections.line_mode;
11017 let ranges = selections
11018 .into_iter()
11019 .map(|s| {
11020 if line_mode {
11021 let start = Point::new(s.start.row, 0);
11022 let end = Point::new(
11023 s.end.row,
11024 display_map
11025 .buffer_snapshot
11026 .line_len(MultiBufferRow(s.end.row)),
11027 );
11028 Crease::simple(start..end, display_map.fold_placeholder.clone())
11029 } else {
11030 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11031 }
11032 })
11033 .collect::<Vec<_>>();
11034 self.fold_creases(ranges, true, cx);
11035 }
11036
11037 pub fn fold_ranges<T: ToOffset + Clone>(
11038 &mut self,
11039 ranges: Vec<Range<T>>,
11040 auto_scroll: bool,
11041 cx: &mut ViewContext<Self>,
11042 ) {
11043 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11044 let ranges = ranges
11045 .into_iter()
11046 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11047 .collect::<Vec<_>>();
11048 self.fold_creases(ranges, auto_scroll, cx);
11049 }
11050
11051 pub fn fold_creases<T: ToOffset + Clone>(
11052 &mut self,
11053 creases: Vec<Crease<T>>,
11054 auto_scroll: bool,
11055 cx: &mut ViewContext<Self>,
11056 ) {
11057 if creases.is_empty() {
11058 return;
11059 }
11060
11061 let mut buffers_affected = HashSet::default();
11062 let multi_buffer = self.buffer().read(cx);
11063 for crease in &creases {
11064 if let Some((_, buffer, _)) =
11065 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11066 {
11067 buffers_affected.insert(buffer.read(cx).remote_id());
11068 };
11069 }
11070
11071 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11072
11073 if auto_scroll {
11074 self.request_autoscroll(Autoscroll::fit(), cx);
11075 }
11076
11077 for buffer_id in buffers_affected {
11078 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11079 }
11080
11081 cx.notify();
11082
11083 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11084 // Clear diagnostics block when folding a range that contains it.
11085 let snapshot = self.snapshot(cx);
11086 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11087 drop(snapshot);
11088 self.active_diagnostics = Some(active_diagnostics);
11089 self.dismiss_diagnostics(cx);
11090 } else {
11091 self.active_diagnostics = Some(active_diagnostics);
11092 }
11093 }
11094
11095 self.scrollbar_marker_state.dirty = true;
11096 }
11097
11098 /// Removes any folds whose ranges intersect any of the given ranges.
11099 pub fn unfold_ranges<T: ToOffset + Clone>(
11100 &mut self,
11101 ranges: &[Range<T>],
11102 inclusive: bool,
11103 auto_scroll: bool,
11104 cx: &mut ViewContext<Self>,
11105 ) {
11106 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11107 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11108 });
11109 }
11110
11111 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11112 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11113 return;
11114 }
11115 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11116 return;
11117 };
11118 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11119 self.display_map
11120 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11121 cx.emit(EditorEvent::BufferFoldToggled {
11122 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11123 folded: true,
11124 });
11125 cx.notify();
11126 }
11127
11128 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11129 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11130 return;
11131 }
11132 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11133 return;
11134 };
11135 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11136 self.display_map.update(cx, |display_map, cx| {
11137 display_map.unfold_buffer(buffer_id, cx);
11138 });
11139 cx.emit(EditorEvent::BufferFoldToggled {
11140 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11141 folded: false,
11142 });
11143 cx.notify();
11144 }
11145
11146 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11147 self.display_map.read(cx).buffer_folded(buffer)
11148 }
11149
11150 /// Removes any folds with the given ranges.
11151 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11152 &mut self,
11153 ranges: &[Range<T>],
11154 type_id: TypeId,
11155 auto_scroll: bool,
11156 cx: &mut ViewContext<Self>,
11157 ) {
11158 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11159 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11160 });
11161 }
11162
11163 fn remove_folds_with<T: ToOffset + Clone>(
11164 &mut self,
11165 ranges: &[Range<T>],
11166 auto_scroll: bool,
11167 cx: &mut ViewContext<Self>,
11168 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11169 ) {
11170 if ranges.is_empty() {
11171 return;
11172 }
11173
11174 let mut buffers_affected = HashSet::default();
11175 let multi_buffer = self.buffer().read(cx);
11176 for range in ranges {
11177 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11178 buffers_affected.insert(buffer.read(cx).remote_id());
11179 };
11180 }
11181
11182 self.display_map.update(cx, update);
11183
11184 if auto_scroll {
11185 self.request_autoscroll(Autoscroll::fit(), cx);
11186 }
11187
11188 for buffer_id in buffers_affected {
11189 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11190 }
11191
11192 cx.notify();
11193 self.scrollbar_marker_state.dirty = true;
11194 self.active_indent_guides_state.dirty = true;
11195 }
11196
11197 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11198 self.display_map.read(cx).fold_placeholder.clone()
11199 }
11200
11201 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11202 if hovered != self.gutter_hovered {
11203 self.gutter_hovered = hovered;
11204 cx.notify();
11205 }
11206 }
11207
11208 pub fn insert_blocks(
11209 &mut self,
11210 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11211 autoscroll: Option<Autoscroll>,
11212 cx: &mut ViewContext<Self>,
11213 ) -> Vec<CustomBlockId> {
11214 let blocks = self
11215 .display_map
11216 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11217 if let Some(autoscroll) = autoscroll {
11218 self.request_autoscroll(autoscroll, cx);
11219 }
11220 cx.notify();
11221 blocks
11222 }
11223
11224 pub fn resize_blocks(
11225 &mut self,
11226 heights: HashMap<CustomBlockId, u32>,
11227 autoscroll: Option<Autoscroll>,
11228 cx: &mut ViewContext<Self>,
11229 ) {
11230 self.display_map
11231 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11232 if let Some(autoscroll) = autoscroll {
11233 self.request_autoscroll(autoscroll, cx);
11234 }
11235 cx.notify();
11236 }
11237
11238 pub fn replace_blocks(
11239 &mut self,
11240 renderers: HashMap<CustomBlockId, RenderBlock>,
11241 autoscroll: Option<Autoscroll>,
11242 cx: &mut ViewContext<Self>,
11243 ) {
11244 self.display_map
11245 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11246 if let Some(autoscroll) = autoscroll {
11247 self.request_autoscroll(autoscroll, cx);
11248 }
11249 cx.notify();
11250 }
11251
11252 pub fn remove_blocks(
11253 &mut self,
11254 block_ids: HashSet<CustomBlockId>,
11255 autoscroll: Option<Autoscroll>,
11256 cx: &mut ViewContext<Self>,
11257 ) {
11258 self.display_map.update(cx, |display_map, cx| {
11259 display_map.remove_blocks(block_ids, cx)
11260 });
11261 if let Some(autoscroll) = autoscroll {
11262 self.request_autoscroll(autoscroll, cx);
11263 }
11264 cx.notify();
11265 }
11266
11267 pub fn row_for_block(
11268 &self,
11269 block_id: CustomBlockId,
11270 cx: &mut ViewContext<Self>,
11271 ) -> Option<DisplayRow> {
11272 self.display_map
11273 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11274 }
11275
11276 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11277 self.focused_block = Some(focused_block);
11278 }
11279
11280 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11281 self.focused_block.take()
11282 }
11283
11284 pub fn insert_creases(
11285 &mut self,
11286 creases: impl IntoIterator<Item = Crease<Anchor>>,
11287 cx: &mut ViewContext<Self>,
11288 ) -> Vec<CreaseId> {
11289 self.display_map
11290 .update(cx, |map, cx| map.insert_creases(creases, cx))
11291 }
11292
11293 pub fn remove_creases(
11294 &mut self,
11295 ids: impl IntoIterator<Item = CreaseId>,
11296 cx: &mut ViewContext<Self>,
11297 ) {
11298 self.display_map
11299 .update(cx, |map, cx| map.remove_creases(ids, cx));
11300 }
11301
11302 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11303 self.display_map
11304 .update(cx, |map, cx| map.snapshot(cx))
11305 .longest_row()
11306 }
11307
11308 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11309 self.display_map
11310 .update(cx, |map, cx| map.snapshot(cx))
11311 .max_point()
11312 }
11313
11314 pub fn text(&self, cx: &AppContext) -> String {
11315 self.buffer.read(cx).read(cx).text()
11316 }
11317
11318 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11319 let text = self.text(cx);
11320 let text = text.trim();
11321
11322 if text.is_empty() {
11323 return None;
11324 }
11325
11326 Some(text.to_string())
11327 }
11328
11329 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11330 self.transact(cx, |this, cx| {
11331 this.buffer
11332 .read(cx)
11333 .as_singleton()
11334 .expect("you can only call set_text on editors for singleton buffers")
11335 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11336 });
11337 }
11338
11339 pub fn display_text(&self, cx: &mut AppContext) -> String {
11340 self.display_map
11341 .update(cx, |map, cx| map.snapshot(cx))
11342 .text()
11343 }
11344
11345 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11346 let mut wrap_guides = smallvec::smallvec![];
11347
11348 if self.show_wrap_guides == Some(false) {
11349 return wrap_guides;
11350 }
11351
11352 let settings = self.buffer.read(cx).settings_at(0, cx);
11353 if settings.show_wrap_guides {
11354 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11355 wrap_guides.push((soft_wrap as usize, true));
11356 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11357 wrap_guides.push((soft_wrap as usize, true));
11358 }
11359 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11360 }
11361
11362 wrap_guides
11363 }
11364
11365 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11366 let settings = self.buffer.read(cx).settings_at(0, cx);
11367 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11368 match mode {
11369 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11370 SoftWrap::None
11371 }
11372 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11373 language_settings::SoftWrap::PreferredLineLength => {
11374 SoftWrap::Column(settings.preferred_line_length)
11375 }
11376 language_settings::SoftWrap::Bounded => {
11377 SoftWrap::Bounded(settings.preferred_line_length)
11378 }
11379 }
11380 }
11381
11382 pub fn set_soft_wrap_mode(
11383 &mut self,
11384 mode: language_settings::SoftWrap,
11385 cx: &mut ViewContext<Self>,
11386 ) {
11387 self.soft_wrap_mode_override = Some(mode);
11388 cx.notify();
11389 }
11390
11391 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11392 self.text_style_refinement = Some(style);
11393 }
11394
11395 /// called by the Element so we know what style we were most recently rendered with.
11396 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11397 let rem_size = cx.rem_size();
11398 self.display_map.update(cx, |map, cx| {
11399 map.set_font(
11400 style.text.font(),
11401 style.text.font_size.to_pixels(rem_size),
11402 cx,
11403 )
11404 });
11405 self.style = Some(style);
11406 }
11407
11408 pub fn style(&self) -> Option<&EditorStyle> {
11409 self.style.as_ref()
11410 }
11411
11412 // Called by the element. This method is not designed to be called outside of the editor
11413 // element's layout code because it does not notify when rewrapping is computed synchronously.
11414 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11415 self.display_map
11416 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11417 }
11418
11419 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11420 if self.soft_wrap_mode_override.is_some() {
11421 self.soft_wrap_mode_override.take();
11422 } else {
11423 let soft_wrap = match self.soft_wrap_mode(cx) {
11424 SoftWrap::GitDiff => return,
11425 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11426 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11427 language_settings::SoftWrap::None
11428 }
11429 };
11430 self.soft_wrap_mode_override = Some(soft_wrap);
11431 }
11432 cx.notify();
11433 }
11434
11435 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11436 let Some(workspace) = self.workspace() else {
11437 return;
11438 };
11439 let fs = workspace.read(cx).app_state().fs.clone();
11440 let current_show = TabBarSettings::get_global(cx).show;
11441 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11442 setting.show = Some(!current_show);
11443 });
11444 }
11445
11446 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11447 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11448 self.buffer
11449 .read(cx)
11450 .settings_at(0, cx)
11451 .indent_guides
11452 .enabled
11453 });
11454 self.show_indent_guides = Some(!currently_enabled);
11455 cx.notify();
11456 }
11457
11458 fn should_show_indent_guides(&self) -> Option<bool> {
11459 self.show_indent_guides
11460 }
11461
11462 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11463 let mut editor_settings = EditorSettings::get_global(cx).clone();
11464 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11465 EditorSettings::override_global(editor_settings, cx);
11466 }
11467
11468 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11469 self.use_relative_line_numbers
11470 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11471 }
11472
11473 pub fn toggle_relative_line_numbers(
11474 &mut self,
11475 _: &ToggleRelativeLineNumbers,
11476 cx: &mut ViewContext<Self>,
11477 ) {
11478 let is_relative = self.should_use_relative_line_numbers(cx);
11479 self.set_relative_line_number(Some(!is_relative), cx)
11480 }
11481
11482 pub fn set_relative_line_number(
11483 &mut self,
11484 is_relative: Option<bool>,
11485 cx: &mut ViewContext<Self>,
11486 ) {
11487 self.use_relative_line_numbers = is_relative;
11488 cx.notify();
11489 }
11490
11491 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11492 self.show_gutter = show_gutter;
11493 cx.notify();
11494 }
11495
11496 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11497 self.show_scrollbars = show_scrollbars;
11498 cx.notify();
11499 }
11500
11501 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11502 self.show_line_numbers = Some(show_line_numbers);
11503 cx.notify();
11504 }
11505
11506 pub fn set_show_git_diff_gutter(
11507 &mut self,
11508 show_git_diff_gutter: bool,
11509 cx: &mut ViewContext<Self>,
11510 ) {
11511 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11512 cx.notify();
11513 }
11514
11515 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11516 self.show_code_actions = Some(show_code_actions);
11517 cx.notify();
11518 }
11519
11520 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11521 self.show_runnables = Some(show_runnables);
11522 cx.notify();
11523 }
11524
11525 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11526 if self.display_map.read(cx).masked != masked {
11527 self.display_map.update(cx, |map, _| map.masked = masked);
11528 }
11529 cx.notify()
11530 }
11531
11532 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11533 self.show_wrap_guides = Some(show_wrap_guides);
11534 cx.notify();
11535 }
11536
11537 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11538 self.show_indent_guides = Some(show_indent_guides);
11539 cx.notify();
11540 }
11541
11542 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11543 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11544 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11545 if let Some(dir) = file.abs_path(cx).parent() {
11546 return Some(dir.to_owned());
11547 }
11548 }
11549
11550 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11551 return Some(project_path.path.to_path_buf());
11552 }
11553 }
11554
11555 None
11556 }
11557
11558 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11559 self.active_excerpt(cx)?
11560 .1
11561 .read(cx)
11562 .file()
11563 .and_then(|f| f.as_local())
11564 }
11565
11566 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11567 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11568 let project_path = buffer.read(cx).project_path(cx)?;
11569 let project = self.project.as_ref()?.read(cx);
11570 project.absolute_path(&project_path, cx)
11571 })
11572 }
11573
11574 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11575 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11576 let project_path = buffer.read(cx).project_path(cx)?;
11577 let project = self.project.as_ref()?.read(cx);
11578 let entry = project.entry_for_path(&project_path, cx)?;
11579 let path = entry.path.to_path_buf();
11580 Some(path)
11581 })
11582 }
11583
11584 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11585 if let Some(target) = self.target_file(cx) {
11586 cx.reveal_path(&target.abs_path(cx));
11587 }
11588 }
11589
11590 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11591 if let Some(path) = self.target_file_abs_path(cx) {
11592 if let Some(path) = path.to_str() {
11593 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11594 }
11595 }
11596 }
11597
11598 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11599 if let Some(path) = self.target_file_path(cx) {
11600 if let Some(path) = path.to_str() {
11601 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11602 }
11603 }
11604 }
11605
11606 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11607 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11608
11609 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11610 self.start_git_blame(true, cx);
11611 }
11612
11613 cx.notify();
11614 }
11615
11616 pub fn toggle_git_blame_inline(
11617 &mut self,
11618 _: &ToggleGitBlameInline,
11619 cx: &mut ViewContext<Self>,
11620 ) {
11621 self.toggle_git_blame_inline_internal(true, cx);
11622 cx.notify();
11623 }
11624
11625 pub fn git_blame_inline_enabled(&self) -> bool {
11626 self.git_blame_inline_enabled
11627 }
11628
11629 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11630 self.show_selection_menu = self
11631 .show_selection_menu
11632 .map(|show_selections_menu| !show_selections_menu)
11633 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11634
11635 cx.notify();
11636 }
11637
11638 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11639 self.show_selection_menu
11640 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11641 }
11642
11643 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11644 if let Some(project) = self.project.as_ref() {
11645 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11646 return;
11647 };
11648
11649 if buffer.read(cx).file().is_none() {
11650 return;
11651 }
11652
11653 let focused = self.focus_handle(cx).contains_focused(cx);
11654
11655 let project = project.clone();
11656 let blame =
11657 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11658 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11659 self.blame = Some(blame);
11660 }
11661 }
11662
11663 fn toggle_git_blame_inline_internal(
11664 &mut self,
11665 user_triggered: bool,
11666 cx: &mut ViewContext<Self>,
11667 ) {
11668 if self.git_blame_inline_enabled {
11669 self.git_blame_inline_enabled = false;
11670 self.show_git_blame_inline = false;
11671 self.show_git_blame_inline_delay_task.take();
11672 } else {
11673 self.git_blame_inline_enabled = true;
11674 self.start_git_blame_inline(user_triggered, cx);
11675 }
11676
11677 cx.notify();
11678 }
11679
11680 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11681 self.start_git_blame(user_triggered, cx);
11682
11683 if ProjectSettings::get_global(cx)
11684 .git
11685 .inline_blame_delay()
11686 .is_some()
11687 {
11688 self.start_inline_blame_timer(cx);
11689 } else {
11690 self.show_git_blame_inline = true
11691 }
11692 }
11693
11694 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11695 self.blame.as_ref()
11696 }
11697
11698 pub fn show_git_blame_gutter(&self) -> bool {
11699 self.show_git_blame_gutter
11700 }
11701
11702 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11703 self.show_git_blame_gutter && self.has_blame_entries(cx)
11704 }
11705
11706 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11707 self.show_git_blame_inline
11708 && self.focus_handle.is_focused(cx)
11709 && !self.newest_selection_head_on_empty_line(cx)
11710 && self.has_blame_entries(cx)
11711 }
11712
11713 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11714 self.blame()
11715 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11716 }
11717
11718 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11719 let cursor_anchor = self.selections.newest_anchor().head();
11720
11721 let snapshot = self.buffer.read(cx).snapshot(cx);
11722 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11723
11724 snapshot.line_len(buffer_row) == 0
11725 }
11726
11727 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11728 let buffer_and_selection = maybe!({
11729 let selection = self.selections.newest::<Point>(cx);
11730 let selection_range = selection.range();
11731
11732 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11733 (buffer, selection_range.start.row..selection_range.end.row)
11734 } else {
11735 let multi_buffer = self.buffer().read(cx);
11736 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11737 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11738
11739 let (excerpt, range) = if selection.reversed {
11740 buffer_ranges.first()
11741 } else {
11742 buffer_ranges.last()
11743 }?;
11744
11745 let snapshot = excerpt.buffer();
11746 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11747 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11748 (
11749 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11750 selection,
11751 )
11752 };
11753
11754 Some((buffer, selection))
11755 });
11756
11757 let Some((buffer, selection)) = buffer_and_selection else {
11758 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11759 };
11760
11761 let Some(project) = self.project.as_ref() else {
11762 return Task::ready(Err(anyhow!("editor does not have project")));
11763 };
11764
11765 project.update(cx, |project, cx| {
11766 project.get_permalink_to_line(&buffer, selection, cx)
11767 })
11768 }
11769
11770 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11771 let permalink_task = self.get_permalink_to_line(cx);
11772 let workspace = self.workspace();
11773
11774 cx.spawn(|_, mut cx| async move {
11775 match permalink_task.await {
11776 Ok(permalink) => {
11777 cx.update(|cx| {
11778 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11779 })
11780 .ok();
11781 }
11782 Err(err) => {
11783 let message = format!("Failed to copy permalink: {err}");
11784
11785 Err::<(), anyhow::Error>(err).log_err();
11786
11787 if let Some(workspace) = workspace {
11788 workspace
11789 .update(&mut cx, |workspace, cx| {
11790 struct CopyPermalinkToLine;
11791
11792 workspace.show_toast(
11793 Toast::new(
11794 NotificationId::unique::<CopyPermalinkToLine>(),
11795 message,
11796 ),
11797 cx,
11798 )
11799 })
11800 .ok();
11801 }
11802 }
11803 }
11804 })
11805 .detach();
11806 }
11807
11808 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11809 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11810 if let Some(file) = self.target_file(cx) {
11811 if let Some(path) = file.path().to_str() {
11812 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11813 }
11814 }
11815 }
11816
11817 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11818 let permalink_task = self.get_permalink_to_line(cx);
11819 let workspace = self.workspace();
11820
11821 cx.spawn(|_, mut cx| async move {
11822 match permalink_task.await {
11823 Ok(permalink) => {
11824 cx.update(|cx| {
11825 cx.open_url(permalink.as_ref());
11826 })
11827 .ok();
11828 }
11829 Err(err) => {
11830 let message = format!("Failed to open permalink: {err}");
11831
11832 Err::<(), anyhow::Error>(err).log_err();
11833
11834 if let Some(workspace) = workspace {
11835 workspace
11836 .update(&mut cx, |workspace, cx| {
11837 struct OpenPermalinkToLine;
11838
11839 workspace.show_toast(
11840 Toast::new(
11841 NotificationId::unique::<OpenPermalinkToLine>(),
11842 message,
11843 ),
11844 cx,
11845 )
11846 })
11847 .ok();
11848 }
11849 }
11850 }
11851 })
11852 .detach();
11853 }
11854
11855 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11856 self.insert_uuid(UuidVersion::V4, cx);
11857 }
11858
11859 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11860 self.insert_uuid(UuidVersion::V7, cx);
11861 }
11862
11863 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11864 self.transact(cx, |this, cx| {
11865 let edits = this
11866 .selections
11867 .all::<Point>(cx)
11868 .into_iter()
11869 .map(|selection| {
11870 let uuid = match version {
11871 UuidVersion::V4 => uuid::Uuid::new_v4(),
11872 UuidVersion::V7 => uuid::Uuid::now_v7(),
11873 };
11874
11875 (selection.range(), uuid.to_string())
11876 });
11877 this.edit(edits, cx);
11878 this.refresh_inline_completion(true, false, cx);
11879 });
11880 }
11881
11882 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11883 /// last highlight added will be used.
11884 ///
11885 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11886 pub fn highlight_rows<T: 'static>(
11887 &mut self,
11888 range: Range<Anchor>,
11889 color: Hsla,
11890 should_autoscroll: bool,
11891 cx: &mut ViewContext<Self>,
11892 ) {
11893 let snapshot = self.buffer().read(cx).snapshot(cx);
11894 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11895 let ix = row_highlights.binary_search_by(|highlight| {
11896 Ordering::Equal
11897 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11898 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11899 });
11900
11901 if let Err(mut ix) = ix {
11902 let index = post_inc(&mut self.highlight_order);
11903
11904 // If this range intersects with the preceding highlight, then merge it with
11905 // the preceding highlight. Otherwise insert a new highlight.
11906 let mut merged = false;
11907 if ix > 0 {
11908 let prev_highlight = &mut row_highlights[ix - 1];
11909 if prev_highlight
11910 .range
11911 .end
11912 .cmp(&range.start, &snapshot)
11913 .is_ge()
11914 {
11915 ix -= 1;
11916 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11917 prev_highlight.range.end = range.end;
11918 }
11919 merged = true;
11920 prev_highlight.index = index;
11921 prev_highlight.color = color;
11922 prev_highlight.should_autoscroll = should_autoscroll;
11923 }
11924 }
11925
11926 if !merged {
11927 row_highlights.insert(
11928 ix,
11929 RowHighlight {
11930 range: range.clone(),
11931 index,
11932 color,
11933 should_autoscroll,
11934 },
11935 );
11936 }
11937
11938 // If any of the following highlights intersect with this one, merge them.
11939 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11940 let highlight = &row_highlights[ix];
11941 if next_highlight
11942 .range
11943 .start
11944 .cmp(&highlight.range.end, &snapshot)
11945 .is_le()
11946 {
11947 if next_highlight
11948 .range
11949 .end
11950 .cmp(&highlight.range.end, &snapshot)
11951 .is_gt()
11952 {
11953 row_highlights[ix].range.end = next_highlight.range.end;
11954 }
11955 row_highlights.remove(ix + 1);
11956 } else {
11957 break;
11958 }
11959 }
11960 }
11961 }
11962
11963 /// Remove any highlighted row ranges of the given type that intersect the
11964 /// given ranges.
11965 pub fn remove_highlighted_rows<T: 'static>(
11966 &mut self,
11967 ranges_to_remove: Vec<Range<Anchor>>,
11968 cx: &mut ViewContext<Self>,
11969 ) {
11970 let snapshot = self.buffer().read(cx).snapshot(cx);
11971 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11972 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11973 row_highlights.retain(|highlight| {
11974 while let Some(range_to_remove) = ranges_to_remove.peek() {
11975 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11976 Ordering::Less | Ordering::Equal => {
11977 ranges_to_remove.next();
11978 }
11979 Ordering::Greater => {
11980 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11981 Ordering::Less | Ordering::Equal => {
11982 return false;
11983 }
11984 Ordering::Greater => break,
11985 }
11986 }
11987 }
11988 }
11989
11990 true
11991 })
11992 }
11993
11994 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11995 pub fn clear_row_highlights<T: 'static>(&mut self) {
11996 self.highlighted_rows.remove(&TypeId::of::<T>());
11997 }
11998
11999 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12000 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12001 self.highlighted_rows
12002 .get(&TypeId::of::<T>())
12003 .map_or(&[] as &[_], |vec| vec.as_slice())
12004 .iter()
12005 .map(|highlight| (highlight.range.clone(), highlight.color))
12006 }
12007
12008 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12009 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12010 /// Allows to ignore certain kinds of highlights.
12011 pub fn highlighted_display_rows(
12012 &mut self,
12013 cx: &mut WindowContext,
12014 ) -> BTreeMap<DisplayRow, Hsla> {
12015 let snapshot = self.snapshot(cx);
12016 let mut used_highlight_orders = HashMap::default();
12017 self.highlighted_rows
12018 .iter()
12019 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12020 .fold(
12021 BTreeMap::<DisplayRow, Hsla>::new(),
12022 |mut unique_rows, highlight| {
12023 let start = highlight.range.start.to_display_point(&snapshot);
12024 let end = highlight.range.end.to_display_point(&snapshot);
12025 let start_row = start.row().0;
12026 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12027 && end.column() == 0
12028 {
12029 end.row().0.saturating_sub(1)
12030 } else {
12031 end.row().0
12032 };
12033 for row in start_row..=end_row {
12034 let used_index =
12035 used_highlight_orders.entry(row).or_insert(highlight.index);
12036 if highlight.index >= *used_index {
12037 *used_index = highlight.index;
12038 unique_rows.insert(DisplayRow(row), highlight.color);
12039 }
12040 }
12041 unique_rows
12042 },
12043 )
12044 }
12045
12046 pub fn highlighted_display_row_for_autoscroll(
12047 &self,
12048 snapshot: &DisplaySnapshot,
12049 ) -> Option<DisplayRow> {
12050 self.highlighted_rows
12051 .values()
12052 .flat_map(|highlighted_rows| highlighted_rows.iter())
12053 .filter_map(|highlight| {
12054 if highlight.should_autoscroll {
12055 Some(highlight.range.start.to_display_point(snapshot).row())
12056 } else {
12057 None
12058 }
12059 })
12060 .min()
12061 }
12062
12063 pub fn set_search_within_ranges(
12064 &mut self,
12065 ranges: &[Range<Anchor>],
12066 cx: &mut ViewContext<Self>,
12067 ) {
12068 self.highlight_background::<SearchWithinRange>(
12069 ranges,
12070 |colors| colors.editor_document_highlight_read_background,
12071 cx,
12072 )
12073 }
12074
12075 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12076 self.breadcrumb_header = Some(new_header);
12077 }
12078
12079 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12080 self.clear_background_highlights::<SearchWithinRange>(cx);
12081 }
12082
12083 pub fn highlight_background<T: 'static>(
12084 &mut self,
12085 ranges: &[Range<Anchor>],
12086 color_fetcher: fn(&ThemeColors) -> Hsla,
12087 cx: &mut ViewContext<Self>,
12088 ) {
12089 self.background_highlights
12090 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12091 self.scrollbar_marker_state.dirty = true;
12092 cx.notify();
12093 }
12094
12095 pub fn clear_background_highlights<T: 'static>(
12096 &mut self,
12097 cx: &mut ViewContext<Self>,
12098 ) -> Option<BackgroundHighlight> {
12099 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12100 if !text_highlights.1.is_empty() {
12101 self.scrollbar_marker_state.dirty = true;
12102 cx.notify();
12103 }
12104 Some(text_highlights)
12105 }
12106
12107 pub fn highlight_gutter<T: 'static>(
12108 &mut self,
12109 ranges: &[Range<Anchor>],
12110 color_fetcher: fn(&AppContext) -> Hsla,
12111 cx: &mut ViewContext<Self>,
12112 ) {
12113 self.gutter_highlights
12114 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12115 cx.notify();
12116 }
12117
12118 pub fn clear_gutter_highlights<T: 'static>(
12119 &mut self,
12120 cx: &mut ViewContext<Self>,
12121 ) -> Option<GutterHighlight> {
12122 cx.notify();
12123 self.gutter_highlights.remove(&TypeId::of::<T>())
12124 }
12125
12126 #[cfg(feature = "test-support")]
12127 pub fn all_text_background_highlights(
12128 &mut self,
12129 cx: &mut ViewContext<Self>,
12130 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12131 let snapshot = self.snapshot(cx);
12132 let buffer = &snapshot.buffer_snapshot;
12133 let start = buffer.anchor_before(0);
12134 let end = buffer.anchor_after(buffer.len());
12135 let theme = cx.theme().colors();
12136 self.background_highlights_in_range(start..end, &snapshot, theme)
12137 }
12138
12139 #[cfg(feature = "test-support")]
12140 pub fn search_background_highlights(
12141 &mut self,
12142 cx: &mut ViewContext<Self>,
12143 ) -> Vec<Range<Point>> {
12144 let snapshot = self.buffer().read(cx).snapshot(cx);
12145
12146 let highlights = self
12147 .background_highlights
12148 .get(&TypeId::of::<items::BufferSearchHighlights>());
12149
12150 if let Some((_color, ranges)) = highlights {
12151 ranges
12152 .iter()
12153 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12154 .collect_vec()
12155 } else {
12156 vec![]
12157 }
12158 }
12159
12160 fn document_highlights_for_position<'a>(
12161 &'a self,
12162 position: Anchor,
12163 buffer: &'a MultiBufferSnapshot,
12164 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12165 let read_highlights = self
12166 .background_highlights
12167 .get(&TypeId::of::<DocumentHighlightRead>())
12168 .map(|h| &h.1);
12169 let write_highlights = self
12170 .background_highlights
12171 .get(&TypeId::of::<DocumentHighlightWrite>())
12172 .map(|h| &h.1);
12173 let left_position = position.bias_left(buffer);
12174 let right_position = position.bias_right(buffer);
12175 read_highlights
12176 .into_iter()
12177 .chain(write_highlights)
12178 .flat_map(move |ranges| {
12179 let start_ix = match ranges.binary_search_by(|probe| {
12180 let cmp = probe.end.cmp(&left_position, buffer);
12181 if cmp.is_ge() {
12182 Ordering::Greater
12183 } else {
12184 Ordering::Less
12185 }
12186 }) {
12187 Ok(i) | Err(i) => i,
12188 };
12189
12190 ranges[start_ix..]
12191 .iter()
12192 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12193 })
12194 }
12195
12196 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12197 self.background_highlights
12198 .get(&TypeId::of::<T>())
12199 .map_or(false, |(_, highlights)| !highlights.is_empty())
12200 }
12201
12202 pub fn background_highlights_in_range(
12203 &self,
12204 search_range: Range<Anchor>,
12205 display_snapshot: &DisplaySnapshot,
12206 theme: &ThemeColors,
12207 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12208 let mut results = Vec::new();
12209 for (color_fetcher, ranges) in self.background_highlights.values() {
12210 let color = color_fetcher(theme);
12211 let start_ix = match ranges.binary_search_by(|probe| {
12212 let cmp = probe
12213 .end
12214 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12215 if cmp.is_gt() {
12216 Ordering::Greater
12217 } else {
12218 Ordering::Less
12219 }
12220 }) {
12221 Ok(i) | Err(i) => i,
12222 };
12223 for range in &ranges[start_ix..] {
12224 if range
12225 .start
12226 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12227 .is_ge()
12228 {
12229 break;
12230 }
12231
12232 let start = range.start.to_display_point(display_snapshot);
12233 let end = range.end.to_display_point(display_snapshot);
12234 results.push((start..end, color))
12235 }
12236 }
12237 results
12238 }
12239
12240 pub fn background_highlight_row_ranges<T: 'static>(
12241 &self,
12242 search_range: Range<Anchor>,
12243 display_snapshot: &DisplaySnapshot,
12244 count: usize,
12245 ) -> Vec<RangeInclusive<DisplayPoint>> {
12246 let mut results = Vec::new();
12247 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12248 return vec![];
12249 };
12250
12251 let start_ix = match ranges.binary_search_by(|probe| {
12252 let cmp = probe
12253 .end
12254 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12255 if cmp.is_gt() {
12256 Ordering::Greater
12257 } else {
12258 Ordering::Less
12259 }
12260 }) {
12261 Ok(i) | Err(i) => i,
12262 };
12263 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12264 if let (Some(start_display), Some(end_display)) = (start, end) {
12265 results.push(
12266 start_display.to_display_point(display_snapshot)
12267 ..=end_display.to_display_point(display_snapshot),
12268 );
12269 }
12270 };
12271 let mut start_row: Option<Point> = None;
12272 let mut end_row: Option<Point> = None;
12273 if ranges.len() > count {
12274 return Vec::new();
12275 }
12276 for range in &ranges[start_ix..] {
12277 if range
12278 .start
12279 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12280 .is_ge()
12281 {
12282 break;
12283 }
12284 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12285 if let Some(current_row) = &end_row {
12286 if end.row == current_row.row {
12287 continue;
12288 }
12289 }
12290 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12291 if start_row.is_none() {
12292 assert_eq!(end_row, None);
12293 start_row = Some(start);
12294 end_row = Some(end);
12295 continue;
12296 }
12297 if let Some(current_end) = end_row.as_mut() {
12298 if start.row > current_end.row + 1 {
12299 push_region(start_row, end_row);
12300 start_row = Some(start);
12301 end_row = Some(end);
12302 } else {
12303 // Merge two hunks.
12304 *current_end = end;
12305 }
12306 } else {
12307 unreachable!();
12308 }
12309 }
12310 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12311 push_region(start_row, end_row);
12312 results
12313 }
12314
12315 pub fn gutter_highlights_in_range(
12316 &self,
12317 search_range: Range<Anchor>,
12318 display_snapshot: &DisplaySnapshot,
12319 cx: &AppContext,
12320 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12321 let mut results = Vec::new();
12322 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12323 let color = color_fetcher(cx);
12324 let start_ix = match ranges.binary_search_by(|probe| {
12325 let cmp = probe
12326 .end
12327 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12328 if cmp.is_gt() {
12329 Ordering::Greater
12330 } else {
12331 Ordering::Less
12332 }
12333 }) {
12334 Ok(i) | Err(i) => i,
12335 };
12336 for range in &ranges[start_ix..] {
12337 if range
12338 .start
12339 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12340 .is_ge()
12341 {
12342 break;
12343 }
12344
12345 let start = range.start.to_display_point(display_snapshot);
12346 let end = range.end.to_display_point(display_snapshot);
12347 results.push((start..end, color))
12348 }
12349 }
12350 results
12351 }
12352
12353 /// Get the text ranges corresponding to the redaction query
12354 pub fn redacted_ranges(
12355 &self,
12356 search_range: Range<Anchor>,
12357 display_snapshot: &DisplaySnapshot,
12358 cx: &WindowContext,
12359 ) -> Vec<Range<DisplayPoint>> {
12360 display_snapshot
12361 .buffer_snapshot
12362 .redacted_ranges(search_range, |file| {
12363 if let Some(file) = file {
12364 file.is_private()
12365 && EditorSettings::get(
12366 Some(SettingsLocation {
12367 worktree_id: file.worktree_id(cx),
12368 path: file.path().as_ref(),
12369 }),
12370 cx,
12371 )
12372 .redact_private_values
12373 } else {
12374 false
12375 }
12376 })
12377 .map(|range| {
12378 range.start.to_display_point(display_snapshot)
12379 ..range.end.to_display_point(display_snapshot)
12380 })
12381 .collect()
12382 }
12383
12384 pub fn highlight_text<T: 'static>(
12385 &mut self,
12386 ranges: Vec<Range<Anchor>>,
12387 style: HighlightStyle,
12388 cx: &mut ViewContext<Self>,
12389 ) {
12390 self.display_map.update(cx, |map, _| {
12391 map.highlight_text(TypeId::of::<T>(), ranges, style)
12392 });
12393 cx.notify();
12394 }
12395
12396 pub(crate) fn highlight_inlays<T: 'static>(
12397 &mut self,
12398 highlights: Vec<InlayHighlight>,
12399 style: HighlightStyle,
12400 cx: &mut ViewContext<Self>,
12401 ) {
12402 self.display_map.update(cx, |map, _| {
12403 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12404 });
12405 cx.notify();
12406 }
12407
12408 pub fn text_highlights<'a, T: 'static>(
12409 &'a self,
12410 cx: &'a AppContext,
12411 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12412 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12413 }
12414
12415 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12416 let cleared = self
12417 .display_map
12418 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12419 if cleared {
12420 cx.notify();
12421 }
12422 }
12423
12424 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12425 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12426 && self.focus_handle.is_focused(cx)
12427 }
12428
12429 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12430 self.show_cursor_when_unfocused = is_enabled;
12431 cx.notify();
12432 }
12433
12434 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12435 self.project
12436 .as_ref()
12437 .map(|project| project.read(cx).lsp_store())
12438 }
12439
12440 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12441 cx.notify();
12442 }
12443
12444 fn on_buffer_event(
12445 &mut self,
12446 multibuffer: Model<MultiBuffer>,
12447 event: &multi_buffer::Event,
12448 cx: &mut ViewContext<Self>,
12449 ) {
12450 match event {
12451 multi_buffer::Event::Edited {
12452 singleton_buffer_edited,
12453 edited_buffer: buffer_edited,
12454 } => {
12455 self.scrollbar_marker_state.dirty = true;
12456 self.active_indent_guides_state.dirty = true;
12457 self.refresh_active_diagnostics(cx);
12458 self.refresh_code_actions(cx);
12459 if self.has_active_inline_completion() {
12460 self.update_visible_inline_completion(cx);
12461 }
12462 if let Some(buffer) = buffer_edited {
12463 let buffer_id = buffer.read(cx).remote_id();
12464 if !self.registered_buffers.contains_key(&buffer_id) {
12465 if let Some(lsp_store) = self.lsp_store(cx) {
12466 lsp_store.update(cx, |lsp_store, cx| {
12467 self.registered_buffers.insert(
12468 buffer_id,
12469 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12470 );
12471 })
12472 }
12473 }
12474 }
12475 cx.emit(EditorEvent::BufferEdited);
12476 cx.emit(SearchEvent::MatchesInvalidated);
12477 if *singleton_buffer_edited {
12478 if let Some(project) = &self.project {
12479 let project = project.read(cx);
12480 #[allow(clippy::mutable_key_type)]
12481 let languages_affected = multibuffer
12482 .read(cx)
12483 .all_buffers()
12484 .into_iter()
12485 .filter_map(|buffer| {
12486 let buffer = buffer.read(cx);
12487 let language = buffer.language()?;
12488 if project.is_local()
12489 && project
12490 .language_servers_for_local_buffer(buffer, cx)
12491 .count()
12492 == 0
12493 {
12494 None
12495 } else {
12496 Some(language)
12497 }
12498 })
12499 .cloned()
12500 .collect::<HashSet<_>>();
12501 if !languages_affected.is_empty() {
12502 self.refresh_inlay_hints(
12503 InlayHintRefreshReason::BufferEdited(languages_affected),
12504 cx,
12505 );
12506 }
12507 }
12508 }
12509
12510 let Some(project) = &self.project else { return };
12511 let (telemetry, is_via_ssh) = {
12512 let project = project.read(cx);
12513 let telemetry = project.client().telemetry().clone();
12514 let is_via_ssh = project.is_via_ssh();
12515 (telemetry, is_via_ssh)
12516 };
12517 refresh_linked_ranges(self, cx);
12518 telemetry.log_edit_event("editor", is_via_ssh);
12519 }
12520 multi_buffer::Event::ExcerptsAdded {
12521 buffer,
12522 predecessor,
12523 excerpts,
12524 } => {
12525 self.tasks_update_task = Some(self.refresh_runnables(cx));
12526 let buffer_id = buffer.read(cx).remote_id();
12527 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12528 if let Some(project) = &self.project {
12529 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12530 }
12531 }
12532 cx.emit(EditorEvent::ExcerptsAdded {
12533 buffer: buffer.clone(),
12534 predecessor: *predecessor,
12535 excerpts: excerpts.clone(),
12536 });
12537 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12538 }
12539 multi_buffer::Event::ExcerptsRemoved { ids } => {
12540 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12541 let buffer = self.buffer.read(cx);
12542 self.registered_buffers
12543 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12544 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12545 }
12546 multi_buffer::Event::ExcerptsEdited { ids } => {
12547 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12548 }
12549 multi_buffer::Event::ExcerptsExpanded { ids } => {
12550 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12551 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12552 }
12553 multi_buffer::Event::Reparsed(buffer_id) => {
12554 self.tasks_update_task = Some(self.refresh_runnables(cx));
12555
12556 cx.emit(EditorEvent::Reparsed(*buffer_id));
12557 }
12558 multi_buffer::Event::LanguageChanged(buffer_id) => {
12559 linked_editing_ranges::refresh_linked_ranges(self, cx);
12560 cx.emit(EditorEvent::Reparsed(*buffer_id));
12561 cx.notify();
12562 }
12563 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12564 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12565 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12566 cx.emit(EditorEvent::TitleChanged)
12567 }
12568 // multi_buffer::Event::DiffBaseChanged => {
12569 // self.scrollbar_marker_state.dirty = true;
12570 // cx.emit(EditorEvent::DiffBaseChanged);
12571 // cx.notify();
12572 // }
12573 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12574 multi_buffer::Event::DiagnosticsUpdated => {
12575 self.refresh_active_diagnostics(cx);
12576 self.scrollbar_marker_state.dirty = true;
12577 cx.notify();
12578 }
12579 _ => {}
12580 };
12581 }
12582
12583 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12584 cx.notify();
12585 }
12586
12587 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12588 self.tasks_update_task = Some(self.refresh_runnables(cx));
12589 self.refresh_inline_completion(true, false, cx);
12590 self.refresh_inlay_hints(
12591 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12592 self.selections.newest_anchor().head(),
12593 &self.buffer.read(cx).snapshot(cx),
12594 cx,
12595 )),
12596 cx,
12597 );
12598
12599 let old_cursor_shape = self.cursor_shape;
12600
12601 {
12602 let editor_settings = EditorSettings::get_global(cx);
12603 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12604 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12605 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12606 }
12607
12608 if old_cursor_shape != self.cursor_shape {
12609 cx.emit(EditorEvent::CursorShapeChanged);
12610 }
12611
12612 let project_settings = ProjectSettings::get_global(cx);
12613 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12614
12615 if self.mode == EditorMode::Full {
12616 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12617 if self.git_blame_inline_enabled != inline_blame_enabled {
12618 self.toggle_git_blame_inline_internal(false, cx);
12619 }
12620 }
12621
12622 cx.notify();
12623 }
12624
12625 pub fn set_searchable(&mut self, searchable: bool) {
12626 self.searchable = searchable;
12627 }
12628
12629 pub fn searchable(&self) -> bool {
12630 self.searchable
12631 }
12632
12633 fn open_proposed_changes_editor(
12634 &mut self,
12635 _: &OpenProposedChangesEditor,
12636 cx: &mut ViewContext<Self>,
12637 ) {
12638 let Some(workspace) = self.workspace() else {
12639 cx.propagate();
12640 return;
12641 };
12642
12643 let selections = self.selections.all::<usize>(cx);
12644 let multi_buffer = self.buffer.read(cx);
12645 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12646 let mut new_selections_by_buffer = HashMap::default();
12647 for selection in selections {
12648 for (excerpt, range) in
12649 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12650 {
12651 let mut range = range.to_point(excerpt.buffer());
12652 range.start.column = 0;
12653 range.end.column = excerpt.buffer().line_len(range.end.row);
12654 new_selections_by_buffer
12655 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12656 .or_insert(Vec::new())
12657 .push(range)
12658 }
12659 }
12660
12661 let proposed_changes_buffers = new_selections_by_buffer
12662 .into_iter()
12663 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12664 .collect::<Vec<_>>();
12665 let proposed_changes_editor = cx.new_view(|cx| {
12666 ProposedChangesEditor::new(
12667 "Proposed changes",
12668 proposed_changes_buffers,
12669 self.project.clone(),
12670 cx,
12671 )
12672 });
12673
12674 cx.window_context().defer(move |cx| {
12675 workspace.update(cx, |workspace, cx| {
12676 workspace.active_pane().update(cx, |pane, cx| {
12677 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12678 });
12679 });
12680 });
12681 }
12682
12683 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12684 self.open_excerpts_common(None, true, cx)
12685 }
12686
12687 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12688 self.open_excerpts_common(None, false, cx)
12689 }
12690
12691 fn open_excerpts_common(
12692 &mut self,
12693 jump_data: Option<JumpData>,
12694 split: bool,
12695 cx: &mut ViewContext<Self>,
12696 ) {
12697 let Some(workspace) = self.workspace() else {
12698 cx.propagate();
12699 return;
12700 };
12701
12702 if self.buffer.read(cx).is_singleton() {
12703 cx.propagate();
12704 return;
12705 }
12706
12707 let mut new_selections_by_buffer = HashMap::default();
12708 match &jump_data {
12709 Some(JumpData::MultiBufferPoint {
12710 excerpt_id,
12711 position,
12712 anchor,
12713 line_offset_from_top,
12714 }) => {
12715 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12716 if let Some(buffer) = multi_buffer_snapshot
12717 .buffer_id_for_excerpt(*excerpt_id)
12718 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12719 {
12720 let buffer_snapshot = buffer.read(cx).snapshot();
12721 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12722 language::ToPoint::to_point(anchor, &buffer_snapshot)
12723 } else {
12724 buffer_snapshot.clip_point(*position, Bias::Left)
12725 };
12726 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12727 new_selections_by_buffer.insert(
12728 buffer,
12729 (
12730 vec![jump_to_offset..jump_to_offset],
12731 Some(*line_offset_from_top),
12732 ),
12733 );
12734 }
12735 }
12736 Some(JumpData::MultiBufferRow {
12737 row,
12738 line_offset_from_top,
12739 }) => {
12740 let point = MultiBufferPoint::new(row.0, 0);
12741 if let Some((buffer, buffer_point, _)) =
12742 self.buffer.read(cx).point_to_buffer_point(point, cx)
12743 {
12744 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12745 new_selections_by_buffer
12746 .entry(buffer)
12747 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12748 .0
12749 .push(buffer_offset..buffer_offset)
12750 }
12751 }
12752 None => {
12753 let selections = self.selections.all::<usize>(cx);
12754 let multi_buffer = self.buffer.read(cx);
12755 for selection in selections {
12756 for (excerpt, mut range) in multi_buffer
12757 .snapshot(cx)
12758 .range_to_buffer_ranges(selection.range())
12759 {
12760 // When editing branch buffers, jump to the corresponding location
12761 // in their base buffer.
12762 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12763 let buffer = buffer_handle.read(cx);
12764 if let Some(base_buffer) = buffer.base_buffer() {
12765 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12766 buffer_handle = base_buffer;
12767 }
12768
12769 if selection.reversed {
12770 mem::swap(&mut range.start, &mut range.end);
12771 }
12772 new_selections_by_buffer
12773 .entry(buffer_handle)
12774 .or_insert((Vec::new(), None))
12775 .0
12776 .push(range)
12777 }
12778 }
12779 }
12780 }
12781
12782 if new_selections_by_buffer.is_empty() {
12783 return;
12784 }
12785
12786 // We defer the pane interaction because we ourselves are a workspace item
12787 // and activating a new item causes the pane to call a method on us reentrantly,
12788 // which panics if we're on the stack.
12789 cx.window_context().defer(move |cx| {
12790 workspace.update(cx, |workspace, cx| {
12791 let pane = if split {
12792 workspace.adjacent_pane(cx)
12793 } else {
12794 workspace.active_pane().clone()
12795 };
12796
12797 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12798 let editor = buffer
12799 .read(cx)
12800 .file()
12801 .is_none()
12802 .then(|| {
12803 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12804 // so `workspace.open_project_item` will never find them, always opening a new editor.
12805 // Instead, we try to activate the existing editor in the pane first.
12806 let (editor, pane_item_index) =
12807 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12808 let editor = item.downcast::<Editor>()?;
12809 let singleton_buffer =
12810 editor.read(cx).buffer().read(cx).as_singleton()?;
12811 if singleton_buffer == buffer {
12812 Some((editor, i))
12813 } else {
12814 None
12815 }
12816 })?;
12817 pane.update(cx, |pane, cx| {
12818 pane.activate_item(pane_item_index, true, true, cx)
12819 });
12820 Some(editor)
12821 })
12822 .flatten()
12823 .unwrap_or_else(|| {
12824 workspace.open_project_item::<Self>(
12825 pane.clone(),
12826 buffer,
12827 true,
12828 true,
12829 cx,
12830 )
12831 });
12832
12833 editor.update(cx, |editor, cx| {
12834 let autoscroll = match scroll_offset {
12835 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12836 None => Autoscroll::newest(),
12837 };
12838 let nav_history = editor.nav_history.take();
12839 editor.change_selections(Some(autoscroll), cx, |s| {
12840 s.select_ranges(ranges);
12841 });
12842 editor.nav_history = nav_history;
12843 });
12844 }
12845 })
12846 });
12847 }
12848
12849 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12850 let snapshot = self.buffer.read(cx).read(cx);
12851 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12852 Some(
12853 ranges
12854 .iter()
12855 .map(move |range| {
12856 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12857 })
12858 .collect(),
12859 )
12860 }
12861
12862 fn selection_replacement_ranges(
12863 &self,
12864 range: Range<OffsetUtf16>,
12865 cx: &mut AppContext,
12866 ) -> Vec<Range<OffsetUtf16>> {
12867 let selections = self.selections.all::<OffsetUtf16>(cx);
12868 let newest_selection = selections
12869 .iter()
12870 .max_by_key(|selection| selection.id)
12871 .unwrap();
12872 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12873 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12874 let snapshot = self.buffer.read(cx).read(cx);
12875 selections
12876 .into_iter()
12877 .map(|mut selection| {
12878 selection.start.0 =
12879 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12880 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12881 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12882 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12883 })
12884 .collect()
12885 }
12886
12887 fn report_editor_event(
12888 &self,
12889 event_type: &'static str,
12890 file_extension: Option<String>,
12891 cx: &AppContext,
12892 ) {
12893 if cfg!(any(test, feature = "test-support")) {
12894 return;
12895 }
12896
12897 let Some(project) = &self.project else { return };
12898
12899 // If None, we are in a file without an extension
12900 let file = self
12901 .buffer
12902 .read(cx)
12903 .as_singleton()
12904 .and_then(|b| b.read(cx).file());
12905 let file_extension = file_extension.or(file
12906 .as_ref()
12907 .and_then(|file| Path::new(file.file_name(cx)).extension())
12908 .and_then(|e| e.to_str())
12909 .map(|a| a.to_string()));
12910
12911 let vim_mode = cx
12912 .global::<SettingsStore>()
12913 .raw_user_settings()
12914 .get("vim_mode")
12915 == Some(&serde_json::Value::Bool(true));
12916
12917 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12918 == language::language_settings::InlineCompletionProvider::Copilot;
12919 let copilot_enabled_for_language = self
12920 .buffer
12921 .read(cx)
12922 .settings_at(0, cx)
12923 .show_inline_completions;
12924
12925 let project = project.read(cx);
12926 telemetry::event!(
12927 event_type,
12928 file_extension,
12929 vim_mode,
12930 copilot_enabled,
12931 copilot_enabled_for_language,
12932 is_via_ssh = project.is_via_ssh(),
12933 );
12934 }
12935
12936 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12937 /// with each line being an array of {text, highlight} objects.
12938 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12939 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12940 return;
12941 };
12942
12943 #[derive(Serialize)]
12944 struct Chunk<'a> {
12945 text: String,
12946 highlight: Option<&'a str>,
12947 }
12948
12949 let snapshot = buffer.read(cx).snapshot();
12950 let range = self
12951 .selected_text_range(false, cx)
12952 .and_then(|selection| {
12953 if selection.range.is_empty() {
12954 None
12955 } else {
12956 Some(selection.range)
12957 }
12958 })
12959 .unwrap_or_else(|| 0..snapshot.len());
12960
12961 let chunks = snapshot.chunks(range, true);
12962 let mut lines = Vec::new();
12963 let mut line: VecDeque<Chunk> = VecDeque::new();
12964
12965 let Some(style) = self.style.as_ref() else {
12966 return;
12967 };
12968
12969 for chunk in chunks {
12970 let highlight = chunk
12971 .syntax_highlight_id
12972 .and_then(|id| id.name(&style.syntax));
12973 let mut chunk_lines = chunk.text.split('\n').peekable();
12974 while let Some(text) = chunk_lines.next() {
12975 let mut merged_with_last_token = false;
12976 if let Some(last_token) = line.back_mut() {
12977 if last_token.highlight == highlight {
12978 last_token.text.push_str(text);
12979 merged_with_last_token = true;
12980 }
12981 }
12982
12983 if !merged_with_last_token {
12984 line.push_back(Chunk {
12985 text: text.into(),
12986 highlight,
12987 });
12988 }
12989
12990 if chunk_lines.peek().is_some() {
12991 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12992 line.pop_front();
12993 }
12994 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12995 line.pop_back();
12996 }
12997
12998 lines.push(mem::take(&mut line));
12999 }
13000 }
13001 }
13002
13003 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13004 return;
13005 };
13006 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13007 }
13008
13009 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13010 self.request_autoscroll(Autoscroll::newest(), cx);
13011 let position = self.selections.newest_display(cx).start;
13012 mouse_context_menu::deploy_context_menu(self, None, position, cx);
13013 }
13014
13015 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13016 &self.inlay_hint_cache
13017 }
13018
13019 pub fn replay_insert_event(
13020 &mut self,
13021 text: &str,
13022 relative_utf16_range: Option<Range<isize>>,
13023 cx: &mut ViewContext<Self>,
13024 ) {
13025 if !self.input_enabled {
13026 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13027 return;
13028 }
13029 if let Some(relative_utf16_range) = relative_utf16_range {
13030 let selections = self.selections.all::<OffsetUtf16>(cx);
13031 self.change_selections(None, cx, |s| {
13032 let new_ranges = selections.into_iter().map(|range| {
13033 let start = OffsetUtf16(
13034 range
13035 .head()
13036 .0
13037 .saturating_add_signed(relative_utf16_range.start),
13038 );
13039 let end = OffsetUtf16(
13040 range
13041 .head()
13042 .0
13043 .saturating_add_signed(relative_utf16_range.end),
13044 );
13045 start..end
13046 });
13047 s.select_ranges(new_ranges);
13048 });
13049 }
13050
13051 self.handle_input(text, cx);
13052 }
13053
13054 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13055 let Some(provider) = self.semantics_provider.as_ref() else {
13056 return false;
13057 };
13058
13059 let mut supports = false;
13060 self.buffer().read(cx).for_each_buffer(|buffer| {
13061 supports |= provider.supports_inlay_hints(buffer, cx);
13062 });
13063 supports
13064 }
13065
13066 pub fn focus(&self, cx: &mut WindowContext) {
13067 cx.focus(&self.focus_handle)
13068 }
13069
13070 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13071 self.focus_handle.is_focused(cx)
13072 }
13073
13074 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13075 cx.emit(EditorEvent::Focused);
13076
13077 if let Some(descendant) = self
13078 .last_focused_descendant
13079 .take()
13080 .and_then(|descendant| descendant.upgrade())
13081 {
13082 cx.focus(&descendant);
13083 } else {
13084 if let Some(blame) = self.blame.as_ref() {
13085 blame.update(cx, GitBlame::focus)
13086 }
13087
13088 self.blink_manager.update(cx, BlinkManager::enable);
13089 self.show_cursor_names(cx);
13090 self.buffer.update(cx, |buffer, cx| {
13091 buffer.finalize_last_transaction(cx);
13092 if self.leader_peer_id.is_none() {
13093 buffer.set_active_selections(
13094 &self.selections.disjoint_anchors(),
13095 self.selections.line_mode,
13096 self.cursor_shape,
13097 cx,
13098 );
13099 }
13100 });
13101 }
13102 }
13103
13104 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13105 cx.emit(EditorEvent::FocusedIn)
13106 }
13107
13108 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13109 if event.blurred != self.focus_handle {
13110 self.last_focused_descendant = Some(event.blurred);
13111 }
13112 }
13113
13114 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13115 self.blink_manager.update(cx, BlinkManager::disable);
13116 self.buffer
13117 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13118
13119 if let Some(blame) = self.blame.as_ref() {
13120 blame.update(cx, GitBlame::blur)
13121 }
13122 if !self.hover_state.focused(cx) {
13123 hide_hover(self, cx);
13124 }
13125
13126 self.hide_context_menu(cx);
13127 cx.emit(EditorEvent::Blurred);
13128 cx.notify();
13129 }
13130
13131 pub fn register_action<A: Action>(
13132 &mut self,
13133 listener: impl Fn(&A, &mut WindowContext) + 'static,
13134 ) -> Subscription {
13135 let id = self.next_editor_action_id.post_inc();
13136 let listener = Arc::new(listener);
13137 self.editor_actions.borrow_mut().insert(
13138 id,
13139 Box::new(move |cx| {
13140 let cx = cx.window_context();
13141 let listener = listener.clone();
13142 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13143 let action = action.downcast_ref().unwrap();
13144 if phase == DispatchPhase::Bubble {
13145 listener(action, cx)
13146 }
13147 })
13148 }),
13149 );
13150
13151 let editor_actions = self.editor_actions.clone();
13152 Subscription::new(move || {
13153 editor_actions.borrow_mut().remove(&id);
13154 })
13155 }
13156
13157 pub fn file_header_size(&self) -> u32 {
13158 FILE_HEADER_HEIGHT
13159 }
13160
13161 pub fn revert(
13162 &mut self,
13163 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13164 cx: &mut ViewContext<Self>,
13165 ) {
13166 self.buffer().update(cx, |multi_buffer, cx| {
13167 for (buffer_id, changes) in revert_changes {
13168 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13169 buffer.update(cx, |buffer, cx| {
13170 buffer.edit(
13171 changes.into_iter().map(|(range, text)| {
13172 (range, text.to_string().map(Arc::<str>::from))
13173 }),
13174 None,
13175 cx,
13176 );
13177 });
13178 }
13179 }
13180 });
13181 self.change_selections(None, cx, |selections| selections.refresh());
13182 }
13183
13184 pub fn to_pixel_point(
13185 &mut self,
13186 source: multi_buffer::Anchor,
13187 editor_snapshot: &EditorSnapshot,
13188 cx: &mut ViewContext<Self>,
13189 ) -> Option<gpui::Point<Pixels>> {
13190 let source_point = source.to_display_point(editor_snapshot);
13191 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13192 }
13193
13194 pub fn display_to_pixel_point(
13195 &self,
13196 source: DisplayPoint,
13197 editor_snapshot: &EditorSnapshot,
13198 cx: &WindowContext,
13199 ) -> Option<gpui::Point<Pixels>> {
13200 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13201 let text_layout_details = self.text_layout_details(cx);
13202 let scroll_top = text_layout_details
13203 .scroll_anchor
13204 .scroll_position(editor_snapshot)
13205 .y;
13206
13207 if source.row().as_f32() < scroll_top.floor() {
13208 return None;
13209 }
13210 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13211 let source_y = line_height * (source.row().as_f32() - scroll_top);
13212 Some(gpui::Point::new(source_x, source_y))
13213 }
13214
13215 pub fn has_active_completions_menu(&self) -> bool {
13216 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13217 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13218 })
13219 }
13220
13221 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13222 self.addons
13223 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13224 }
13225
13226 pub fn unregister_addon<T: Addon>(&mut self) {
13227 self.addons.remove(&std::any::TypeId::of::<T>());
13228 }
13229
13230 pub fn addon<T: Addon>(&self) -> Option<&T> {
13231 let type_id = std::any::TypeId::of::<T>();
13232 self.addons
13233 .get(&type_id)
13234 .and_then(|item| item.to_any().downcast_ref::<T>())
13235 }
13236
13237 pub fn add_change_set(
13238 &mut self,
13239 change_set: Model<BufferChangeSet>,
13240 cx: &mut ViewContext<Self>,
13241 ) {
13242 self.diff_map.add_change_set(change_set, cx);
13243 }
13244
13245 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13246 let text_layout_details = self.text_layout_details(cx);
13247 let style = &text_layout_details.editor_style;
13248 let font_id = cx.text_system().resolve_font(&style.text.font());
13249 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13250 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13251
13252 let em_width = cx
13253 .text_system()
13254 .typographic_bounds(font_id, font_size, 'm')
13255 .unwrap()
13256 .size
13257 .width;
13258
13259 gpui::Point::new(em_width, line_height)
13260 }
13261}
13262
13263fn get_unstaged_changes_for_buffers(
13264 project: &Model<Project>,
13265 buffers: impl IntoIterator<Item = Model<Buffer>>,
13266 cx: &mut ViewContext<Editor>,
13267) {
13268 let mut tasks = Vec::new();
13269 project.update(cx, |project, cx| {
13270 for buffer in buffers {
13271 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13272 }
13273 });
13274 cx.spawn(|this, mut cx| async move {
13275 let change_sets = futures::future::join_all(tasks).await;
13276 this.update(&mut cx, |this, cx| {
13277 for change_set in change_sets {
13278 if let Some(change_set) = change_set.log_err() {
13279 this.diff_map.add_change_set(change_set, cx);
13280 }
13281 }
13282 })
13283 .ok();
13284 })
13285 .detach();
13286}
13287
13288fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13289 let tab_size = tab_size.get() as usize;
13290 let mut width = offset;
13291
13292 for ch in text.chars() {
13293 width += if ch == '\t' {
13294 tab_size - (width % tab_size)
13295 } else {
13296 1
13297 };
13298 }
13299
13300 width - offset
13301}
13302
13303#[cfg(test)]
13304mod tests {
13305 use super::*;
13306
13307 #[test]
13308 fn test_string_size_with_expanded_tabs() {
13309 let nz = |val| NonZeroU32::new(val).unwrap();
13310 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13311 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13312 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13313 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13314 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13315 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13316 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13317 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13318 }
13319}
13320
13321/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13322struct WordBreakingTokenizer<'a> {
13323 input: &'a str,
13324}
13325
13326impl<'a> WordBreakingTokenizer<'a> {
13327 fn new(input: &'a str) -> Self {
13328 Self { input }
13329 }
13330}
13331
13332fn is_char_ideographic(ch: char) -> bool {
13333 use unicode_script::Script::*;
13334 use unicode_script::UnicodeScript;
13335 matches!(ch.script(), Han | Tangut | Yi)
13336}
13337
13338fn is_grapheme_ideographic(text: &str) -> bool {
13339 text.chars().any(is_char_ideographic)
13340}
13341
13342fn is_grapheme_whitespace(text: &str) -> bool {
13343 text.chars().any(|x| x.is_whitespace())
13344}
13345
13346fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13347 text.chars().next().map_or(false, |ch| {
13348 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13349 })
13350}
13351
13352#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13353struct WordBreakToken<'a> {
13354 token: &'a str,
13355 grapheme_len: usize,
13356 is_whitespace: bool,
13357}
13358
13359impl<'a> Iterator for WordBreakingTokenizer<'a> {
13360 /// Yields a span, the count of graphemes in the token, and whether it was
13361 /// whitespace. Note that it also breaks at word boundaries.
13362 type Item = WordBreakToken<'a>;
13363
13364 fn next(&mut self) -> Option<Self::Item> {
13365 use unicode_segmentation::UnicodeSegmentation;
13366 if self.input.is_empty() {
13367 return None;
13368 }
13369
13370 let mut iter = self.input.graphemes(true).peekable();
13371 let mut offset = 0;
13372 let mut graphemes = 0;
13373 if let Some(first_grapheme) = iter.next() {
13374 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13375 offset += first_grapheme.len();
13376 graphemes += 1;
13377 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13378 if let Some(grapheme) = iter.peek().copied() {
13379 if should_stay_with_preceding_ideograph(grapheme) {
13380 offset += grapheme.len();
13381 graphemes += 1;
13382 }
13383 }
13384 } else {
13385 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13386 let mut next_word_bound = words.peek().copied();
13387 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13388 next_word_bound = words.next();
13389 }
13390 while let Some(grapheme) = iter.peek().copied() {
13391 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13392 break;
13393 };
13394 if is_grapheme_whitespace(grapheme) != is_whitespace {
13395 break;
13396 };
13397 offset += grapheme.len();
13398 graphemes += 1;
13399 iter.next();
13400 }
13401 }
13402 let token = &self.input[..offset];
13403 self.input = &self.input[offset..];
13404 if is_whitespace {
13405 Some(WordBreakToken {
13406 token: " ",
13407 grapheme_len: 1,
13408 is_whitespace: true,
13409 })
13410 } else {
13411 Some(WordBreakToken {
13412 token,
13413 grapheme_len: graphemes,
13414 is_whitespace: false,
13415 })
13416 }
13417 } else {
13418 None
13419 }
13420 }
13421}
13422
13423#[test]
13424fn test_word_breaking_tokenizer() {
13425 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13426 ("", &[]),
13427 (" ", &[(" ", 1, true)]),
13428 ("Ʒ", &[("Ʒ", 1, false)]),
13429 ("Ǽ", &[("Ǽ", 1, false)]),
13430 ("⋑", &[("⋑", 1, false)]),
13431 ("⋑⋑", &[("⋑⋑", 2, false)]),
13432 (
13433 "原理,进而",
13434 &[
13435 ("原", 1, false),
13436 ("理,", 2, false),
13437 ("进", 1, false),
13438 ("而", 1, false),
13439 ],
13440 ),
13441 (
13442 "hello world",
13443 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13444 ),
13445 (
13446 "hello, world",
13447 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13448 ),
13449 (
13450 " hello world",
13451 &[
13452 (" ", 1, true),
13453 ("hello", 5, false),
13454 (" ", 1, true),
13455 ("world", 5, false),
13456 ],
13457 ),
13458 (
13459 "这是什么 \n 钢笔",
13460 &[
13461 ("这", 1, false),
13462 ("是", 1, false),
13463 ("什", 1, false),
13464 ("么", 1, false),
13465 (" ", 1, true),
13466 ("钢", 1, false),
13467 ("笔", 1, false),
13468 ],
13469 ),
13470 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13471 ];
13472
13473 for (input, result) in tests {
13474 assert_eq!(
13475 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13476 result
13477 .iter()
13478 .copied()
13479 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13480 token,
13481 grapheme_len,
13482 is_whitespace,
13483 })
13484 .collect::<Vec<_>>()
13485 );
13486 }
13487}
13488
13489fn wrap_with_prefix(
13490 line_prefix: String,
13491 unwrapped_text: String,
13492 wrap_column: usize,
13493 tab_size: NonZeroU32,
13494) -> String {
13495 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13496 let mut wrapped_text = String::new();
13497 let mut current_line = line_prefix.clone();
13498
13499 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13500 let mut current_line_len = line_prefix_len;
13501 for WordBreakToken {
13502 token,
13503 grapheme_len,
13504 is_whitespace,
13505 } in tokenizer
13506 {
13507 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13508 wrapped_text.push_str(current_line.trim_end());
13509 wrapped_text.push('\n');
13510 current_line.truncate(line_prefix.len());
13511 current_line_len = line_prefix_len;
13512 if !is_whitespace {
13513 current_line.push_str(token);
13514 current_line_len += grapheme_len;
13515 }
13516 } else if !is_whitespace {
13517 current_line.push_str(token);
13518 current_line_len += grapheme_len;
13519 } else if current_line_len != line_prefix_len {
13520 current_line.push(' ');
13521 current_line_len += 1;
13522 }
13523 }
13524
13525 if !current_line.is_empty() {
13526 wrapped_text.push_str(¤t_line);
13527 }
13528 wrapped_text
13529}
13530
13531#[test]
13532fn test_wrap_with_prefix() {
13533 assert_eq!(
13534 wrap_with_prefix(
13535 "# ".to_string(),
13536 "abcdefg".to_string(),
13537 4,
13538 NonZeroU32::new(4).unwrap()
13539 ),
13540 "# abcdefg"
13541 );
13542 assert_eq!(
13543 wrap_with_prefix(
13544 "".to_string(),
13545 "\thello world".to_string(),
13546 8,
13547 NonZeroU32::new(4).unwrap()
13548 ),
13549 "hello\nworld"
13550 );
13551 assert_eq!(
13552 wrap_with_prefix(
13553 "// ".to_string(),
13554 "xx \nyy zz aa bb cc".to_string(),
13555 12,
13556 NonZeroU32::new(4).unwrap()
13557 ),
13558 "// xx yy zz\n// aa bb cc"
13559 );
13560 assert_eq!(
13561 wrap_with_prefix(
13562 String::new(),
13563 "这是什么 \n 钢笔".to_string(),
13564 3,
13565 NonZeroU32::new(4).unwrap()
13566 ),
13567 "这是什\n么 钢\n笔"
13568 );
13569}
13570
13571fn hunks_for_selections(
13572 snapshot: &EditorSnapshot,
13573 selections: &[Selection<Point>],
13574) -> Vec<MultiBufferDiffHunk> {
13575 hunks_for_ranges(
13576 selections.iter().map(|selection| selection.range()),
13577 snapshot,
13578 )
13579}
13580
13581pub fn hunks_for_ranges(
13582 ranges: impl Iterator<Item = Range<Point>>,
13583 snapshot: &EditorSnapshot,
13584) -> Vec<MultiBufferDiffHunk> {
13585 let mut hunks = Vec::new();
13586 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13587 HashMap::default();
13588 for query_range in ranges {
13589 let query_rows =
13590 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13591 for hunk in snapshot.diff_map.diff_hunks_in_range(
13592 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13593 &snapshot.buffer_snapshot,
13594 ) {
13595 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13596 // when the caret is just above or just below the deleted hunk.
13597 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13598 let related_to_selection = if allow_adjacent {
13599 hunk.row_range.overlaps(&query_rows)
13600 || hunk.row_range.start == query_rows.end
13601 || hunk.row_range.end == query_rows.start
13602 } else {
13603 hunk.row_range.overlaps(&query_rows)
13604 };
13605 if related_to_selection {
13606 if !processed_buffer_rows
13607 .entry(hunk.buffer_id)
13608 .or_default()
13609 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13610 {
13611 continue;
13612 }
13613 hunks.push(hunk);
13614 }
13615 }
13616 }
13617
13618 hunks
13619}
13620
13621pub trait CollaborationHub {
13622 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13623 fn user_participant_indices<'a>(
13624 &self,
13625 cx: &'a AppContext,
13626 ) -> &'a HashMap<u64, ParticipantIndex>;
13627 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13628}
13629
13630impl CollaborationHub for Model<Project> {
13631 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13632 self.read(cx).collaborators()
13633 }
13634
13635 fn user_participant_indices<'a>(
13636 &self,
13637 cx: &'a AppContext,
13638 ) -> &'a HashMap<u64, ParticipantIndex> {
13639 self.read(cx).user_store().read(cx).participant_indices()
13640 }
13641
13642 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13643 let this = self.read(cx);
13644 let user_ids = this.collaborators().values().map(|c| c.user_id);
13645 this.user_store().read_with(cx, |user_store, cx| {
13646 user_store.participant_names(user_ids, cx)
13647 })
13648 }
13649}
13650
13651pub trait SemanticsProvider {
13652 fn hover(
13653 &self,
13654 buffer: &Model<Buffer>,
13655 position: text::Anchor,
13656 cx: &mut AppContext,
13657 ) -> Option<Task<Vec<project::Hover>>>;
13658
13659 fn inlay_hints(
13660 &self,
13661 buffer_handle: Model<Buffer>,
13662 range: Range<text::Anchor>,
13663 cx: &mut AppContext,
13664 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13665
13666 fn resolve_inlay_hint(
13667 &self,
13668 hint: InlayHint,
13669 buffer_handle: Model<Buffer>,
13670 server_id: LanguageServerId,
13671 cx: &mut AppContext,
13672 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13673
13674 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13675
13676 fn document_highlights(
13677 &self,
13678 buffer: &Model<Buffer>,
13679 position: text::Anchor,
13680 cx: &mut AppContext,
13681 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13682
13683 fn definitions(
13684 &self,
13685 buffer: &Model<Buffer>,
13686 position: text::Anchor,
13687 kind: GotoDefinitionKind,
13688 cx: &mut AppContext,
13689 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13690
13691 fn range_for_rename(
13692 &self,
13693 buffer: &Model<Buffer>,
13694 position: text::Anchor,
13695 cx: &mut AppContext,
13696 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13697
13698 fn perform_rename(
13699 &self,
13700 buffer: &Model<Buffer>,
13701 position: text::Anchor,
13702 new_name: String,
13703 cx: &mut AppContext,
13704 ) -> Option<Task<Result<ProjectTransaction>>>;
13705}
13706
13707pub trait CompletionProvider {
13708 fn completions(
13709 &self,
13710 buffer: &Model<Buffer>,
13711 buffer_position: text::Anchor,
13712 trigger: CompletionContext,
13713 cx: &mut ViewContext<Editor>,
13714 ) -> Task<Result<Vec<Completion>>>;
13715
13716 fn resolve_completions(
13717 &self,
13718 buffer: Model<Buffer>,
13719 completion_indices: Vec<usize>,
13720 completions: Rc<RefCell<Box<[Completion]>>>,
13721 cx: &mut ViewContext<Editor>,
13722 ) -> Task<Result<bool>>;
13723
13724 fn apply_additional_edits_for_completion(
13725 &self,
13726 _buffer: Model<Buffer>,
13727 _completions: Rc<RefCell<Box<[Completion]>>>,
13728 _completion_index: usize,
13729 _push_to_history: bool,
13730 _cx: &mut ViewContext<Editor>,
13731 ) -> Task<Result<Option<language::Transaction>>> {
13732 Task::ready(Ok(None))
13733 }
13734
13735 fn is_completion_trigger(
13736 &self,
13737 buffer: &Model<Buffer>,
13738 position: language::Anchor,
13739 text: &str,
13740 trigger_in_words: bool,
13741 cx: &mut ViewContext<Editor>,
13742 ) -> bool;
13743
13744 fn sort_completions(&self) -> bool {
13745 true
13746 }
13747}
13748
13749pub trait CodeActionProvider {
13750 fn id(&self) -> Arc<str>;
13751
13752 fn code_actions(
13753 &self,
13754 buffer: &Model<Buffer>,
13755 range: Range<text::Anchor>,
13756 cx: &mut WindowContext,
13757 ) -> Task<Result<Vec<CodeAction>>>;
13758
13759 fn apply_code_action(
13760 &self,
13761 buffer_handle: Model<Buffer>,
13762 action: CodeAction,
13763 excerpt_id: ExcerptId,
13764 push_to_history: bool,
13765 cx: &mut WindowContext,
13766 ) -> Task<Result<ProjectTransaction>>;
13767}
13768
13769impl CodeActionProvider for Model<Project> {
13770 fn id(&self) -> Arc<str> {
13771 "project".into()
13772 }
13773
13774 fn code_actions(
13775 &self,
13776 buffer: &Model<Buffer>,
13777 range: Range<text::Anchor>,
13778 cx: &mut WindowContext,
13779 ) -> Task<Result<Vec<CodeAction>>> {
13780 self.update(cx, |project, cx| {
13781 project.code_actions(buffer, range, None, cx)
13782 })
13783 }
13784
13785 fn apply_code_action(
13786 &self,
13787 buffer_handle: Model<Buffer>,
13788 action: CodeAction,
13789 _excerpt_id: ExcerptId,
13790 push_to_history: bool,
13791 cx: &mut WindowContext,
13792 ) -> Task<Result<ProjectTransaction>> {
13793 self.update(cx, |project, cx| {
13794 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13795 })
13796 }
13797}
13798
13799fn snippet_completions(
13800 project: &Project,
13801 buffer: &Model<Buffer>,
13802 buffer_position: text::Anchor,
13803 cx: &mut AppContext,
13804) -> Task<Result<Vec<Completion>>> {
13805 let language = buffer.read(cx).language_at(buffer_position);
13806 let language_name = language.as_ref().map(|language| language.lsp_id());
13807 let snippet_store = project.snippets().read(cx);
13808 let snippets = snippet_store.snippets_for(language_name, cx);
13809
13810 if snippets.is_empty() {
13811 return Task::ready(Ok(vec![]));
13812 }
13813 let snapshot = buffer.read(cx).text_snapshot();
13814 let chars: String = snapshot
13815 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13816 .collect();
13817
13818 let scope = language.map(|language| language.default_scope());
13819 let executor = cx.background_executor().clone();
13820
13821 cx.background_executor().spawn(async move {
13822 let classifier = CharClassifier::new(scope).for_completion(true);
13823 let mut last_word = chars
13824 .chars()
13825 .take_while(|c| classifier.is_word(*c))
13826 .collect::<String>();
13827 last_word = last_word.chars().rev().collect();
13828
13829 if last_word.is_empty() {
13830 return Ok(vec![]);
13831 }
13832
13833 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13834 let to_lsp = |point: &text::Anchor| {
13835 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13836 point_to_lsp(end)
13837 };
13838 let lsp_end = to_lsp(&buffer_position);
13839
13840 let candidates = snippets
13841 .iter()
13842 .enumerate()
13843 .flat_map(|(ix, snippet)| {
13844 snippet
13845 .prefix
13846 .iter()
13847 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13848 })
13849 .collect::<Vec<StringMatchCandidate>>();
13850
13851 let mut matches = fuzzy::match_strings(
13852 &candidates,
13853 &last_word,
13854 last_word.chars().any(|c| c.is_uppercase()),
13855 100,
13856 &Default::default(),
13857 executor,
13858 )
13859 .await;
13860
13861 // Remove all candidates where the query's start does not match the start of any word in the candidate
13862 if let Some(query_start) = last_word.chars().next() {
13863 matches.retain(|string_match| {
13864 split_words(&string_match.string).any(|word| {
13865 // Check that the first codepoint of the word as lowercase matches the first
13866 // codepoint of the query as lowercase
13867 word.chars()
13868 .flat_map(|codepoint| codepoint.to_lowercase())
13869 .zip(query_start.to_lowercase())
13870 .all(|(word_cp, query_cp)| word_cp == query_cp)
13871 })
13872 });
13873 }
13874
13875 let matched_strings = matches
13876 .into_iter()
13877 .map(|m| m.string)
13878 .collect::<HashSet<_>>();
13879
13880 let result: Vec<Completion> = snippets
13881 .into_iter()
13882 .filter_map(|snippet| {
13883 let matching_prefix = snippet
13884 .prefix
13885 .iter()
13886 .find(|prefix| matched_strings.contains(*prefix))?;
13887 let start = as_offset - last_word.len();
13888 let start = snapshot.anchor_before(start);
13889 let range = start..buffer_position;
13890 let lsp_start = to_lsp(&start);
13891 let lsp_range = lsp::Range {
13892 start: lsp_start,
13893 end: lsp_end,
13894 };
13895 Some(Completion {
13896 old_range: range,
13897 new_text: snippet.body.clone(),
13898 resolved: false,
13899 label: CodeLabel {
13900 text: matching_prefix.clone(),
13901 runs: vec![],
13902 filter_range: 0..matching_prefix.len(),
13903 },
13904 server_id: LanguageServerId(usize::MAX),
13905 documentation: snippet.description.clone().map(Documentation::SingleLine),
13906 lsp_completion: lsp::CompletionItem {
13907 label: snippet.prefix.first().unwrap().clone(),
13908 kind: Some(CompletionItemKind::SNIPPET),
13909 label_details: snippet.description.as_ref().map(|description| {
13910 lsp::CompletionItemLabelDetails {
13911 detail: Some(description.clone()),
13912 description: None,
13913 }
13914 }),
13915 insert_text_format: Some(InsertTextFormat::SNIPPET),
13916 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13917 lsp::InsertReplaceEdit {
13918 new_text: snippet.body.clone(),
13919 insert: lsp_range,
13920 replace: lsp_range,
13921 },
13922 )),
13923 filter_text: Some(snippet.body.clone()),
13924 sort_text: Some(char::MAX.to_string()),
13925 ..Default::default()
13926 },
13927 confirm: None,
13928 })
13929 })
13930 .collect();
13931
13932 Ok(result)
13933 })
13934}
13935
13936impl CompletionProvider for Model<Project> {
13937 fn completions(
13938 &self,
13939 buffer: &Model<Buffer>,
13940 buffer_position: text::Anchor,
13941 options: CompletionContext,
13942 cx: &mut ViewContext<Editor>,
13943 ) -> Task<Result<Vec<Completion>>> {
13944 self.update(cx, |project, cx| {
13945 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13946 let project_completions = project.completions(buffer, buffer_position, options, cx);
13947 cx.background_executor().spawn(async move {
13948 let mut completions = project_completions.await?;
13949 let snippets_completions = snippets.await?;
13950 completions.extend(snippets_completions);
13951 Ok(completions)
13952 })
13953 })
13954 }
13955
13956 fn resolve_completions(
13957 &self,
13958 buffer: Model<Buffer>,
13959 completion_indices: Vec<usize>,
13960 completions: Rc<RefCell<Box<[Completion]>>>,
13961 cx: &mut ViewContext<Editor>,
13962 ) -> Task<Result<bool>> {
13963 self.update(cx, |project, cx| {
13964 project.lsp_store().update(cx, |lsp_store, cx| {
13965 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13966 })
13967 })
13968 }
13969
13970 fn apply_additional_edits_for_completion(
13971 &self,
13972 buffer: Model<Buffer>,
13973 completions: Rc<RefCell<Box<[Completion]>>>,
13974 completion_index: usize,
13975 push_to_history: bool,
13976 cx: &mut ViewContext<Editor>,
13977 ) -> Task<Result<Option<language::Transaction>>> {
13978 self.update(cx, |project, cx| {
13979 project.lsp_store().update(cx, |lsp_store, cx| {
13980 lsp_store.apply_additional_edits_for_completion(
13981 buffer,
13982 completions,
13983 completion_index,
13984 push_to_history,
13985 cx,
13986 )
13987 })
13988 })
13989 }
13990
13991 fn is_completion_trigger(
13992 &self,
13993 buffer: &Model<Buffer>,
13994 position: language::Anchor,
13995 text: &str,
13996 trigger_in_words: bool,
13997 cx: &mut ViewContext<Editor>,
13998 ) -> bool {
13999 let mut chars = text.chars();
14000 let char = if let Some(char) = chars.next() {
14001 char
14002 } else {
14003 return false;
14004 };
14005 if chars.next().is_some() {
14006 return false;
14007 }
14008
14009 let buffer = buffer.read(cx);
14010 let snapshot = buffer.snapshot();
14011 if !snapshot.settings_at(position, cx).show_completions_on_input {
14012 return false;
14013 }
14014 let classifier = snapshot.char_classifier_at(position).for_completion(true);
14015 if trigger_in_words && classifier.is_word(char) {
14016 return true;
14017 }
14018
14019 buffer.completion_triggers().contains(text)
14020 }
14021}
14022
14023impl SemanticsProvider for Model<Project> {
14024 fn hover(
14025 &self,
14026 buffer: &Model<Buffer>,
14027 position: text::Anchor,
14028 cx: &mut AppContext,
14029 ) -> Option<Task<Vec<project::Hover>>> {
14030 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14031 }
14032
14033 fn document_highlights(
14034 &self,
14035 buffer: &Model<Buffer>,
14036 position: text::Anchor,
14037 cx: &mut AppContext,
14038 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14039 Some(self.update(cx, |project, cx| {
14040 project.document_highlights(buffer, position, cx)
14041 }))
14042 }
14043
14044 fn definitions(
14045 &self,
14046 buffer: &Model<Buffer>,
14047 position: text::Anchor,
14048 kind: GotoDefinitionKind,
14049 cx: &mut AppContext,
14050 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14051 Some(self.update(cx, |project, cx| match kind {
14052 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14053 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14054 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14055 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14056 }))
14057 }
14058
14059 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14060 // TODO: make this work for remote projects
14061 self.read(cx)
14062 .language_servers_for_local_buffer(buffer.read(cx), cx)
14063 .any(
14064 |(_, server)| match server.capabilities().inlay_hint_provider {
14065 Some(lsp::OneOf::Left(enabled)) => enabled,
14066 Some(lsp::OneOf::Right(_)) => true,
14067 None => false,
14068 },
14069 )
14070 }
14071
14072 fn inlay_hints(
14073 &self,
14074 buffer_handle: Model<Buffer>,
14075 range: Range<text::Anchor>,
14076 cx: &mut AppContext,
14077 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14078 Some(self.update(cx, |project, cx| {
14079 project.inlay_hints(buffer_handle, range, cx)
14080 }))
14081 }
14082
14083 fn resolve_inlay_hint(
14084 &self,
14085 hint: InlayHint,
14086 buffer_handle: Model<Buffer>,
14087 server_id: LanguageServerId,
14088 cx: &mut AppContext,
14089 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14090 Some(self.update(cx, |project, cx| {
14091 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14092 }))
14093 }
14094
14095 fn range_for_rename(
14096 &self,
14097 buffer: &Model<Buffer>,
14098 position: text::Anchor,
14099 cx: &mut AppContext,
14100 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14101 Some(self.update(cx, |project, cx| {
14102 let buffer = buffer.clone();
14103 let task = project.prepare_rename(buffer.clone(), position, cx);
14104 cx.spawn(|_, mut cx| async move {
14105 Ok(match task.await? {
14106 PrepareRenameResponse::Success(range) => Some(range),
14107 PrepareRenameResponse::InvalidPosition => None,
14108 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14109 // Fallback on using TreeSitter info to determine identifier range
14110 buffer.update(&mut cx, |buffer, _| {
14111 let snapshot = buffer.snapshot();
14112 let (range, kind) = snapshot.surrounding_word(position);
14113 if kind != Some(CharKind::Word) {
14114 return None;
14115 }
14116 Some(
14117 snapshot.anchor_before(range.start)
14118 ..snapshot.anchor_after(range.end),
14119 )
14120 })?
14121 }
14122 })
14123 })
14124 }))
14125 }
14126
14127 fn perform_rename(
14128 &self,
14129 buffer: &Model<Buffer>,
14130 position: text::Anchor,
14131 new_name: String,
14132 cx: &mut AppContext,
14133 ) -> Option<Task<Result<ProjectTransaction>>> {
14134 Some(self.update(cx, |project, cx| {
14135 project.perform_rename(buffer.clone(), position, new_name, cx)
14136 }))
14137 }
14138}
14139
14140fn inlay_hint_settings(
14141 location: Anchor,
14142 snapshot: &MultiBufferSnapshot,
14143 cx: &mut ViewContext<Editor>,
14144) -> InlayHintSettings {
14145 let file = snapshot.file_at(location);
14146 let language = snapshot.language_at(location).map(|l| l.name());
14147 language_settings(language, file, cx).inlay_hints
14148}
14149
14150fn consume_contiguous_rows(
14151 contiguous_row_selections: &mut Vec<Selection<Point>>,
14152 selection: &Selection<Point>,
14153 display_map: &DisplaySnapshot,
14154 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14155) -> (MultiBufferRow, MultiBufferRow) {
14156 contiguous_row_selections.push(selection.clone());
14157 let start_row = MultiBufferRow(selection.start.row);
14158 let mut end_row = ending_row(selection, display_map);
14159
14160 while let Some(next_selection) = selections.peek() {
14161 if next_selection.start.row <= end_row.0 {
14162 end_row = ending_row(next_selection, display_map);
14163 contiguous_row_selections.push(selections.next().unwrap().clone());
14164 } else {
14165 break;
14166 }
14167 }
14168 (start_row, end_row)
14169}
14170
14171fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14172 if next_selection.end.column > 0 || next_selection.is_empty() {
14173 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14174 } else {
14175 MultiBufferRow(next_selection.end.row)
14176 }
14177}
14178
14179impl EditorSnapshot {
14180 pub fn remote_selections_in_range<'a>(
14181 &'a self,
14182 range: &'a Range<Anchor>,
14183 collaboration_hub: &dyn CollaborationHub,
14184 cx: &'a AppContext,
14185 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14186 let participant_names = collaboration_hub.user_names(cx);
14187 let participant_indices = collaboration_hub.user_participant_indices(cx);
14188 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14189 let collaborators_by_replica_id = collaborators_by_peer_id
14190 .iter()
14191 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14192 .collect::<HashMap<_, _>>();
14193 self.buffer_snapshot
14194 .selections_in_range(range, false)
14195 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14196 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14197 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14198 let user_name = participant_names.get(&collaborator.user_id).cloned();
14199 Some(RemoteSelection {
14200 replica_id,
14201 selection,
14202 cursor_shape,
14203 line_mode,
14204 participant_index,
14205 peer_id: collaborator.peer_id,
14206 user_name,
14207 })
14208 })
14209 }
14210
14211 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14212 self.display_snapshot.buffer_snapshot.language_at(position)
14213 }
14214
14215 pub fn is_focused(&self) -> bool {
14216 self.is_focused
14217 }
14218
14219 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14220 self.placeholder_text.as_ref()
14221 }
14222
14223 pub fn scroll_position(&self) -> gpui::Point<f32> {
14224 self.scroll_anchor.scroll_position(&self.display_snapshot)
14225 }
14226
14227 fn gutter_dimensions(
14228 &self,
14229 font_id: FontId,
14230 font_size: Pixels,
14231 em_width: Pixels,
14232 em_advance: Pixels,
14233 max_line_number_width: Pixels,
14234 cx: &AppContext,
14235 ) -> GutterDimensions {
14236 if !self.show_gutter {
14237 return GutterDimensions::default();
14238 }
14239 let descent = cx.text_system().descent(font_id, font_size);
14240
14241 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14242 matches!(
14243 ProjectSettings::get_global(cx).git.git_gutter,
14244 Some(GitGutterSetting::TrackedFiles)
14245 )
14246 });
14247 let gutter_settings = EditorSettings::get_global(cx).gutter;
14248 let show_line_numbers = self
14249 .show_line_numbers
14250 .unwrap_or(gutter_settings.line_numbers);
14251 let line_gutter_width = if show_line_numbers {
14252 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14253 let min_width_for_number_on_gutter = em_advance * 4.0;
14254 max_line_number_width.max(min_width_for_number_on_gutter)
14255 } else {
14256 0.0.into()
14257 };
14258
14259 let show_code_actions = self
14260 .show_code_actions
14261 .unwrap_or(gutter_settings.code_actions);
14262
14263 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14264
14265 let git_blame_entries_width =
14266 self.git_blame_gutter_max_author_length
14267 .map(|max_author_length| {
14268 // Length of the author name, but also space for the commit hash,
14269 // the spacing and the timestamp.
14270 let max_char_count = max_author_length
14271 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14272 + 7 // length of commit sha
14273 + 14 // length of max relative timestamp ("60 minutes ago")
14274 + 4; // gaps and margins
14275
14276 em_advance * max_char_count
14277 });
14278
14279 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14280 left_padding += if show_code_actions || show_runnables {
14281 em_width * 3.0
14282 } else if show_git_gutter && show_line_numbers {
14283 em_width * 2.0
14284 } else if show_git_gutter || show_line_numbers {
14285 em_width
14286 } else {
14287 px(0.)
14288 };
14289
14290 let right_padding = if gutter_settings.folds && show_line_numbers {
14291 em_width * 4.0
14292 } else if gutter_settings.folds {
14293 em_width * 3.0
14294 } else if show_line_numbers {
14295 em_width
14296 } else {
14297 px(0.)
14298 };
14299
14300 GutterDimensions {
14301 left_padding,
14302 right_padding,
14303 width: line_gutter_width + left_padding + right_padding,
14304 margin: -descent,
14305 git_blame_entries_width,
14306 }
14307 }
14308
14309 pub fn render_crease_toggle(
14310 &self,
14311 buffer_row: MultiBufferRow,
14312 row_contains_cursor: bool,
14313 editor: View<Editor>,
14314 cx: &mut WindowContext,
14315 ) -> Option<AnyElement> {
14316 let folded = self.is_line_folded(buffer_row);
14317 let mut is_foldable = false;
14318
14319 if let Some(crease) = self
14320 .crease_snapshot
14321 .query_row(buffer_row, &self.buffer_snapshot)
14322 {
14323 is_foldable = true;
14324 match crease {
14325 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14326 if let Some(render_toggle) = render_toggle {
14327 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14328 if folded {
14329 editor.update(cx, |editor, cx| {
14330 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14331 });
14332 } else {
14333 editor.update(cx, |editor, cx| {
14334 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14335 });
14336 }
14337 });
14338 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14339 }
14340 }
14341 }
14342 }
14343
14344 is_foldable |= self.starts_indent(buffer_row);
14345
14346 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14347 Some(
14348 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14349 .toggle_state(folded)
14350 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14351 if folded {
14352 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14353 } else {
14354 this.fold_at(&FoldAt { buffer_row }, cx);
14355 }
14356 }))
14357 .into_any_element(),
14358 )
14359 } else {
14360 None
14361 }
14362 }
14363
14364 pub fn render_crease_trailer(
14365 &self,
14366 buffer_row: MultiBufferRow,
14367 cx: &mut WindowContext,
14368 ) -> Option<AnyElement> {
14369 let folded = self.is_line_folded(buffer_row);
14370 if let Crease::Inline { render_trailer, .. } = self
14371 .crease_snapshot
14372 .query_row(buffer_row, &self.buffer_snapshot)?
14373 {
14374 let render_trailer = render_trailer.as_ref()?;
14375 Some(render_trailer(buffer_row, folded, cx))
14376 } else {
14377 None
14378 }
14379 }
14380}
14381
14382impl Deref for EditorSnapshot {
14383 type Target = DisplaySnapshot;
14384
14385 fn deref(&self) -> &Self::Target {
14386 &self.display_snapshot
14387 }
14388}
14389
14390#[derive(Clone, Debug, PartialEq, Eq)]
14391pub enum EditorEvent {
14392 InputIgnored {
14393 text: Arc<str>,
14394 },
14395 InputHandled {
14396 utf16_range_to_replace: Option<Range<isize>>,
14397 text: Arc<str>,
14398 },
14399 ExcerptsAdded {
14400 buffer: Model<Buffer>,
14401 predecessor: ExcerptId,
14402 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14403 },
14404 ExcerptsRemoved {
14405 ids: Vec<ExcerptId>,
14406 },
14407 BufferFoldToggled {
14408 ids: Vec<ExcerptId>,
14409 folded: bool,
14410 },
14411 ExcerptsEdited {
14412 ids: Vec<ExcerptId>,
14413 },
14414 ExcerptsExpanded {
14415 ids: Vec<ExcerptId>,
14416 },
14417 BufferEdited,
14418 Edited {
14419 transaction_id: clock::Lamport,
14420 },
14421 Reparsed(BufferId),
14422 Focused,
14423 FocusedIn,
14424 Blurred,
14425 DirtyChanged,
14426 Saved,
14427 TitleChanged,
14428 DiffBaseChanged,
14429 SelectionsChanged {
14430 local: bool,
14431 },
14432 ScrollPositionChanged {
14433 local: bool,
14434 autoscroll: bool,
14435 },
14436 Closed,
14437 TransactionUndone {
14438 transaction_id: clock::Lamport,
14439 },
14440 TransactionBegun {
14441 transaction_id: clock::Lamport,
14442 },
14443 Reloaded,
14444 CursorShapeChanged,
14445}
14446
14447impl EventEmitter<EditorEvent> for Editor {}
14448
14449impl FocusableView for Editor {
14450 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14451 self.focus_handle.clone()
14452 }
14453}
14454
14455impl Render for Editor {
14456 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14457 let settings = ThemeSettings::get_global(cx);
14458
14459 let mut text_style = match self.mode {
14460 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14461 color: cx.theme().colors().editor_foreground,
14462 font_family: settings.ui_font.family.clone(),
14463 font_features: settings.ui_font.features.clone(),
14464 font_fallbacks: settings.ui_font.fallbacks.clone(),
14465 font_size: rems(0.875).into(),
14466 font_weight: settings.ui_font.weight,
14467 line_height: relative(settings.buffer_line_height.value()),
14468 ..Default::default()
14469 },
14470 EditorMode::Full => TextStyle {
14471 color: cx.theme().colors().editor_foreground,
14472 font_family: settings.buffer_font.family.clone(),
14473 font_features: settings.buffer_font.features.clone(),
14474 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14475 font_size: settings.buffer_font_size().into(),
14476 font_weight: settings.buffer_font.weight,
14477 line_height: relative(settings.buffer_line_height.value()),
14478 ..Default::default()
14479 },
14480 };
14481 if let Some(text_style_refinement) = &self.text_style_refinement {
14482 text_style.refine(text_style_refinement)
14483 }
14484
14485 let background = match self.mode {
14486 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14487 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14488 EditorMode::Full => cx.theme().colors().editor_background,
14489 };
14490
14491 EditorElement::new(
14492 cx.view(),
14493 EditorStyle {
14494 background,
14495 local_player: cx.theme().players().local(),
14496 text: text_style,
14497 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14498 syntax: cx.theme().syntax().clone(),
14499 status: cx.theme().status().clone(),
14500 inlay_hints_style: make_inlay_hints_style(cx),
14501 inline_completion_styles: make_suggestion_styles(cx),
14502 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14503 },
14504 )
14505 }
14506}
14507
14508impl ViewInputHandler for Editor {
14509 fn text_for_range(
14510 &mut self,
14511 range_utf16: Range<usize>,
14512 adjusted_range: &mut Option<Range<usize>>,
14513 cx: &mut ViewContext<Self>,
14514 ) -> Option<String> {
14515 let snapshot = self.buffer.read(cx).read(cx);
14516 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14517 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14518 if (start.0..end.0) != range_utf16 {
14519 adjusted_range.replace(start.0..end.0);
14520 }
14521 Some(snapshot.text_for_range(start..end).collect())
14522 }
14523
14524 fn selected_text_range(
14525 &mut self,
14526 ignore_disabled_input: bool,
14527 cx: &mut ViewContext<Self>,
14528 ) -> Option<UTF16Selection> {
14529 // Prevent the IME menu from appearing when holding down an alphabetic key
14530 // while input is disabled.
14531 if !ignore_disabled_input && !self.input_enabled {
14532 return None;
14533 }
14534
14535 let selection = self.selections.newest::<OffsetUtf16>(cx);
14536 let range = selection.range();
14537
14538 Some(UTF16Selection {
14539 range: range.start.0..range.end.0,
14540 reversed: selection.reversed,
14541 })
14542 }
14543
14544 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14545 let snapshot = self.buffer.read(cx).read(cx);
14546 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14547 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14548 }
14549
14550 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14551 self.clear_highlights::<InputComposition>(cx);
14552 self.ime_transaction.take();
14553 }
14554
14555 fn replace_text_in_range(
14556 &mut self,
14557 range_utf16: Option<Range<usize>>,
14558 text: &str,
14559 cx: &mut ViewContext<Self>,
14560 ) {
14561 if !self.input_enabled {
14562 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14563 return;
14564 }
14565
14566 self.transact(cx, |this, cx| {
14567 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14568 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14569 Some(this.selection_replacement_ranges(range_utf16, cx))
14570 } else {
14571 this.marked_text_ranges(cx)
14572 };
14573
14574 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14575 let newest_selection_id = this.selections.newest_anchor().id;
14576 this.selections
14577 .all::<OffsetUtf16>(cx)
14578 .iter()
14579 .zip(ranges_to_replace.iter())
14580 .find_map(|(selection, range)| {
14581 if selection.id == newest_selection_id {
14582 Some(
14583 (range.start.0 as isize - selection.head().0 as isize)
14584 ..(range.end.0 as isize - selection.head().0 as isize),
14585 )
14586 } else {
14587 None
14588 }
14589 })
14590 });
14591
14592 cx.emit(EditorEvent::InputHandled {
14593 utf16_range_to_replace: range_to_replace,
14594 text: text.into(),
14595 });
14596
14597 if let Some(new_selected_ranges) = new_selected_ranges {
14598 this.change_selections(None, cx, |selections| {
14599 selections.select_ranges(new_selected_ranges)
14600 });
14601 this.backspace(&Default::default(), cx);
14602 }
14603
14604 this.handle_input(text, cx);
14605 });
14606
14607 if let Some(transaction) = self.ime_transaction {
14608 self.buffer.update(cx, |buffer, cx| {
14609 buffer.group_until_transaction(transaction, cx);
14610 });
14611 }
14612
14613 self.unmark_text(cx);
14614 }
14615
14616 fn replace_and_mark_text_in_range(
14617 &mut self,
14618 range_utf16: Option<Range<usize>>,
14619 text: &str,
14620 new_selected_range_utf16: Option<Range<usize>>,
14621 cx: &mut ViewContext<Self>,
14622 ) {
14623 if !self.input_enabled {
14624 return;
14625 }
14626
14627 let transaction = self.transact(cx, |this, cx| {
14628 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14629 let snapshot = this.buffer.read(cx).read(cx);
14630 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14631 for marked_range in &mut marked_ranges {
14632 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14633 marked_range.start.0 += relative_range_utf16.start;
14634 marked_range.start =
14635 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14636 marked_range.end =
14637 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14638 }
14639 }
14640 Some(marked_ranges)
14641 } else if let Some(range_utf16) = range_utf16 {
14642 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14643 Some(this.selection_replacement_ranges(range_utf16, cx))
14644 } else {
14645 None
14646 };
14647
14648 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14649 let newest_selection_id = this.selections.newest_anchor().id;
14650 this.selections
14651 .all::<OffsetUtf16>(cx)
14652 .iter()
14653 .zip(ranges_to_replace.iter())
14654 .find_map(|(selection, range)| {
14655 if selection.id == newest_selection_id {
14656 Some(
14657 (range.start.0 as isize - selection.head().0 as isize)
14658 ..(range.end.0 as isize - selection.head().0 as isize),
14659 )
14660 } else {
14661 None
14662 }
14663 })
14664 });
14665
14666 cx.emit(EditorEvent::InputHandled {
14667 utf16_range_to_replace: range_to_replace,
14668 text: text.into(),
14669 });
14670
14671 if let Some(ranges) = ranges_to_replace {
14672 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14673 }
14674
14675 let marked_ranges = {
14676 let snapshot = this.buffer.read(cx).read(cx);
14677 this.selections
14678 .disjoint_anchors()
14679 .iter()
14680 .map(|selection| {
14681 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14682 })
14683 .collect::<Vec<_>>()
14684 };
14685
14686 if text.is_empty() {
14687 this.unmark_text(cx);
14688 } else {
14689 this.highlight_text::<InputComposition>(
14690 marked_ranges.clone(),
14691 HighlightStyle {
14692 underline: Some(UnderlineStyle {
14693 thickness: px(1.),
14694 color: None,
14695 wavy: false,
14696 }),
14697 ..Default::default()
14698 },
14699 cx,
14700 );
14701 }
14702
14703 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14704 let use_autoclose = this.use_autoclose;
14705 let use_auto_surround = this.use_auto_surround;
14706 this.set_use_autoclose(false);
14707 this.set_use_auto_surround(false);
14708 this.handle_input(text, cx);
14709 this.set_use_autoclose(use_autoclose);
14710 this.set_use_auto_surround(use_auto_surround);
14711
14712 if let Some(new_selected_range) = new_selected_range_utf16 {
14713 let snapshot = this.buffer.read(cx).read(cx);
14714 let new_selected_ranges = marked_ranges
14715 .into_iter()
14716 .map(|marked_range| {
14717 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14718 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14719 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14720 snapshot.clip_offset_utf16(new_start, Bias::Left)
14721 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14722 })
14723 .collect::<Vec<_>>();
14724
14725 drop(snapshot);
14726 this.change_selections(None, cx, |selections| {
14727 selections.select_ranges(new_selected_ranges)
14728 });
14729 }
14730 });
14731
14732 self.ime_transaction = self.ime_transaction.or(transaction);
14733 if let Some(transaction) = self.ime_transaction {
14734 self.buffer.update(cx, |buffer, cx| {
14735 buffer.group_until_transaction(transaction, cx);
14736 });
14737 }
14738
14739 if self.text_highlights::<InputComposition>(cx).is_none() {
14740 self.ime_transaction.take();
14741 }
14742 }
14743
14744 fn bounds_for_range(
14745 &mut self,
14746 range_utf16: Range<usize>,
14747 element_bounds: gpui::Bounds<Pixels>,
14748 cx: &mut ViewContext<Self>,
14749 ) -> Option<gpui::Bounds<Pixels>> {
14750 let text_layout_details = self.text_layout_details(cx);
14751 let gpui::Point {
14752 x: em_width,
14753 y: line_height,
14754 } = self.character_size(cx);
14755
14756 let snapshot = self.snapshot(cx);
14757 let scroll_position = snapshot.scroll_position();
14758 let scroll_left = scroll_position.x * em_width;
14759
14760 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14761 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14762 + self.gutter_dimensions.width
14763 + self.gutter_dimensions.margin;
14764 let y = line_height * (start.row().as_f32() - scroll_position.y);
14765
14766 Some(Bounds {
14767 origin: element_bounds.origin + point(x, y),
14768 size: size(em_width, line_height),
14769 })
14770 }
14771}
14772
14773trait SelectionExt {
14774 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14775 fn spanned_rows(
14776 &self,
14777 include_end_if_at_line_start: bool,
14778 map: &DisplaySnapshot,
14779 ) -> Range<MultiBufferRow>;
14780}
14781
14782impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14783 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14784 let start = self
14785 .start
14786 .to_point(&map.buffer_snapshot)
14787 .to_display_point(map);
14788 let end = self
14789 .end
14790 .to_point(&map.buffer_snapshot)
14791 .to_display_point(map);
14792 if self.reversed {
14793 end..start
14794 } else {
14795 start..end
14796 }
14797 }
14798
14799 fn spanned_rows(
14800 &self,
14801 include_end_if_at_line_start: bool,
14802 map: &DisplaySnapshot,
14803 ) -> Range<MultiBufferRow> {
14804 let start = self.start.to_point(&map.buffer_snapshot);
14805 let mut end = self.end.to_point(&map.buffer_snapshot);
14806 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14807 end.row -= 1;
14808 }
14809
14810 let buffer_start = map.prev_line_boundary(start).0;
14811 let buffer_end = map.next_line_boundary(end).0;
14812 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14813 }
14814}
14815
14816impl<T: InvalidationRegion> InvalidationStack<T> {
14817 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14818 where
14819 S: Clone + ToOffset,
14820 {
14821 while let Some(region) = self.last() {
14822 let all_selections_inside_invalidation_ranges =
14823 if selections.len() == region.ranges().len() {
14824 selections
14825 .iter()
14826 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14827 .all(|(selection, invalidation_range)| {
14828 let head = selection.head().to_offset(buffer);
14829 invalidation_range.start <= head && invalidation_range.end >= head
14830 })
14831 } else {
14832 false
14833 };
14834
14835 if all_selections_inside_invalidation_ranges {
14836 break;
14837 } else {
14838 self.pop();
14839 }
14840 }
14841 }
14842}
14843
14844impl<T> Default for InvalidationStack<T> {
14845 fn default() -> Self {
14846 Self(Default::default())
14847 }
14848}
14849
14850impl<T> Deref for InvalidationStack<T> {
14851 type Target = Vec<T>;
14852
14853 fn deref(&self) -> &Self::Target {
14854 &self.0
14855 }
14856}
14857
14858impl<T> DerefMut for InvalidationStack<T> {
14859 fn deref_mut(&mut self) -> &mut Self::Target {
14860 &mut self.0
14861 }
14862}
14863
14864impl InvalidationRegion for SnippetState {
14865 fn ranges(&self) -> &[Range<Anchor>] {
14866 &self.ranges[self.active_index]
14867 }
14868}
14869
14870pub fn diagnostic_block_renderer(
14871 diagnostic: Diagnostic,
14872 max_message_rows: Option<u8>,
14873 allow_closing: bool,
14874 _is_valid: bool,
14875) -> RenderBlock {
14876 let (text_without_backticks, code_ranges) =
14877 highlight_diagnostic_message(&diagnostic, max_message_rows);
14878
14879 Arc::new(move |cx: &mut BlockContext| {
14880 let group_id: SharedString = cx.block_id.to_string().into();
14881
14882 let mut text_style = cx.text_style().clone();
14883 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14884 let theme_settings = ThemeSettings::get_global(cx);
14885 text_style.font_family = theme_settings.buffer_font.family.clone();
14886 text_style.font_style = theme_settings.buffer_font.style;
14887 text_style.font_features = theme_settings.buffer_font.features.clone();
14888 text_style.font_weight = theme_settings.buffer_font.weight;
14889
14890 let multi_line_diagnostic = diagnostic.message.contains('\n');
14891
14892 let buttons = |diagnostic: &Diagnostic| {
14893 if multi_line_diagnostic {
14894 v_flex()
14895 } else {
14896 h_flex()
14897 }
14898 .when(allow_closing, |div| {
14899 div.children(diagnostic.is_primary.then(|| {
14900 IconButton::new("close-block", IconName::XCircle)
14901 .icon_color(Color::Muted)
14902 .size(ButtonSize::Compact)
14903 .style(ButtonStyle::Transparent)
14904 .visible_on_hover(group_id.clone())
14905 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14906 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14907 }))
14908 })
14909 .child(
14910 IconButton::new("copy-block", IconName::Copy)
14911 .icon_color(Color::Muted)
14912 .size(ButtonSize::Compact)
14913 .style(ButtonStyle::Transparent)
14914 .visible_on_hover(group_id.clone())
14915 .on_click({
14916 let message = diagnostic.message.clone();
14917 move |_click, cx| {
14918 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14919 }
14920 })
14921 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14922 )
14923 };
14924
14925 let icon_size = buttons(&diagnostic)
14926 .into_any_element()
14927 .layout_as_root(AvailableSpace::min_size(), cx);
14928
14929 h_flex()
14930 .id(cx.block_id)
14931 .group(group_id.clone())
14932 .relative()
14933 .size_full()
14934 .block_mouse_down()
14935 .pl(cx.gutter_dimensions.width)
14936 .w(cx.max_width - cx.gutter_dimensions.full_width())
14937 .child(
14938 div()
14939 .flex()
14940 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14941 .flex_shrink(),
14942 )
14943 .child(buttons(&diagnostic))
14944 .child(div().flex().flex_shrink_0().child(
14945 StyledText::new(text_without_backticks.clone()).with_highlights(
14946 &text_style,
14947 code_ranges.iter().map(|range| {
14948 (
14949 range.clone(),
14950 HighlightStyle {
14951 font_weight: Some(FontWeight::BOLD),
14952 ..Default::default()
14953 },
14954 )
14955 }),
14956 ),
14957 ))
14958 .into_any_element()
14959 })
14960}
14961
14962fn inline_completion_edit_text(
14963 editor_snapshot: &EditorSnapshot,
14964 edits: &Vec<(Range<Anchor>, String)>,
14965 include_deletions: bool,
14966 cx: &WindowContext,
14967) -> InlineCompletionText {
14968 let edit_start = edits
14969 .first()
14970 .unwrap()
14971 .0
14972 .start
14973 .to_display_point(editor_snapshot);
14974
14975 let mut text = String::new();
14976 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14977 let mut highlights = Vec::new();
14978 for (old_range, new_text) in edits {
14979 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14980 text.extend(
14981 editor_snapshot
14982 .buffer_snapshot
14983 .chunks(offset..old_offset_range.start, false)
14984 .map(|chunk| chunk.text),
14985 );
14986 offset = old_offset_range.end;
14987
14988 let start = text.len();
14989 let color = if include_deletions && new_text.is_empty() {
14990 text.extend(
14991 editor_snapshot
14992 .buffer_snapshot
14993 .chunks(old_offset_range.start..offset, false)
14994 .map(|chunk| chunk.text),
14995 );
14996 cx.theme().status().deleted_background
14997 } else {
14998 text.push_str(new_text);
14999 cx.theme().status().created_background
15000 };
15001 let end = text.len();
15002
15003 highlights.push((
15004 start..end,
15005 HighlightStyle {
15006 background_color: Some(color),
15007 ..Default::default()
15008 },
15009 ));
15010 }
15011
15012 let edit_end = edits
15013 .last()
15014 .unwrap()
15015 .0
15016 .end
15017 .to_display_point(editor_snapshot);
15018 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
15019 .to_offset(editor_snapshot, Bias::Right);
15020 text.extend(
15021 editor_snapshot
15022 .buffer_snapshot
15023 .chunks(offset..end_of_line, false)
15024 .map(|chunk| chunk.text),
15025 );
15026
15027 InlineCompletionText::Edit {
15028 text: text.into(),
15029 highlights,
15030 }
15031}
15032
15033pub fn highlight_diagnostic_message(
15034 diagnostic: &Diagnostic,
15035 mut max_message_rows: Option<u8>,
15036) -> (SharedString, Vec<Range<usize>>) {
15037 let mut text_without_backticks = String::new();
15038 let mut code_ranges = Vec::new();
15039
15040 if let Some(source) = &diagnostic.source {
15041 text_without_backticks.push_str(source);
15042 code_ranges.push(0..source.len());
15043 text_without_backticks.push_str(": ");
15044 }
15045
15046 let mut prev_offset = 0;
15047 let mut in_code_block = false;
15048 let has_row_limit = max_message_rows.is_some();
15049 let mut newline_indices = diagnostic
15050 .message
15051 .match_indices('\n')
15052 .filter(|_| has_row_limit)
15053 .map(|(ix, _)| ix)
15054 .fuse()
15055 .peekable();
15056
15057 for (quote_ix, _) in diagnostic
15058 .message
15059 .match_indices('`')
15060 .chain([(diagnostic.message.len(), "")])
15061 {
15062 let mut first_newline_ix = None;
15063 let mut last_newline_ix = None;
15064 while let Some(newline_ix) = newline_indices.peek() {
15065 if *newline_ix < quote_ix {
15066 if first_newline_ix.is_none() {
15067 first_newline_ix = Some(*newline_ix);
15068 }
15069 last_newline_ix = Some(*newline_ix);
15070
15071 if let Some(rows_left) = &mut max_message_rows {
15072 if *rows_left == 0 {
15073 break;
15074 } else {
15075 *rows_left -= 1;
15076 }
15077 }
15078 let _ = newline_indices.next();
15079 } else {
15080 break;
15081 }
15082 }
15083 let prev_len = text_without_backticks.len();
15084 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15085 text_without_backticks.push_str(new_text);
15086 if in_code_block {
15087 code_ranges.push(prev_len..text_without_backticks.len());
15088 }
15089 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15090 in_code_block = !in_code_block;
15091 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15092 text_without_backticks.push_str("...");
15093 break;
15094 }
15095 }
15096
15097 (text_without_backticks.into(), code_ranges)
15098}
15099
15100fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15101 match severity {
15102 DiagnosticSeverity::ERROR => colors.error,
15103 DiagnosticSeverity::WARNING => colors.warning,
15104 DiagnosticSeverity::INFORMATION => colors.info,
15105 DiagnosticSeverity::HINT => colors.info,
15106 _ => colors.ignored,
15107 }
15108}
15109
15110pub fn styled_runs_for_code_label<'a>(
15111 label: &'a CodeLabel,
15112 syntax_theme: &'a theme::SyntaxTheme,
15113) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15114 let fade_out = HighlightStyle {
15115 fade_out: Some(0.35),
15116 ..Default::default()
15117 };
15118
15119 let mut prev_end = label.filter_range.end;
15120 label
15121 .runs
15122 .iter()
15123 .enumerate()
15124 .flat_map(move |(ix, (range, highlight_id))| {
15125 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15126 style
15127 } else {
15128 return Default::default();
15129 };
15130 let mut muted_style = style;
15131 muted_style.highlight(fade_out);
15132
15133 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15134 if range.start >= label.filter_range.end {
15135 if range.start > prev_end {
15136 runs.push((prev_end..range.start, fade_out));
15137 }
15138 runs.push((range.clone(), muted_style));
15139 } else if range.end <= label.filter_range.end {
15140 runs.push((range.clone(), style));
15141 } else {
15142 runs.push((range.start..label.filter_range.end, style));
15143 runs.push((label.filter_range.end..range.end, muted_style));
15144 }
15145 prev_end = cmp::max(prev_end, range.end);
15146
15147 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15148 runs.push((prev_end..label.text.len(), fade_out));
15149 }
15150
15151 runs
15152 })
15153}
15154
15155pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15156 let mut prev_index = 0;
15157 let mut prev_codepoint: Option<char> = None;
15158 text.char_indices()
15159 .chain([(text.len(), '\0')])
15160 .filter_map(move |(index, codepoint)| {
15161 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15162 let is_boundary = index == text.len()
15163 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15164 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15165 if is_boundary {
15166 let chunk = &text[prev_index..index];
15167 prev_index = index;
15168 Some(chunk)
15169 } else {
15170 None
15171 }
15172 })
15173}
15174
15175pub trait RangeToAnchorExt: Sized {
15176 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15177
15178 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15179 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15180 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15181 }
15182}
15183
15184impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15185 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15186 let start_offset = self.start.to_offset(snapshot);
15187 let end_offset = self.end.to_offset(snapshot);
15188 if start_offset == end_offset {
15189 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15190 } else {
15191 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15192 }
15193 }
15194}
15195
15196pub trait RowExt {
15197 fn as_f32(&self) -> f32;
15198
15199 fn next_row(&self) -> Self;
15200
15201 fn previous_row(&self) -> Self;
15202
15203 fn minus(&self, other: Self) -> u32;
15204}
15205
15206impl RowExt for DisplayRow {
15207 fn as_f32(&self) -> f32 {
15208 self.0 as f32
15209 }
15210
15211 fn next_row(&self) -> Self {
15212 Self(self.0 + 1)
15213 }
15214
15215 fn previous_row(&self) -> Self {
15216 Self(self.0.saturating_sub(1))
15217 }
15218
15219 fn minus(&self, other: Self) -> u32 {
15220 self.0 - other.0
15221 }
15222}
15223
15224impl RowExt for MultiBufferRow {
15225 fn as_f32(&self) -> f32 {
15226 self.0 as f32
15227 }
15228
15229 fn next_row(&self) -> Self {
15230 Self(self.0 + 1)
15231 }
15232
15233 fn previous_row(&self) -> Self {
15234 Self(self.0.saturating_sub(1))
15235 }
15236
15237 fn minus(&self, other: Self) -> u32 {
15238 self.0 - other.0
15239 }
15240}
15241
15242trait RowRangeExt {
15243 type Row;
15244
15245 fn len(&self) -> usize;
15246
15247 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15248}
15249
15250impl RowRangeExt for Range<MultiBufferRow> {
15251 type Row = MultiBufferRow;
15252
15253 fn len(&self) -> usize {
15254 (self.end.0 - self.start.0) as usize
15255 }
15256
15257 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15258 (self.start.0..self.end.0).map(MultiBufferRow)
15259 }
15260}
15261
15262impl RowRangeExt for Range<DisplayRow> {
15263 type Row = DisplayRow;
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 = DisplayRow> {
15270 (self.start.0..self.end.0).map(DisplayRow)
15271 }
15272}
15273
15274fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15275 if hunk.diff_base_byte_range.is_empty() {
15276 DiffHunkStatus::Added
15277 } else if hunk.row_range.is_empty() {
15278 DiffHunkStatus::Removed
15279 } else {
15280 DiffHunkStatus::Modified
15281 }
15282}
15283
15284/// If select range has more than one line, we
15285/// just point the cursor to range.start.
15286fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15287 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15288 range
15289 } else {
15290 range.start..range.start
15291 }
15292}
15293pub struct KillRing(ClipboardItem);
15294impl Global for KillRing {}
15295
15296const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
15297
15298fn all_edits_insertions_or_deletions(
15299 edits: &Vec<(Range<Anchor>, String)>,
15300 snapshot: &MultiBufferSnapshot,
15301) -> bool {
15302 let mut all_insertions = true;
15303 let mut all_deletions = true;
15304
15305 for (range, new_text) in edits.iter() {
15306 let range_is_empty = range.to_offset(&snapshot).is_empty();
15307 let text_is_empty = new_text.is_empty();
15308
15309 if range_is_empty != text_is_empty {
15310 if range_is_empty {
15311 all_deletions = false;
15312 } else {
15313 all_insertions = false;
15314 }
15315 } else {
15316 return false;
15317 }
15318
15319 if !all_insertions && !all_deletions {
15320 return false;
15321 }
15322 }
15323 all_insertions || all_deletions
15324}