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
488enum InlineCompletion {
489 Edit(Vec<(Range<Anchor>, String)>),
490 Move(Anchor),
491}
492
493struct InlineCompletionState {
494 inlay_ids: Vec<InlayId>,
495 completion: InlineCompletion,
496 invalidation_range: Range<Anchor>,
497}
498
499enum InlineCompletionHighlight {}
500
501#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
502struct EditorActionId(usize);
503
504impl EditorActionId {
505 pub fn post_inc(&mut self) -> Self {
506 let answer = self.0;
507
508 *self = Self(answer + 1);
509
510 Self(answer)
511 }
512}
513
514// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
515// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
516
517type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
518type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
519
520#[derive(Default)]
521struct ScrollbarMarkerState {
522 scrollbar_size: Size<Pixels>,
523 dirty: bool,
524 markers: Arc<[PaintQuad]>,
525 pending_refresh: Option<Task<Result<()>>>,
526}
527
528impl ScrollbarMarkerState {
529 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
530 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
531 }
532}
533
534#[derive(Clone, Debug)]
535struct RunnableTasks {
536 templates: Vec<(TaskSourceKind, TaskTemplate)>,
537 offset: MultiBufferOffset,
538 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
539 column: u32,
540 // Values of all named captures, including those starting with '_'
541 extra_variables: HashMap<String, String>,
542 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
543 context_range: Range<BufferOffset>,
544}
545
546impl RunnableTasks {
547 fn resolve<'a>(
548 &'a self,
549 cx: &'a task::TaskContext,
550 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
551 self.templates.iter().filter_map(|(kind, template)| {
552 template
553 .resolve_task(&kind.to_id_base(), cx)
554 .map(|task| (kind.clone(), task))
555 })
556 }
557}
558
559#[derive(Clone)]
560struct ResolvedTasks {
561 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
562 position: Anchor,
563}
564#[derive(Copy, Clone, Debug)]
565struct MultiBufferOffset(usize);
566#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
567struct BufferOffset(usize);
568
569// Addons allow storing per-editor state in other crates (e.g. Vim)
570pub trait Addon: 'static {
571 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
572
573 fn to_any(&self) -> &dyn std::any::Any;
574}
575
576#[derive(Debug, Copy, Clone, PartialEq, Eq)]
577pub enum IsVimMode {
578 Yes,
579 No,
580}
581
582/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
583///
584/// See the [module level documentation](self) for more information.
585pub struct Editor {
586 focus_handle: FocusHandle,
587 last_focused_descendant: Option<WeakFocusHandle>,
588 /// The text buffer being edited
589 buffer: Model<MultiBuffer>,
590 /// Map of how text in the buffer should be displayed.
591 /// Handles soft wraps, folds, fake inlay text insertions, etc.
592 pub display_map: Model<DisplayMap>,
593 pub selections: SelectionsCollection,
594 pub scroll_manager: ScrollManager,
595 /// When inline assist editors are linked, they all render cursors because
596 /// typing enters text into each of them, even the ones that aren't focused.
597 pub(crate) show_cursor_when_unfocused: bool,
598 columnar_selection_tail: Option<Anchor>,
599 add_selections_state: Option<AddSelectionsState>,
600 select_next_state: Option<SelectNextState>,
601 select_prev_state: Option<SelectNextState>,
602 selection_history: SelectionHistory,
603 autoclose_regions: Vec<AutocloseRegion>,
604 snippet_stack: InvalidationStack<SnippetState>,
605 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
606 ime_transaction: Option<TransactionId>,
607 active_diagnostics: Option<ActiveDiagnosticGroup>,
608 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
609
610 project: Option<Model<Project>>,
611 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
612 completion_provider: Option<Box<dyn CompletionProvider>>,
613 collaboration_hub: Option<Box<dyn CollaborationHub>>,
614 blink_manager: Model<BlinkManager>,
615 show_cursor_names: bool,
616 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
617 pub show_local_selections: bool,
618 mode: EditorMode,
619 show_breadcrumbs: bool,
620 show_gutter: bool,
621 show_scrollbars: bool,
622 show_line_numbers: Option<bool>,
623 use_relative_line_numbers: Option<bool>,
624 show_git_diff_gutter: Option<bool>,
625 show_code_actions: Option<bool>,
626 show_runnables: Option<bool>,
627 show_wrap_guides: Option<bool>,
628 show_indent_guides: Option<bool>,
629 placeholder_text: Option<Arc<str>>,
630 highlight_order: usize,
631 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
632 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
633 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
634 scrollbar_marker_state: ScrollbarMarkerState,
635 active_indent_guides_state: ActiveIndentGuidesState,
636 nav_history: Option<ItemNavHistory>,
637 context_menu: RefCell<Option<CodeContextMenu>>,
638 mouse_context_menu: Option<MouseContextMenu>,
639 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
640 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
641 signature_help_state: SignatureHelpState,
642 auto_signature_help: Option<bool>,
643 find_all_references_task_sources: Vec<Anchor>,
644 next_completion_id: CompletionId,
645 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
646 code_actions_task: Option<Task<Result<()>>>,
647 document_highlights_task: Option<Task<()>>,
648 linked_editing_range_task: Option<Task<Option<()>>>,
649 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
650 pending_rename: Option<RenameState>,
651 searchable: bool,
652 cursor_shape: CursorShape,
653 current_line_highlight: Option<CurrentLineHighlight>,
654 collapse_matches: bool,
655 autoindent_mode: Option<AutoindentMode>,
656 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
657 input_enabled: bool,
658 use_modal_editing: bool,
659 read_only: bool,
660 leader_peer_id: Option<PeerId>,
661 remote_id: Option<ViewId>,
662 hover_state: HoverState,
663 gutter_hovered: bool,
664 hovered_link_state: Option<HoveredLinkState>,
665 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
666 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
667 active_inline_completion: Option<InlineCompletionState>,
668 // enable_inline_completions is a switch that Vim can use to disable
669 // inline completions based on its mode.
670 enable_inline_completions: bool,
671 show_inline_completions_override: Option<bool>,
672 inlay_hint_cache: InlayHintCache,
673 diff_map: DiffMap,
674 next_inlay_id: usize,
675 _subscriptions: Vec<Subscription>,
676 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
677 gutter_dimensions: GutterDimensions,
678 style: Option<EditorStyle>,
679 text_style_refinement: Option<TextStyleRefinement>,
680 next_editor_action_id: EditorActionId,
681 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
682 use_autoclose: bool,
683 use_auto_surround: bool,
684 auto_replace_emoji_shortcode: bool,
685 show_git_blame_gutter: bool,
686 show_git_blame_inline: bool,
687 show_git_blame_inline_delay_task: Option<Task<()>>,
688 git_blame_inline_enabled: bool,
689 serialize_dirty_buffers: bool,
690 show_selection_menu: Option<bool>,
691 blame: Option<Model<GitBlame>>,
692 blame_subscription: Option<Subscription>,
693 custom_context_menu: Option<
694 Box<
695 dyn 'static
696 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
697 >,
698 >,
699 last_bounds: Option<Bounds<Pixels>>,
700 expect_bounds_change: Option<Bounds<Pixels>>,
701 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
702 tasks_update_task: Option<Task<()>>,
703 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
704 breadcrumb_header: Option<String>,
705 focused_block: Option<FocusedBlock>,
706 next_scroll_position: NextScrollCursorCenterTopBottom,
707 addons: HashMap<TypeId, Box<dyn Addon>>,
708 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
709 selection_mark_mode: bool,
710 toggle_fold_multiple_buffers: Task<()>,
711 _scroll_cursor_center_top_bottom_task: Task<()>,
712}
713
714#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
715enum NextScrollCursorCenterTopBottom {
716 #[default]
717 Center,
718 Top,
719 Bottom,
720}
721
722impl NextScrollCursorCenterTopBottom {
723 fn next(&self) -> Self {
724 match self {
725 Self::Center => Self::Top,
726 Self::Top => Self::Bottom,
727 Self::Bottom => Self::Center,
728 }
729 }
730}
731
732#[derive(Clone)]
733pub struct EditorSnapshot {
734 pub mode: EditorMode,
735 show_gutter: bool,
736 show_line_numbers: Option<bool>,
737 show_git_diff_gutter: Option<bool>,
738 show_code_actions: Option<bool>,
739 show_runnables: Option<bool>,
740 git_blame_gutter_max_author_length: Option<usize>,
741 pub display_snapshot: DisplaySnapshot,
742 pub placeholder_text: Option<Arc<str>>,
743 diff_map: DiffMapSnapshot,
744 is_focused: bool,
745 scroll_anchor: ScrollAnchor,
746 ongoing_scroll: OngoingScroll,
747 current_line_highlight: CurrentLineHighlight,
748 gutter_hovered: bool,
749}
750
751const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
752
753#[derive(Default, Debug, Clone, Copy)]
754pub struct GutterDimensions {
755 pub left_padding: Pixels,
756 pub right_padding: Pixels,
757 pub width: Pixels,
758 pub margin: Pixels,
759 pub git_blame_entries_width: Option<Pixels>,
760}
761
762impl GutterDimensions {
763 /// The full width of the space taken up by the gutter.
764 pub fn full_width(&self) -> Pixels {
765 self.margin + self.width
766 }
767
768 /// The width of the space reserved for the fold indicators,
769 /// use alongside 'justify_end' and `gutter_width` to
770 /// right align content with the line numbers
771 pub fn fold_area_width(&self) -> Pixels {
772 self.margin + self.right_padding
773 }
774}
775
776#[derive(Debug)]
777pub struct RemoteSelection {
778 pub replica_id: ReplicaId,
779 pub selection: Selection<Anchor>,
780 pub cursor_shape: CursorShape,
781 pub peer_id: PeerId,
782 pub line_mode: bool,
783 pub participant_index: Option<ParticipantIndex>,
784 pub user_name: Option<SharedString>,
785}
786
787#[derive(Clone, Debug)]
788struct SelectionHistoryEntry {
789 selections: Arc<[Selection<Anchor>]>,
790 select_next_state: Option<SelectNextState>,
791 select_prev_state: Option<SelectNextState>,
792 add_selections_state: Option<AddSelectionsState>,
793}
794
795enum SelectionHistoryMode {
796 Normal,
797 Undoing,
798 Redoing,
799}
800
801#[derive(Clone, PartialEq, Eq, Hash)]
802struct HoveredCursor {
803 replica_id: u16,
804 selection_id: usize,
805}
806
807impl Default for SelectionHistoryMode {
808 fn default() -> Self {
809 Self::Normal
810 }
811}
812
813#[derive(Default)]
814struct SelectionHistory {
815 #[allow(clippy::type_complexity)]
816 selections_by_transaction:
817 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
818 mode: SelectionHistoryMode,
819 undo_stack: VecDeque<SelectionHistoryEntry>,
820 redo_stack: VecDeque<SelectionHistoryEntry>,
821}
822
823impl SelectionHistory {
824 fn insert_transaction(
825 &mut self,
826 transaction_id: TransactionId,
827 selections: Arc<[Selection<Anchor>]>,
828 ) {
829 self.selections_by_transaction
830 .insert(transaction_id, (selections, None));
831 }
832
833 #[allow(clippy::type_complexity)]
834 fn transaction(
835 &self,
836 transaction_id: TransactionId,
837 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
838 self.selections_by_transaction.get(&transaction_id)
839 }
840
841 #[allow(clippy::type_complexity)]
842 fn transaction_mut(
843 &mut self,
844 transaction_id: TransactionId,
845 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
846 self.selections_by_transaction.get_mut(&transaction_id)
847 }
848
849 fn push(&mut self, entry: SelectionHistoryEntry) {
850 if !entry.selections.is_empty() {
851 match self.mode {
852 SelectionHistoryMode::Normal => {
853 self.push_undo(entry);
854 self.redo_stack.clear();
855 }
856 SelectionHistoryMode::Undoing => self.push_redo(entry),
857 SelectionHistoryMode::Redoing => self.push_undo(entry),
858 }
859 }
860 }
861
862 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
863 if self
864 .undo_stack
865 .back()
866 .map_or(true, |e| e.selections != entry.selections)
867 {
868 self.undo_stack.push_back(entry);
869 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
870 self.undo_stack.pop_front();
871 }
872 }
873 }
874
875 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
876 if self
877 .redo_stack
878 .back()
879 .map_or(true, |e| e.selections != entry.selections)
880 {
881 self.redo_stack.push_back(entry);
882 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
883 self.redo_stack.pop_front();
884 }
885 }
886 }
887}
888
889struct RowHighlight {
890 index: usize,
891 range: Range<Anchor>,
892 color: Hsla,
893 should_autoscroll: bool,
894}
895
896#[derive(Clone, Debug)]
897struct AddSelectionsState {
898 above: bool,
899 stack: Vec<usize>,
900}
901
902#[derive(Clone)]
903struct SelectNextState {
904 query: AhoCorasick,
905 wordwise: bool,
906 done: bool,
907}
908
909impl std::fmt::Debug for SelectNextState {
910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
911 f.debug_struct(std::any::type_name::<Self>())
912 .field("wordwise", &self.wordwise)
913 .field("done", &self.done)
914 .finish()
915 }
916}
917
918#[derive(Debug)]
919struct AutocloseRegion {
920 selection_id: usize,
921 range: Range<Anchor>,
922 pair: BracketPair,
923}
924
925#[derive(Debug)]
926struct SnippetState {
927 ranges: Vec<Vec<Range<Anchor>>>,
928 active_index: usize,
929 choices: Vec<Option<Vec<String>>>,
930}
931
932#[doc(hidden)]
933pub struct RenameState {
934 pub range: Range<Anchor>,
935 pub old_name: Arc<str>,
936 pub editor: View<Editor>,
937 block_id: CustomBlockId,
938}
939
940struct InvalidationStack<T>(Vec<T>);
941
942struct RegisteredInlineCompletionProvider {
943 provider: Arc<dyn InlineCompletionProviderHandle>,
944 _subscription: Subscription,
945}
946
947#[derive(Debug)]
948struct ActiveDiagnosticGroup {
949 primary_range: Range<Anchor>,
950 primary_message: String,
951 group_id: usize,
952 blocks: HashMap<CustomBlockId, Diagnostic>,
953 is_valid: bool,
954}
955
956#[derive(Serialize, Deserialize, Clone, Debug)]
957pub struct ClipboardSelection {
958 pub len: usize,
959 pub is_entire_line: bool,
960 pub first_line_indent: u32,
961}
962
963#[derive(Debug)]
964pub(crate) struct NavigationData {
965 cursor_anchor: Anchor,
966 cursor_position: Point,
967 scroll_anchor: ScrollAnchor,
968 scroll_top_row: u32,
969}
970
971#[derive(Debug, Clone, Copy, PartialEq, Eq)]
972pub enum GotoDefinitionKind {
973 Symbol,
974 Declaration,
975 Type,
976 Implementation,
977}
978
979#[derive(Debug, Clone)]
980enum InlayHintRefreshReason {
981 Toggle(bool),
982 SettingsChange(InlayHintSettings),
983 NewLinesShown,
984 BufferEdited(HashSet<Arc<Language>>),
985 RefreshRequested,
986 ExcerptsRemoved(Vec<ExcerptId>),
987}
988
989impl InlayHintRefreshReason {
990 fn description(&self) -> &'static str {
991 match self {
992 Self::Toggle(_) => "toggle",
993 Self::SettingsChange(_) => "settings change",
994 Self::NewLinesShown => "new lines shown",
995 Self::BufferEdited(_) => "buffer edited",
996 Self::RefreshRequested => "refresh requested",
997 Self::ExcerptsRemoved(_) => "excerpts removed",
998 }
999 }
1000}
1001
1002pub enum FormatTarget {
1003 Buffers,
1004 Ranges(Vec<Range<MultiBufferPoint>>),
1005}
1006
1007pub(crate) struct FocusedBlock {
1008 id: BlockId,
1009 focus_handle: WeakFocusHandle,
1010}
1011
1012#[derive(Clone)]
1013enum JumpData {
1014 MultiBufferRow {
1015 row: MultiBufferRow,
1016 line_offset_from_top: u32,
1017 },
1018 MultiBufferPoint {
1019 excerpt_id: ExcerptId,
1020 position: Point,
1021 anchor: text::Anchor,
1022 line_offset_from_top: u32,
1023 },
1024}
1025
1026impl Editor {
1027 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1028 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1029 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1030 Self::new(
1031 EditorMode::SingleLine { auto_width: false },
1032 buffer,
1033 None,
1034 false,
1035 cx,
1036 )
1037 }
1038
1039 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1040 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1041 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1042 Self::new(EditorMode::Full, buffer, None, false, cx)
1043 }
1044
1045 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1046 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1047 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1048 Self::new(
1049 EditorMode::SingleLine { auto_width: true },
1050 buffer,
1051 None,
1052 false,
1053 cx,
1054 )
1055 }
1056
1057 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1058 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1059 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1060 Self::new(
1061 EditorMode::AutoHeight { max_lines },
1062 buffer,
1063 None,
1064 false,
1065 cx,
1066 )
1067 }
1068
1069 pub fn for_buffer(
1070 buffer: Model<Buffer>,
1071 project: Option<Model<Project>>,
1072 cx: &mut ViewContext<Self>,
1073 ) -> Self {
1074 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1075 Self::new(EditorMode::Full, buffer, project, false, cx)
1076 }
1077
1078 pub fn for_multibuffer(
1079 buffer: Model<MultiBuffer>,
1080 project: Option<Model<Project>>,
1081 show_excerpt_controls: bool,
1082 cx: &mut ViewContext<Self>,
1083 ) -> Self {
1084 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1085 }
1086
1087 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1088 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1089 let mut clone = Self::new(
1090 self.mode,
1091 self.buffer.clone(),
1092 self.project.clone(),
1093 show_excerpt_controls,
1094 cx,
1095 );
1096 self.display_map.update(cx, |display_map, cx| {
1097 let snapshot = display_map.snapshot(cx);
1098 clone.display_map.update(cx, |display_map, cx| {
1099 display_map.set_state(&snapshot, cx);
1100 });
1101 });
1102 clone.selections.clone_state(&self.selections);
1103 clone.scroll_manager.clone_state(&self.scroll_manager);
1104 clone.searchable = self.searchable;
1105 clone
1106 }
1107
1108 pub fn new(
1109 mode: EditorMode,
1110 buffer: Model<MultiBuffer>,
1111 project: Option<Model<Project>>,
1112 show_excerpt_controls: bool,
1113 cx: &mut ViewContext<Self>,
1114 ) -> Self {
1115 let style = cx.text_style();
1116 let font_size = style.font_size.to_pixels(cx.rem_size());
1117 let editor = cx.view().downgrade();
1118 let fold_placeholder = FoldPlaceholder {
1119 constrain_width: true,
1120 render: Arc::new(move |fold_id, fold_range, cx| {
1121 let editor = editor.clone();
1122 div()
1123 .id(fold_id)
1124 .bg(cx.theme().colors().ghost_element_background)
1125 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1126 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1127 .rounded_sm()
1128 .size_full()
1129 .cursor_pointer()
1130 .child("⋯")
1131 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1132 .on_click(move |_, cx| {
1133 editor
1134 .update(cx, |editor, cx| {
1135 editor.unfold_ranges(
1136 &[fold_range.start..fold_range.end],
1137 true,
1138 false,
1139 cx,
1140 );
1141 cx.stop_propagation();
1142 })
1143 .ok();
1144 })
1145 .into_any()
1146 }),
1147 merge_adjacent: true,
1148 ..Default::default()
1149 };
1150 let display_map = cx.new_model(|cx| {
1151 DisplayMap::new(
1152 buffer.clone(),
1153 style.font(),
1154 font_size,
1155 None,
1156 show_excerpt_controls,
1157 FILE_HEADER_HEIGHT,
1158 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1159 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1160 fold_placeholder,
1161 cx,
1162 )
1163 });
1164
1165 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1166
1167 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1168
1169 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1170 .then(|| language_settings::SoftWrap::None);
1171
1172 let mut project_subscriptions = Vec::new();
1173 if mode == EditorMode::Full {
1174 if let Some(project) = project.as_ref() {
1175 if buffer.read(cx).is_singleton() {
1176 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1177 cx.emit(EditorEvent::TitleChanged);
1178 }));
1179 }
1180 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1181 if let project::Event::RefreshInlayHints = event {
1182 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1183 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1184 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1185 let focus_handle = editor.focus_handle(cx);
1186 if focus_handle.is_focused(cx) {
1187 let snapshot = buffer.read(cx).snapshot();
1188 for (range, snippet) in snippet_edits {
1189 let editor_range =
1190 language::range_from_lsp(*range).to_offset(&snapshot);
1191 editor
1192 .insert_snippet(&[editor_range], snippet.clone(), cx)
1193 .ok();
1194 }
1195 }
1196 }
1197 }
1198 }));
1199 if let Some(task_inventory) = project
1200 .read(cx)
1201 .task_store()
1202 .read(cx)
1203 .task_inventory()
1204 .cloned()
1205 {
1206 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1207 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1208 }));
1209 }
1210 }
1211 }
1212
1213 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1214
1215 let inlay_hint_settings =
1216 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1217 let focus_handle = cx.focus_handle();
1218 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1219 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1220 .detach();
1221 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1222 .detach();
1223 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1224
1225 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1226 Some(false)
1227 } else {
1228 None
1229 };
1230
1231 let mut code_action_providers = Vec::new();
1232 if let Some(project) = project.clone() {
1233 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1234 code_action_providers.push(Rc::new(project) as Rc<_>);
1235 }
1236
1237 let mut this = Self {
1238 focus_handle,
1239 show_cursor_when_unfocused: false,
1240 last_focused_descendant: None,
1241 buffer: buffer.clone(),
1242 display_map: display_map.clone(),
1243 selections,
1244 scroll_manager: ScrollManager::new(cx),
1245 columnar_selection_tail: None,
1246 add_selections_state: None,
1247 select_next_state: None,
1248 select_prev_state: None,
1249 selection_history: Default::default(),
1250 autoclose_regions: Default::default(),
1251 snippet_stack: Default::default(),
1252 select_larger_syntax_node_stack: Vec::new(),
1253 ime_transaction: Default::default(),
1254 active_diagnostics: None,
1255 soft_wrap_mode_override,
1256 completion_provider: project.clone().map(|project| Box::new(project) as _),
1257 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1258 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1259 project,
1260 blink_manager: blink_manager.clone(),
1261 show_local_selections: true,
1262 show_scrollbars: true,
1263 mode,
1264 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1265 show_gutter: mode == EditorMode::Full,
1266 show_line_numbers: None,
1267 use_relative_line_numbers: None,
1268 show_git_diff_gutter: None,
1269 show_code_actions: None,
1270 show_runnables: None,
1271 show_wrap_guides: None,
1272 show_indent_guides,
1273 placeholder_text: None,
1274 highlight_order: 0,
1275 highlighted_rows: HashMap::default(),
1276 background_highlights: Default::default(),
1277 gutter_highlights: TreeMap::default(),
1278 scrollbar_marker_state: ScrollbarMarkerState::default(),
1279 active_indent_guides_state: ActiveIndentGuidesState::default(),
1280 nav_history: None,
1281 context_menu: RefCell::new(None),
1282 mouse_context_menu: None,
1283 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1284 completion_tasks: Default::default(),
1285 signature_help_state: SignatureHelpState::default(),
1286 auto_signature_help: None,
1287 find_all_references_task_sources: Vec::new(),
1288 next_completion_id: 0,
1289 next_inlay_id: 0,
1290 code_action_providers,
1291 available_code_actions: Default::default(),
1292 code_actions_task: Default::default(),
1293 document_highlights_task: Default::default(),
1294 linked_editing_range_task: Default::default(),
1295 pending_rename: Default::default(),
1296 searchable: true,
1297 cursor_shape: EditorSettings::get_global(cx)
1298 .cursor_shape
1299 .unwrap_or_default(),
1300 current_line_highlight: None,
1301 autoindent_mode: Some(AutoindentMode::EachLine),
1302 collapse_matches: false,
1303 workspace: None,
1304 input_enabled: true,
1305 use_modal_editing: mode == EditorMode::Full,
1306 read_only: false,
1307 use_autoclose: true,
1308 use_auto_surround: true,
1309 auto_replace_emoji_shortcode: false,
1310 leader_peer_id: None,
1311 remote_id: None,
1312 hover_state: Default::default(),
1313 hovered_link_state: Default::default(),
1314 inline_completion_provider: None,
1315 active_inline_completion: None,
1316 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1317 diff_map: DiffMap::default(),
1318 gutter_hovered: false,
1319 pixel_position_of_newest_cursor: None,
1320 last_bounds: None,
1321 expect_bounds_change: None,
1322 gutter_dimensions: GutterDimensions::default(),
1323 style: None,
1324 show_cursor_names: false,
1325 hovered_cursors: Default::default(),
1326 next_editor_action_id: EditorActionId::default(),
1327 editor_actions: Rc::default(),
1328 show_inline_completions_override: None,
1329 enable_inline_completions: true,
1330 custom_context_menu: None,
1331 show_git_blame_gutter: false,
1332 show_git_blame_inline: false,
1333 show_selection_menu: None,
1334 show_git_blame_inline_delay_task: None,
1335 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1336 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1337 .session
1338 .restore_unsaved_buffers,
1339 blame: None,
1340 blame_subscription: None,
1341 tasks: Default::default(),
1342 _subscriptions: vec![
1343 cx.observe(&buffer, Self::on_buffer_changed),
1344 cx.subscribe(&buffer, Self::on_buffer_event),
1345 cx.observe(&display_map, Self::on_display_map_changed),
1346 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1347 cx.observe_global::<SettingsStore>(Self::settings_changed),
1348 cx.observe_window_activation(|editor, cx| {
1349 let active = cx.is_window_active();
1350 editor.blink_manager.update(cx, |blink_manager, cx| {
1351 if active {
1352 blink_manager.enable(cx);
1353 } else {
1354 blink_manager.disable(cx);
1355 }
1356 });
1357 }),
1358 ],
1359 tasks_update_task: None,
1360 linked_edit_ranges: Default::default(),
1361 previous_search_ranges: None,
1362 breadcrumb_header: None,
1363 focused_block: None,
1364 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1365 addons: HashMap::default(),
1366 registered_buffers: HashMap::default(),
1367 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1368 selection_mark_mode: false,
1369 toggle_fold_multiple_buffers: Task::ready(()),
1370 text_style_refinement: None,
1371 };
1372 this.tasks_update_task = Some(this.refresh_runnables(cx));
1373 this._subscriptions.extend(project_subscriptions);
1374
1375 this.end_selection(cx);
1376 this.scroll_manager.show_scrollbar(cx);
1377
1378 if mode == EditorMode::Full {
1379 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1380 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1381
1382 if this.git_blame_inline_enabled {
1383 this.git_blame_inline_enabled = true;
1384 this.start_git_blame_inline(false, cx);
1385 }
1386
1387 if let Some(buffer) = buffer.read(cx).as_singleton() {
1388 if let Some(project) = this.project.as_ref() {
1389 let lsp_store = project.read(cx).lsp_store();
1390 let handle = lsp_store.update(cx, |lsp_store, cx| {
1391 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1392 });
1393 this.registered_buffers
1394 .insert(buffer.read(cx).remote_id(), handle);
1395 }
1396 }
1397 }
1398
1399 this.report_editor_event("Editor Opened", None, cx);
1400 this
1401 }
1402
1403 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1404 self.mouse_context_menu
1405 .as_ref()
1406 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1407 }
1408
1409 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1410 let mut key_context = KeyContext::new_with_defaults();
1411 key_context.add("Editor");
1412 let mode = match self.mode {
1413 EditorMode::SingleLine { .. } => "single_line",
1414 EditorMode::AutoHeight { .. } => "auto_height",
1415 EditorMode::Full => "full",
1416 };
1417
1418 if EditorSettings::jupyter_enabled(cx) {
1419 key_context.add("jupyter");
1420 }
1421
1422 key_context.set("mode", mode);
1423 if self.pending_rename.is_some() {
1424 key_context.add("renaming");
1425 }
1426 match self.context_menu.borrow().as_ref() {
1427 Some(CodeContextMenu::Completions(_)) => {
1428 key_context.add("menu");
1429 key_context.add("showing_completions")
1430 }
1431 Some(CodeContextMenu::CodeActions(_)) => {
1432 key_context.add("menu");
1433 key_context.add("showing_code_actions")
1434 }
1435 None => {}
1436 }
1437
1438 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1439 if !self.focus_handle(cx).contains_focused(cx)
1440 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1441 {
1442 for addon in self.addons.values() {
1443 addon.extend_key_context(&mut key_context, cx)
1444 }
1445 }
1446
1447 if let Some(extension) = self
1448 .buffer
1449 .read(cx)
1450 .as_singleton()
1451 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1452 {
1453 key_context.set("extension", extension.to_string());
1454 }
1455
1456 if self.has_active_inline_completion() {
1457 key_context.add("copilot_suggestion");
1458 key_context.add("inline_completion");
1459 }
1460
1461 if self.selection_mark_mode {
1462 key_context.add("selection_mode");
1463 }
1464
1465 key_context
1466 }
1467
1468 pub fn new_file(
1469 workspace: &mut Workspace,
1470 _: &workspace::NewFile,
1471 cx: &mut ViewContext<Workspace>,
1472 ) {
1473 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1474 "Failed to create buffer",
1475 cx,
1476 |e, _| match e.error_code() {
1477 ErrorCode::RemoteUpgradeRequired => Some(format!(
1478 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1479 e.error_tag("required").unwrap_or("the latest version")
1480 )),
1481 _ => None,
1482 },
1483 );
1484 }
1485
1486 pub fn new_in_workspace(
1487 workspace: &mut Workspace,
1488 cx: &mut ViewContext<Workspace>,
1489 ) -> Task<Result<View<Editor>>> {
1490 let project = workspace.project().clone();
1491 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1492
1493 cx.spawn(|workspace, mut cx| async move {
1494 let buffer = create.await?;
1495 workspace.update(&mut cx, |workspace, cx| {
1496 let editor =
1497 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1498 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1499 editor
1500 })
1501 })
1502 }
1503
1504 fn new_file_vertical(
1505 workspace: &mut Workspace,
1506 _: &workspace::NewFileSplitVertical,
1507 cx: &mut ViewContext<Workspace>,
1508 ) {
1509 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1510 }
1511
1512 fn new_file_horizontal(
1513 workspace: &mut Workspace,
1514 _: &workspace::NewFileSplitHorizontal,
1515 cx: &mut ViewContext<Workspace>,
1516 ) {
1517 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1518 }
1519
1520 fn new_file_in_direction(
1521 workspace: &mut Workspace,
1522 direction: SplitDirection,
1523 cx: &mut ViewContext<Workspace>,
1524 ) {
1525 let project = workspace.project().clone();
1526 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1527
1528 cx.spawn(|workspace, mut cx| async move {
1529 let buffer = create.await?;
1530 workspace.update(&mut cx, move |workspace, cx| {
1531 workspace.split_item(
1532 direction,
1533 Box::new(
1534 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1535 ),
1536 cx,
1537 )
1538 })?;
1539 anyhow::Ok(())
1540 })
1541 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1542 ErrorCode::RemoteUpgradeRequired => Some(format!(
1543 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1544 e.error_tag("required").unwrap_or("the latest version")
1545 )),
1546 _ => None,
1547 });
1548 }
1549
1550 pub fn leader_peer_id(&self) -> Option<PeerId> {
1551 self.leader_peer_id
1552 }
1553
1554 pub fn buffer(&self) -> &Model<MultiBuffer> {
1555 &self.buffer
1556 }
1557
1558 pub fn workspace(&self) -> Option<View<Workspace>> {
1559 self.workspace.as_ref()?.0.upgrade()
1560 }
1561
1562 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1563 self.buffer().read(cx).title(cx)
1564 }
1565
1566 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1567 let git_blame_gutter_max_author_length = self
1568 .render_git_blame_gutter(cx)
1569 .then(|| {
1570 if let Some(blame) = self.blame.as_ref() {
1571 let max_author_length =
1572 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1573 Some(max_author_length)
1574 } else {
1575 None
1576 }
1577 })
1578 .flatten();
1579
1580 EditorSnapshot {
1581 mode: self.mode,
1582 show_gutter: self.show_gutter,
1583 show_line_numbers: self.show_line_numbers,
1584 show_git_diff_gutter: self.show_git_diff_gutter,
1585 show_code_actions: self.show_code_actions,
1586 show_runnables: self.show_runnables,
1587 git_blame_gutter_max_author_length,
1588 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1589 scroll_anchor: self.scroll_manager.anchor(),
1590 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1591 placeholder_text: self.placeholder_text.clone(),
1592 diff_map: self.diff_map.snapshot(),
1593 is_focused: self.focus_handle.is_focused(cx),
1594 current_line_highlight: self
1595 .current_line_highlight
1596 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1597 gutter_hovered: self.gutter_hovered,
1598 }
1599 }
1600
1601 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1602 self.buffer.read(cx).language_at(point, cx)
1603 }
1604
1605 pub fn file_at<T: ToOffset>(
1606 &self,
1607 point: T,
1608 cx: &AppContext,
1609 ) -> Option<Arc<dyn language::File>> {
1610 self.buffer.read(cx).read(cx).file_at(point).cloned()
1611 }
1612
1613 pub fn active_excerpt(
1614 &self,
1615 cx: &AppContext,
1616 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1617 self.buffer
1618 .read(cx)
1619 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1620 }
1621
1622 pub fn mode(&self) -> EditorMode {
1623 self.mode
1624 }
1625
1626 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1627 self.collaboration_hub.as_deref()
1628 }
1629
1630 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1631 self.collaboration_hub = Some(hub);
1632 }
1633
1634 pub fn set_custom_context_menu(
1635 &mut self,
1636 f: impl 'static
1637 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1638 ) {
1639 self.custom_context_menu = Some(Box::new(f))
1640 }
1641
1642 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1643 self.completion_provider = provider;
1644 }
1645
1646 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1647 self.semantics_provider.clone()
1648 }
1649
1650 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1651 self.semantics_provider = provider;
1652 }
1653
1654 pub fn set_inline_completion_provider<T>(
1655 &mut self,
1656 provider: Option<Model<T>>,
1657 cx: &mut ViewContext<Self>,
1658 ) where
1659 T: InlineCompletionProvider,
1660 {
1661 self.inline_completion_provider =
1662 provider.map(|provider| RegisteredInlineCompletionProvider {
1663 _subscription: cx.observe(&provider, |this, _, cx| {
1664 if this.focus_handle.is_focused(cx) {
1665 this.update_visible_inline_completion(cx);
1666 }
1667 }),
1668 provider: Arc::new(provider),
1669 });
1670 self.refresh_inline_completion(false, false, cx);
1671 }
1672
1673 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1674 self.placeholder_text.as_deref()
1675 }
1676
1677 pub fn set_placeholder_text(
1678 &mut self,
1679 placeholder_text: impl Into<Arc<str>>,
1680 cx: &mut ViewContext<Self>,
1681 ) {
1682 let placeholder_text = Some(placeholder_text.into());
1683 if self.placeholder_text != placeholder_text {
1684 self.placeholder_text = placeholder_text;
1685 cx.notify();
1686 }
1687 }
1688
1689 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1690 self.cursor_shape = cursor_shape;
1691
1692 // Disrupt blink for immediate user feedback that the cursor shape has changed
1693 self.blink_manager.update(cx, BlinkManager::show_cursor);
1694
1695 cx.notify();
1696 }
1697
1698 pub fn set_current_line_highlight(
1699 &mut self,
1700 current_line_highlight: Option<CurrentLineHighlight>,
1701 ) {
1702 self.current_line_highlight = current_line_highlight;
1703 }
1704
1705 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1706 self.collapse_matches = collapse_matches;
1707 }
1708
1709 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1710 let buffers = self.buffer.read(cx).all_buffers();
1711 let Some(lsp_store) = self.lsp_store(cx) else {
1712 return;
1713 };
1714 lsp_store.update(cx, |lsp_store, cx| {
1715 for buffer in buffers {
1716 self.registered_buffers
1717 .entry(buffer.read(cx).remote_id())
1718 .or_insert_with(|| {
1719 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1720 });
1721 }
1722 })
1723 }
1724
1725 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1726 if self.collapse_matches {
1727 return range.start..range.start;
1728 }
1729 range.clone()
1730 }
1731
1732 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1733 if self.display_map.read(cx).clip_at_line_ends != clip {
1734 self.display_map
1735 .update(cx, |map, _| map.clip_at_line_ends = clip);
1736 }
1737 }
1738
1739 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1740 self.input_enabled = input_enabled;
1741 }
1742
1743 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1744 self.enable_inline_completions = enabled;
1745 if !self.enable_inline_completions {
1746 self.take_active_inline_completion(cx);
1747 cx.notify();
1748 }
1749 }
1750
1751 pub fn set_autoindent(&mut self, autoindent: bool) {
1752 if autoindent {
1753 self.autoindent_mode = Some(AutoindentMode::EachLine);
1754 } else {
1755 self.autoindent_mode = None;
1756 }
1757 }
1758
1759 pub fn read_only(&self, cx: &AppContext) -> bool {
1760 self.read_only || self.buffer.read(cx).read_only()
1761 }
1762
1763 pub fn set_read_only(&mut self, read_only: bool) {
1764 self.read_only = read_only;
1765 }
1766
1767 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1768 self.use_autoclose = autoclose;
1769 }
1770
1771 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1772 self.use_auto_surround = auto_surround;
1773 }
1774
1775 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1776 self.auto_replace_emoji_shortcode = auto_replace;
1777 }
1778
1779 pub fn toggle_inline_completions(
1780 &mut self,
1781 _: &ToggleInlineCompletions,
1782 cx: &mut ViewContext<Self>,
1783 ) {
1784 if self.show_inline_completions_override.is_some() {
1785 self.set_show_inline_completions(None, cx);
1786 } else {
1787 let cursor = self.selections.newest_anchor().head();
1788 if let Some((buffer, cursor_buffer_position)) =
1789 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1790 {
1791 let show_inline_completions =
1792 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1793 self.set_show_inline_completions(Some(show_inline_completions), cx);
1794 }
1795 }
1796 }
1797
1798 pub fn set_show_inline_completions(
1799 &mut self,
1800 show_inline_completions: Option<bool>,
1801 cx: &mut ViewContext<Self>,
1802 ) {
1803 self.show_inline_completions_override = show_inline_completions;
1804 self.refresh_inline_completion(false, true, cx);
1805 }
1806
1807 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1808 let cursor = self.selections.newest_anchor().head();
1809 if let Some((buffer, buffer_position)) =
1810 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1811 {
1812 self.should_show_inline_completions(&buffer, buffer_position, cx)
1813 } else {
1814 false
1815 }
1816 }
1817
1818 fn should_show_inline_completions(
1819 &self,
1820 buffer: &Model<Buffer>,
1821 buffer_position: language::Anchor,
1822 cx: &AppContext,
1823 ) -> bool {
1824 if !self.snippet_stack.is_empty() {
1825 return false;
1826 }
1827
1828 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1829 return false;
1830 }
1831
1832 if let Some(provider) = self.inline_completion_provider() {
1833 if let Some(show_inline_completions) = self.show_inline_completions_override {
1834 show_inline_completions
1835 } else {
1836 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1837 }
1838 } else {
1839 false
1840 }
1841 }
1842
1843 fn inline_completions_disabled_in_scope(
1844 &self,
1845 buffer: &Model<Buffer>,
1846 buffer_position: language::Anchor,
1847 cx: &AppContext,
1848 ) -> bool {
1849 let snapshot = buffer.read(cx).snapshot();
1850 let settings = snapshot.settings_at(buffer_position, cx);
1851
1852 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1853 return false;
1854 };
1855
1856 scope.override_name().map_or(false, |scope_name| {
1857 settings
1858 .inline_completions_disabled_in
1859 .iter()
1860 .any(|s| s == scope_name)
1861 })
1862 }
1863
1864 pub fn set_use_modal_editing(&mut self, to: bool) {
1865 self.use_modal_editing = to;
1866 }
1867
1868 pub fn use_modal_editing(&self) -> bool {
1869 self.use_modal_editing
1870 }
1871
1872 fn selections_did_change(
1873 &mut self,
1874 local: bool,
1875 old_cursor_position: &Anchor,
1876 show_completions: bool,
1877 cx: &mut ViewContext<Self>,
1878 ) {
1879 cx.invalidate_character_coordinates();
1880
1881 // Copy selections to primary selection buffer
1882 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1883 if local {
1884 let selections = self.selections.all::<usize>(cx);
1885 let buffer_handle = self.buffer.read(cx).read(cx);
1886
1887 let mut text = String::new();
1888 for (index, selection) in selections.iter().enumerate() {
1889 let text_for_selection = buffer_handle
1890 .text_for_range(selection.start..selection.end)
1891 .collect::<String>();
1892
1893 text.push_str(&text_for_selection);
1894 if index != selections.len() - 1 {
1895 text.push('\n');
1896 }
1897 }
1898
1899 if !text.is_empty() {
1900 cx.write_to_primary(ClipboardItem::new_string(text));
1901 }
1902 }
1903
1904 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1905 self.buffer.update(cx, |buffer, cx| {
1906 buffer.set_active_selections(
1907 &self.selections.disjoint_anchors(),
1908 self.selections.line_mode,
1909 self.cursor_shape,
1910 cx,
1911 )
1912 });
1913 }
1914 let display_map = self
1915 .display_map
1916 .update(cx, |display_map, cx| display_map.snapshot(cx));
1917 let buffer = &display_map.buffer_snapshot;
1918 self.add_selections_state = None;
1919 self.select_next_state = None;
1920 self.select_prev_state = None;
1921 self.select_larger_syntax_node_stack.clear();
1922 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1923 self.snippet_stack
1924 .invalidate(&self.selections.disjoint_anchors(), buffer);
1925 self.take_rename(false, cx);
1926
1927 let new_cursor_position = self.selections.newest_anchor().head();
1928
1929 self.push_to_nav_history(
1930 *old_cursor_position,
1931 Some(new_cursor_position.to_point(buffer)),
1932 cx,
1933 );
1934
1935 if local {
1936 let new_cursor_position = self.selections.newest_anchor().head();
1937 let mut context_menu = self.context_menu.borrow_mut();
1938 let completion_menu = match context_menu.as_ref() {
1939 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1940 _ => {
1941 *context_menu = None;
1942 None
1943 }
1944 };
1945
1946 if let Some(completion_menu) = completion_menu {
1947 let cursor_position = new_cursor_position.to_offset(buffer);
1948 let (word_range, kind) =
1949 buffer.surrounding_word(completion_menu.initial_position, true);
1950 if kind == Some(CharKind::Word)
1951 && word_range.to_inclusive().contains(&cursor_position)
1952 {
1953 let mut completion_menu = completion_menu.clone();
1954 drop(context_menu);
1955
1956 let query = Self::completion_query(buffer, cursor_position);
1957 cx.spawn(move |this, mut cx| async move {
1958 completion_menu
1959 .filter(query.as_deref(), cx.background_executor().clone())
1960 .await;
1961
1962 this.update(&mut cx, |this, cx| {
1963 let mut context_menu = this.context_menu.borrow_mut();
1964 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1965 else {
1966 return;
1967 };
1968
1969 if menu.id > completion_menu.id {
1970 return;
1971 }
1972
1973 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1974 drop(context_menu);
1975 cx.notify();
1976 })
1977 })
1978 .detach();
1979
1980 if show_completions {
1981 self.show_completions(&ShowCompletions { trigger: None }, cx);
1982 }
1983 } else {
1984 drop(context_menu);
1985 self.hide_context_menu(cx);
1986 }
1987 } else {
1988 drop(context_menu);
1989 }
1990
1991 hide_hover(self, cx);
1992
1993 if old_cursor_position.to_display_point(&display_map).row()
1994 != new_cursor_position.to_display_point(&display_map).row()
1995 {
1996 self.available_code_actions.take();
1997 }
1998 self.refresh_code_actions(cx);
1999 self.refresh_document_highlights(cx);
2000 refresh_matching_bracket_highlights(self, cx);
2001 self.update_visible_inline_completion(cx);
2002 linked_editing_ranges::refresh_linked_ranges(self, cx);
2003 if self.git_blame_inline_enabled {
2004 self.start_inline_blame_timer(cx);
2005 }
2006 }
2007
2008 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2009 cx.emit(EditorEvent::SelectionsChanged { local });
2010
2011 if self.selections.disjoint_anchors().len() == 1 {
2012 cx.emit(SearchEvent::ActiveMatchChanged)
2013 }
2014 cx.notify();
2015 }
2016
2017 pub fn change_selections<R>(
2018 &mut self,
2019 autoscroll: Option<Autoscroll>,
2020 cx: &mut ViewContext<Self>,
2021 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2022 ) -> R {
2023 self.change_selections_inner(autoscroll, true, cx, change)
2024 }
2025
2026 pub fn change_selections_inner<R>(
2027 &mut self,
2028 autoscroll: Option<Autoscroll>,
2029 request_completions: bool,
2030 cx: &mut ViewContext<Self>,
2031 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2032 ) -> R {
2033 let old_cursor_position = self.selections.newest_anchor().head();
2034 self.push_to_selection_history();
2035
2036 let (changed, result) = self.selections.change_with(cx, change);
2037
2038 if changed {
2039 if let Some(autoscroll) = autoscroll {
2040 self.request_autoscroll(autoscroll, cx);
2041 }
2042 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2043
2044 if self.should_open_signature_help_automatically(
2045 &old_cursor_position,
2046 self.signature_help_state.backspace_pressed(),
2047 cx,
2048 ) {
2049 self.show_signature_help(&ShowSignatureHelp, cx);
2050 }
2051 self.signature_help_state.set_backspace_pressed(false);
2052 }
2053
2054 result
2055 }
2056
2057 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2058 where
2059 I: IntoIterator<Item = (Range<S>, T)>,
2060 S: ToOffset,
2061 T: Into<Arc<str>>,
2062 {
2063 if self.read_only(cx) {
2064 return;
2065 }
2066
2067 self.buffer
2068 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2069 }
2070
2071 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2072 where
2073 I: IntoIterator<Item = (Range<S>, T)>,
2074 S: ToOffset,
2075 T: Into<Arc<str>>,
2076 {
2077 if self.read_only(cx) {
2078 return;
2079 }
2080
2081 self.buffer.update(cx, |buffer, cx| {
2082 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2083 });
2084 }
2085
2086 pub fn edit_with_block_indent<I, S, T>(
2087 &mut self,
2088 edits: I,
2089 original_indent_columns: Vec<u32>,
2090 cx: &mut ViewContext<Self>,
2091 ) where
2092 I: IntoIterator<Item = (Range<S>, T)>,
2093 S: ToOffset,
2094 T: Into<Arc<str>>,
2095 {
2096 if self.read_only(cx) {
2097 return;
2098 }
2099
2100 self.buffer.update(cx, |buffer, cx| {
2101 buffer.edit(
2102 edits,
2103 Some(AutoindentMode::Block {
2104 original_indent_columns,
2105 }),
2106 cx,
2107 )
2108 });
2109 }
2110
2111 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2112 self.hide_context_menu(cx);
2113
2114 match phase {
2115 SelectPhase::Begin {
2116 position,
2117 add,
2118 click_count,
2119 } => self.begin_selection(position, add, click_count, cx),
2120 SelectPhase::BeginColumnar {
2121 position,
2122 goal_column,
2123 reset,
2124 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2125 SelectPhase::Extend {
2126 position,
2127 click_count,
2128 } => self.extend_selection(position, click_count, cx),
2129 SelectPhase::Update {
2130 position,
2131 goal_column,
2132 scroll_delta,
2133 } => self.update_selection(position, goal_column, scroll_delta, cx),
2134 SelectPhase::End => self.end_selection(cx),
2135 }
2136 }
2137
2138 fn extend_selection(
2139 &mut self,
2140 position: DisplayPoint,
2141 click_count: usize,
2142 cx: &mut ViewContext<Self>,
2143 ) {
2144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2145 let tail = self.selections.newest::<usize>(cx).tail();
2146 self.begin_selection(position, false, click_count, cx);
2147
2148 let position = position.to_offset(&display_map, Bias::Left);
2149 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2150
2151 let mut pending_selection = self
2152 .selections
2153 .pending_anchor()
2154 .expect("extend_selection not called with pending selection");
2155 if position >= tail {
2156 pending_selection.start = tail_anchor;
2157 } else {
2158 pending_selection.end = tail_anchor;
2159 pending_selection.reversed = true;
2160 }
2161
2162 let mut pending_mode = self.selections.pending_mode().unwrap();
2163 match &mut pending_mode {
2164 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2165 _ => {}
2166 }
2167
2168 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2169 s.set_pending(pending_selection, pending_mode)
2170 });
2171 }
2172
2173 fn begin_selection(
2174 &mut self,
2175 position: DisplayPoint,
2176 add: bool,
2177 click_count: usize,
2178 cx: &mut ViewContext<Self>,
2179 ) {
2180 if !self.focus_handle.is_focused(cx) {
2181 self.last_focused_descendant = None;
2182 cx.focus(&self.focus_handle);
2183 }
2184
2185 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2186 let buffer = &display_map.buffer_snapshot;
2187 let newest_selection = self.selections.newest_anchor().clone();
2188 let position = display_map.clip_point(position, Bias::Left);
2189
2190 let start;
2191 let end;
2192 let mode;
2193 let mut auto_scroll;
2194 match click_count {
2195 1 => {
2196 start = buffer.anchor_before(position.to_point(&display_map));
2197 end = start;
2198 mode = SelectMode::Character;
2199 auto_scroll = true;
2200 }
2201 2 => {
2202 let range = movement::surrounding_word(&display_map, position);
2203 start = buffer.anchor_before(range.start.to_point(&display_map));
2204 end = buffer.anchor_before(range.end.to_point(&display_map));
2205 mode = SelectMode::Word(start..end);
2206 auto_scroll = true;
2207 }
2208 3 => {
2209 let position = display_map
2210 .clip_point(position, Bias::Left)
2211 .to_point(&display_map);
2212 let line_start = display_map.prev_line_boundary(position).0;
2213 let next_line_start = buffer.clip_point(
2214 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2215 Bias::Left,
2216 );
2217 start = buffer.anchor_before(line_start);
2218 end = buffer.anchor_before(next_line_start);
2219 mode = SelectMode::Line(start..end);
2220 auto_scroll = true;
2221 }
2222 _ => {
2223 start = buffer.anchor_before(0);
2224 end = buffer.anchor_before(buffer.len());
2225 mode = SelectMode::All;
2226 auto_scroll = false;
2227 }
2228 }
2229 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2230
2231 let point_to_delete: Option<usize> = {
2232 let selected_points: Vec<Selection<Point>> =
2233 self.selections.disjoint_in_range(start..end, cx);
2234
2235 if !add || click_count > 1 {
2236 None
2237 } else if !selected_points.is_empty() {
2238 Some(selected_points[0].id)
2239 } else {
2240 let clicked_point_already_selected =
2241 self.selections.disjoint.iter().find(|selection| {
2242 selection.start.to_point(buffer) == start.to_point(buffer)
2243 || selection.end.to_point(buffer) == end.to_point(buffer)
2244 });
2245
2246 clicked_point_already_selected.map(|selection| selection.id)
2247 }
2248 };
2249
2250 let selections_count = self.selections.count();
2251
2252 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2253 if let Some(point_to_delete) = point_to_delete {
2254 s.delete(point_to_delete);
2255
2256 if selections_count == 1 {
2257 s.set_pending_anchor_range(start..end, mode);
2258 }
2259 } else {
2260 if !add {
2261 s.clear_disjoint();
2262 } else if click_count > 1 {
2263 s.delete(newest_selection.id)
2264 }
2265
2266 s.set_pending_anchor_range(start..end, mode);
2267 }
2268 });
2269 }
2270
2271 fn begin_columnar_selection(
2272 &mut self,
2273 position: DisplayPoint,
2274 goal_column: u32,
2275 reset: bool,
2276 cx: &mut ViewContext<Self>,
2277 ) {
2278 if !self.focus_handle.is_focused(cx) {
2279 self.last_focused_descendant = None;
2280 cx.focus(&self.focus_handle);
2281 }
2282
2283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2284
2285 if reset {
2286 let pointer_position = display_map
2287 .buffer_snapshot
2288 .anchor_before(position.to_point(&display_map));
2289
2290 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2291 s.clear_disjoint();
2292 s.set_pending_anchor_range(
2293 pointer_position..pointer_position,
2294 SelectMode::Character,
2295 );
2296 });
2297 }
2298
2299 let tail = self.selections.newest::<Point>(cx).tail();
2300 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2301
2302 if !reset {
2303 self.select_columns(
2304 tail.to_display_point(&display_map),
2305 position,
2306 goal_column,
2307 &display_map,
2308 cx,
2309 );
2310 }
2311 }
2312
2313 fn update_selection(
2314 &mut self,
2315 position: DisplayPoint,
2316 goal_column: u32,
2317 scroll_delta: gpui::Point<f32>,
2318 cx: &mut ViewContext<Self>,
2319 ) {
2320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2321
2322 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2323 let tail = tail.to_display_point(&display_map);
2324 self.select_columns(tail, position, goal_column, &display_map, cx);
2325 } else if let Some(mut pending) = self.selections.pending_anchor() {
2326 let buffer = self.buffer.read(cx).snapshot(cx);
2327 let head;
2328 let tail;
2329 let mode = self.selections.pending_mode().unwrap();
2330 match &mode {
2331 SelectMode::Character => {
2332 head = position.to_point(&display_map);
2333 tail = pending.tail().to_point(&buffer);
2334 }
2335 SelectMode::Word(original_range) => {
2336 let original_display_range = original_range.start.to_display_point(&display_map)
2337 ..original_range.end.to_display_point(&display_map);
2338 let original_buffer_range = original_display_range.start.to_point(&display_map)
2339 ..original_display_range.end.to_point(&display_map);
2340 if movement::is_inside_word(&display_map, position)
2341 || original_display_range.contains(&position)
2342 {
2343 let word_range = movement::surrounding_word(&display_map, position);
2344 if word_range.start < original_display_range.start {
2345 head = word_range.start.to_point(&display_map);
2346 } else {
2347 head = word_range.end.to_point(&display_map);
2348 }
2349 } else {
2350 head = position.to_point(&display_map);
2351 }
2352
2353 if head <= original_buffer_range.start {
2354 tail = original_buffer_range.end;
2355 } else {
2356 tail = original_buffer_range.start;
2357 }
2358 }
2359 SelectMode::Line(original_range) => {
2360 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2361
2362 let position = display_map
2363 .clip_point(position, Bias::Left)
2364 .to_point(&display_map);
2365 let line_start = display_map.prev_line_boundary(position).0;
2366 let next_line_start = buffer.clip_point(
2367 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2368 Bias::Left,
2369 );
2370
2371 if line_start < original_range.start {
2372 head = line_start
2373 } else {
2374 head = next_line_start
2375 }
2376
2377 if head <= original_range.start {
2378 tail = original_range.end;
2379 } else {
2380 tail = original_range.start;
2381 }
2382 }
2383 SelectMode::All => {
2384 return;
2385 }
2386 };
2387
2388 if head < tail {
2389 pending.start = buffer.anchor_before(head);
2390 pending.end = buffer.anchor_before(tail);
2391 pending.reversed = true;
2392 } else {
2393 pending.start = buffer.anchor_before(tail);
2394 pending.end = buffer.anchor_before(head);
2395 pending.reversed = false;
2396 }
2397
2398 self.change_selections(None, cx, |s| {
2399 s.set_pending(pending, mode);
2400 });
2401 } else {
2402 log::error!("update_selection dispatched with no pending selection");
2403 return;
2404 }
2405
2406 self.apply_scroll_delta(scroll_delta, cx);
2407 cx.notify();
2408 }
2409
2410 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2411 self.columnar_selection_tail.take();
2412 if self.selections.pending_anchor().is_some() {
2413 let selections = self.selections.all::<usize>(cx);
2414 self.change_selections(None, cx, |s| {
2415 s.select(selections);
2416 s.clear_pending();
2417 });
2418 }
2419 }
2420
2421 fn select_columns(
2422 &mut self,
2423 tail: DisplayPoint,
2424 head: DisplayPoint,
2425 goal_column: u32,
2426 display_map: &DisplaySnapshot,
2427 cx: &mut ViewContext<Self>,
2428 ) {
2429 let start_row = cmp::min(tail.row(), head.row());
2430 let end_row = cmp::max(tail.row(), head.row());
2431 let start_column = cmp::min(tail.column(), goal_column);
2432 let end_column = cmp::max(tail.column(), goal_column);
2433 let reversed = start_column < tail.column();
2434
2435 let selection_ranges = (start_row.0..=end_row.0)
2436 .map(DisplayRow)
2437 .filter_map(|row| {
2438 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2439 let start = display_map
2440 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2441 .to_point(display_map);
2442 let end = display_map
2443 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2444 .to_point(display_map);
2445 if reversed {
2446 Some(end..start)
2447 } else {
2448 Some(start..end)
2449 }
2450 } else {
2451 None
2452 }
2453 })
2454 .collect::<Vec<_>>();
2455
2456 self.change_selections(None, cx, |s| {
2457 s.select_ranges(selection_ranges);
2458 });
2459 cx.notify();
2460 }
2461
2462 pub fn has_pending_nonempty_selection(&self) -> bool {
2463 let pending_nonempty_selection = match self.selections.pending_anchor() {
2464 Some(Selection { start, end, .. }) => start != end,
2465 None => false,
2466 };
2467
2468 pending_nonempty_selection
2469 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2470 }
2471
2472 pub fn has_pending_selection(&self) -> bool {
2473 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2474 }
2475
2476 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2477 self.selection_mark_mode = false;
2478
2479 if self.clear_expanded_diff_hunks(cx) {
2480 cx.notify();
2481 return;
2482 }
2483 if self.dismiss_menus_and_popups(true, cx) {
2484 return;
2485 }
2486
2487 if self.mode == EditorMode::Full
2488 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2489 {
2490 return;
2491 }
2492
2493 cx.propagate();
2494 }
2495
2496 pub fn dismiss_menus_and_popups(
2497 &mut self,
2498 should_report_inline_completion_event: bool,
2499 cx: &mut ViewContext<Self>,
2500 ) -> bool {
2501 if self.take_rename(false, cx).is_some() {
2502 return true;
2503 }
2504
2505 if hide_hover(self, cx) {
2506 return true;
2507 }
2508
2509 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2510 return true;
2511 }
2512
2513 if self.hide_context_menu(cx).is_some() {
2514 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2515 self.update_visible_inline_completion(cx);
2516 }
2517 return true;
2518 }
2519
2520 if self.mouse_context_menu.take().is_some() {
2521 return true;
2522 }
2523
2524 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2525 return true;
2526 }
2527
2528 if self.snippet_stack.pop().is_some() {
2529 return true;
2530 }
2531
2532 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2533 self.dismiss_diagnostics(cx);
2534 return true;
2535 }
2536
2537 false
2538 }
2539
2540 fn linked_editing_ranges_for(
2541 &self,
2542 selection: Range<text::Anchor>,
2543 cx: &AppContext,
2544 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2545 if self.linked_edit_ranges.is_empty() {
2546 return None;
2547 }
2548 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2549 selection.end.buffer_id.and_then(|end_buffer_id| {
2550 if selection.start.buffer_id != Some(end_buffer_id) {
2551 return None;
2552 }
2553 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2554 let snapshot = buffer.read(cx).snapshot();
2555 self.linked_edit_ranges
2556 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2557 .map(|ranges| (ranges, snapshot, buffer))
2558 })?;
2559 use text::ToOffset as TO;
2560 // find offset from the start of current range to current cursor position
2561 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2562
2563 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2564 let start_difference = start_offset - start_byte_offset;
2565 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2566 let end_difference = end_offset - start_byte_offset;
2567 // Current range has associated linked ranges.
2568 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2569 for range in linked_ranges.iter() {
2570 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2571 let end_offset = start_offset + end_difference;
2572 let start_offset = start_offset + start_difference;
2573 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2574 continue;
2575 }
2576 if self.selections.disjoint_anchor_ranges().any(|s| {
2577 if s.start.buffer_id != selection.start.buffer_id
2578 || s.end.buffer_id != selection.end.buffer_id
2579 {
2580 return false;
2581 }
2582 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2583 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2584 }) {
2585 continue;
2586 }
2587 let start = buffer_snapshot.anchor_after(start_offset);
2588 let end = buffer_snapshot.anchor_after(end_offset);
2589 linked_edits
2590 .entry(buffer.clone())
2591 .or_default()
2592 .push(start..end);
2593 }
2594 Some(linked_edits)
2595 }
2596
2597 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2598 let text: Arc<str> = text.into();
2599
2600 if self.read_only(cx) {
2601 return;
2602 }
2603
2604 let selections = self.selections.all_adjusted(cx);
2605 let mut bracket_inserted = false;
2606 let mut edits = Vec::new();
2607 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2608 let mut new_selections = Vec::with_capacity(selections.len());
2609 let mut new_autoclose_regions = Vec::new();
2610 let snapshot = self.buffer.read(cx).read(cx);
2611
2612 for (selection, autoclose_region) in
2613 self.selections_with_autoclose_regions(selections, &snapshot)
2614 {
2615 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2616 // Determine if the inserted text matches the opening or closing
2617 // bracket of any of this language's bracket pairs.
2618 let mut bracket_pair = None;
2619 let mut is_bracket_pair_start = false;
2620 let mut is_bracket_pair_end = false;
2621 if !text.is_empty() {
2622 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2623 // and they are removing the character that triggered IME popup.
2624 for (pair, enabled) in scope.brackets() {
2625 if !pair.close && !pair.surround {
2626 continue;
2627 }
2628
2629 if enabled && pair.start.ends_with(text.as_ref()) {
2630 let prefix_len = pair.start.len() - text.len();
2631 let preceding_text_matches_prefix = prefix_len == 0
2632 || (selection.start.column >= (prefix_len as u32)
2633 && snapshot.contains_str_at(
2634 Point::new(
2635 selection.start.row,
2636 selection.start.column - (prefix_len as u32),
2637 ),
2638 &pair.start[..prefix_len],
2639 ));
2640 if preceding_text_matches_prefix {
2641 bracket_pair = Some(pair.clone());
2642 is_bracket_pair_start = true;
2643 break;
2644 }
2645 }
2646 if pair.end.as_str() == text.as_ref() {
2647 bracket_pair = Some(pair.clone());
2648 is_bracket_pair_end = true;
2649 break;
2650 }
2651 }
2652 }
2653
2654 if let Some(bracket_pair) = bracket_pair {
2655 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2656 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2657 let auto_surround =
2658 self.use_auto_surround && snapshot_settings.use_auto_surround;
2659 if selection.is_empty() {
2660 if is_bracket_pair_start {
2661 // If the inserted text is a suffix of an opening bracket and the
2662 // selection is preceded by the rest of the opening bracket, then
2663 // insert the closing bracket.
2664 let following_text_allows_autoclose = snapshot
2665 .chars_at(selection.start)
2666 .next()
2667 .map_or(true, |c| scope.should_autoclose_before(c));
2668
2669 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2670 && bracket_pair.start.len() == 1
2671 {
2672 let target = bracket_pair.start.chars().next().unwrap();
2673 let current_line_count = snapshot
2674 .reversed_chars_at(selection.start)
2675 .take_while(|&c| c != '\n')
2676 .filter(|&c| c == target)
2677 .count();
2678 current_line_count % 2 == 1
2679 } else {
2680 false
2681 };
2682
2683 if autoclose
2684 && bracket_pair.close
2685 && following_text_allows_autoclose
2686 && !is_closing_quote
2687 {
2688 let anchor = snapshot.anchor_before(selection.end);
2689 new_selections.push((selection.map(|_| anchor), text.len()));
2690 new_autoclose_regions.push((
2691 anchor,
2692 text.len(),
2693 selection.id,
2694 bracket_pair.clone(),
2695 ));
2696 edits.push((
2697 selection.range(),
2698 format!("{}{}", text, bracket_pair.end).into(),
2699 ));
2700 bracket_inserted = true;
2701 continue;
2702 }
2703 }
2704
2705 if let Some(region) = autoclose_region {
2706 // If the selection is followed by an auto-inserted closing bracket,
2707 // then don't insert that closing bracket again; just move the selection
2708 // past the closing bracket.
2709 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2710 && text.as_ref() == region.pair.end.as_str();
2711 if should_skip {
2712 let anchor = snapshot.anchor_after(selection.end);
2713 new_selections
2714 .push((selection.map(|_| anchor), region.pair.end.len()));
2715 continue;
2716 }
2717 }
2718
2719 let always_treat_brackets_as_autoclosed = snapshot
2720 .settings_at(selection.start, cx)
2721 .always_treat_brackets_as_autoclosed;
2722 if always_treat_brackets_as_autoclosed
2723 && is_bracket_pair_end
2724 && snapshot.contains_str_at(selection.end, text.as_ref())
2725 {
2726 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2727 // and the inserted text is a closing bracket and the selection is followed
2728 // by the closing bracket then move the selection past the closing bracket.
2729 let anchor = snapshot.anchor_after(selection.end);
2730 new_selections.push((selection.map(|_| anchor), text.len()));
2731 continue;
2732 }
2733 }
2734 // If an opening bracket is 1 character long and is typed while
2735 // text is selected, then surround that text with the bracket pair.
2736 else if auto_surround
2737 && bracket_pair.surround
2738 && is_bracket_pair_start
2739 && bracket_pair.start.chars().count() == 1
2740 {
2741 edits.push((selection.start..selection.start, text.clone()));
2742 edits.push((
2743 selection.end..selection.end,
2744 bracket_pair.end.as_str().into(),
2745 ));
2746 bracket_inserted = true;
2747 new_selections.push((
2748 Selection {
2749 id: selection.id,
2750 start: snapshot.anchor_after(selection.start),
2751 end: snapshot.anchor_before(selection.end),
2752 reversed: selection.reversed,
2753 goal: selection.goal,
2754 },
2755 0,
2756 ));
2757 continue;
2758 }
2759 }
2760 }
2761
2762 if self.auto_replace_emoji_shortcode
2763 && selection.is_empty()
2764 && text.as_ref().ends_with(':')
2765 {
2766 if let Some(possible_emoji_short_code) =
2767 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2768 {
2769 if !possible_emoji_short_code.is_empty() {
2770 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2771 let emoji_shortcode_start = Point::new(
2772 selection.start.row,
2773 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2774 );
2775
2776 // Remove shortcode from buffer
2777 edits.push((
2778 emoji_shortcode_start..selection.start,
2779 "".to_string().into(),
2780 ));
2781 new_selections.push((
2782 Selection {
2783 id: selection.id,
2784 start: snapshot.anchor_after(emoji_shortcode_start),
2785 end: snapshot.anchor_before(selection.start),
2786 reversed: selection.reversed,
2787 goal: selection.goal,
2788 },
2789 0,
2790 ));
2791
2792 // Insert emoji
2793 let selection_start_anchor = snapshot.anchor_after(selection.start);
2794 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2795 edits.push((selection.start..selection.end, emoji.to_string().into()));
2796
2797 continue;
2798 }
2799 }
2800 }
2801 }
2802
2803 // If not handling any auto-close operation, then just replace the selected
2804 // text with the given input and move the selection to the end of the
2805 // newly inserted text.
2806 let anchor = snapshot.anchor_after(selection.end);
2807 if !self.linked_edit_ranges.is_empty() {
2808 let start_anchor = snapshot.anchor_before(selection.start);
2809
2810 let is_word_char = text.chars().next().map_or(true, |char| {
2811 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2812 classifier.is_word(char)
2813 });
2814
2815 if is_word_char {
2816 if let Some(ranges) = self
2817 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2818 {
2819 for (buffer, edits) in ranges {
2820 linked_edits
2821 .entry(buffer.clone())
2822 .or_default()
2823 .extend(edits.into_iter().map(|range| (range, text.clone())));
2824 }
2825 }
2826 }
2827 }
2828
2829 new_selections.push((selection.map(|_| anchor), 0));
2830 edits.push((selection.start..selection.end, text.clone()));
2831 }
2832
2833 drop(snapshot);
2834
2835 self.transact(cx, |this, cx| {
2836 this.buffer.update(cx, |buffer, cx| {
2837 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2838 });
2839 for (buffer, edits) in linked_edits {
2840 buffer.update(cx, |buffer, cx| {
2841 let snapshot = buffer.snapshot();
2842 let edits = edits
2843 .into_iter()
2844 .map(|(range, text)| {
2845 use text::ToPoint as TP;
2846 let end_point = TP::to_point(&range.end, &snapshot);
2847 let start_point = TP::to_point(&range.start, &snapshot);
2848 (start_point..end_point, text)
2849 })
2850 .sorted_by_key(|(range, _)| range.start)
2851 .collect::<Vec<_>>();
2852 buffer.edit(edits, None, cx);
2853 })
2854 }
2855 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2856 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2857 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2858 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2859 .zip(new_selection_deltas)
2860 .map(|(selection, delta)| Selection {
2861 id: selection.id,
2862 start: selection.start + delta,
2863 end: selection.end + delta,
2864 reversed: selection.reversed,
2865 goal: SelectionGoal::None,
2866 })
2867 .collect::<Vec<_>>();
2868
2869 let mut i = 0;
2870 for (position, delta, selection_id, pair) in new_autoclose_regions {
2871 let position = position.to_offset(&map.buffer_snapshot) + delta;
2872 let start = map.buffer_snapshot.anchor_before(position);
2873 let end = map.buffer_snapshot.anchor_after(position);
2874 while let Some(existing_state) = this.autoclose_regions.get(i) {
2875 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2876 Ordering::Less => i += 1,
2877 Ordering::Greater => break,
2878 Ordering::Equal => {
2879 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2880 Ordering::Less => i += 1,
2881 Ordering::Equal => break,
2882 Ordering::Greater => break,
2883 }
2884 }
2885 }
2886 }
2887 this.autoclose_regions.insert(
2888 i,
2889 AutocloseRegion {
2890 selection_id,
2891 range: start..end,
2892 pair,
2893 },
2894 );
2895 }
2896
2897 let had_active_inline_completion = this.has_active_inline_completion();
2898 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2899 s.select(new_selections)
2900 });
2901
2902 if !bracket_inserted {
2903 if let Some(on_type_format_task) =
2904 this.trigger_on_type_formatting(text.to_string(), cx)
2905 {
2906 on_type_format_task.detach_and_log_err(cx);
2907 }
2908 }
2909
2910 let editor_settings = EditorSettings::get_global(cx);
2911 if bracket_inserted
2912 && (editor_settings.auto_signature_help
2913 || editor_settings.show_signature_help_after_edits)
2914 {
2915 this.show_signature_help(&ShowSignatureHelp, cx);
2916 }
2917
2918 let trigger_in_words =
2919 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2920 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2921 linked_editing_ranges::refresh_linked_ranges(this, cx);
2922 this.refresh_inline_completion(true, false, cx);
2923 });
2924 }
2925
2926 fn find_possible_emoji_shortcode_at_position(
2927 snapshot: &MultiBufferSnapshot,
2928 position: Point,
2929 ) -> Option<String> {
2930 let mut chars = Vec::new();
2931 let mut found_colon = false;
2932 for char in snapshot.reversed_chars_at(position).take(100) {
2933 // Found a possible emoji shortcode in the middle of the buffer
2934 if found_colon {
2935 if char.is_whitespace() {
2936 chars.reverse();
2937 return Some(chars.iter().collect());
2938 }
2939 // If the previous character is not a whitespace, we are in the middle of a word
2940 // and we only want to complete the shortcode if the word is made up of other emojis
2941 let mut containing_word = String::new();
2942 for ch in snapshot
2943 .reversed_chars_at(position)
2944 .skip(chars.len() + 1)
2945 .take(100)
2946 {
2947 if ch.is_whitespace() {
2948 break;
2949 }
2950 containing_word.push(ch);
2951 }
2952 let containing_word = containing_word.chars().rev().collect::<String>();
2953 if util::word_consists_of_emojis(containing_word.as_str()) {
2954 chars.reverse();
2955 return Some(chars.iter().collect());
2956 }
2957 }
2958
2959 if char.is_whitespace() || !char.is_ascii() {
2960 return None;
2961 }
2962 if char == ':' {
2963 found_colon = true;
2964 } else {
2965 chars.push(char);
2966 }
2967 }
2968 // Found a possible emoji shortcode at the beginning of the buffer
2969 chars.reverse();
2970 Some(chars.iter().collect())
2971 }
2972
2973 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2974 self.transact(cx, |this, cx| {
2975 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2976 let selections = this.selections.all::<usize>(cx);
2977 let multi_buffer = this.buffer.read(cx);
2978 let buffer = multi_buffer.snapshot(cx);
2979 selections
2980 .iter()
2981 .map(|selection| {
2982 let start_point = selection.start.to_point(&buffer);
2983 let mut indent =
2984 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2985 indent.len = cmp::min(indent.len, start_point.column);
2986 let start = selection.start;
2987 let end = selection.end;
2988 let selection_is_empty = start == end;
2989 let language_scope = buffer.language_scope_at(start);
2990 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2991 &language_scope
2992 {
2993 let leading_whitespace_len = buffer
2994 .reversed_chars_at(start)
2995 .take_while(|c| c.is_whitespace() && *c != '\n')
2996 .map(|c| c.len_utf8())
2997 .sum::<usize>();
2998
2999 let trailing_whitespace_len = buffer
3000 .chars_at(end)
3001 .take_while(|c| c.is_whitespace() && *c != '\n')
3002 .map(|c| c.len_utf8())
3003 .sum::<usize>();
3004
3005 let insert_extra_newline =
3006 language.brackets().any(|(pair, enabled)| {
3007 let pair_start = pair.start.trim_end();
3008 let pair_end = pair.end.trim_start();
3009
3010 enabled
3011 && pair.newline
3012 && buffer.contains_str_at(
3013 end + trailing_whitespace_len,
3014 pair_end,
3015 )
3016 && buffer.contains_str_at(
3017 (start - leading_whitespace_len)
3018 .saturating_sub(pair_start.len()),
3019 pair_start,
3020 )
3021 });
3022
3023 // Comment extension on newline is allowed only for cursor selections
3024 let comment_delimiter = maybe!({
3025 if !selection_is_empty {
3026 return None;
3027 }
3028
3029 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3030 return None;
3031 }
3032
3033 let delimiters = language.line_comment_prefixes();
3034 let max_len_of_delimiter =
3035 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3036 let (snapshot, range) =
3037 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3038
3039 let mut index_of_first_non_whitespace = 0;
3040 let comment_candidate = snapshot
3041 .chars_for_range(range)
3042 .skip_while(|c| {
3043 let should_skip = c.is_whitespace();
3044 if should_skip {
3045 index_of_first_non_whitespace += 1;
3046 }
3047 should_skip
3048 })
3049 .take(max_len_of_delimiter)
3050 .collect::<String>();
3051 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3052 comment_candidate.starts_with(comment_prefix.as_ref())
3053 })?;
3054 let cursor_is_placed_after_comment_marker =
3055 index_of_first_non_whitespace + comment_prefix.len()
3056 <= start_point.column as usize;
3057 if cursor_is_placed_after_comment_marker {
3058 Some(comment_prefix.clone())
3059 } else {
3060 None
3061 }
3062 });
3063 (comment_delimiter, insert_extra_newline)
3064 } else {
3065 (None, false)
3066 };
3067
3068 let capacity_for_delimiter = comment_delimiter
3069 .as_deref()
3070 .map(str::len)
3071 .unwrap_or_default();
3072 let mut new_text =
3073 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3074 new_text.push('\n');
3075 new_text.extend(indent.chars());
3076 if let Some(delimiter) = &comment_delimiter {
3077 new_text.push_str(delimiter);
3078 }
3079 if insert_extra_newline {
3080 new_text = new_text.repeat(2);
3081 }
3082
3083 let anchor = buffer.anchor_after(end);
3084 let new_selection = selection.map(|_| anchor);
3085 (
3086 (start..end, new_text),
3087 (insert_extra_newline, new_selection),
3088 )
3089 })
3090 .unzip()
3091 };
3092
3093 this.edit_with_autoindent(edits, cx);
3094 let buffer = this.buffer.read(cx).snapshot(cx);
3095 let new_selections = selection_fixup_info
3096 .into_iter()
3097 .map(|(extra_newline_inserted, new_selection)| {
3098 let mut cursor = new_selection.end.to_point(&buffer);
3099 if extra_newline_inserted {
3100 cursor.row -= 1;
3101 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3102 }
3103 new_selection.map(|_| cursor)
3104 })
3105 .collect();
3106
3107 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3108 this.refresh_inline_completion(true, false, cx);
3109 });
3110 }
3111
3112 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3113 let buffer = self.buffer.read(cx);
3114 let snapshot = buffer.snapshot(cx);
3115
3116 let mut edits = Vec::new();
3117 let mut rows = Vec::new();
3118
3119 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3120 let cursor = selection.head();
3121 let row = cursor.row;
3122
3123 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3124
3125 let newline = "\n".to_string();
3126 edits.push((start_of_line..start_of_line, newline));
3127
3128 rows.push(row + rows_inserted as u32);
3129 }
3130
3131 self.transact(cx, |editor, cx| {
3132 editor.edit(edits, cx);
3133
3134 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3135 let mut index = 0;
3136 s.move_cursors_with(|map, _, _| {
3137 let row = rows[index];
3138 index += 1;
3139
3140 let point = Point::new(row, 0);
3141 let boundary = map.next_line_boundary(point).1;
3142 let clipped = map.clip_point(boundary, Bias::Left);
3143
3144 (clipped, SelectionGoal::None)
3145 });
3146 });
3147
3148 let mut indent_edits = Vec::new();
3149 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3150 for row in rows {
3151 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3152 for (row, indent) in indents {
3153 if indent.len == 0 {
3154 continue;
3155 }
3156
3157 let text = match indent.kind {
3158 IndentKind::Space => " ".repeat(indent.len as usize),
3159 IndentKind::Tab => "\t".repeat(indent.len as usize),
3160 };
3161 let point = Point::new(row.0, 0);
3162 indent_edits.push((point..point, text));
3163 }
3164 }
3165 editor.edit(indent_edits, cx);
3166 });
3167 }
3168
3169 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3170 let buffer = self.buffer.read(cx);
3171 let snapshot = buffer.snapshot(cx);
3172
3173 let mut edits = Vec::new();
3174 let mut rows = Vec::new();
3175 let mut rows_inserted = 0;
3176
3177 for selection in self.selections.all_adjusted(cx) {
3178 let cursor = selection.head();
3179 let row = cursor.row;
3180
3181 let point = Point::new(row + 1, 0);
3182 let start_of_line = snapshot.clip_point(point, Bias::Left);
3183
3184 let newline = "\n".to_string();
3185 edits.push((start_of_line..start_of_line, newline));
3186
3187 rows_inserted += 1;
3188 rows.push(row + rows_inserted);
3189 }
3190
3191 self.transact(cx, |editor, cx| {
3192 editor.edit(edits, cx);
3193
3194 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3195 let mut index = 0;
3196 s.move_cursors_with(|map, _, _| {
3197 let row = rows[index];
3198 index += 1;
3199
3200 let point = Point::new(row, 0);
3201 let boundary = map.next_line_boundary(point).1;
3202 let clipped = map.clip_point(boundary, Bias::Left);
3203
3204 (clipped, SelectionGoal::None)
3205 });
3206 });
3207
3208 let mut indent_edits = Vec::new();
3209 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3210 for row in rows {
3211 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3212 for (row, indent) in indents {
3213 if indent.len == 0 {
3214 continue;
3215 }
3216
3217 let text = match indent.kind {
3218 IndentKind::Space => " ".repeat(indent.len as usize),
3219 IndentKind::Tab => "\t".repeat(indent.len as usize),
3220 };
3221 let point = Point::new(row.0, 0);
3222 indent_edits.push((point..point, text));
3223 }
3224 }
3225 editor.edit(indent_edits, cx);
3226 });
3227 }
3228
3229 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3230 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3231 original_indent_columns: Vec::new(),
3232 });
3233 self.insert_with_autoindent_mode(text, autoindent, cx);
3234 }
3235
3236 fn insert_with_autoindent_mode(
3237 &mut self,
3238 text: &str,
3239 autoindent_mode: Option<AutoindentMode>,
3240 cx: &mut ViewContext<Self>,
3241 ) {
3242 if self.read_only(cx) {
3243 return;
3244 }
3245
3246 let text: Arc<str> = text.into();
3247 self.transact(cx, |this, cx| {
3248 let old_selections = this.selections.all_adjusted(cx);
3249 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3250 let anchors = {
3251 let snapshot = buffer.read(cx);
3252 old_selections
3253 .iter()
3254 .map(|s| {
3255 let anchor = snapshot.anchor_after(s.head());
3256 s.map(|_| anchor)
3257 })
3258 .collect::<Vec<_>>()
3259 };
3260 buffer.edit(
3261 old_selections
3262 .iter()
3263 .map(|s| (s.start..s.end, text.clone())),
3264 autoindent_mode,
3265 cx,
3266 );
3267 anchors
3268 });
3269
3270 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3271 s.select_anchors(selection_anchors);
3272 })
3273 });
3274 }
3275
3276 fn trigger_completion_on_input(
3277 &mut self,
3278 text: &str,
3279 trigger_in_words: bool,
3280 cx: &mut ViewContext<Self>,
3281 ) {
3282 if self.is_completion_trigger(text, trigger_in_words, cx) {
3283 self.show_completions(
3284 &ShowCompletions {
3285 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3286 },
3287 cx,
3288 );
3289 } else {
3290 self.hide_context_menu(cx);
3291 }
3292 }
3293
3294 fn is_completion_trigger(
3295 &self,
3296 text: &str,
3297 trigger_in_words: bool,
3298 cx: &mut ViewContext<Self>,
3299 ) -> bool {
3300 let position = self.selections.newest_anchor().head();
3301 let multibuffer = self.buffer.read(cx);
3302 let Some(buffer) = position
3303 .buffer_id
3304 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3305 else {
3306 return false;
3307 };
3308
3309 if let Some(completion_provider) = &self.completion_provider {
3310 completion_provider.is_completion_trigger(
3311 &buffer,
3312 position.text_anchor,
3313 text,
3314 trigger_in_words,
3315 cx,
3316 )
3317 } else {
3318 false
3319 }
3320 }
3321
3322 /// If any empty selections is touching the start of its innermost containing autoclose
3323 /// region, expand it to select the brackets.
3324 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3325 let selections = self.selections.all::<usize>(cx);
3326 let buffer = self.buffer.read(cx).read(cx);
3327 let new_selections = self
3328 .selections_with_autoclose_regions(selections, &buffer)
3329 .map(|(mut selection, region)| {
3330 if !selection.is_empty() {
3331 return selection;
3332 }
3333
3334 if let Some(region) = region {
3335 let mut range = region.range.to_offset(&buffer);
3336 if selection.start == range.start && range.start >= region.pair.start.len() {
3337 range.start -= region.pair.start.len();
3338 if buffer.contains_str_at(range.start, ®ion.pair.start)
3339 && buffer.contains_str_at(range.end, ®ion.pair.end)
3340 {
3341 range.end += region.pair.end.len();
3342 selection.start = range.start;
3343 selection.end = range.end;
3344
3345 return selection;
3346 }
3347 }
3348 }
3349
3350 let always_treat_brackets_as_autoclosed = buffer
3351 .settings_at(selection.start, cx)
3352 .always_treat_brackets_as_autoclosed;
3353
3354 if !always_treat_brackets_as_autoclosed {
3355 return selection;
3356 }
3357
3358 if let Some(scope) = buffer.language_scope_at(selection.start) {
3359 for (pair, enabled) in scope.brackets() {
3360 if !enabled || !pair.close {
3361 continue;
3362 }
3363
3364 if buffer.contains_str_at(selection.start, &pair.end) {
3365 let pair_start_len = pair.start.len();
3366 if buffer.contains_str_at(
3367 selection.start.saturating_sub(pair_start_len),
3368 &pair.start,
3369 ) {
3370 selection.start -= pair_start_len;
3371 selection.end += pair.end.len();
3372
3373 return selection;
3374 }
3375 }
3376 }
3377 }
3378
3379 selection
3380 })
3381 .collect();
3382
3383 drop(buffer);
3384 self.change_selections(None, cx, |selections| selections.select(new_selections));
3385 }
3386
3387 /// Iterate the given selections, and for each one, find the smallest surrounding
3388 /// autoclose region. This uses the ordering of the selections and the autoclose
3389 /// regions to avoid repeated comparisons.
3390 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3391 &'a self,
3392 selections: impl IntoIterator<Item = Selection<D>>,
3393 buffer: &'a MultiBufferSnapshot,
3394 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3395 let mut i = 0;
3396 let mut regions = self.autoclose_regions.as_slice();
3397 selections.into_iter().map(move |selection| {
3398 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3399
3400 let mut enclosing = None;
3401 while let Some(pair_state) = regions.get(i) {
3402 if pair_state.range.end.to_offset(buffer) < range.start {
3403 regions = ®ions[i + 1..];
3404 i = 0;
3405 } else if pair_state.range.start.to_offset(buffer) > range.end {
3406 break;
3407 } else {
3408 if pair_state.selection_id == selection.id {
3409 enclosing = Some(pair_state);
3410 }
3411 i += 1;
3412 }
3413 }
3414
3415 (selection, enclosing)
3416 })
3417 }
3418
3419 /// Remove any autoclose regions that no longer contain their selection.
3420 fn invalidate_autoclose_regions(
3421 &mut self,
3422 mut selections: &[Selection<Anchor>],
3423 buffer: &MultiBufferSnapshot,
3424 ) {
3425 self.autoclose_regions.retain(|state| {
3426 let mut i = 0;
3427 while let Some(selection) = selections.get(i) {
3428 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3429 selections = &selections[1..];
3430 continue;
3431 }
3432 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3433 break;
3434 }
3435 if selection.id == state.selection_id {
3436 return true;
3437 } else {
3438 i += 1;
3439 }
3440 }
3441 false
3442 });
3443 }
3444
3445 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3446 let offset = position.to_offset(buffer);
3447 let (word_range, kind) = buffer.surrounding_word(offset, true);
3448 if offset > word_range.start && kind == Some(CharKind::Word) {
3449 Some(
3450 buffer
3451 .text_for_range(word_range.start..offset)
3452 .collect::<String>(),
3453 )
3454 } else {
3455 None
3456 }
3457 }
3458
3459 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3460 self.refresh_inlay_hints(
3461 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3462 cx,
3463 );
3464 }
3465
3466 pub fn inlay_hints_enabled(&self) -> bool {
3467 self.inlay_hint_cache.enabled
3468 }
3469
3470 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3471 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3472 return;
3473 }
3474
3475 let reason_description = reason.description();
3476 let ignore_debounce = matches!(
3477 reason,
3478 InlayHintRefreshReason::SettingsChange(_)
3479 | InlayHintRefreshReason::Toggle(_)
3480 | InlayHintRefreshReason::ExcerptsRemoved(_)
3481 );
3482 let (invalidate_cache, required_languages) = match reason {
3483 InlayHintRefreshReason::Toggle(enabled) => {
3484 self.inlay_hint_cache.enabled = enabled;
3485 if enabled {
3486 (InvalidationStrategy::RefreshRequested, None)
3487 } else {
3488 self.inlay_hint_cache.clear();
3489 self.splice_inlays(
3490 self.visible_inlay_hints(cx)
3491 .iter()
3492 .map(|inlay| inlay.id)
3493 .collect(),
3494 Vec::new(),
3495 cx,
3496 );
3497 return;
3498 }
3499 }
3500 InlayHintRefreshReason::SettingsChange(new_settings) => {
3501 match self.inlay_hint_cache.update_settings(
3502 &self.buffer,
3503 new_settings,
3504 self.visible_inlay_hints(cx),
3505 cx,
3506 ) {
3507 ControlFlow::Break(Some(InlaySplice {
3508 to_remove,
3509 to_insert,
3510 })) => {
3511 self.splice_inlays(to_remove, to_insert, cx);
3512 return;
3513 }
3514 ControlFlow::Break(None) => return,
3515 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3516 }
3517 }
3518 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3519 if let Some(InlaySplice {
3520 to_remove,
3521 to_insert,
3522 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3523 {
3524 self.splice_inlays(to_remove, to_insert, cx);
3525 }
3526 return;
3527 }
3528 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3529 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3530 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3531 }
3532 InlayHintRefreshReason::RefreshRequested => {
3533 (InvalidationStrategy::RefreshRequested, None)
3534 }
3535 };
3536
3537 if let Some(InlaySplice {
3538 to_remove,
3539 to_insert,
3540 }) = self.inlay_hint_cache.spawn_hint_refresh(
3541 reason_description,
3542 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3543 invalidate_cache,
3544 ignore_debounce,
3545 cx,
3546 ) {
3547 self.splice_inlays(to_remove, to_insert, cx);
3548 }
3549 }
3550
3551 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3552 self.display_map
3553 .read(cx)
3554 .current_inlays()
3555 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3556 .cloned()
3557 .collect()
3558 }
3559
3560 pub fn excerpts_for_inlay_hints_query(
3561 &self,
3562 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3563 cx: &mut ViewContext<Editor>,
3564 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3565 let Some(project) = self.project.as_ref() else {
3566 return HashMap::default();
3567 };
3568 let project = project.read(cx);
3569 let multi_buffer = self.buffer().read(cx);
3570 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3571 let multi_buffer_visible_start = self
3572 .scroll_manager
3573 .anchor()
3574 .anchor
3575 .to_point(&multi_buffer_snapshot);
3576 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3577 multi_buffer_visible_start
3578 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3579 Bias::Left,
3580 );
3581 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3582 multi_buffer_snapshot
3583 .range_to_buffer_ranges(multi_buffer_visible_range)
3584 .into_iter()
3585 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3586 .filter_map(|(excerpt, excerpt_visible_range)| {
3587 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3588 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3589 let worktree_entry = buffer_worktree
3590 .read(cx)
3591 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3592 if worktree_entry.is_ignored {
3593 return None;
3594 }
3595
3596 let language = excerpt.buffer().language()?;
3597 if let Some(restrict_to_languages) = restrict_to_languages {
3598 if !restrict_to_languages.contains(language) {
3599 return None;
3600 }
3601 }
3602 Some((
3603 excerpt.id(),
3604 (
3605 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3606 excerpt.buffer().version().clone(),
3607 excerpt_visible_range,
3608 ),
3609 ))
3610 })
3611 .collect()
3612 }
3613
3614 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3615 TextLayoutDetails {
3616 text_system: cx.text_system().clone(),
3617 editor_style: self.style.clone().unwrap(),
3618 rem_size: cx.rem_size(),
3619 scroll_anchor: self.scroll_manager.anchor(),
3620 visible_rows: self.visible_line_count(),
3621 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3622 }
3623 }
3624
3625 pub fn splice_inlays(
3626 &self,
3627 to_remove: Vec<InlayId>,
3628 to_insert: Vec<Inlay>,
3629 cx: &mut ViewContext<Self>,
3630 ) {
3631 self.display_map.update(cx, |display_map, cx| {
3632 display_map.splice_inlays(to_remove, to_insert, cx)
3633 });
3634 cx.notify();
3635 }
3636
3637 fn trigger_on_type_formatting(
3638 &self,
3639 input: String,
3640 cx: &mut ViewContext<Self>,
3641 ) -> Option<Task<Result<()>>> {
3642 if input.len() != 1 {
3643 return None;
3644 }
3645
3646 let project = self.project.as_ref()?;
3647 let position = self.selections.newest_anchor().head();
3648 let (buffer, buffer_position) = self
3649 .buffer
3650 .read(cx)
3651 .text_anchor_for_position(position, cx)?;
3652
3653 let settings = language_settings::language_settings(
3654 buffer
3655 .read(cx)
3656 .language_at(buffer_position)
3657 .map(|l| l.name()),
3658 buffer.read(cx).file(),
3659 cx,
3660 );
3661 if !settings.use_on_type_format {
3662 return None;
3663 }
3664
3665 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3666 // hence we do LSP request & edit on host side only — add formats to host's history.
3667 let push_to_lsp_host_history = true;
3668 // If this is not the host, append its history with new edits.
3669 let push_to_client_history = project.read(cx).is_via_collab();
3670
3671 let on_type_formatting = project.update(cx, |project, cx| {
3672 project.on_type_format(
3673 buffer.clone(),
3674 buffer_position,
3675 input,
3676 push_to_lsp_host_history,
3677 cx,
3678 )
3679 });
3680 Some(cx.spawn(|editor, mut cx| async move {
3681 if let Some(transaction) = on_type_formatting.await? {
3682 if push_to_client_history {
3683 buffer
3684 .update(&mut cx, |buffer, _| {
3685 buffer.push_transaction(transaction, Instant::now());
3686 })
3687 .ok();
3688 }
3689 editor.update(&mut cx, |editor, cx| {
3690 editor.refresh_document_highlights(cx);
3691 })?;
3692 }
3693 Ok(())
3694 }))
3695 }
3696
3697 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3698 if self.pending_rename.is_some() {
3699 return;
3700 }
3701
3702 let Some(provider) = self.completion_provider.as_ref() else {
3703 return;
3704 };
3705
3706 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3707 return;
3708 }
3709
3710 let position = self.selections.newest_anchor().head();
3711 let (buffer, buffer_position) =
3712 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3713 output
3714 } else {
3715 return;
3716 };
3717 let show_completion_documentation = buffer
3718 .read(cx)
3719 .snapshot()
3720 .settings_at(buffer_position, cx)
3721 .show_completion_documentation;
3722
3723 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3724
3725 let trigger_kind = match &options.trigger {
3726 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3727 CompletionTriggerKind::TRIGGER_CHARACTER
3728 }
3729 _ => CompletionTriggerKind::INVOKED,
3730 };
3731 let completion_context = CompletionContext {
3732 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3733 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3734 Some(String::from(trigger))
3735 } else {
3736 None
3737 }
3738 }),
3739 trigger_kind,
3740 };
3741 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3742 let sort_completions = provider.sort_completions();
3743
3744 let id = post_inc(&mut self.next_completion_id);
3745 let task = cx.spawn(|editor, mut cx| {
3746 async move {
3747 editor.update(&mut cx, |this, _| {
3748 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3749 })?;
3750 let completions = completions.await.log_err();
3751 let menu = if let Some(completions) = completions {
3752 let mut menu = CompletionsMenu::new(
3753 id,
3754 sort_completions,
3755 show_completion_documentation,
3756 position,
3757 buffer.clone(),
3758 completions.into(),
3759 );
3760
3761 menu.filter(query.as_deref(), cx.background_executor().clone())
3762 .await;
3763
3764 menu.visible().then_some(menu)
3765 } else {
3766 None
3767 };
3768
3769 editor.update(&mut cx, |editor, cx| {
3770 match editor.context_menu.borrow().as_ref() {
3771 None => {}
3772 Some(CodeContextMenu::Completions(prev_menu)) => {
3773 if prev_menu.id > id {
3774 return;
3775 }
3776 }
3777 _ => return,
3778 }
3779
3780 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3781 let mut menu = menu.unwrap();
3782 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3783
3784 if editor.show_inline_completions_in_menu(cx) {
3785 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3786 menu.show_inline_completion_hint(hint);
3787 }
3788 } else {
3789 editor.discard_inline_completion(false, cx);
3790 }
3791
3792 *editor.context_menu.borrow_mut() =
3793 Some(CodeContextMenu::Completions(menu));
3794
3795 cx.notify();
3796 } else if editor.completion_tasks.len() <= 1 {
3797 // If there are no more completion tasks and the last menu was
3798 // empty, we should hide it.
3799 let was_hidden = editor.hide_context_menu(cx).is_none();
3800 // If it was already hidden and we don't show inline
3801 // completions in the menu, we should also show the
3802 // inline-completion when available.
3803 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3804 editor.update_visible_inline_completion(cx);
3805 }
3806 }
3807 })?;
3808
3809 Ok::<_, anyhow::Error>(())
3810 }
3811 .log_err()
3812 });
3813
3814 self.completion_tasks.push((id, task));
3815 }
3816
3817 pub fn confirm_completion(
3818 &mut self,
3819 action: &ConfirmCompletion,
3820 cx: &mut ViewContext<Self>,
3821 ) -> Option<Task<Result<()>>> {
3822 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3823 }
3824
3825 pub fn compose_completion(
3826 &mut self,
3827 action: &ComposeCompletion,
3828 cx: &mut ViewContext<Self>,
3829 ) -> Option<Task<Result<()>>> {
3830 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3831 }
3832
3833 fn toggle_zed_predict_tos(&mut self, cx: &mut ViewContext<Self>) {
3834 let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
3835 return;
3836 };
3837
3838 ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), cx);
3839 }
3840
3841 fn do_completion(
3842 &mut self,
3843 item_ix: Option<usize>,
3844 intent: CompletionIntent,
3845 cx: &mut ViewContext<Editor>,
3846 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3847 use language::ToOffset as _;
3848
3849 {
3850 let context_menu = self.context_menu.borrow();
3851 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3852 let entries = menu.entries.borrow();
3853 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3854 match entry {
3855 Some(CompletionEntry::InlineCompletionHint(
3856 InlineCompletionMenuHint::Loading,
3857 )) => return Some(Task::ready(Ok(()))),
3858 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3859 drop(entries);
3860 drop(context_menu);
3861 self.context_menu_next(&Default::default(), cx);
3862 return Some(Task::ready(Ok(())));
3863 }
3864 Some(CompletionEntry::InlineCompletionHint(
3865 InlineCompletionMenuHint::PendingTermsAcceptance,
3866 )) => {
3867 drop(entries);
3868 drop(context_menu);
3869 self.toggle_zed_predict_tos(cx);
3870 return Some(Task::ready(Ok(())));
3871 }
3872 _ => {}
3873 }
3874 }
3875 }
3876
3877 let completions_menu =
3878 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3879 menu
3880 } else {
3881 return None;
3882 };
3883
3884 let entries = completions_menu.entries.borrow();
3885 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3886 let mat = match mat {
3887 CompletionEntry::InlineCompletionHint(_) => {
3888 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3889 cx.stop_propagation();
3890 return Some(Task::ready(Ok(())));
3891 }
3892 CompletionEntry::Match(mat) => {
3893 if self.show_inline_completions_in_menu(cx) {
3894 self.discard_inline_completion(true, cx);
3895 }
3896 mat
3897 }
3898 };
3899 let candidate_id = mat.candidate_id;
3900 drop(entries);
3901
3902 let buffer_handle = completions_menu.buffer;
3903 let completion = completions_menu
3904 .completions
3905 .borrow()
3906 .get(candidate_id)?
3907 .clone();
3908 cx.stop_propagation();
3909
3910 let snippet;
3911 let text;
3912
3913 if completion.is_snippet() {
3914 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3915 text = snippet.as_ref().unwrap().text.clone();
3916 } else {
3917 snippet = None;
3918 text = completion.new_text.clone();
3919 };
3920 let selections = self.selections.all::<usize>(cx);
3921 let buffer = buffer_handle.read(cx);
3922 let old_range = completion.old_range.to_offset(buffer);
3923 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3924
3925 let newest_selection = self.selections.newest_anchor();
3926 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3927 return None;
3928 }
3929
3930 let lookbehind = newest_selection
3931 .start
3932 .text_anchor
3933 .to_offset(buffer)
3934 .saturating_sub(old_range.start);
3935 let lookahead = old_range
3936 .end
3937 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3938 let mut common_prefix_len = old_text
3939 .bytes()
3940 .zip(text.bytes())
3941 .take_while(|(a, b)| a == b)
3942 .count();
3943
3944 let snapshot = self.buffer.read(cx).snapshot(cx);
3945 let mut range_to_replace: Option<Range<isize>> = None;
3946 let mut ranges = Vec::new();
3947 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3948 for selection in &selections {
3949 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3950 let start = selection.start.saturating_sub(lookbehind);
3951 let end = selection.end + lookahead;
3952 if selection.id == newest_selection.id {
3953 range_to_replace = Some(
3954 ((start + common_prefix_len) as isize - selection.start as isize)
3955 ..(end as isize - selection.start as isize),
3956 );
3957 }
3958 ranges.push(start + common_prefix_len..end);
3959 } else {
3960 common_prefix_len = 0;
3961 ranges.clear();
3962 ranges.extend(selections.iter().map(|s| {
3963 if s.id == newest_selection.id {
3964 range_to_replace = Some(
3965 old_range.start.to_offset_utf16(&snapshot).0 as isize
3966 - selection.start as isize
3967 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3968 - selection.start as isize,
3969 );
3970 old_range.clone()
3971 } else {
3972 s.start..s.end
3973 }
3974 }));
3975 break;
3976 }
3977 if !self.linked_edit_ranges.is_empty() {
3978 let start_anchor = snapshot.anchor_before(selection.head());
3979 let end_anchor = snapshot.anchor_after(selection.tail());
3980 if let Some(ranges) = self
3981 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3982 {
3983 for (buffer, edits) in ranges {
3984 linked_edits.entry(buffer.clone()).or_default().extend(
3985 edits
3986 .into_iter()
3987 .map(|range| (range, text[common_prefix_len..].to_owned())),
3988 );
3989 }
3990 }
3991 }
3992 }
3993 let text = &text[common_prefix_len..];
3994
3995 cx.emit(EditorEvent::InputHandled {
3996 utf16_range_to_replace: range_to_replace,
3997 text: text.into(),
3998 });
3999
4000 self.transact(cx, |this, cx| {
4001 if let Some(mut snippet) = snippet {
4002 snippet.text = text.to_string();
4003 for tabstop in snippet
4004 .tabstops
4005 .iter_mut()
4006 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4007 {
4008 tabstop.start -= common_prefix_len as isize;
4009 tabstop.end -= common_prefix_len as isize;
4010 }
4011
4012 this.insert_snippet(&ranges, snippet, cx).log_err();
4013 } else {
4014 this.buffer.update(cx, |buffer, cx| {
4015 buffer.edit(
4016 ranges.iter().map(|range| (range.clone(), text)),
4017 this.autoindent_mode.clone(),
4018 cx,
4019 );
4020 });
4021 }
4022 for (buffer, edits) in linked_edits {
4023 buffer.update(cx, |buffer, cx| {
4024 let snapshot = buffer.snapshot();
4025 let edits = edits
4026 .into_iter()
4027 .map(|(range, text)| {
4028 use text::ToPoint as TP;
4029 let end_point = TP::to_point(&range.end, &snapshot);
4030 let start_point = TP::to_point(&range.start, &snapshot);
4031 (start_point..end_point, text)
4032 })
4033 .sorted_by_key(|(range, _)| range.start)
4034 .collect::<Vec<_>>();
4035 buffer.edit(edits, None, cx);
4036 })
4037 }
4038
4039 this.refresh_inline_completion(true, false, cx);
4040 });
4041
4042 let show_new_completions_on_confirm = completion
4043 .confirm
4044 .as_ref()
4045 .map_or(false, |confirm| confirm(intent, cx));
4046 if show_new_completions_on_confirm {
4047 self.show_completions(&ShowCompletions { trigger: None }, cx);
4048 }
4049
4050 let provider = self.completion_provider.as_ref()?;
4051 drop(completion);
4052 let apply_edits = provider.apply_additional_edits_for_completion(
4053 buffer_handle,
4054 completions_menu.completions.clone(),
4055 candidate_id,
4056 true,
4057 cx,
4058 );
4059
4060 let editor_settings = EditorSettings::get_global(cx);
4061 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4062 // After the code completion is finished, users often want to know what signatures are needed.
4063 // so we should automatically call signature_help
4064 self.show_signature_help(&ShowSignatureHelp, cx);
4065 }
4066
4067 Some(cx.foreground_executor().spawn(async move {
4068 apply_edits.await?;
4069 Ok(())
4070 }))
4071 }
4072
4073 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4074 let mut context_menu = self.context_menu.borrow_mut();
4075 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4076 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4077 // Toggle if we're selecting the same one
4078 *context_menu = None;
4079 cx.notify();
4080 return;
4081 } else {
4082 // Otherwise, clear it and start a new one
4083 *context_menu = None;
4084 cx.notify();
4085 }
4086 }
4087 drop(context_menu);
4088 let snapshot = self.snapshot(cx);
4089 let deployed_from_indicator = action.deployed_from_indicator;
4090 let mut task = self.code_actions_task.take();
4091 let action = action.clone();
4092 cx.spawn(|editor, mut cx| async move {
4093 while let Some(prev_task) = task {
4094 prev_task.await.log_err();
4095 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4096 }
4097
4098 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4099 if editor.focus_handle.is_focused(cx) {
4100 let multibuffer_point = action
4101 .deployed_from_indicator
4102 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4103 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4104 let (buffer, buffer_row) = snapshot
4105 .buffer_snapshot
4106 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4107 .and_then(|(buffer_snapshot, range)| {
4108 editor
4109 .buffer
4110 .read(cx)
4111 .buffer(buffer_snapshot.remote_id())
4112 .map(|buffer| (buffer, range.start.row))
4113 })?;
4114 let (_, code_actions) = editor
4115 .available_code_actions
4116 .clone()
4117 .and_then(|(location, code_actions)| {
4118 let snapshot = location.buffer.read(cx).snapshot();
4119 let point_range = location.range.to_point(&snapshot);
4120 let point_range = point_range.start.row..=point_range.end.row;
4121 if point_range.contains(&buffer_row) {
4122 Some((location, code_actions))
4123 } else {
4124 None
4125 }
4126 })
4127 .unzip();
4128 let buffer_id = buffer.read(cx).remote_id();
4129 let tasks = editor
4130 .tasks
4131 .get(&(buffer_id, buffer_row))
4132 .map(|t| Arc::new(t.to_owned()));
4133 if tasks.is_none() && code_actions.is_none() {
4134 return None;
4135 }
4136
4137 editor.completion_tasks.clear();
4138 editor.discard_inline_completion(false, cx);
4139 let task_context =
4140 tasks
4141 .as_ref()
4142 .zip(editor.project.clone())
4143 .map(|(tasks, project)| {
4144 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4145 });
4146
4147 Some(cx.spawn(|editor, mut cx| async move {
4148 let task_context = match task_context {
4149 Some(task_context) => task_context.await,
4150 None => None,
4151 };
4152 let resolved_tasks =
4153 tasks.zip(task_context).map(|(tasks, task_context)| {
4154 Rc::new(ResolvedTasks {
4155 templates: tasks.resolve(&task_context).collect(),
4156 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4157 multibuffer_point.row,
4158 tasks.column,
4159 )),
4160 })
4161 });
4162 let spawn_straight_away = resolved_tasks
4163 .as_ref()
4164 .map_or(false, |tasks| tasks.templates.len() == 1)
4165 && code_actions
4166 .as_ref()
4167 .map_or(true, |actions| actions.is_empty());
4168 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4169 *editor.context_menu.borrow_mut() =
4170 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4171 buffer,
4172 actions: CodeActionContents {
4173 tasks: resolved_tasks,
4174 actions: code_actions,
4175 },
4176 selected_item: Default::default(),
4177 scroll_handle: UniformListScrollHandle::default(),
4178 deployed_from_indicator,
4179 }));
4180 if spawn_straight_away {
4181 if let Some(task) = editor.confirm_code_action(
4182 &ConfirmCodeAction { item_ix: Some(0) },
4183 cx,
4184 ) {
4185 cx.notify();
4186 return task;
4187 }
4188 }
4189 cx.notify();
4190 Task::ready(Ok(()))
4191 }) {
4192 task.await
4193 } else {
4194 Ok(())
4195 }
4196 }))
4197 } else {
4198 Some(Task::ready(Ok(())))
4199 }
4200 })?;
4201 if let Some(task) = spawned_test_task {
4202 task.await?;
4203 }
4204
4205 Ok::<_, anyhow::Error>(())
4206 })
4207 .detach_and_log_err(cx);
4208 }
4209
4210 pub fn confirm_code_action(
4211 &mut self,
4212 action: &ConfirmCodeAction,
4213 cx: &mut ViewContext<Self>,
4214 ) -> Option<Task<Result<()>>> {
4215 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4216 menu
4217 } else {
4218 return None;
4219 };
4220 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4221 let action = actions_menu.actions.get(action_ix)?;
4222 let title = action.label();
4223 let buffer = actions_menu.buffer;
4224 let workspace = self.workspace()?;
4225
4226 match action {
4227 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4228 workspace.update(cx, |workspace, cx| {
4229 workspace::tasks::schedule_resolved_task(
4230 workspace,
4231 task_source_kind,
4232 resolved_task,
4233 false,
4234 cx,
4235 );
4236
4237 Some(Task::ready(Ok(())))
4238 })
4239 }
4240 CodeActionsItem::CodeAction {
4241 excerpt_id,
4242 action,
4243 provider,
4244 } => {
4245 let apply_code_action =
4246 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4247 let workspace = workspace.downgrade();
4248 Some(cx.spawn(|editor, cx| async move {
4249 let project_transaction = apply_code_action.await?;
4250 Self::open_project_transaction(
4251 &editor,
4252 workspace,
4253 project_transaction,
4254 title,
4255 cx,
4256 )
4257 .await
4258 }))
4259 }
4260 }
4261 }
4262
4263 pub async fn open_project_transaction(
4264 this: &WeakView<Editor>,
4265 workspace: WeakView<Workspace>,
4266 transaction: ProjectTransaction,
4267 title: String,
4268 mut cx: AsyncWindowContext,
4269 ) -> Result<()> {
4270 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4271 cx.update(|cx| {
4272 entries.sort_unstable_by_key(|(buffer, _)| {
4273 buffer.read(cx).file().map(|f| f.path().clone())
4274 });
4275 })?;
4276
4277 // If the project transaction's edits are all contained within this editor, then
4278 // avoid opening a new editor to display them.
4279
4280 if let Some((buffer, transaction)) = entries.first() {
4281 if entries.len() == 1 {
4282 let excerpt = this.update(&mut cx, |editor, cx| {
4283 editor
4284 .buffer()
4285 .read(cx)
4286 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4287 })?;
4288 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4289 if excerpted_buffer == *buffer {
4290 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4291 let excerpt_range = excerpt_range.to_offset(buffer);
4292 buffer
4293 .edited_ranges_for_transaction::<usize>(transaction)
4294 .all(|range| {
4295 excerpt_range.start <= range.start
4296 && excerpt_range.end >= range.end
4297 })
4298 })?;
4299
4300 if all_edits_within_excerpt {
4301 return Ok(());
4302 }
4303 }
4304 }
4305 }
4306 } else {
4307 return Ok(());
4308 }
4309
4310 let mut ranges_to_highlight = Vec::new();
4311 let excerpt_buffer = cx.new_model(|cx| {
4312 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4313 for (buffer_handle, transaction) in &entries {
4314 let buffer = buffer_handle.read(cx);
4315 ranges_to_highlight.extend(
4316 multibuffer.push_excerpts_with_context_lines(
4317 buffer_handle.clone(),
4318 buffer
4319 .edited_ranges_for_transaction::<usize>(transaction)
4320 .collect(),
4321 DEFAULT_MULTIBUFFER_CONTEXT,
4322 cx,
4323 ),
4324 );
4325 }
4326 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4327 multibuffer
4328 })?;
4329
4330 workspace.update(&mut cx, |workspace, cx| {
4331 let project = workspace.project().clone();
4332 let editor =
4333 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4334 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4335 editor.update(cx, |editor, cx| {
4336 editor.highlight_background::<Self>(
4337 &ranges_to_highlight,
4338 |theme| theme.editor_highlighted_line_background,
4339 cx,
4340 );
4341 });
4342 })?;
4343
4344 Ok(())
4345 }
4346
4347 pub fn clear_code_action_providers(&mut self) {
4348 self.code_action_providers.clear();
4349 self.available_code_actions.take();
4350 }
4351
4352 pub fn add_code_action_provider(
4353 &mut self,
4354 provider: Rc<dyn CodeActionProvider>,
4355 cx: &mut ViewContext<Self>,
4356 ) {
4357 if self
4358 .code_action_providers
4359 .iter()
4360 .any(|existing_provider| existing_provider.id() == provider.id())
4361 {
4362 return;
4363 }
4364
4365 self.code_action_providers.push(provider);
4366 self.refresh_code_actions(cx);
4367 }
4368
4369 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4370 self.code_action_providers
4371 .retain(|provider| provider.id() != id);
4372 self.refresh_code_actions(cx);
4373 }
4374
4375 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4376 let buffer = self.buffer.read(cx);
4377 let newest_selection = self.selections.newest_anchor().clone();
4378 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4379 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4380 if start_buffer != end_buffer {
4381 return None;
4382 }
4383
4384 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4385 cx.background_executor()
4386 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4387 .await;
4388
4389 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4390 let providers = this.code_action_providers.clone();
4391 let tasks = this
4392 .code_action_providers
4393 .iter()
4394 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4395 .collect::<Vec<_>>();
4396 (providers, tasks)
4397 })?;
4398
4399 let mut actions = Vec::new();
4400 for (provider, provider_actions) in
4401 providers.into_iter().zip(future::join_all(tasks).await)
4402 {
4403 if let Some(provider_actions) = provider_actions.log_err() {
4404 actions.extend(provider_actions.into_iter().map(|action| {
4405 AvailableCodeAction {
4406 excerpt_id: newest_selection.start.excerpt_id,
4407 action,
4408 provider: provider.clone(),
4409 }
4410 }));
4411 }
4412 }
4413
4414 this.update(&mut cx, |this, cx| {
4415 this.available_code_actions = if actions.is_empty() {
4416 None
4417 } else {
4418 Some((
4419 Location {
4420 buffer: start_buffer,
4421 range: start..end,
4422 },
4423 actions.into(),
4424 ))
4425 };
4426 cx.notify();
4427 })
4428 }));
4429 None
4430 }
4431
4432 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4433 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4434 self.show_git_blame_inline = false;
4435
4436 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4437 cx.background_executor().timer(delay).await;
4438
4439 this.update(&mut cx, |this, cx| {
4440 this.show_git_blame_inline = true;
4441 cx.notify();
4442 })
4443 .log_err();
4444 }));
4445 }
4446 }
4447
4448 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4449 if self.pending_rename.is_some() {
4450 return None;
4451 }
4452
4453 let provider = self.semantics_provider.clone()?;
4454 let buffer = self.buffer.read(cx);
4455 let newest_selection = self.selections.newest_anchor().clone();
4456 let cursor_position = newest_selection.head();
4457 let (cursor_buffer, cursor_buffer_position) =
4458 buffer.text_anchor_for_position(cursor_position, cx)?;
4459 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4460 if cursor_buffer != tail_buffer {
4461 return None;
4462 }
4463 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4464 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4465 cx.background_executor()
4466 .timer(Duration::from_millis(debounce))
4467 .await;
4468
4469 let highlights = if let Some(highlights) = cx
4470 .update(|cx| {
4471 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4472 })
4473 .ok()
4474 .flatten()
4475 {
4476 highlights.await.log_err()
4477 } else {
4478 None
4479 };
4480
4481 if let Some(highlights) = highlights {
4482 this.update(&mut cx, |this, cx| {
4483 if this.pending_rename.is_some() {
4484 return;
4485 }
4486
4487 let buffer_id = cursor_position.buffer_id;
4488 let buffer = this.buffer.read(cx);
4489 if !buffer
4490 .text_anchor_for_position(cursor_position, cx)
4491 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4492 {
4493 return;
4494 }
4495
4496 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4497 let mut write_ranges = Vec::new();
4498 let mut read_ranges = Vec::new();
4499 for highlight in highlights {
4500 for (excerpt_id, excerpt_range) in
4501 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4502 {
4503 let start = highlight
4504 .range
4505 .start
4506 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4507 let end = highlight
4508 .range
4509 .end
4510 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4511 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4512 continue;
4513 }
4514
4515 let range = Anchor {
4516 buffer_id,
4517 excerpt_id,
4518 text_anchor: start,
4519 }..Anchor {
4520 buffer_id,
4521 excerpt_id,
4522 text_anchor: end,
4523 };
4524 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4525 write_ranges.push(range);
4526 } else {
4527 read_ranges.push(range);
4528 }
4529 }
4530 }
4531
4532 this.highlight_background::<DocumentHighlightRead>(
4533 &read_ranges,
4534 |theme| theme.editor_document_highlight_read_background,
4535 cx,
4536 );
4537 this.highlight_background::<DocumentHighlightWrite>(
4538 &write_ranges,
4539 |theme| theme.editor_document_highlight_write_background,
4540 cx,
4541 );
4542 cx.notify();
4543 })
4544 .log_err();
4545 }
4546 }));
4547 None
4548 }
4549
4550 pub fn refresh_inline_completion(
4551 &mut self,
4552 debounce: bool,
4553 user_requested: bool,
4554 cx: &mut ViewContext<Self>,
4555 ) -> Option<()> {
4556 let provider = self.inline_completion_provider()?;
4557 let cursor = self.selections.newest_anchor().head();
4558 let (buffer, cursor_buffer_position) =
4559 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4560
4561 if !user_requested
4562 && (!self.enable_inline_completions
4563 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4564 || !self.is_focused(cx)
4565 || buffer.read(cx).is_empty())
4566 {
4567 self.discard_inline_completion(false, cx);
4568 return None;
4569 }
4570
4571 self.update_visible_inline_completion(cx);
4572 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4573 Some(())
4574 }
4575
4576 fn cycle_inline_completion(
4577 &mut self,
4578 direction: Direction,
4579 cx: &mut ViewContext<Self>,
4580 ) -> Option<()> {
4581 let provider = self.inline_completion_provider()?;
4582 let cursor = self.selections.newest_anchor().head();
4583 let (buffer, cursor_buffer_position) =
4584 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4585 if !self.enable_inline_completions
4586 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4587 {
4588 return None;
4589 }
4590
4591 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4592 self.update_visible_inline_completion(cx);
4593
4594 Some(())
4595 }
4596
4597 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4598 if !self.has_active_inline_completion() {
4599 self.refresh_inline_completion(false, true, cx);
4600 return;
4601 }
4602
4603 self.update_visible_inline_completion(cx);
4604 }
4605
4606 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4607 self.show_cursor_names(cx);
4608 }
4609
4610 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4611 self.show_cursor_names = true;
4612 cx.notify();
4613 cx.spawn(|this, mut cx| async move {
4614 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4615 this.update(&mut cx, |this, cx| {
4616 this.show_cursor_names = false;
4617 cx.notify()
4618 })
4619 .ok()
4620 })
4621 .detach();
4622 }
4623
4624 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4625 if self.has_active_inline_completion() {
4626 self.cycle_inline_completion(Direction::Next, cx);
4627 } else {
4628 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4629 if is_copilot_disabled {
4630 cx.propagate();
4631 }
4632 }
4633 }
4634
4635 pub fn previous_inline_completion(
4636 &mut self,
4637 _: &PreviousInlineCompletion,
4638 cx: &mut ViewContext<Self>,
4639 ) {
4640 if self.has_active_inline_completion() {
4641 self.cycle_inline_completion(Direction::Prev, cx);
4642 } else {
4643 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4644 if is_copilot_disabled {
4645 cx.propagate();
4646 }
4647 }
4648 }
4649
4650 pub fn accept_inline_completion(
4651 &mut self,
4652 _: &AcceptInlineCompletion,
4653 cx: &mut ViewContext<Self>,
4654 ) {
4655 let buffer = self.buffer.read(cx);
4656 let snapshot = buffer.snapshot(cx);
4657 let selection = self.selections.newest_adjusted(cx);
4658 let cursor = selection.head();
4659 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4660 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4661 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4662 {
4663 if cursor.column < suggested_indent.len
4664 && cursor.column <= current_indent.len
4665 && current_indent.len <= suggested_indent.len
4666 {
4667 self.tab(&Default::default(), cx);
4668 return;
4669 }
4670 }
4671
4672 if self.show_inline_completions_in_menu(cx) {
4673 self.hide_context_menu(cx);
4674 }
4675
4676 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4677 return;
4678 };
4679
4680 self.report_inline_completion_event(true, cx);
4681
4682 match &active_inline_completion.completion {
4683 InlineCompletion::Move(position) => {
4684 let position = *position;
4685 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4686 selections.select_anchor_ranges([position..position]);
4687 });
4688 }
4689 InlineCompletion::Edit(edits) => {
4690 if let Some(provider) = self.inline_completion_provider() {
4691 provider.accept(cx);
4692 }
4693
4694 let snapshot = self.buffer.read(cx).snapshot(cx);
4695 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4696
4697 self.buffer.update(cx, |buffer, cx| {
4698 buffer.edit(edits.iter().cloned(), None, cx)
4699 });
4700
4701 self.change_selections(None, cx, |s| {
4702 s.select_anchor_ranges([last_edit_end..last_edit_end])
4703 });
4704
4705 self.update_visible_inline_completion(cx);
4706 if self.active_inline_completion.is_none() {
4707 self.refresh_inline_completion(true, true, cx);
4708 }
4709
4710 cx.notify();
4711 }
4712 }
4713 }
4714
4715 pub fn accept_partial_inline_completion(
4716 &mut self,
4717 _: &AcceptPartialInlineCompletion,
4718 cx: &mut ViewContext<Self>,
4719 ) {
4720 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4721 return;
4722 };
4723 if self.selections.count() != 1 {
4724 return;
4725 }
4726
4727 self.report_inline_completion_event(true, cx);
4728
4729 match &active_inline_completion.completion {
4730 InlineCompletion::Move(position) => {
4731 let position = *position;
4732 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4733 selections.select_anchor_ranges([position..position]);
4734 });
4735 }
4736 InlineCompletion::Edit(edits) => {
4737 // Find an insertion that starts at the cursor position.
4738 let snapshot = self.buffer.read(cx).snapshot(cx);
4739 let cursor_offset = self.selections.newest::<usize>(cx).head();
4740 let insertion = edits.iter().find_map(|(range, text)| {
4741 let range = range.to_offset(&snapshot);
4742 if range.is_empty() && range.start == cursor_offset {
4743 Some(text)
4744 } else {
4745 None
4746 }
4747 });
4748
4749 if let Some(text) = insertion {
4750 let mut partial_completion = text
4751 .chars()
4752 .by_ref()
4753 .take_while(|c| c.is_alphabetic())
4754 .collect::<String>();
4755 if partial_completion.is_empty() {
4756 partial_completion = text
4757 .chars()
4758 .by_ref()
4759 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4760 .collect::<String>();
4761 }
4762
4763 cx.emit(EditorEvent::InputHandled {
4764 utf16_range_to_replace: None,
4765 text: partial_completion.clone().into(),
4766 });
4767
4768 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4769
4770 self.refresh_inline_completion(true, true, cx);
4771 cx.notify();
4772 } else {
4773 self.accept_inline_completion(&Default::default(), cx);
4774 }
4775 }
4776 }
4777 }
4778
4779 fn discard_inline_completion(
4780 &mut self,
4781 should_report_inline_completion_event: bool,
4782 cx: &mut ViewContext<Self>,
4783 ) -> bool {
4784 if should_report_inline_completion_event {
4785 self.report_inline_completion_event(false, cx);
4786 }
4787
4788 if let Some(provider) = self.inline_completion_provider() {
4789 provider.discard(cx);
4790 }
4791
4792 self.take_active_inline_completion(cx).is_some()
4793 }
4794
4795 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4796 let Some(provider) = self.inline_completion_provider() else {
4797 return;
4798 };
4799
4800 let Some((_, buffer, _)) = self
4801 .buffer
4802 .read(cx)
4803 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4804 else {
4805 return;
4806 };
4807
4808 let extension = buffer
4809 .read(cx)
4810 .file()
4811 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4812
4813 let event_type = match accepted {
4814 true => "Inline Completion Accepted",
4815 false => "Inline Completion Discarded",
4816 };
4817 telemetry::event!(
4818 event_type,
4819 provider = provider.name(),
4820 suggestion_accepted = accepted,
4821 file_extension = extension,
4822 );
4823 }
4824
4825 pub fn has_active_inline_completion(&self) -> bool {
4826 self.active_inline_completion.is_some()
4827 }
4828
4829 fn take_active_inline_completion(
4830 &mut self,
4831 cx: &mut ViewContext<Self>,
4832 ) -> Option<InlineCompletion> {
4833 let active_inline_completion = self.active_inline_completion.take()?;
4834 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4835 self.clear_highlights::<InlineCompletionHighlight>(cx);
4836 Some(active_inline_completion.completion)
4837 }
4838
4839 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4840 let selection = self.selections.newest_anchor();
4841 let cursor = selection.head();
4842 let multibuffer = self.buffer.read(cx).snapshot(cx);
4843 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4844 let excerpt_id = cursor.excerpt_id;
4845
4846 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4847 && (self.context_menu.borrow().is_some()
4848 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4849 if completions_menu_has_precedence
4850 || !offset_selection.is_empty()
4851 || !self.enable_inline_completions
4852 || self
4853 .active_inline_completion
4854 .as_ref()
4855 .map_or(false, |completion| {
4856 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4857 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4858 !invalidation_range.contains(&offset_selection.head())
4859 })
4860 {
4861 self.discard_inline_completion(false, cx);
4862 return None;
4863 }
4864
4865 self.take_active_inline_completion(cx);
4866 let provider = self.inline_completion_provider()?;
4867
4868 let (buffer, cursor_buffer_position) =
4869 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4870
4871 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4872 let edits = completion
4873 .edits
4874 .into_iter()
4875 .flat_map(|(range, new_text)| {
4876 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4877 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4878 Some((start..end, new_text))
4879 })
4880 .collect::<Vec<_>>();
4881 if edits.is_empty() {
4882 return None;
4883 }
4884
4885 let first_edit_start = edits.first().unwrap().0.start;
4886 let edit_start_row = first_edit_start
4887 .to_point(&multibuffer)
4888 .row
4889 .saturating_sub(2);
4890
4891 let last_edit_end = edits.last().unwrap().0.end;
4892 let edit_end_row = cmp::min(
4893 multibuffer.max_point().row,
4894 last_edit_end.to_point(&multibuffer).row + 2,
4895 );
4896
4897 let cursor_row = cursor.to_point(&multibuffer).row;
4898
4899 let mut inlay_ids = Vec::new();
4900 let invalidation_row_range;
4901 let completion;
4902 if cursor_row < edit_start_row {
4903 invalidation_row_range = cursor_row..edit_end_row;
4904 completion = InlineCompletion::Move(first_edit_start);
4905 } else if cursor_row > edit_end_row {
4906 invalidation_row_range = edit_start_row..cursor_row;
4907 completion = InlineCompletion::Move(first_edit_start);
4908 } else {
4909 if edits
4910 .iter()
4911 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4912 {
4913 let mut inlays = Vec::new();
4914 for (range, new_text) in &edits {
4915 let inlay = Inlay::inline_completion(
4916 post_inc(&mut self.next_inlay_id),
4917 range.start,
4918 new_text.as_str(),
4919 );
4920 inlay_ids.push(inlay.id);
4921 inlays.push(inlay);
4922 }
4923
4924 self.splice_inlays(vec![], inlays, cx);
4925 } else {
4926 let background_color = cx.theme().status().deleted_background;
4927 self.highlight_text::<InlineCompletionHighlight>(
4928 edits.iter().map(|(range, _)| range.clone()).collect(),
4929 HighlightStyle {
4930 background_color: Some(background_color),
4931 ..Default::default()
4932 },
4933 cx,
4934 );
4935 }
4936
4937 invalidation_row_range = edit_start_row..edit_end_row;
4938 completion = InlineCompletion::Edit(edits);
4939 };
4940
4941 let invalidation_range = multibuffer
4942 .anchor_before(Point::new(invalidation_row_range.start, 0))
4943 ..multibuffer.anchor_after(Point::new(
4944 invalidation_row_range.end,
4945 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4946 ));
4947
4948 self.active_inline_completion = Some(InlineCompletionState {
4949 inlay_ids,
4950 completion,
4951 invalidation_range,
4952 });
4953
4954 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4955 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4956 match self.context_menu.borrow_mut().as_mut() {
4957 Some(CodeContextMenu::Completions(menu)) => {
4958 menu.show_inline_completion_hint(hint);
4959 }
4960 _ => {}
4961 }
4962 }
4963 }
4964
4965 cx.notify();
4966
4967 Some(())
4968 }
4969
4970 fn inline_completion_menu_hint(
4971 &mut self,
4972 cx: &mut ViewContext<Self>,
4973 ) -> Option<InlineCompletionMenuHint> {
4974 let provider = self.inline_completion_provider()?;
4975 if self.has_active_inline_completion() {
4976 let editor_snapshot = self.snapshot(cx);
4977
4978 let text = match &self.active_inline_completion.as_ref()?.completion {
4979 InlineCompletion::Edit(edits) => {
4980 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4981 }
4982 InlineCompletion::Move(target) => {
4983 let target_point =
4984 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4985 let target_line = target_point.row + 1;
4986 InlineCompletionText::Move(
4987 format!("Jump to edit in line {}", target_line).into(),
4988 )
4989 }
4990 };
4991
4992 Some(InlineCompletionMenuHint::Loaded { text })
4993 } else if provider.is_refreshing(cx) {
4994 Some(InlineCompletionMenuHint::Loading)
4995 } else if provider.needs_terms_acceptance(cx) {
4996 Some(InlineCompletionMenuHint::PendingTermsAcceptance)
4997 } else {
4998 Some(InlineCompletionMenuHint::None)
4999 }
5000 }
5001
5002 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5003 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5004 }
5005
5006 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
5007 EditorSettings::get_global(cx).show_inline_completions_in_menu
5008 && self
5009 .inline_completion_provider()
5010 .map_or(false, |provider| provider.show_completions_in_menu())
5011 }
5012
5013 fn render_code_actions_indicator(
5014 &self,
5015 _style: &EditorStyle,
5016 row: DisplayRow,
5017 is_active: bool,
5018 cx: &mut ViewContext<Self>,
5019 ) -> Option<IconButton> {
5020 if self.available_code_actions.is_some() {
5021 Some(
5022 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5023 .shape(ui::IconButtonShape::Square)
5024 .icon_size(IconSize::XSmall)
5025 .icon_color(Color::Muted)
5026 .toggle_state(is_active)
5027 .tooltip({
5028 let focus_handle = self.focus_handle.clone();
5029 move |cx| {
5030 Tooltip::for_action_in(
5031 "Toggle Code Actions",
5032 &ToggleCodeActions {
5033 deployed_from_indicator: None,
5034 },
5035 &focus_handle,
5036 cx,
5037 )
5038 }
5039 })
5040 .on_click(cx.listener(move |editor, _e, cx| {
5041 editor.focus(cx);
5042 editor.toggle_code_actions(
5043 &ToggleCodeActions {
5044 deployed_from_indicator: Some(row),
5045 },
5046 cx,
5047 );
5048 })),
5049 )
5050 } else {
5051 None
5052 }
5053 }
5054
5055 fn clear_tasks(&mut self) {
5056 self.tasks.clear()
5057 }
5058
5059 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5060 if self.tasks.insert(key, value).is_some() {
5061 // This case should hopefully be rare, but just in case...
5062 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5063 }
5064 }
5065
5066 fn build_tasks_context(
5067 project: &Model<Project>,
5068 buffer: &Model<Buffer>,
5069 buffer_row: u32,
5070 tasks: &Arc<RunnableTasks>,
5071 cx: &mut ViewContext<Self>,
5072 ) -> Task<Option<task::TaskContext>> {
5073 let position = Point::new(buffer_row, tasks.column);
5074 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5075 let location = Location {
5076 buffer: buffer.clone(),
5077 range: range_start..range_start,
5078 };
5079 // Fill in the environmental variables from the tree-sitter captures
5080 let mut captured_task_variables = TaskVariables::default();
5081 for (capture_name, value) in tasks.extra_variables.clone() {
5082 captured_task_variables.insert(
5083 task::VariableName::Custom(capture_name.into()),
5084 value.clone(),
5085 );
5086 }
5087 project.update(cx, |project, cx| {
5088 project.task_store().update(cx, |task_store, cx| {
5089 task_store.task_context_for_location(captured_task_variables, location, cx)
5090 })
5091 })
5092 }
5093
5094 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5095 let Some((workspace, _)) = self.workspace.clone() else {
5096 return;
5097 };
5098 let Some(project) = self.project.clone() else {
5099 return;
5100 };
5101
5102 // Try to find a closest, enclosing node using tree-sitter that has a
5103 // task
5104 let Some((buffer, buffer_row, tasks)) = self
5105 .find_enclosing_node_task(cx)
5106 // Or find the task that's closest in row-distance.
5107 .or_else(|| self.find_closest_task(cx))
5108 else {
5109 return;
5110 };
5111
5112 let reveal_strategy = action.reveal;
5113 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5114 cx.spawn(|_, mut cx| async move {
5115 let context = task_context.await?;
5116 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5117
5118 let resolved = resolved_task.resolved.as_mut()?;
5119 resolved.reveal = reveal_strategy;
5120
5121 workspace
5122 .update(&mut cx, |workspace, cx| {
5123 workspace::tasks::schedule_resolved_task(
5124 workspace,
5125 task_source_kind,
5126 resolved_task,
5127 false,
5128 cx,
5129 );
5130 })
5131 .ok()
5132 })
5133 .detach();
5134 }
5135
5136 fn find_closest_task(
5137 &mut self,
5138 cx: &mut ViewContext<Self>,
5139 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5140 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5141
5142 let ((buffer_id, row), tasks) = self
5143 .tasks
5144 .iter()
5145 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5146
5147 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5148 let tasks = Arc::new(tasks.to_owned());
5149 Some((buffer, *row, tasks))
5150 }
5151
5152 fn find_enclosing_node_task(
5153 &mut self,
5154 cx: &mut ViewContext<Self>,
5155 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5156 let snapshot = self.buffer.read(cx).snapshot(cx);
5157 let offset = self.selections.newest::<usize>(cx).head();
5158 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5159 let buffer_id = excerpt.buffer().remote_id();
5160
5161 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5162 let mut cursor = layer.node().walk();
5163
5164 while cursor.goto_first_child_for_byte(offset).is_some() {
5165 if cursor.node().end_byte() == offset {
5166 cursor.goto_next_sibling();
5167 }
5168 }
5169
5170 // Ascend to the smallest ancestor that contains the range and has a task.
5171 loop {
5172 let node = cursor.node();
5173 let node_range = node.byte_range();
5174 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5175
5176 // Check if this node contains our offset
5177 if node_range.start <= offset && node_range.end >= offset {
5178 // If it contains offset, check for task
5179 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5180 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5181 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5182 }
5183 }
5184
5185 if !cursor.goto_parent() {
5186 break;
5187 }
5188 }
5189 None
5190 }
5191
5192 fn render_run_indicator(
5193 &self,
5194 _style: &EditorStyle,
5195 is_active: bool,
5196 row: DisplayRow,
5197 cx: &mut ViewContext<Self>,
5198 ) -> IconButton {
5199 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5200 .shape(ui::IconButtonShape::Square)
5201 .icon_size(IconSize::XSmall)
5202 .icon_color(Color::Muted)
5203 .toggle_state(is_active)
5204 .on_click(cx.listener(move |editor, _e, cx| {
5205 editor.focus(cx);
5206 editor.toggle_code_actions(
5207 &ToggleCodeActions {
5208 deployed_from_indicator: Some(row),
5209 },
5210 cx,
5211 );
5212 }))
5213 }
5214
5215 #[cfg(any(feature = "test-support", test))]
5216 pub fn context_menu_visible(&self) -> bool {
5217 self.context_menu
5218 .borrow()
5219 .as_ref()
5220 .map_or(false, |menu| menu.visible())
5221 }
5222
5223 #[cfg(feature = "test-support")]
5224 pub fn context_menu_contains_inline_completion(&self) -> bool {
5225 self.context_menu
5226 .borrow()
5227 .as_ref()
5228 .map_or(false, |menu| match menu {
5229 CodeContextMenu::Completions(menu) => {
5230 menu.entries.borrow().first().map_or(false, |entry| {
5231 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5232 })
5233 }
5234 CodeContextMenu::CodeActions(_) => false,
5235 })
5236 }
5237
5238 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5239 self.context_menu
5240 .borrow()
5241 .as_ref()
5242 .map(|menu| menu.origin(cursor_position))
5243 }
5244
5245 fn render_context_menu(
5246 &self,
5247 style: &EditorStyle,
5248 max_height_in_lines: u32,
5249 y_flipped: bool,
5250 cx: &mut ViewContext<Editor>,
5251 ) -> Option<AnyElement> {
5252 self.context_menu.borrow().as_ref().and_then(|menu| {
5253 if menu.visible() {
5254 Some(menu.render(style, max_height_in_lines, y_flipped, cx))
5255 } else {
5256 None
5257 }
5258 })
5259 }
5260
5261 fn render_context_menu_aside(
5262 &self,
5263 style: &EditorStyle,
5264 max_size: Size<Pixels>,
5265 cx: &mut ViewContext<Editor>,
5266 ) -> Option<AnyElement> {
5267 self.context_menu.borrow().as_ref().and_then(|menu| {
5268 if menu.visible() {
5269 menu.render_aside(
5270 style,
5271 max_size,
5272 self.workspace.as_ref().map(|(w, _)| w.clone()),
5273 cx,
5274 )
5275 } else {
5276 None
5277 }
5278 })
5279 }
5280
5281 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5282 cx.notify();
5283 self.completion_tasks.clear();
5284 let context_menu = self.context_menu.borrow_mut().take();
5285 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5286 self.update_visible_inline_completion(cx);
5287 }
5288 context_menu
5289 }
5290
5291 fn show_snippet_choices(
5292 &mut self,
5293 choices: &Vec<String>,
5294 selection: Range<Anchor>,
5295 cx: &mut ViewContext<Self>,
5296 ) {
5297 if selection.start.buffer_id.is_none() {
5298 return;
5299 }
5300 let buffer_id = selection.start.buffer_id.unwrap();
5301 let buffer = self.buffer().read(cx).buffer(buffer_id);
5302 let id = post_inc(&mut self.next_completion_id);
5303
5304 if let Some(buffer) = buffer {
5305 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5306 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5307 ));
5308 }
5309 }
5310
5311 pub fn insert_snippet(
5312 &mut self,
5313 insertion_ranges: &[Range<usize>],
5314 snippet: Snippet,
5315 cx: &mut ViewContext<Self>,
5316 ) -> Result<()> {
5317 struct Tabstop<T> {
5318 is_end_tabstop: bool,
5319 ranges: Vec<Range<T>>,
5320 choices: Option<Vec<String>>,
5321 }
5322
5323 let tabstops = self.buffer.update(cx, |buffer, cx| {
5324 let snippet_text: Arc<str> = snippet.text.clone().into();
5325 buffer.edit(
5326 insertion_ranges
5327 .iter()
5328 .cloned()
5329 .map(|range| (range, snippet_text.clone())),
5330 Some(AutoindentMode::EachLine),
5331 cx,
5332 );
5333
5334 let snapshot = &*buffer.read(cx);
5335 let snippet = &snippet;
5336 snippet
5337 .tabstops
5338 .iter()
5339 .map(|tabstop| {
5340 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5341 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5342 });
5343 let mut tabstop_ranges = tabstop
5344 .ranges
5345 .iter()
5346 .flat_map(|tabstop_range| {
5347 let mut delta = 0_isize;
5348 insertion_ranges.iter().map(move |insertion_range| {
5349 let insertion_start = insertion_range.start as isize + delta;
5350 delta +=
5351 snippet.text.len() as isize - insertion_range.len() as isize;
5352
5353 let start = ((insertion_start + tabstop_range.start) as usize)
5354 .min(snapshot.len());
5355 let end = ((insertion_start + tabstop_range.end) as usize)
5356 .min(snapshot.len());
5357 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5358 })
5359 })
5360 .collect::<Vec<_>>();
5361 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5362
5363 Tabstop {
5364 is_end_tabstop,
5365 ranges: tabstop_ranges,
5366 choices: tabstop.choices.clone(),
5367 }
5368 })
5369 .collect::<Vec<_>>()
5370 });
5371 if let Some(tabstop) = tabstops.first() {
5372 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5373 s.select_ranges(tabstop.ranges.iter().cloned());
5374 });
5375
5376 if let Some(choices) = &tabstop.choices {
5377 if let Some(selection) = tabstop.ranges.first() {
5378 self.show_snippet_choices(choices, selection.clone(), cx)
5379 }
5380 }
5381
5382 // If we're already at the last tabstop and it's at the end of the snippet,
5383 // we're done, we don't need to keep the state around.
5384 if !tabstop.is_end_tabstop {
5385 let choices = tabstops
5386 .iter()
5387 .map(|tabstop| tabstop.choices.clone())
5388 .collect();
5389
5390 let ranges = tabstops
5391 .into_iter()
5392 .map(|tabstop| tabstop.ranges)
5393 .collect::<Vec<_>>();
5394
5395 self.snippet_stack.push(SnippetState {
5396 active_index: 0,
5397 ranges,
5398 choices,
5399 });
5400 }
5401
5402 // Check whether the just-entered snippet ends with an auto-closable bracket.
5403 if self.autoclose_regions.is_empty() {
5404 let snapshot = self.buffer.read(cx).snapshot(cx);
5405 for selection in &mut self.selections.all::<Point>(cx) {
5406 let selection_head = selection.head();
5407 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5408 continue;
5409 };
5410
5411 let mut bracket_pair = None;
5412 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5413 let prev_chars = snapshot
5414 .reversed_chars_at(selection_head)
5415 .collect::<String>();
5416 for (pair, enabled) in scope.brackets() {
5417 if enabled
5418 && pair.close
5419 && prev_chars.starts_with(pair.start.as_str())
5420 && next_chars.starts_with(pair.end.as_str())
5421 {
5422 bracket_pair = Some(pair.clone());
5423 break;
5424 }
5425 }
5426 if let Some(pair) = bracket_pair {
5427 let start = snapshot.anchor_after(selection_head);
5428 let end = snapshot.anchor_after(selection_head);
5429 self.autoclose_regions.push(AutocloseRegion {
5430 selection_id: selection.id,
5431 range: start..end,
5432 pair,
5433 });
5434 }
5435 }
5436 }
5437 }
5438 Ok(())
5439 }
5440
5441 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5442 self.move_to_snippet_tabstop(Bias::Right, cx)
5443 }
5444
5445 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5446 self.move_to_snippet_tabstop(Bias::Left, cx)
5447 }
5448
5449 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5450 if let Some(mut snippet) = self.snippet_stack.pop() {
5451 match bias {
5452 Bias::Left => {
5453 if snippet.active_index > 0 {
5454 snippet.active_index -= 1;
5455 } else {
5456 self.snippet_stack.push(snippet);
5457 return false;
5458 }
5459 }
5460 Bias::Right => {
5461 if snippet.active_index + 1 < snippet.ranges.len() {
5462 snippet.active_index += 1;
5463 } else {
5464 self.snippet_stack.push(snippet);
5465 return false;
5466 }
5467 }
5468 }
5469 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5471 s.select_anchor_ranges(current_ranges.iter().cloned())
5472 });
5473
5474 if let Some(choices) = &snippet.choices[snippet.active_index] {
5475 if let Some(selection) = current_ranges.first() {
5476 self.show_snippet_choices(&choices, selection.clone(), cx);
5477 }
5478 }
5479
5480 // If snippet state is not at the last tabstop, push it back on the stack
5481 if snippet.active_index + 1 < snippet.ranges.len() {
5482 self.snippet_stack.push(snippet);
5483 }
5484 return true;
5485 }
5486 }
5487
5488 false
5489 }
5490
5491 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5492 self.transact(cx, |this, cx| {
5493 this.select_all(&SelectAll, cx);
5494 this.insert("", cx);
5495 });
5496 }
5497
5498 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5499 self.transact(cx, |this, cx| {
5500 this.select_autoclose_pair(cx);
5501 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5502 if !this.linked_edit_ranges.is_empty() {
5503 let selections = this.selections.all::<MultiBufferPoint>(cx);
5504 let snapshot = this.buffer.read(cx).snapshot(cx);
5505
5506 for selection in selections.iter() {
5507 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5508 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5509 if selection_start.buffer_id != selection_end.buffer_id {
5510 continue;
5511 }
5512 if let Some(ranges) =
5513 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5514 {
5515 for (buffer, entries) in ranges {
5516 linked_ranges.entry(buffer).or_default().extend(entries);
5517 }
5518 }
5519 }
5520 }
5521
5522 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5523 if !this.selections.line_mode {
5524 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5525 for selection in &mut selections {
5526 if selection.is_empty() {
5527 let old_head = selection.head();
5528 let mut new_head =
5529 movement::left(&display_map, old_head.to_display_point(&display_map))
5530 .to_point(&display_map);
5531 if let Some((buffer, line_buffer_range)) = display_map
5532 .buffer_snapshot
5533 .buffer_line_for_row(MultiBufferRow(old_head.row))
5534 {
5535 let indent_size =
5536 buffer.indent_size_for_line(line_buffer_range.start.row);
5537 let indent_len = match indent_size.kind {
5538 IndentKind::Space => {
5539 buffer.settings_at(line_buffer_range.start, cx).tab_size
5540 }
5541 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5542 };
5543 if old_head.column <= indent_size.len && old_head.column > 0 {
5544 let indent_len = indent_len.get();
5545 new_head = cmp::min(
5546 new_head,
5547 MultiBufferPoint::new(
5548 old_head.row,
5549 ((old_head.column - 1) / indent_len) * indent_len,
5550 ),
5551 );
5552 }
5553 }
5554
5555 selection.set_head(new_head, SelectionGoal::None);
5556 }
5557 }
5558 }
5559
5560 this.signature_help_state.set_backspace_pressed(true);
5561 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5562 this.insert("", cx);
5563 let empty_str: Arc<str> = Arc::from("");
5564 for (buffer, edits) in linked_ranges {
5565 let snapshot = buffer.read(cx).snapshot();
5566 use text::ToPoint as TP;
5567
5568 let edits = edits
5569 .into_iter()
5570 .map(|range| {
5571 let end_point = TP::to_point(&range.end, &snapshot);
5572 let mut start_point = TP::to_point(&range.start, &snapshot);
5573
5574 if end_point == start_point {
5575 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5576 .saturating_sub(1);
5577 start_point =
5578 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5579 };
5580
5581 (start_point..end_point, empty_str.clone())
5582 })
5583 .sorted_by_key(|(range, _)| range.start)
5584 .collect::<Vec<_>>();
5585 buffer.update(cx, |this, cx| {
5586 this.edit(edits, None, cx);
5587 })
5588 }
5589 this.refresh_inline_completion(true, false, cx);
5590 linked_editing_ranges::refresh_linked_ranges(this, cx);
5591 });
5592 }
5593
5594 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5595 self.transact(cx, |this, cx| {
5596 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5597 let line_mode = s.line_mode;
5598 s.move_with(|map, selection| {
5599 if selection.is_empty() && !line_mode {
5600 let cursor = movement::right(map, selection.head());
5601 selection.end = cursor;
5602 selection.reversed = true;
5603 selection.goal = SelectionGoal::None;
5604 }
5605 })
5606 });
5607 this.insert("", cx);
5608 this.refresh_inline_completion(true, false, cx);
5609 });
5610 }
5611
5612 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5613 if self.move_to_prev_snippet_tabstop(cx) {
5614 return;
5615 }
5616
5617 self.outdent(&Outdent, cx);
5618 }
5619
5620 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5621 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5622 return;
5623 }
5624
5625 let mut selections = self.selections.all_adjusted(cx);
5626 let buffer = self.buffer.read(cx);
5627 let snapshot = buffer.snapshot(cx);
5628 let rows_iter = selections.iter().map(|s| s.head().row);
5629 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5630
5631 let mut edits = Vec::new();
5632 let mut prev_edited_row = 0;
5633 let mut row_delta = 0;
5634 for selection in &mut selections {
5635 if selection.start.row != prev_edited_row {
5636 row_delta = 0;
5637 }
5638 prev_edited_row = selection.end.row;
5639
5640 // If the selection is non-empty, then increase the indentation of the selected lines.
5641 if !selection.is_empty() {
5642 row_delta =
5643 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5644 continue;
5645 }
5646
5647 // If the selection is empty and the cursor is in the leading whitespace before the
5648 // suggested indentation, then auto-indent the line.
5649 let cursor = selection.head();
5650 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5651 if let Some(suggested_indent) =
5652 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5653 {
5654 if cursor.column < suggested_indent.len
5655 && cursor.column <= current_indent.len
5656 && current_indent.len <= suggested_indent.len
5657 {
5658 selection.start = Point::new(cursor.row, suggested_indent.len);
5659 selection.end = selection.start;
5660 if row_delta == 0 {
5661 edits.extend(Buffer::edit_for_indent_size_adjustment(
5662 cursor.row,
5663 current_indent,
5664 suggested_indent,
5665 ));
5666 row_delta = suggested_indent.len - current_indent.len;
5667 }
5668 continue;
5669 }
5670 }
5671
5672 // Otherwise, insert a hard or soft tab.
5673 let settings = buffer.settings_at(cursor, cx);
5674 let tab_size = if settings.hard_tabs {
5675 IndentSize::tab()
5676 } else {
5677 let tab_size = settings.tab_size.get();
5678 let char_column = snapshot
5679 .text_for_range(Point::new(cursor.row, 0)..cursor)
5680 .flat_map(str::chars)
5681 .count()
5682 + row_delta as usize;
5683 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5684 IndentSize::spaces(chars_to_next_tab_stop)
5685 };
5686 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5687 selection.end = selection.start;
5688 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5689 row_delta += tab_size.len;
5690 }
5691
5692 self.transact(cx, |this, cx| {
5693 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5694 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5695 this.refresh_inline_completion(true, false, cx);
5696 });
5697 }
5698
5699 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5700 if self.read_only(cx) {
5701 return;
5702 }
5703 let mut selections = self.selections.all::<Point>(cx);
5704 let mut prev_edited_row = 0;
5705 let mut row_delta = 0;
5706 let mut edits = Vec::new();
5707 let buffer = self.buffer.read(cx);
5708 let snapshot = buffer.snapshot(cx);
5709 for selection in &mut selections {
5710 if selection.start.row != prev_edited_row {
5711 row_delta = 0;
5712 }
5713 prev_edited_row = selection.end.row;
5714
5715 row_delta =
5716 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5717 }
5718
5719 self.transact(cx, |this, cx| {
5720 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5721 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5722 });
5723 }
5724
5725 fn indent_selection(
5726 buffer: &MultiBuffer,
5727 snapshot: &MultiBufferSnapshot,
5728 selection: &mut Selection<Point>,
5729 edits: &mut Vec<(Range<Point>, String)>,
5730 delta_for_start_row: u32,
5731 cx: &AppContext,
5732 ) -> u32 {
5733 let settings = buffer.settings_at(selection.start, cx);
5734 let tab_size = settings.tab_size.get();
5735 let indent_kind = if settings.hard_tabs {
5736 IndentKind::Tab
5737 } else {
5738 IndentKind::Space
5739 };
5740 let mut start_row = selection.start.row;
5741 let mut end_row = selection.end.row + 1;
5742
5743 // If a selection ends at the beginning of a line, don't indent
5744 // that last line.
5745 if selection.end.column == 0 && selection.end.row > selection.start.row {
5746 end_row -= 1;
5747 }
5748
5749 // Avoid re-indenting a row that has already been indented by a
5750 // previous selection, but still update this selection's column
5751 // to reflect that indentation.
5752 if delta_for_start_row > 0 {
5753 start_row += 1;
5754 selection.start.column += delta_for_start_row;
5755 if selection.end.row == selection.start.row {
5756 selection.end.column += delta_for_start_row;
5757 }
5758 }
5759
5760 let mut delta_for_end_row = 0;
5761 let has_multiple_rows = start_row + 1 != end_row;
5762 for row in start_row..end_row {
5763 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5764 let indent_delta = match (current_indent.kind, indent_kind) {
5765 (IndentKind::Space, IndentKind::Space) => {
5766 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5767 IndentSize::spaces(columns_to_next_tab_stop)
5768 }
5769 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5770 (_, IndentKind::Tab) => IndentSize::tab(),
5771 };
5772
5773 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5774 0
5775 } else {
5776 selection.start.column
5777 };
5778 let row_start = Point::new(row, start);
5779 edits.push((
5780 row_start..row_start,
5781 indent_delta.chars().collect::<String>(),
5782 ));
5783
5784 // Update this selection's endpoints to reflect the indentation.
5785 if row == selection.start.row {
5786 selection.start.column += indent_delta.len;
5787 }
5788 if row == selection.end.row {
5789 selection.end.column += indent_delta.len;
5790 delta_for_end_row = indent_delta.len;
5791 }
5792 }
5793
5794 if selection.start.row == selection.end.row {
5795 delta_for_start_row + delta_for_end_row
5796 } else {
5797 delta_for_end_row
5798 }
5799 }
5800
5801 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5802 if self.read_only(cx) {
5803 return;
5804 }
5805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5806 let selections = self.selections.all::<Point>(cx);
5807 let mut deletion_ranges = Vec::new();
5808 let mut last_outdent = None;
5809 {
5810 let buffer = self.buffer.read(cx);
5811 let snapshot = buffer.snapshot(cx);
5812 for selection in &selections {
5813 let settings = buffer.settings_at(selection.start, cx);
5814 let tab_size = settings.tab_size.get();
5815 let mut rows = selection.spanned_rows(false, &display_map);
5816
5817 // Avoid re-outdenting a row that has already been outdented by a
5818 // previous selection.
5819 if let Some(last_row) = last_outdent {
5820 if last_row == rows.start {
5821 rows.start = rows.start.next_row();
5822 }
5823 }
5824 let has_multiple_rows = rows.len() > 1;
5825 for row in rows.iter_rows() {
5826 let indent_size = snapshot.indent_size_for_line(row);
5827 if indent_size.len > 0 {
5828 let deletion_len = match indent_size.kind {
5829 IndentKind::Space => {
5830 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5831 if columns_to_prev_tab_stop == 0 {
5832 tab_size
5833 } else {
5834 columns_to_prev_tab_stop
5835 }
5836 }
5837 IndentKind::Tab => 1,
5838 };
5839 let start = if has_multiple_rows
5840 || deletion_len > selection.start.column
5841 || indent_size.len < selection.start.column
5842 {
5843 0
5844 } else {
5845 selection.start.column - deletion_len
5846 };
5847 deletion_ranges.push(
5848 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5849 );
5850 last_outdent = Some(row);
5851 }
5852 }
5853 }
5854 }
5855
5856 self.transact(cx, |this, cx| {
5857 this.buffer.update(cx, |buffer, cx| {
5858 let empty_str: Arc<str> = Arc::default();
5859 buffer.edit(
5860 deletion_ranges
5861 .into_iter()
5862 .map(|range| (range, empty_str.clone())),
5863 None,
5864 cx,
5865 );
5866 });
5867 let selections = this.selections.all::<usize>(cx);
5868 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5869 });
5870 }
5871
5872 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5873 if self.read_only(cx) {
5874 return;
5875 }
5876 let selections = self
5877 .selections
5878 .all::<usize>(cx)
5879 .into_iter()
5880 .map(|s| s.range());
5881
5882 self.transact(cx, |this, cx| {
5883 this.buffer.update(cx, |buffer, cx| {
5884 buffer.autoindent_ranges(selections, cx);
5885 });
5886 let selections = this.selections.all::<usize>(cx);
5887 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5888 });
5889 }
5890
5891 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5892 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5893 let selections = self.selections.all::<Point>(cx);
5894
5895 let mut new_cursors = Vec::new();
5896 let mut edit_ranges = Vec::new();
5897 let mut selections = selections.iter().peekable();
5898 while let Some(selection) = selections.next() {
5899 let mut rows = selection.spanned_rows(false, &display_map);
5900 let goal_display_column = selection.head().to_display_point(&display_map).column();
5901
5902 // Accumulate contiguous regions of rows that we want to delete.
5903 while let Some(next_selection) = selections.peek() {
5904 let next_rows = next_selection.spanned_rows(false, &display_map);
5905 if next_rows.start <= rows.end {
5906 rows.end = next_rows.end;
5907 selections.next().unwrap();
5908 } else {
5909 break;
5910 }
5911 }
5912
5913 let buffer = &display_map.buffer_snapshot;
5914 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5915 let edit_end;
5916 let cursor_buffer_row;
5917 if buffer.max_point().row >= rows.end.0 {
5918 // If there's a line after the range, delete the \n from the end of the row range
5919 // and position the cursor on the next line.
5920 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5921 cursor_buffer_row = rows.end;
5922 } else {
5923 // If there isn't a line after the range, delete the \n from the line before the
5924 // start of the row range and position the cursor there.
5925 edit_start = edit_start.saturating_sub(1);
5926 edit_end = buffer.len();
5927 cursor_buffer_row = rows.start.previous_row();
5928 }
5929
5930 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5931 *cursor.column_mut() =
5932 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5933
5934 new_cursors.push((
5935 selection.id,
5936 buffer.anchor_after(cursor.to_point(&display_map)),
5937 ));
5938 edit_ranges.push(edit_start..edit_end);
5939 }
5940
5941 self.transact(cx, |this, cx| {
5942 let buffer = this.buffer.update(cx, |buffer, cx| {
5943 let empty_str: Arc<str> = Arc::default();
5944 buffer.edit(
5945 edit_ranges
5946 .into_iter()
5947 .map(|range| (range, empty_str.clone())),
5948 None,
5949 cx,
5950 );
5951 buffer.snapshot(cx)
5952 });
5953 let new_selections = new_cursors
5954 .into_iter()
5955 .map(|(id, cursor)| {
5956 let cursor = cursor.to_point(&buffer);
5957 Selection {
5958 id,
5959 start: cursor,
5960 end: cursor,
5961 reversed: false,
5962 goal: SelectionGoal::None,
5963 }
5964 })
5965 .collect();
5966
5967 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5968 s.select(new_selections);
5969 });
5970 });
5971 }
5972
5973 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5974 if self.read_only(cx) {
5975 return;
5976 }
5977 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5978 for selection in self.selections.all::<Point>(cx) {
5979 let start = MultiBufferRow(selection.start.row);
5980 // Treat single line selections as if they include the next line. Otherwise this action
5981 // would do nothing for single line selections individual cursors.
5982 let end = if selection.start.row == selection.end.row {
5983 MultiBufferRow(selection.start.row + 1)
5984 } else {
5985 MultiBufferRow(selection.end.row)
5986 };
5987
5988 if let Some(last_row_range) = row_ranges.last_mut() {
5989 if start <= last_row_range.end {
5990 last_row_range.end = end;
5991 continue;
5992 }
5993 }
5994 row_ranges.push(start..end);
5995 }
5996
5997 let snapshot = self.buffer.read(cx).snapshot(cx);
5998 let mut cursor_positions = Vec::new();
5999 for row_range in &row_ranges {
6000 let anchor = snapshot.anchor_before(Point::new(
6001 row_range.end.previous_row().0,
6002 snapshot.line_len(row_range.end.previous_row()),
6003 ));
6004 cursor_positions.push(anchor..anchor);
6005 }
6006
6007 self.transact(cx, |this, cx| {
6008 for row_range in row_ranges.into_iter().rev() {
6009 for row in row_range.iter_rows().rev() {
6010 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6011 let next_line_row = row.next_row();
6012 let indent = snapshot.indent_size_for_line(next_line_row);
6013 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6014
6015 let replace =
6016 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6017 " "
6018 } else {
6019 ""
6020 };
6021
6022 this.buffer.update(cx, |buffer, cx| {
6023 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6024 });
6025 }
6026 }
6027
6028 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6029 s.select_anchor_ranges(cursor_positions)
6030 });
6031 });
6032 }
6033
6034 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6035 self.join_lines_impl(true, cx);
6036 }
6037
6038 pub fn sort_lines_case_sensitive(
6039 &mut self,
6040 _: &SortLinesCaseSensitive,
6041 cx: &mut ViewContext<Self>,
6042 ) {
6043 self.manipulate_lines(cx, |lines| lines.sort())
6044 }
6045
6046 pub fn sort_lines_case_insensitive(
6047 &mut self,
6048 _: &SortLinesCaseInsensitive,
6049 cx: &mut ViewContext<Self>,
6050 ) {
6051 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6052 }
6053
6054 pub fn unique_lines_case_insensitive(
6055 &mut self,
6056 _: &UniqueLinesCaseInsensitive,
6057 cx: &mut ViewContext<Self>,
6058 ) {
6059 self.manipulate_lines(cx, |lines| {
6060 let mut seen = HashSet::default();
6061 lines.retain(|line| seen.insert(line.to_lowercase()));
6062 })
6063 }
6064
6065 pub fn unique_lines_case_sensitive(
6066 &mut self,
6067 _: &UniqueLinesCaseSensitive,
6068 cx: &mut ViewContext<Self>,
6069 ) {
6070 self.manipulate_lines(cx, |lines| {
6071 let mut seen = HashSet::default();
6072 lines.retain(|line| seen.insert(*line));
6073 })
6074 }
6075
6076 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6077 let mut revert_changes = HashMap::default();
6078 let snapshot = self.snapshot(cx);
6079 for hunk in hunks_for_ranges(
6080 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6081 &snapshot,
6082 ) {
6083 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6084 }
6085 if !revert_changes.is_empty() {
6086 self.transact(cx, |editor, cx| {
6087 editor.revert(revert_changes, cx);
6088 });
6089 }
6090 }
6091
6092 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6093 let Some(project) = self.project.clone() else {
6094 return;
6095 };
6096 self.reload(project, cx).detach_and_notify_err(cx);
6097 }
6098
6099 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6100 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6101 if !revert_changes.is_empty() {
6102 self.transact(cx, |editor, cx| {
6103 editor.revert(revert_changes, cx);
6104 });
6105 }
6106 }
6107
6108 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6109 let snapshot = self.buffer.read(cx).read(cx);
6110 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6111 drop(snapshot);
6112 let mut revert_changes = HashMap::default();
6113 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6114 if !revert_changes.is_empty() {
6115 self.revert(revert_changes, cx)
6116 }
6117 }
6118 }
6119
6120 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6121 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6122 let project_path = buffer.read(cx).project_path(cx)?;
6123 let project = self.project.as_ref()?.read(cx);
6124 let entry = project.entry_for_path(&project_path, cx)?;
6125 let parent = match &entry.canonical_path {
6126 Some(canonical_path) => canonical_path.to_path_buf(),
6127 None => project.absolute_path(&project_path, cx)?,
6128 }
6129 .parent()?
6130 .to_path_buf();
6131 Some(parent)
6132 }) {
6133 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6134 }
6135 }
6136
6137 fn gather_revert_changes(
6138 &mut self,
6139 selections: &[Selection<Point>],
6140 cx: &mut ViewContext<Editor>,
6141 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6142 let mut revert_changes = HashMap::default();
6143 let snapshot = self.snapshot(cx);
6144 for hunk in hunks_for_selections(&snapshot, selections) {
6145 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6146 }
6147 revert_changes
6148 }
6149
6150 pub fn prepare_revert_change(
6151 &mut self,
6152 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6153 hunk: &MultiBufferDiffHunk,
6154 cx: &AppContext,
6155 ) -> Option<()> {
6156 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6157 let buffer = buffer.read(cx);
6158 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6159 let original_text = change_set
6160 .read(cx)
6161 .base_text
6162 .as_ref()?
6163 .read(cx)
6164 .as_rope()
6165 .slice(hunk.diff_base_byte_range.clone());
6166 let buffer_snapshot = buffer.snapshot();
6167 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6168 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6169 probe
6170 .0
6171 .start
6172 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6173 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6174 }) {
6175 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6176 Some(())
6177 } else {
6178 None
6179 }
6180 }
6181
6182 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6183 self.manipulate_lines(cx, |lines| lines.reverse())
6184 }
6185
6186 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6187 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6188 }
6189
6190 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6191 where
6192 Fn: FnMut(&mut Vec<&str>),
6193 {
6194 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6195 let buffer = self.buffer.read(cx).snapshot(cx);
6196
6197 let mut edits = Vec::new();
6198
6199 let selections = self.selections.all::<Point>(cx);
6200 let mut selections = selections.iter().peekable();
6201 let mut contiguous_row_selections = Vec::new();
6202 let mut new_selections = Vec::new();
6203 let mut added_lines = 0;
6204 let mut removed_lines = 0;
6205
6206 while let Some(selection) = selections.next() {
6207 let (start_row, end_row) = consume_contiguous_rows(
6208 &mut contiguous_row_selections,
6209 selection,
6210 &display_map,
6211 &mut selections,
6212 );
6213
6214 let start_point = Point::new(start_row.0, 0);
6215 let end_point = Point::new(
6216 end_row.previous_row().0,
6217 buffer.line_len(end_row.previous_row()),
6218 );
6219 let text = buffer
6220 .text_for_range(start_point..end_point)
6221 .collect::<String>();
6222
6223 let mut lines = text.split('\n').collect_vec();
6224
6225 let lines_before = lines.len();
6226 callback(&mut lines);
6227 let lines_after = lines.len();
6228
6229 edits.push((start_point..end_point, lines.join("\n")));
6230
6231 // Selections must change based on added and removed line count
6232 let start_row =
6233 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6234 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6235 new_selections.push(Selection {
6236 id: selection.id,
6237 start: start_row,
6238 end: end_row,
6239 goal: SelectionGoal::None,
6240 reversed: selection.reversed,
6241 });
6242
6243 if lines_after > lines_before {
6244 added_lines += lines_after - lines_before;
6245 } else if lines_before > lines_after {
6246 removed_lines += lines_before - lines_after;
6247 }
6248 }
6249
6250 self.transact(cx, |this, cx| {
6251 let buffer = this.buffer.update(cx, |buffer, cx| {
6252 buffer.edit(edits, None, cx);
6253 buffer.snapshot(cx)
6254 });
6255
6256 // Recalculate offsets on newly edited buffer
6257 let new_selections = new_selections
6258 .iter()
6259 .map(|s| {
6260 let start_point = Point::new(s.start.0, 0);
6261 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6262 Selection {
6263 id: s.id,
6264 start: buffer.point_to_offset(start_point),
6265 end: buffer.point_to_offset(end_point),
6266 goal: s.goal,
6267 reversed: s.reversed,
6268 }
6269 })
6270 .collect();
6271
6272 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6273 s.select(new_selections);
6274 });
6275
6276 this.request_autoscroll(Autoscroll::fit(), cx);
6277 });
6278 }
6279
6280 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6281 self.manipulate_text(cx, |text| text.to_uppercase())
6282 }
6283
6284 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6285 self.manipulate_text(cx, |text| text.to_lowercase())
6286 }
6287
6288 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6289 self.manipulate_text(cx, |text| {
6290 text.split('\n')
6291 .map(|line| line.to_case(Case::Title))
6292 .join("\n")
6293 })
6294 }
6295
6296 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6297 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6298 }
6299
6300 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6301 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6302 }
6303
6304 pub fn convert_to_upper_camel_case(
6305 &mut self,
6306 _: &ConvertToUpperCamelCase,
6307 cx: &mut ViewContext<Self>,
6308 ) {
6309 self.manipulate_text(cx, |text| {
6310 text.split('\n')
6311 .map(|line| line.to_case(Case::UpperCamel))
6312 .join("\n")
6313 })
6314 }
6315
6316 pub fn convert_to_lower_camel_case(
6317 &mut self,
6318 _: &ConvertToLowerCamelCase,
6319 cx: &mut ViewContext<Self>,
6320 ) {
6321 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6322 }
6323
6324 pub fn convert_to_opposite_case(
6325 &mut self,
6326 _: &ConvertToOppositeCase,
6327 cx: &mut ViewContext<Self>,
6328 ) {
6329 self.manipulate_text(cx, |text| {
6330 text.chars()
6331 .fold(String::with_capacity(text.len()), |mut t, c| {
6332 if c.is_uppercase() {
6333 t.extend(c.to_lowercase());
6334 } else {
6335 t.extend(c.to_uppercase());
6336 }
6337 t
6338 })
6339 })
6340 }
6341
6342 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6343 where
6344 Fn: FnMut(&str) -> String,
6345 {
6346 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6347 let buffer = self.buffer.read(cx).snapshot(cx);
6348
6349 let mut new_selections = Vec::new();
6350 let mut edits = Vec::new();
6351 let mut selection_adjustment = 0i32;
6352
6353 for selection in self.selections.all::<usize>(cx) {
6354 let selection_is_empty = selection.is_empty();
6355
6356 let (start, end) = if selection_is_empty {
6357 let word_range = movement::surrounding_word(
6358 &display_map,
6359 selection.start.to_display_point(&display_map),
6360 );
6361 let start = word_range.start.to_offset(&display_map, Bias::Left);
6362 let end = word_range.end.to_offset(&display_map, Bias::Left);
6363 (start, end)
6364 } else {
6365 (selection.start, selection.end)
6366 };
6367
6368 let text = buffer.text_for_range(start..end).collect::<String>();
6369 let old_length = text.len() as i32;
6370 let text = callback(&text);
6371
6372 new_selections.push(Selection {
6373 start: (start as i32 - selection_adjustment) as usize,
6374 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6375 goal: SelectionGoal::None,
6376 ..selection
6377 });
6378
6379 selection_adjustment += old_length - text.len() as i32;
6380
6381 edits.push((start..end, text));
6382 }
6383
6384 self.transact(cx, |this, cx| {
6385 this.buffer.update(cx, |buffer, cx| {
6386 buffer.edit(edits, None, cx);
6387 });
6388
6389 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6390 s.select(new_selections);
6391 });
6392
6393 this.request_autoscroll(Autoscroll::fit(), cx);
6394 });
6395 }
6396
6397 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6399 let buffer = &display_map.buffer_snapshot;
6400 let selections = self.selections.all::<Point>(cx);
6401
6402 let mut edits = Vec::new();
6403 let mut selections_iter = selections.iter().peekable();
6404 while let Some(selection) = selections_iter.next() {
6405 let mut rows = selection.spanned_rows(false, &display_map);
6406 // duplicate line-wise
6407 if whole_lines || selection.start == selection.end {
6408 // Avoid duplicating the same lines twice.
6409 while let Some(next_selection) = selections_iter.peek() {
6410 let next_rows = next_selection.spanned_rows(false, &display_map);
6411 if next_rows.start < rows.end {
6412 rows.end = next_rows.end;
6413 selections_iter.next().unwrap();
6414 } else {
6415 break;
6416 }
6417 }
6418
6419 // Copy the text from the selected row region and splice it either at the start
6420 // or end of the region.
6421 let start = Point::new(rows.start.0, 0);
6422 let end = Point::new(
6423 rows.end.previous_row().0,
6424 buffer.line_len(rows.end.previous_row()),
6425 );
6426 let text = buffer
6427 .text_for_range(start..end)
6428 .chain(Some("\n"))
6429 .collect::<String>();
6430 let insert_location = if upwards {
6431 Point::new(rows.end.0, 0)
6432 } else {
6433 start
6434 };
6435 edits.push((insert_location..insert_location, text));
6436 } else {
6437 // duplicate character-wise
6438 let start = selection.start;
6439 let end = selection.end;
6440 let text = buffer.text_for_range(start..end).collect::<String>();
6441 edits.push((selection.end..selection.end, text));
6442 }
6443 }
6444
6445 self.transact(cx, |this, cx| {
6446 this.buffer.update(cx, |buffer, cx| {
6447 buffer.edit(edits, None, cx);
6448 });
6449
6450 this.request_autoscroll(Autoscroll::fit(), cx);
6451 });
6452 }
6453
6454 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6455 self.duplicate(true, true, cx);
6456 }
6457
6458 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6459 self.duplicate(false, true, cx);
6460 }
6461
6462 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6463 self.duplicate(false, false, cx);
6464 }
6465
6466 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6468 let buffer = self.buffer.read(cx).snapshot(cx);
6469
6470 let mut edits = Vec::new();
6471 let mut unfold_ranges = Vec::new();
6472 let mut refold_creases = Vec::new();
6473
6474 let selections = self.selections.all::<Point>(cx);
6475 let mut selections = selections.iter().peekable();
6476 let mut contiguous_row_selections = Vec::new();
6477 let mut new_selections = Vec::new();
6478
6479 while let Some(selection) = selections.next() {
6480 // Find all the selections that span a contiguous row range
6481 let (start_row, end_row) = consume_contiguous_rows(
6482 &mut contiguous_row_selections,
6483 selection,
6484 &display_map,
6485 &mut selections,
6486 );
6487
6488 // Move the text spanned by the row range to be before the line preceding the row range
6489 if start_row.0 > 0 {
6490 let range_to_move = Point::new(
6491 start_row.previous_row().0,
6492 buffer.line_len(start_row.previous_row()),
6493 )
6494 ..Point::new(
6495 end_row.previous_row().0,
6496 buffer.line_len(end_row.previous_row()),
6497 );
6498 let insertion_point = display_map
6499 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6500 .0;
6501
6502 // Don't move lines across excerpts
6503 if buffer
6504 .excerpt_boundaries_in_range((
6505 Bound::Excluded(insertion_point),
6506 Bound::Included(range_to_move.end),
6507 ))
6508 .next()
6509 .is_none()
6510 {
6511 let text = buffer
6512 .text_for_range(range_to_move.clone())
6513 .flat_map(|s| s.chars())
6514 .skip(1)
6515 .chain(['\n'])
6516 .collect::<String>();
6517
6518 edits.push((
6519 buffer.anchor_after(range_to_move.start)
6520 ..buffer.anchor_before(range_to_move.end),
6521 String::new(),
6522 ));
6523 let insertion_anchor = buffer.anchor_after(insertion_point);
6524 edits.push((insertion_anchor..insertion_anchor, text));
6525
6526 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6527
6528 // Move selections up
6529 new_selections.extend(contiguous_row_selections.drain(..).map(
6530 |mut selection| {
6531 selection.start.row -= row_delta;
6532 selection.end.row -= row_delta;
6533 selection
6534 },
6535 ));
6536
6537 // Move folds up
6538 unfold_ranges.push(range_to_move.clone());
6539 for fold in display_map.folds_in_range(
6540 buffer.anchor_before(range_to_move.start)
6541 ..buffer.anchor_after(range_to_move.end),
6542 ) {
6543 let mut start = fold.range.start.to_point(&buffer);
6544 let mut end = fold.range.end.to_point(&buffer);
6545 start.row -= row_delta;
6546 end.row -= row_delta;
6547 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6548 }
6549 }
6550 }
6551
6552 // If we didn't move line(s), preserve the existing selections
6553 new_selections.append(&mut contiguous_row_selections);
6554 }
6555
6556 self.transact(cx, |this, cx| {
6557 this.unfold_ranges(&unfold_ranges, true, true, cx);
6558 this.buffer.update(cx, |buffer, cx| {
6559 for (range, text) in edits {
6560 buffer.edit([(range, text)], None, cx);
6561 }
6562 });
6563 this.fold_creases(refold_creases, true, cx);
6564 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6565 s.select(new_selections);
6566 })
6567 });
6568 }
6569
6570 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6571 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6572 let buffer = self.buffer.read(cx).snapshot(cx);
6573
6574 let mut edits = Vec::new();
6575 let mut unfold_ranges = Vec::new();
6576 let mut refold_creases = Vec::new();
6577
6578 let selections = self.selections.all::<Point>(cx);
6579 let mut selections = selections.iter().peekable();
6580 let mut contiguous_row_selections = Vec::new();
6581 let mut new_selections = Vec::new();
6582
6583 while let Some(selection) = selections.next() {
6584 // Find all the selections that span a contiguous row range
6585 let (start_row, end_row) = consume_contiguous_rows(
6586 &mut contiguous_row_selections,
6587 selection,
6588 &display_map,
6589 &mut selections,
6590 );
6591
6592 // Move the text spanned by the row range to be after the last line of the row range
6593 if end_row.0 <= buffer.max_point().row {
6594 let range_to_move =
6595 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6596 let insertion_point = display_map
6597 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6598 .0;
6599
6600 // Don't move lines across excerpt boundaries
6601 if buffer
6602 .excerpt_boundaries_in_range((
6603 Bound::Excluded(range_to_move.start),
6604 Bound::Included(insertion_point),
6605 ))
6606 .next()
6607 .is_none()
6608 {
6609 let mut text = String::from("\n");
6610 text.extend(buffer.text_for_range(range_to_move.clone()));
6611 text.pop(); // Drop trailing newline
6612 edits.push((
6613 buffer.anchor_after(range_to_move.start)
6614 ..buffer.anchor_before(range_to_move.end),
6615 String::new(),
6616 ));
6617 let insertion_anchor = buffer.anchor_after(insertion_point);
6618 edits.push((insertion_anchor..insertion_anchor, text));
6619
6620 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6621
6622 // Move selections down
6623 new_selections.extend(contiguous_row_selections.drain(..).map(
6624 |mut selection| {
6625 selection.start.row += row_delta;
6626 selection.end.row += row_delta;
6627 selection
6628 },
6629 ));
6630
6631 // Move folds down
6632 unfold_ranges.push(range_to_move.clone());
6633 for fold in display_map.folds_in_range(
6634 buffer.anchor_before(range_to_move.start)
6635 ..buffer.anchor_after(range_to_move.end),
6636 ) {
6637 let mut start = fold.range.start.to_point(&buffer);
6638 let mut end = fold.range.end.to_point(&buffer);
6639 start.row += row_delta;
6640 end.row += row_delta;
6641 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6642 }
6643 }
6644 }
6645
6646 // If we didn't move line(s), preserve the existing selections
6647 new_selections.append(&mut contiguous_row_selections);
6648 }
6649
6650 self.transact(cx, |this, cx| {
6651 this.unfold_ranges(&unfold_ranges, true, true, cx);
6652 this.buffer.update(cx, |buffer, cx| {
6653 for (range, text) in edits {
6654 buffer.edit([(range, text)], None, cx);
6655 }
6656 });
6657 this.fold_creases(refold_creases, true, cx);
6658 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6659 });
6660 }
6661
6662 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6663 let text_layout_details = &self.text_layout_details(cx);
6664 self.transact(cx, |this, cx| {
6665 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6666 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6667 let line_mode = s.line_mode;
6668 s.move_with(|display_map, selection| {
6669 if !selection.is_empty() || line_mode {
6670 return;
6671 }
6672
6673 let mut head = selection.head();
6674 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6675 if head.column() == display_map.line_len(head.row()) {
6676 transpose_offset = display_map
6677 .buffer_snapshot
6678 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6679 }
6680
6681 if transpose_offset == 0 {
6682 return;
6683 }
6684
6685 *head.column_mut() += 1;
6686 head = display_map.clip_point(head, Bias::Right);
6687 let goal = SelectionGoal::HorizontalPosition(
6688 display_map
6689 .x_for_display_point(head, text_layout_details)
6690 .into(),
6691 );
6692 selection.collapse_to(head, goal);
6693
6694 let transpose_start = display_map
6695 .buffer_snapshot
6696 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6697 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6698 let transpose_end = display_map
6699 .buffer_snapshot
6700 .clip_offset(transpose_offset + 1, Bias::Right);
6701 if let Some(ch) =
6702 display_map.buffer_snapshot.chars_at(transpose_start).next()
6703 {
6704 edits.push((transpose_start..transpose_offset, String::new()));
6705 edits.push((transpose_end..transpose_end, ch.to_string()));
6706 }
6707 }
6708 });
6709 edits
6710 });
6711 this.buffer
6712 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6713 let selections = this.selections.all::<usize>(cx);
6714 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6715 s.select(selections);
6716 });
6717 });
6718 }
6719
6720 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6721 self.rewrap_impl(IsVimMode::No, cx)
6722 }
6723
6724 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6725 let buffer = self.buffer.read(cx).snapshot(cx);
6726 let selections = self.selections.all::<Point>(cx);
6727 let mut selections = selections.iter().peekable();
6728
6729 let mut edits = Vec::new();
6730 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6731
6732 while let Some(selection) = selections.next() {
6733 let mut start_row = selection.start.row;
6734 let mut end_row = selection.end.row;
6735
6736 // Skip selections that overlap with a range that has already been rewrapped.
6737 let selection_range = start_row..end_row;
6738 if rewrapped_row_ranges
6739 .iter()
6740 .any(|range| range.overlaps(&selection_range))
6741 {
6742 continue;
6743 }
6744
6745 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6746
6747 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6748 match language_scope.language_name().0.as_ref() {
6749 "Markdown" | "Plain Text" => {
6750 should_rewrap = true;
6751 }
6752 _ => {}
6753 }
6754 }
6755
6756 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6757
6758 // Since not all lines in the selection may be at the same indent
6759 // level, choose the indent size that is the most common between all
6760 // of the lines.
6761 //
6762 // If there is a tie, we use the deepest indent.
6763 let (indent_size, indent_end) = {
6764 let mut indent_size_occurrences = HashMap::default();
6765 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6766
6767 for row in start_row..=end_row {
6768 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6769 rows_by_indent_size.entry(indent).or_default().push(row);
6770 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6771 }
6772
6773 let indent_size = indent_size_occurrences
6774 .into_iter()
6775 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6776 .map(|(indent, _)| indent)
6777 .unwrap_or_default();
6778 let row = rows_by_indent_size[&indent_size][0];
6779 let indent_end = Point::new(row, indent_size.len);
6780
6781 (indent_size, indent_end)
6782 };
6783
6784 let mut line_prefix = indent_size.chars().collect::<String>();
6785
6786 if let Some(comment_prefix) =
6787 buffer
6788 .language_scope_at(selection.head())
6789 .and_then(|language| {
6790 language
6791 .line_comment_prefixes()
6792 .iter()
6793 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6794 .cloned()
6795 })
6796 {
6797 line_prefix.push_str(&comment_prefix);
6798 should_rewrap = true;
6799 }
6800
6801 if !should_rewrap {
6802 continue;
6803 }
6804
6805 if selection.is_empty() {
6806 'expand_upwards: while start_row > 0 {
6807 let prev_row = start_row - 1;
6808 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6809 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6810 {
6811 start_row = prev_row;
6812 } else {
6813 break 'expand_upwards;
6814 }
6815 }
6816
6817 'expand_downwards: while end_row < buffer.max_point().row {
6818 let next_row = end_row + 1;
6819 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6820 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6821 {
6822 end_row = next_row;
6823 } else {
6824 break 'expand_downwards;
6825 }
6826 }
6827 }
6828
6829 let start = Point::new(start_row, 0);
6830 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6831 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6832 let Some(lines_without_prefixes) = selection_text
6833 .lines()
6834 .map(|line| {
6835 line.strip_prefix(&line_prefix)
6836 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6837 .ok_or_else(|| {
6838 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6839 })
6840 })
6841 .collect::<Result<Vec<_>, _>>()
6842 .log_err()
6843 else {
6844 continue;
6845 };
6846
6847 let wrap_column = buffer
6848 .settings_at(Point::new(start_row, 0), cx)
6849 .preferred_line_length as usize;
6850 let wrapped_text = wrap_with_prefix(
6851 line_prefix,
6852 lines_without_prefixes.join(" "),
6853 wrap_column,
6854 tab_size,
6855 );
6856
6857 // TODO: should always use char-based diff while still supporting cursor behavior that
6858 // matches vim.
6859 let diff = match is_vim_mode {
6860 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6861 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6862 };
6863 let mut offset = start.to_offset(&buffer);
6864 let mut moved_since_edit = true;
6865
6866 for change in diff.iter_all_changes() {
6867 let value = change.value();
6868 match change.tag() {
6869 ChangeTag::Equal => {
6870 offset += value.len();
6871 moved_since_edit = true;
6872 }
6873 ChangeTag::Delete => {
6874 let start = buffer.anchor_after(offset);
6875 let end = buffer.anchor_before(offset + value.len());
6876
6877 if moved_since_edit {
6878 edits.push((start..end, String::new()));
6879 } else {
6880 edits.last_mut().unwrap().0.end = end;
6881 }
6882
6883 offset += value.len();
6884 moved_since_edit = false;
6885 }
6886 ChangeTag::Insert => {
6887 if moved_since_edit {
6888 let anchor = buffer.anchor_after(offset);
6889 edits.push((anchor..anchor, value.to_string()));
6890 } else {
6891 edits.last_mut().unwrap().1.push_str(value);
6892 }
6893
6894 moved_since_edit = false;
6895 }
6896 }
6897 }
6898
6899 rewrapped_row_ranges.push(start_row..=end_row);
6900 }
6901
6902 self.buffer
6903 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6904 }
6905
6906 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6907 let mut text = String::new();
6908 let buffer = self.buffer.read(cx).snapshot(cx);
6909 let mut selections = self.selections.all::<Point>(cx);
6910 let mut clipboard_selections = Vec::with_capacity(selections.len());
6911 {
6912 let max_point = buffer.max_point();
6913 let mut is_first = true;
6914 for selection in &mut selections {
6915 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6916 if is_entire_line {
6917 selection.start = Point::new(selection.start.row, 0);
6918 if !selection.is_empty() && selection.end.column == 0 {
6919 selection.end = cmp::min(max_point, selection.end);
6920 } else {
6921 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6922 }
6923 selection.goal = SelectionGoal::None;
6924 }
6925 if is_first {
6926 is_first = false;
6927 } else {
6928 text += "\n";
6929 }
6930 let mut len = 0;
6931 for chunk in buffer.text_for_range(selection.start..selection.end) {
6932 text.push_str(chunk);
6933 len += chunk.len();
6934 }
6935 clipboard_selections.push(ClipboardSelection {
6936 len,
6937 is_entire_line,
6938 first_line_indent: buffer
6939 .indent_size_for_line(MultiBufferRow(selection.start.row))
6940 .len,
6941 });
6942 }
6943 }
6944
6945 self.transact(cx, |this, cx| {
6946 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6947 s.select(selections);
6948 });
6949 this.insert("", cx);
6950 });
6951 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6952 }
6953
6954 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6955 let item = self.cut_common(cx);
6956 cx.write_to_clipboard(item);
6957 }
6958
6959 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6960 self.change_selections(None, cx, |s| {
6961 s.move_with(|snapshot, sel| {
6962 if sel.is_empty() {
6963 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6964 }
6965 });
6966 });
6967 let item = self.cut_common(cx);
6968 cx.set_global(KillRing(item))
6969 }
6970
6971 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6972 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6973 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6974 (kill_ring.text().to_string(), kill_ring.metadata_json())
6975 } else {
6976 return;
6977 }
6978 } else {
6979 return;
6980 };
6981 self.do_paste(&text, metadata, false, cx);
6982 }
6983
6984 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6985 let selections = self.selections.all::<Point>(cx);
6986 let buffer = self.buffer.read(cx).read(cx);
6987 let mut text = String::new();
6988
6989 let mut clipboard_selections = Vec::with_capacity(selections.len());
6990 {
6991 let max_point = buffer.max_point();
6992 let mut is_first = true;
6993 for selection in selections.iter() {
6994 let mut start = selection.start;
6995 let mut end = selection.end;
6996 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6997 if is_entire_line {
6998 start = Point::new(start.row, 0);
6999 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7000 }
7001 if is_first {
7002 is_first = false;
7003 } else {
7004 text += "\n";
7005 }
7006 let mut len = 0;
7007 for chunk in buffer.text_for_range(start..end) {
7008 text.push_str(chunk);
7009 len += chunk.len();
7010 }
7011 clipboard_selections.push(ClipboardSelection {
7012 len,
7013 is_entire_line,
7014 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7015 });
7016 }
7017 }
7018
7019 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7020 text,
7021 clipboard_selections,
7022 ));
7023 }
7024
7025 pub fn do_paste(
7026 &mut self,
7027 text: &String,
7028 clipboard_selections: Option<Vec<ClipboardSelection>>,
7029 handle_entire_lines: bool,
7030 cx: &mut ViewContext<Self>,
7031 ) {
7032 if self.read_only(cx) {
7033 return;
7034 }
7035
7036 let clipboard_text = Cow::Borrowed(text);
7037
7038 self.transact(cx, |this, cx| {
7039 if let Some(mut clipboard_selections) = clipboard_selections {
7040 let old_selections = this.selections.all::<usize>(cx);
7041 let all_selections_were_entire_line =
7042 clipboard_selections.iter().all(|s| s.is_entire_line);
7043 let first_selection_indent_column =
7044 clipboard_selections.first().map(|s| s.first_line_indent);
7045 if clipboard_selections.len() != old_selections.len() {
7046 clipboard_selections.drain(..);
7047 }
7048 let cursor_offset = this.selections.last::<usize>(cx).head();
7049 let mut auto_indent_on_paste = true;
7050
7051 this.buffer.update(cx, |buffer, cx| {
7052 let snapshot = buffer.read(cx);
7053 auto_indent_on_paste =
7054 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7055
7056 let mut start_offset = 0;
7057 let mut edits = Vec::new();
7058 let mut original_indent_columns = Vec::new();
7059 for (ix, selection) in old_selections.iter().enumerate() {
7060 let to_insert;
7061 let entire_line;
7062 let original_indent_column;
7063 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7064 let end_offset = start_offset + clipboard_selection.len;
7065 to_insert = &clipboard_text[start_offset..end_offset];
7066 entire_line = clipboard_selection.is_entire_line;
7067 start_offset = end_offset + 1;
7068 original_indent_column = Some(clipboard_selection.first_line_indent);
7069 } else {
7070 to_insert = clipboard_text.as_str();
7071 entire_line = all_selections_were_entire_line;
7072 original_indent_column = first_selection_indent_column
7073 }
7074
7075 // If the corresponding selection was empty when this slice of the
7076 // clipboard text was written, then the entire line containing the
7077 // selection was copied. If this selection is also currently empty,
7078 // then paste the line before the current line of the buffer.
7079 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7080 let column = selection.start.to_point(&snapshot).column as usize;
7081 let line_start = selection.start - column;
7082 line_start..line_start
7083 } else {
7084 selection.range()
7085 };
7086
7087 edits.push((range, to_insert));
7088 original_indent_columns.extend(original_indent_column);
7089 }
7090 drop(snapshot);
7091
7092 buffer.edit(
7093 edits,
7094 if auto_indent_on_paste {
7095 Some(AutoindentMode::Block {
7096 original_indent_columns,
7097 })
7098 } else {
7099 None
7100 },
7101 cx,
7102 );
7103 });
7104
7105 let selections = this.selections.all::<usize>(cx);
7106 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7107 } else {
7108 this.insert(&clipboard_text, cx);
7109 }
7110 });
7111 }
7112
7113 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7114 if let Some(item) = cx.read_from_clipboard() {
7115 let entries = item.entries();
7116
7117 match entries.first() {
7118 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7119 // of all the pasted entries.
7120 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7121 .do_paste(
7122 clipboard_string.text(),
7123 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7124 true,
7125 cx,
7126 ),
7127 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7128 }
7129 }
7130 }
7131
7132 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7133 if self.read_only(cx) {
7134 return;
7135 }
7136
7137 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7138 if let Some((selections, _)) =
7139 self.selection_history.transaction(transaction_id).cloned()
7140 {
7141 self.change_selections(None, cx, |s| {
7142 s.select_anchors(selections.to_vec());
7143 });
7144 }
7145 self.request_autoscroll(Autoscroll::fit(), cx);
7146 self.unmark_text(cx);
7147 self.refresh_inline_completion(true, false, cx);
7148 cx.emit(EditorEvent::Edited { transaction_id });
7149 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7150 }
7151 }
7152
7153 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7154 if self.read_only(cx) {
7155 return;
7156 }
7157
7158 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7159 if let Some((_, Some(selections))) =
7160 self.selection_history.transaction(transaction_id).cloned()
7161 {
7162 self.change_selections(None, cx, |s| {
7163 s.select_anchors(selections.to_vec());
7164 });
7165 }
7166 self.request_autoscroll(Autoscroll::fit(), cx);
7167 self.unmark_text(cx);
7168 self.refresh_inline_completion(true, false, cx);
7169 cx.emit(EditorEvent::Edited { transaction_id });
7170 }
7171 }
7172
7173 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7174 self.buffer
7175 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7176 }
7177
7178 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7179 self.buffer
7180 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7181 }
7182
7183 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7184 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7185 let line_mode = s.line_mode;
7186 s.move_with(|map, selection| {
7187 let cursor = if selection.is_empty() && !line_mode {
7188 movement::left(map, selection.start)
7189 } else {
7190 selection.start
7191 };
7192 selection.collapse_to(cursor, SelectionGoal::None);
7193 });
7194 })
7195 }
7196
7197 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7198 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7199 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7200 })
7201 }
7202
7203 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7205 let line_mode = s.line_mode;
7206 s.move_with(|map, selection| {
7207 let cursor = if selection.is_empty() && !line_mode {
7208 movement::right(map, selection.end)
7209 } else {
7210 selection.end
7211 };
7212 selection.collapse_to(cursor, SelectionGoal::None)
7213 });
7214 })
7215 }
7216
7217 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7219 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7220 })
7221 }
7222
7223 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7224 if self.take_rename(true, cx).is_some() {
7225 return;
7226 }
7227
7228 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7229 cx.propagate();
7230 return;
7231 }
7232
7233 let text_layout_details = &self.text_layout_details(cx);
7234 let selection_count = self.selections.count();
7235 let first_selection = self.selections.first_anchor();
7236
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 let line_mode = s.line_mode;
7239 s.move_with(|map, selection| {
7240 if !selection.is_empty() && !line_mode {
7241 selection.goal = SelectionGoal::None;
7242 }
7243 let (cursor, goal) = movement::up(
7244 map,
7245 selection.start,
7246 selection.goal,
7247 false,
7248 text_layout_details,
7249 );
7250 selection.collapse_to(cursor, goal);
7251 });
7252 });
7253
7254 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7255 {
7256 cx.propagate();
7257 }
7258 }
7259
7260 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7261 if self.take_rename(true, cx).is_some() {
7262 return;
7263 }
7264
7265 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7266 cx.propagate();
7267 return;
7268 }
7269
7270 let text_layout_details = &self.text_layout_details(cx);
7271
7272 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7273 let line_mode = s.line_mode;
7274 s.move_with(|map, selection| {
7275 if !selection.is_empty() && !line_mode {
7276 selection.goal = SelectionGoal::None;
7277 }
7278 let (cursor, goal) = movement::up_by_rows(
7279 map,
7280 selection.start,
7281 action.lines,
7282 selection.goal,
7283 false,
7284 text_layout_details,
7285 );
7286 selection.collapse_to(cursor, goal);
7287 });
7288 })
7289 }
7290
7291 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7292 if self.take_rename(true, cx).is_some() {
7293 return;
7294 }
7295
7296 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7297 cx.propagate();
7298 return;
7299 }
7300
7301 let text_layout_details = &self.text_layout_details(cx);
7302
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 let line_mode = s.line_mode;
7305 s.move_with(|map, selection| {
7306 if !selection.is_empty() && !line_mode {
7307 selection.goal = SelectionGoal::None;
7308 }
7309 let (cursor, goal) = movement::down_by_rows(
7310 map,
7311 selection.start,
7312 action.lines,
7313 selection.goal,
7314 false,
7315 text_layout_details,
7316 );
7317 selection.collapse_to(cursor, goal);
7318 });
7319 })
7320 }
7321
7322 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7323 let text_layout_details = &self.text_layout_details(cx);
7324 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7325 s.move_heads_with(|map, head, goal| {
7326 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7327 })
7328 })
7329 }
7330
7331 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7332 let text_layout_details = &self.text_layout_details(cx);
7333 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7334 s.move_heads_with(|map, head, goal| {
7335 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7336 })
7337 })
7338 }
7339
7340 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7341 let Some(row_count) = self.visible_row_count() else {
7342 return;
7343 };
7344
7345 let text_layout_details = &self.text_layout_details(cx);
7346
7347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7348 s.move_heads_with(|map, head, goal| {
7349 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7350 })
7351 })
7352 }
7353
7354 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7355 if self.take_rename(true, cx).is_some() {
7356 return;
7357 }
7358
7359 if self
7360 .context_menu
7361 .borrow_mut()
7362 .as_mut()
7363 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7364 .unwrap_or(false)
7365 {
7366 return;
7367 }
7368
7369 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7370 cx.propagate();
7371 return;
7372 }
7373
7374 let Some(row_count) = self.visible_row_count() else {
7375 return;
7376 };
7377
7378 let autoscroll = if action.center_cursor {
7379 Autoscroll::center()
7380 } else {
7381 Autoscroll::fit()
7382 };
7383
7384 let text_layout_details = &self.text_layout_details(cx);
7385
7386 self.change_selections(Some(autoscroll), cx, |s| {
7387 let line_mode = s.line_mode;
7388 s.move_with(|map, selection| {
7389 if !selection.is_empty() && !line_mode {
7390 selection.goal = SelectionGoal::None;
7391 }
7392 let (cursor, goal) = movement::up_by_rows(
7393 map,
7394 selection.end,
7395 row_count,
7396 selection.goal,
7397 false,
7398 text_layout_details,
7399 );
7400 selection.collapse_to(cursor, goal);
7401 });
7402 });
7403 }
7404
7405 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7406 let text_layout_details = &self.text_layout_details(cx);
7407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7408 s.move_heads_with(|map, head, goal| {
7409 movement::up(map, head, goal, false, text_layout_details)
7410 })
7411 })
7412 }
7413
7414 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7415 self.take_rename(true, cx);
7416
7417 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7418 cx.propagate();
7419 return;
7420 }
7421
7422 let text_layout_details = &self.text_layout_details(cx);
7423 let selection_count = self.selections.count();
7424 let first_selection = self.selections.first_anchor();
7425
7426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7427 let line_mode = s.line_mode;
7428 s.move_with(|map, selection| {
7429 if !selection.is_empty() && !line_mode {
7430 selection.goal = SelectionGoal::None;
7431 }
7432 let (cursor, goal) = movement::down(
7433 map,
7434 selection.end,
7435 selection.goal,
7436 false,
7437 text_layout_details,
7438 );
7439 selection.collapse_to(cursor, goal);
7440 });
7441 });
7442
7443 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7444 {
7445 cx.propagate();
7446 }
7447 }
7448
7449 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7450 let Some(row_count) = self.visible_row_count() else {
7451 return;
7452 };
7453
7454 let text_layout_details = &self.text_layout_details(cx);
7455
7456 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7457 s.move_heads_with(|map, head, goal| {
7458 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7459 })
7460 })
7461 }
7462
7463 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7464 if self.take_rename(true, cx).is_some() {
7465 return;
7466 }
7467
7468 if self
7469 .context_menu
7470 .borrow_mut()
7471 .as_mut()
7472 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7473 .unwrap_or(false)
7474 {
7475 return;
7476 }
7477
7478 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7479 cx.propagate();
7480 return;
7481 }
7482
7483 let Some(row_count) = self.visible_row_count() else {
7484 return;
7485 };
7486
7487 let autoscroll = if action.center_cursor {
7488 Autoscroll::center()
7489 } else {
7490 Autoscroll::fit()
7491 };
7492
7493 let text_layout_details = &self.text_layout_details(cx);
7494 self.change_selections(Some(autoscroll), cx, |s| {
7495 let line_mode = s.line_mode;
7496 s.move_with(|map, selection| {
7497 if !selection.is_empty() && !line_mode {
7498 selection.goal = SelectionGoal::None;
7499 }
7500 let (cursor, goal) = movement::down_by_rows(
7501 map,
7502 selection.end,
7503 row_count,
7504 selection.goal,
7505 false,
7506 text_layout_details,
7507 );
7508 selection.collapse_to(cursor, goal);
7509 });
7510 });
7511 }
7512
7513 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7514 let text_layout_details = &self.text_layout_details(cx);
7515 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7516 s.move_heads_with(|map, head, goal| {
7517 movement::down(map, head, goal, false, text_layout_details)
7518 })
7519 });
7520 }
7521
7522 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7523 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7524 context_menu.select_first(self.completion_provider.as_deref(), cx);
7525 }
7526 }
7527
7528 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7529 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7530 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7531 }
7532 }
7533
7534 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7535 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7536 context_menu.select_next(self.completion_provider.as_deref(), cx);
7537 }
7538 }
7539
7540 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7541 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7542 context_menu.select_last(self.completion_provider.as_deref(), cx);
7543 }
7544 }
7545
7546 pub fn move_to_previous_word_start(
7547 &mut self,
7548 _: &MoveToPreviousWordStart,
7549 cx: &mut ViewContext<Self>,
7550 ) {
7551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 s.move_cursors_with(|map, head, _| {
7553 (
7554 movement::previous_word_start(map, head),
7555 SelectionGoal::None,
7556 )
7557 });
7558 })
7559 }
7560
7561 pub fn move_to_previous_subword_start(
7562 &mut self,
7563 _: &MoveToPreviousSubwordStart,
7564 cx: &mut ViewContext<Self>,
7565 ) {
7566 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7567 s.move_cursors_with(|map, head, _| {
7568 (
7569 movement::previous_subword_start(map, head),
7570 SelectionGoal::None,
7571 )
7572 });
7573 })
7574 }
7575
7576 pub fn select_to_previous_word_start(
7577 &mut self,
7578 _: &SelectToPreviousWordStart,
7579 cx: &mut ViewContext<Self>,
7580 ) {
7581 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7582 s.move_heads_with(|map, head, _| {
7583 (
7584 movement::previous_word_start(map, head),
7585 SelectionGoal::None,
7586 )
7587 });
7588 })
7589 }
7590
7591 pub fn select_to_previous_subword_start(
7592 &mut self,
7593 _: &SelectToPreviousSubwordStart,
7594 cx: &mut ViewContext<Self>,
7595 ) {
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.move_heads_with(|map, head, _| {
7598 (
7599 movement::previous_subword_start(map, head),
7600 SelectionGoal::None,
7601 )
7602 });
7603 })
7604 }
7605
7606 pub fn delete_to_previous_word_start(
7607 &mut self,
7608 action: &DeleteToPreviousWordStart,
7609 cx: &mut ViewContext<Self>,
7610 ) {
7611 self.transact(cx, |this, cx| {
7612 this.select_autoclose_pair(cx);
7613 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 let line_mode = s.line_mode;
7615 s.move_with(|map, selection| {
7616 if selection.is_empty() && !line_mode {
7617 let cursor = if action.ignore_newlines {
7618 movement::previous_word_start(map, selection.head())
7619 } else {
7620 movement::previous_word_start_or_newline(map, selection.head())
7621 };
7622 selection.set_head(cursor, SelectionGoal::None);
7623 }
7624 });
7625 });
7626 this.insert("", cx);
7627 });
7628 }
7629
7630 pub fn delete_to_previous_subword_start(
7631 &mut self,
7632 _: &DeleteToPreviousSubwordStart,
7633 cx: &mut ViewContext<Self>,
7634 ) {
7635 self.transact(cx, |this, cx| {
7636 this.select_autoclose_pair(cx);
7637 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 let line_mode = s.line_mode;
7639 s.move_with(|map, selection| {
7640 if selection.is_empty() && !line_mode {
7641 let cursor = movement::previous_subword_start(map, selection.head());
7642 selection.set_head(cursor, SelectionGoal::None);
7643 }
7644 });
7645 });
7646 this.insert("", cx);
7647 });
7648 }
7649
7650 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7651 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7652 s.move_cursors_with(|map, head, _| {
7653 (movement::next_word_end(map, head), SelectionGoal::None)
7654 });
7655 })
7656 }
7657
7658 pub fn move_to_next_subword_end(
7659 &mut self,
7660 _: &MoveToNextSubwordEnd,
7661 cx: &mut ViewContext<Self>,
7662 ) {
7663 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7664 s.move_cursors_with(|map, head, _| {
7665 (movement::next_subword_end(map, head), SelectionGoal::None)
7666 });
7667 })
7668 }
7669
7670 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7671 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 s.move_heads_with(|map, head, _| {
7673 (movement::next_word_end(map, head), SelectionGoal::None)
7674 });
7675 })
7676 }
7677
7678 pub fn select_to_next_subword_end(
7679 &mut self,
7680 _: &SelectToNextSubwordEnd,
7681 cx: &mut ViewContext<Self>,
7682 ) {
7683 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7684 s.move_heads_with(|map, head, _| {
7685 (movement::next_subword_end(map, head), SelectionGoal::None)
7686 });
7687 })
7688 }
7689
7690 pub fn delete_to_next_word_end(
7691 &mut self,
7692 action: &DeleteToNextWordEnd,
7693 cx: &mut ViewContext<Self>,
7694 ) {
7695 self.transact(cx, |this, cx| {
7696 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7697 let line_mode = s.line_mode;
7698 s.move_with(|map, selection| {
7699 if selection.is_empty() && !line_mode {
7700 let cursor = if action.ignore_newlines {
7701 movement::next_word_end(map, selection.head())
7702 } else {
7703 movement::next_word_end_or_newline(map, selection.head())
7704 };
7705 selection.set_head(cursor, SelectionGoal::None);
7706 }
7707 });
7708 });
7709 this.insert("", cx);
7710 });
7711 }
7712
7713 pub fn delete_to_next_subword_end(
7714 &mut self,
7715 _: &DeleteToNextSubwordEnd,
7716 cx: &mut ViewContext<Self>,
7717 ) {
7718 self.transact(cx, |this, cx| {
7719 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7720 s.move_with(|map, selection| {
7721 if selection.is_empty() {
7722 let cursor = movement::next_subword_end(map, selection.head());
7723 selection.set_head(cursor, SelectionGoal::None);
7724 }
7725 });
7726 });
7727 this.insert("", cx);
7728 });
7729 }
7730
7731 pub fn move_to_beginning_of_line(
7732 &mut self,
7733 action: &MoveToBeginningOfLine,
7734 cx: &mut ViewContext<Self>,
7735 ) {
7736 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7737 s.move_cursors_with(|map, head, _| {
7738 (
7739 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7740 SelectionGoal::None,
7741 )
7742 });
7743 })
7744 }
7745
7746 pub fn select_to_beginning_of_line(
7747 &mut self,
7748 action: &SelectToBeginningOfLine,
7749 cx: &mut ViewContext<Self>,
7750 ) {
7751 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7752 s.move_heads_with(|map, head, _| {
7753 (
7754 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7755 SelectionGoal::None,
7756 )
7757 });
7758 });
7759 }
7760
7761 pub fn delete_to_beginning_of_line(
7762 &mut self,
7763 _: &DeleteToBeginningOfLine,
7764 cx: &mut ViewContext<Self>,
7765 ) {
7766 self.transact(cx, |this, cx| {
7767 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7768 s.move_with(|_, selection| {
7769 selection.reversed = true;
7770 });
7771 });
7772
7773 this.select_to_beginning_of_line(
7774 &SelectToBeginningOfLine {
7775 stop_at_soft_wraps: false,
7776 },
7777 cx,
7778 );
7779 this.backspace(&Backspace, cx);
7780 });
7781 }
7782
7783 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7784 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7785 s.move_cursors_with(|map, head, _| {
7786 (
7787 movement::line_end(map, head, action.stop_at_soft_wraps),
7788 SelectionGoal::None,
7789 )
7790 });
7791 })
7792 }
7793
7794 pub fn select_to_end_of_line(
7795 &mut self,
7796 action: &SelectToEndOfLine,
7797 cx: &mut ViewContext<Self>,
7798 ) {
7799 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7800 s.move_heads_with(|map, head, _| {
7801 (
7802 movement::line_end(map, head, action.stop_at_soft_wraps),
7803 SelectionGoal::None,
7804 )
7805 });
7806 })
7807 }
7808
7809 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7810 self.transact(cx, |this, cx| {
7811 this.select_to_end_of_line(
7812 &SelectToEndOfLine {
7813 stop_at_soft_wraps: false,
7814 },
7815 cx,
7816 );
7817 this.delete(&Delete, cx);
7818 });
7819 }
7820
7821 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7822 self.transact(cx, |this, cx| {
7823 this.select_to_end_of_line(
7824 &SelectToEndOfLine {
7825 stop_at_soft_wraps: false,
7826 },
7827 cx,
7828 );
7829 this.cut(&Cut, cx);
7830 });
7831 }
7832
7833 pub fn move_to_start_of_paragraph(
7834 &mut self,
7835 _: &MoveToStartOfParagraph,
7836 cx: &mut ViewContext<Self>,
7837 ) {
7838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7839 cx.propagate();
7840 return;
7841 }
7842
7843 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7844 s.move_with(|map, selection| {
7845 selection.collapse_to(
7846 movement::start_of_paragraph(map, selection.head(), 1),
7847 SelectionGoal::None,
7848 )
7849 });
7850 })
7851 }
7852
7853 pub fn move_to_end_of_paragraph(
7854 &mut self,
7855 _: &MoveToEndOfParagraph,
7856 cx: &mut ViewContext<Self>,
7857 ) {
7858 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7859 cx.propagate();
7860 return;
7861 }
7862
7863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7864 s.move_with(|map, selection| {
7865 selection.collapse_to(
7866 movement::end_of_paragraph(map, selection.head(), 1),
7867 SelectionGoal::None,
7868 )
7869 });
7870 })
7871 }
7872
7873 pub fn select_to_start_of_paragraph(
7874 &mut self,
7875 _: &SelectToStartOfParagraph,
7876 cx: &mut ViewContext<Self>,
7877 ) {
7878 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7879 cx.propagate();
7880 return;
7881 }
7882
7883 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7884 s.move_heads_with(|map, head, _| {
7885 (
7886 movement::start_of_paragraph(map, head, 1),
7887 SelectionGoal::None,
7888 )
7889 });
7890 })
7891 }
7892
7893 pub fn select_to_end_of_paragraph(
7894 &mut self,
7895 _: &SelectToEndOfParagraph,
7896 cx: &mut ViewContext<Self>,
7897 ) {
7898 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7899 cx.propagate();
7900 return;
7901 }
7902
7903 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7904 s.move_heads_with(|map, head, _| {
7905 (
7906 movement::end_of_paragraph(map, head, 1),
7907 SelectionGoal::None,
7908 )
7909 });
7910 })
7911 }
7912
7913 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7914 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7915 cx.propagate();
7916 return;
7917 }
7918
7919 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7920 s.select_ranges(vec![0..0]);
7921 });
7922 }
7923
7924 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7925 let mut selection = self.selections.last::<Point>(cx);
7926 selection.set_head(Point::zero(), SelectionGoal::None);
7927
7928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7929 s.select(vec![selection]);
7930 });
7931 }
7932
7933 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7934 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7935 cx.propagate();
7936 return;
7937 }
7938
7939 let cursor = self.buffer.read(cx).read(cx).len();
7940 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7941 s.select_ranges(vec![cursor..cursor])
7942 });
7943 }
7944
7945 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7946 self.nav_history = nav_history;
7947 }
7948
7949 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7950 self.nav_history.as_ref()
7951 }
7952
7953 fn push_to_nav_history(
7954 &mut self,
7955 cursor_anchor: Anchor,
7956 new_position: Option<Point>,
7957 cx: &mut ViewContext<Self>,
7958 ) {
7959 if let Some(nav_history) = self.nav_history.as_mut() {
7960 let buffer = self.buffer.read(cx).read(cx);
7961 let cursor_position = cursor_anchor.to_point(&buffer);
7962 let scroll_state = self.scroll_manager.anchor();
7963 let scroll_top_row = scroll_state.top_row(&buffer);
7964 drop(buffer);
7965
7966 if let Some(new_position) = new_position {
7967 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7968 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7969 return;
7970 }
7971 }
7972
7973 nav_history.push(
7974 Some(NavigationData {
7975 cursor_anchor,
7976 cursor_position,
7977 scroll_anchor: scroll_state,
7978 scroll_top_row,
7979 }),
7980 cx,
7981 );
7982 }
7983 }
7984
7985 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7986 let buffer = self.buffer.read(cx).snapshot(cx);
7987 let mut selection = self.selections.first::<usize>(cx);
7988 selection.set_head(buffer.len(), SelectionGoal::None);
7989 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7990 s.select(vec![selection]);
7991 });
7992 }
7993
7994 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7995 let end = self.buffer.read(cx).read(cx).len();
7996 self.change_selections(None, cx, |s| {
7997 s.select_ranges(vec![0..end]);
7998 });
7999 }
8000
8001 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8003 let mut selections = self.selections.all::<Point>(cx);
8004 let max_point = display_map.buffer_snapshot.max_point();
8005 for selection in &mut selections {
8006 let rows = selection.spanned_rows(true, &display_map);
8007 selection.start = Point::new(rows.start.0, 0);
8008 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8009 selection.reversed = false;
8010 }
8011 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8012 s.select(selections);
8013 });
8014 }
8015
8016 pub fn split_selection_into_lines(
8017 &mut self,
8018 _: &SplitSelectionIntoLines,
8019 cx: &mut ViewContext<Self>,
8020 ) {
8021 let mut to_unfold = Vec::new();
8022 let mut new_selection_ranges = Vec::new();
8023 {
8024 let selections = self.selections.all::<Point>(cx);
8025 let buffer = self.buffer.read(cx).read(cx);
8026 for selection in selections {
8027 for row in selection.start.row..selection.end.row {
8028 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8029 new_selection_ranges.push(cursor..cursor);
8030 }
8031 new_selection_ranges.push(selection.end..selection.end);
8032 to_unfold.push(selection.start..selection.end);
8033 }
8034 }
8035 self.unfold_ranges(&to_unfold, true, true, cx);
8036 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8037 s.select_ranges(new_selection_ranges);
8038 });
8039 }
8040
8041 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8042 self.add_selection(true, cx);
8043 }
8044
8045 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8046 self.add_selection(false, cx);
8047 }
8048
8049 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8051 let mut selections = self.selections.all::<Point>(cx);
8052 let text_layout_details = self.text_layout_details(cx);
8053 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8054 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8055 let range = oldest_selection.display_range(&display_map).sorted();
8056
8057 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8058 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8059 let positions = start_x.min(end_x)..start_x.max(end_x);
8060
8061 selections.clear();
8062 let mut stack = Vec::new();
8063 for row in range.start.row().0..=range.end.row().0 {
8064 if let Some(selection) = self.selections.build_columnar_selection(
8065 &display_map,
8066 DisplayRow(row),
8067 &positions,
8068 oldest_selection.reversed,
8069 &text_layout_details,
8070 ) {
8071 stack.push(selection.id);
8072 selections.push(selection);
8073 }
8074 }
8075
8076 if above {
8077 stack.reverse();
8078 }
8079
8080 AddSelectionsState { above, stack }
8081 });
8082
8083 let last_added_selection = *state.stack.last().unwrap();
8084 let mut new_selections = Vec::new();
8085 if above == state.above {
8086 let end_row = if above {
8087 DisplayRow(0)
8088 } else {
8089 display_map.max_point().row()
8090 };
8091
8092 'outer: for selection in selections {
8093 if selection.id == last_added_selection {
8094 let range = selection.display_range(&display_map).sorted();
8095 debug_assert_eq!(range.start.row(), range.end.row());
8096 let mut row = range.start.row();
8097 let positions =
8098 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8099 px(start)..px(end)
8100 } else {
8101 let start_x =
8102 display_map.x_for_display_point(range.start, &text_layout_details);
8103 let end_x =
8104 display_map.x_for_display_point(range.end, &text_layout_details);
8105 start_x.min(end_x)..start_x.max(end_x)
8106 };
8107
8108 while row != end_row {
8109 if above {
8110 row.0 -= 1;
8111 } else {
8112 row.0 += 1;
8113 }
8114
8115 if let Some(new_selection) = self.selections.build_columnar_selection(
8116 &display_map,
8117 row,
8118 &positions,
8119 selection.reversed,
8120 &text_layout_details,
8121 ) {
8122 state.stack.push(new_selection.id);
8123 if above {
8124 new_selections.push(new_selection);
8125 new_selections.push(selection);
8126 } else {
8127 new_selections.push(selection);
8128 new_selections.push(new_selection);
8129 }
8130
8131 continue 'outer;
8132 }
8133 }
8134 }
8135
8136 new_selections.push(selection);
8137 }
8138 } else {
8139 new_selections = selections;
8140 new_selections.retain(|s| s.id != last_added_selection);
8141 state.stack.pop();
8142 }
8143
8144 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8145 s.select(new_selections);
8146 });
8147 if state.stack.len() > 1 {
8148 self.add_selections_state = Some(state);
8149 }
8150 }
8151
8152 pub fn select_next_match_internal(
8153 &mut self,
8154 display_map: &DisplaySnapshot,
8155 replace_newest: bool,
8156 autoscroll: Option<Autoscroll>,
8157 cx: &mut ViewContext<Self>,
8158 ) -> Result<()> {
8159 fn select_next_match_ranges(
8160 this: &mut Editor,
8161 range: Range<usize>,
8162 replace_newest: bool,
8163 auto_scroll: Option<Autoscroll>,
8164 cx: &mut ViewContext<Editor>,
8165 ) {
8166 this.unfold_ranges(&[range.clone()], false, true, cx);
8167 this.change_selections(auto_scroll, cx, |s| {
8168 if replace_newest {
8169 s.delete(s.newest_anchor().id);
8170 }
8171 s.insert_range(range.clone());
8172 });
8173 }
8174
8175 let buffer = &display_map.buffer_snapshot;
8176 let mut selections = self.selections.all::<usize>(cx);
8177 if let Some(mut select_next_state) = self.select_next_state.take() {
8178 let query = &select_next_state.query;
8179 if !select_next_state.done {
8180 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8181 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8182 let mut next_selected_range = None;
8183
8184 let bytes_after_last_selection =
8185 buffer.bytes_in_range(last_selection.end..buffer.len());
8186 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8187 let query_matches = query
8188 .stream_find_iter(bytes_after_last_selection)
8189 .map(|result| (last_selection.end, result))
8190 .chain(
8191 query
8192 .stream_find_iter(bytes_before_first_selection)
8193 .map(|result| (0, result)),
8194 );
8195
8196 for (start_offset, query_match) in query_matches {
8197 let query_match = query_match.unwrap(); // can only fail due to I/O
8198 let offset_range =
8199 start_offset + query_match.start()..start_offset + query_match.end();
8200 let display_range = offset_range.start.to_display_point(display_map)
8201 ..offset_range.end.to_display_point(display_map);
8202
8203 if !select_next_state.wordwise
8204 || (!movement::is_inside_word(display_map, display_range.start)
8205 && !movement::is_inside_word(display_map, display_range.end))
8206 {
8207 // TODO: This is n^2, because we might check all the selections
8208 if !selections
8209 .iter()
8210 .any(|selection| selection.range().overlaps(&offset_range))
8211 {
8212 next_selected_range = Some(offset_range);
8213 break;
8214 }
8215 }
8216 }
8217
8218 if let Some(next_selected_range) = next_selected_range {
8219 select_next_match_ranges(
8220 self,
8221 next_selected_range,
8222 replace_newest,
8223 autoscroll,
8224 cx,
8225 );
8226 } else {
8227 select_next_state.done = true;
8228 }
8229 }
8230
8231 self.select_next_state = Some(select_next_state);
8232 } else {
8233 let mut only_carets = true;
8234 let mut same_text_selected = true;
8235 let mut selected_text = None;
8236
8237 let mut selections_iter = selections.iter().peekable();
8238 while let Some(selection) = selections_iter.next() {
8239 if selection.start != selection.end {
8240 only_carets = false;
8241 }
8242
8243 if same_text_selected {
8244 if selected_text.is_none() {
8245 selected_text =
8246 Some(buffer.text_for_range(selection.range()).collect::<String>());
8247 }
8248
8249 if let Some(next_selection) = selections_iter.peek() {
8250 if next_selection.range().len() == selection.range().len() {
8251 let next_selected_text = buffer
8252 .text_for_range(next_selection.range())
8253 .collect::<String>();
8254 if Some(next_selected_text) != selected_text {
8255 same_text_selected = false;
8256 selected_text = None;
8257 }
8258 } else {
8259 same_text_selected = false;
8260 selected_text = None;
8261 }
8262 }
8263 }
8264 }
8265
8266 if only_carets {
8267 for selection in &mut selections {
8268 let word_range = movement::surrounding_word(
8269 display_map,
8270 selection.start.to_display_point(display_map),
8271 );
8272 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8273 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8274 selection.goal = SelectionGoal::None;
8275 selection.reversed = false;
8276 select_next_match_ranges(
8277 self,
8278 selection.start..selection.end,
8279 replace_newest,
8280 autoscroll,
8281 cx,
8282 );
8283 }
8284
8285 if selections.len() == 1 {
8286 let selection = selections
8287 .last()
8288 .expect("ensured that there's only one selection");
8289 let query = buffer
8290 .text_for_range(selection.start..selection.end)
8291 .collect::<String>();
8292 let is_empty = query.is_empty();
8293 let select_state = SelectNextState {
8294 query: AhoCorasick::new(&[query])?,
8295 wordwise: true,
8296 done: is_empty,
8297 };
8298 self.select_next_state = Some(select_state);
8299 } else {
8300 self.select_next_state = None;
8301 }
8302 } else if let Some(selected_text) = selected_text {
8303 self.select_next_state = Some(SelectNextState {
8304 query: AhoCorasick::new(&[selected_text])?,
8305 wordwise: false,
8306 done: false,
8307 });
8308 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8309 }
8310 }
8311 Ok(())
8312 }
8313
8314 pub fn select_all_matches(
8315 &mut self,
8316 _action: &SelectAllMatches,
8317 cx: &mut ViewContext<Self>,
8318 ) -> Result<()> {
8319 self.push_to_selection_history();
8320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8321
8322 self.select_next_match_internal(&display_map, false, None, cx)?;
8323 let Some(select_next_state) = self.select_next_state.as_mut() else {
8324 return Ok(());
8325 };
8326 if select_next_state.done {
8327 return Ok(());
8328 }
8329
8330 let mut new_selections = self.selections.all::<usize>(cx);
8331
8332 let buffer = &display_map.buffer_snapshot;
8333 let query_matches = select_next_state
8334 .query
8335 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8336
8337 for query_match in query_matches {
8338 let query_match = query_match.unwrap(); // can only fail due to I/O
8339 let offset_range = query_match.start()..query_match.end();
8340 let display_range = offset_range.start.to_display_point(&display_map)
8341 ..offset_range.end.to_display_point(&display_map);
8342
8343 if !select_next_state.wordwise
8344 || (!movement::is_inside_word(&display_map, display_range.start)
8345 && !movement::is_inside_word(&display_map, display_range.end))
8346 {
8347 self.selections.change_with(cx, |selections| {
8348 new_selections.push(Selection {
8349 id: selections.new_selection_id(),
8350 start: offset_range.start,
8351 end: offset_range.end,
8352 reversed: false,
8353 goal: SelectionGoal::None,
8354 });
8355 });
8356 }
8357 }
8358
8359 new_selections.sort_by_key(|selection| selection.start);
8360 let mut ix = 0;
8361 while ix + 1 < new_selections.len() {
8362 let current_selection = &new_selections[ix];
8363 let next_selection = &new_selections[ix + 1];
8364 if current_selection.range().overlaps(&next_selection.range()) {
8365 if current_selection.id < next_selection.id {
8366 new_selections.remove(ix + 1);
8367 } else {
8368 new_selections.remove(ix);
8369 }
8370 } else {
8371 ix += 1;
8372 }
8373 }
8374
8375 select_next_state.done = true;
8376 self.unfold_ranges(
8377 &new_selections
8378 .iter()
8379 .map(|selection| selection.range())
8380 .collect::<Vec<_>>(),
8381 false,
8382 false,
8383 cx,
8384 );
8385 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8386 selections.select(new_selections)
8387 });
8388
8389 Ok(())
8390 }
8391
8392 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8393 self.push_to_selection_history();
8394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8395 self.select_next_match_internal(
8396 &display_map,
8397 action.replace_newest,
8398 Some(Autoscroll::newest()),
8399 cx,
8400 )?;
8401 Ok(())
8402 }
8403
8404 pub fn select_previous(
8405 &mut self,
8406 action: &SelectPrevious,
8407 cx: &mut ViewContext<Self>,
8408 ) -> Result<()> {
8409 self.push_to_selection_history();
8410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8411 let buffer = &display_map.buffer_snapshot;
8412 let mut selections = self.selections.all::<usize>(cx);
8413 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8414 let query = &select_prev_state.query;
8415 if !select_prev_state.done {
8416 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8417 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8418 let mut next_selected_range = None;
8419 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8420 let bytes_before_last_selection =
8421 buffer.reversed_bytes_in_range(0..last_selection.start);
8422 let bytes_after_first_selection =
8423 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8424 let query_matches = query
8425 .stream_find_iter(bytes_before_last_selection)
8426 .map(|result| (last_selection.start, result))
8427 .chain(
8428 query
8429 .stream_find_iter(bytes_after_first_selection)
8430 .map(|result| (buffer.len(), result)),
8431 );
8432 for (end_offset, query_match) in query_matches {
8433 let query_match = query_match.unwrap(); // can only fail due to I/O
8434 let offset_range =
8435 end_offset - query_match.end()..end_offset - query_match.start();
8436 let display_range = offset_range.start.to_display_point(&display_map)
8437 ..offset_range.end.to_display_point(&display_map);
8438
8439 if !select_prev_state.wordwise
8440 || (!movement::is_inside_word(&display_map, display_range.start)
8441 && !movement::is_inside_word(&display_map, display_range.end))
8442 {
8443 next_selected_range = Some(offset_range);
8444 break;
8445 }
8446 }
8447
8448 if let Some(next_selected_range) = next_selected_range {
8449 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8450 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8451 if action.replace_newest {
8452 s.delete(s.newest_anchor().id);
8453 }
8454 s.insert_range(next_selected_range);
8455 });
8456 } else {
8457 select_prev_state.done = true;
8458 }
8459 }
8460
8461 self.select_prev_state = Some(select_prev_state);
8462 } else {
8463 let mut only_carets = true;
8464 let mut same_text_selected = true;
8465 let mut selected_text = None;
8466
8467 let mut selections_iter = selections.iter().peekable();
8468 while let Some(selection) = selections_iter.next() {
8469 if selection.start != selection.end {
8470 only_carets = false;
8471 }
8472
8473 if same_text_selected {
8474 if selected_text.is_none() {
8475 selected_text =
8476 Some(buffer.text_for_range(selection.range()).collect::<String>());
8477 }
8478
8479 if let Some(next_selection) = selections_iter.peek() {
8480 if next_selection.range().len() == selection.range().len() {
8481 let next_selected_text = buffer
8482 .text_for_range(next_selection.range())
8483 .collect::<String>();
8484 if Some(next_selected_text) != selected_text {
8485 same_text_selected = false;
8486 selected_text = None;
8487 }
8488 } else {
8489 same_text_selected = false;
8490 selected_text = None;
8491 }
8492 }
8493 }
8494 }
8495
8496 if only_carets {
8497 for selection in &mut selections {
8498 let word_range = movement::surrounding_word(
8499 &display_map,
8500 selection.start.to_display_point(&display_map),
8501 );
8502 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8503 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8504 selection.goal = SelectionGoal::None;
8505 selection.reversed = false;
8506 }
8507 if selections.len() == 1 {
8508 let selection = selections
8509 .last()
8510 .expect("ensured that there's only one selection");
8511 let query = buffer
8512 .text_for_range(selection.start..selection.end)
8513 .collect::<String>();
8514 let is_empty = query.is_empty();
8515 let select_state = SelectNextState {
8516 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8517 wordwise: true,
8518 done: is_empty,
8519 };
8520 self.select_prev_state = Some(select_state);
8521 } else {
8522 self.select_prev_state = None;
8523 }
8524
8525 self.unfold_ranges(
8526 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8527 false,
8528 true,
8529 cx,
8530 );
8531 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8532 s.select(selections);
8533 });
8534 } else if let Some(selected_text) = selected_text {
8535 self.select_prev_state = Some(SelectNextState {
8536 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8537 wordwise: false,
8538 done: false,
8539 });
8540 self.select_previous(action, cx)?;
8541 }
8542 }
8543 Ok(())
8544 }
8545
8546 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8547 if self.read_only(cx) {
8548 return;
8549 }
8550 let text_layout_details = &self.text_layout_details(cx);
8551 self.transact(cx, |this, cx| {
8552 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8553 let mut edits = Vec::new();
8554 let mut selection_edit_ranges = Vec::new();
8555 let mut last_toggled_row = None;
8556 let snapshot = this.buffer.read(cx).read(cx);
8557 let empty_str: Arc<str> = Arc::default();
8558 let mut suffixes_inserted = Vec::new();
8559 let ignore_indent = action.ignore_indent;
8560
8561 fn comment_prefix_range(
8562 snapshot: &MultiBufferSnapshot,
8563 row: MultiBufferRow,
8564 comment_prefix: &str,
8565 comment_prefix_whitespace: &str,
8566 ignore_indent: bool,
8567 ) -> Range<Point> {
8568 let indent_size = if ignore_indent {
8569 0
8570 } else {
8571 snapshot.indent_size_for_line(row).len
8572 };
8573
8574 let start = Point::new(row.0, indent_size);
8575
8576 let mut line_bytes = snapshot
8577 .bytes_in_range(start..snapshot.max_point())
8578 .flatten()
8579 .copied();
8580
8581 // If this line currently begins with the line comment prefix, then record
8582 // the range containing the prefix.
8583 if line_bytes
8584 .by_ref()
8585 .take(comment_prefix.len())
8586 .eq(comment_prefix.bytes())
8587 {
8588 // Include any whitespace that matches the comment prefix.
8589 let matching_whitespace_len = line_bytes
8590 .zip(comment_prefix_whitespace.bytes())
8591 .take_while(|(a, b)| a == b)
8592 .count() as u32;
8593 let end = Point::new(
8594 start.row,
8595 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8596 );
8597 start..end
8598 } else {
8599 start..start
8600 }
8601 }
8602
8603 fn comment_suffix_range(
8604 snapshot: &MultiBufferSnapshot,
8605 row: MultiBufferRow,
8606 comment_suffix: &str,
8607 comment_suffix_has_leading_space: bool,
8608 ) -> Range<Point> {
8609 let end = Point::new(row.0, snapshot.line_len(row));
8610 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8611
8612 let mut line_end_bytes = snapshot
8613 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8614 .flatten()
8615 .copied();
8616
8617 let leading_space_len = if suffix_start_column > 0
8618 && line_end_bytes.next() == Some(b' ')
8619 && comment_suffix_has_leading_space
8620 {
8621 1
8622 } else {
8623 0
8624 };
8625
8626 // If this line currently begins with the line comment prefix, then record
8627 // the range containing the prefix.
8628 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8629 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8630 start..end
8631 } else {
8632 end..end
8633 }
8634 }
8635
8636 // TODO: Handle selections that cross excerpts
8637 for selection in &mut selections {
8638 let start_column = snapshot
8639 .indent_size_for_line(MultiBufferRow(selection.start.row))
8640 .len;
8641 let language = if let Some(language) =
8642 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8643 {
8644 language
8645 } else {
8646 continue;
8647 };
8648
8649 selection_edit_ranges.clear();
8650
8651 // If multiple selections contain a given row, avoid processing that
8652 // row more than once.
8653 let mut start_row = MultiBufferRow(selection.start.row);
8654 if last_toggled_row == Some(start_row) {
8655 start_row = start_row.next_row();
8656 }
8657 let end_row =
8658 if selection.end.row > selection.start.row && selection.end.column == 0 {
8659 MultiBufferRow(selection.end.row - 1)
8660 } else {
8661 MultiBufferRow(selection.end.row)
8662 };
8663 last_toggled_row = Some(end_row);
8664
8665 if start_row > end_row {
8666 continue;
8667 }
8668
8669 // If the language has line comments, toggle those.
8670 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8671
8672 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8673 if ignore_indent {
8674 full_comment_prefixes = full_comment_prefixes
8675 .into_iter()
8676 .map(|s| Arc::from(s.trim_end()))
8677 .collect();
8678 }
8679
8680 if !full_comment_prefixes.is_empty() {
8681 let first_prefix = full_comment_prefixes
8682 .first()
8683 .expect("prefixes is non-empty");
8684 let prefix_trimmed_lengths = full_comment_prefixes
8685 .iter()
8686 .map(|p| p.trim_end_matches(' ').len())
8687 .collect::<SmallVec<[usize; 4]>>();
8688
8689 let mut all_selection_lines_are_comments = true;
8690
8691 for row in start_row.0..=end_row.0 {
8692 let row = MultiBufferRow(row);
8693 if start_row < end_row && snapshot.is_line_blank(row) {
8694 continue;
8695 }
8696
8697 let prefix_range = full_comment_prefixes
8698 .iter()
8699 .zip(prefix_trimmed_lengths.iter().copied())
8700 .map(|(prefix, trimmed_prefix_len)| {
8701 comment_prefix_range(
8702 snapshot.deref(),
8703 row,
8704 &prefix[..trimmed_prefix_len],
8705 &prefix[trimmed_prefix_len..],
8706 ignore_indent,
8707 )
8708 })
8709 .max_by_key(|range| range.end.column - range.start.column)
8710 .expect("prefixes is non-empty");
8711
8712 if prefix_range.is_empty() {
8713 all_selection_lines_are_comments = false;
8714 }
8715
8716 selection_edit_ranges.push(prefix_range);
8717 }
8718
8719 if all_selection_lines_are_comments {
8720 edits.extend(
8721 selection_edit_ranges
8722 .iter()
8723 .cloned()
8724 .map(|range| (range, empty_str.clone())),
8725 );
8726 } else {
8727 let min_column = selection_edit_ranges
8728 .iter()
8729 .map(|range| range.start.column)
8730 .min()
8731 .unwrap_or(0);
8732 edits.extend(selection_edit_ranges.iter().map(|range| {
8733 let position = Point::new(range.start.row, min_column);
8734 (position..position, first_prefix.clone())
8735 }));
8736 }
8737 } else if let Some((full_comment_prefix, comment_suffix)) =
8738 language.block_comment_delimiters()
8739 {
8740 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8741 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8742 let prefix_range = comment_prefix_range(
8743 snapshot.deref(),
8744 start_row,
8745 comment_prefix,
8746 comment_prefix_whitespace,
8747 ignore_indent,
8748 );
8749 let suffix_range = comment_suffix_range(
8750 snapshot.deref(),
8751 end_row,
8752 comment_suffix.trim_start_matches(' '),
8753 comment_suffix.starts_with(' '),
8754 );
8755
8756 if prefix_range.is_empty() || suffix_range.is_empty() {
8757 edits.push((
8758 prefix_range.start..prefix_range.start,
8759 full_comment_prefix.clone(),
8760 ));
8761 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8762 suffixes_inserted.push((end_row, comment_suffix.len()));
8763 } else {
8764 edits.push((prefix_range, empty_str.clone()));
8765 edits.push((suffix_range, empty_str.clone()));
8766 }
8767 } else {
8768 continue;
8769 }
8770 }
8771
8772 drop(snapshot);
8773 this.buffer.update(cx, |buffer, cx| {
8774 buffer.edit(edits, None, cx);
8775 });
8776
8777 // Adjust selections so that they end before any comment suffixes that
8778 // were inserted.
8779 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8780 let mut selections = this.selections.all::<Point>(cx);
8781 let snapshot = this.buffer.read(cx).read(cx);
8782 for selection in &mut selections {
8783 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8784 match row.cmp(&MultiBufferRow(selection.end.row)) {
8785 Ordering::Less => {
8786 suffixes_inserted.next();
8787 continue;
8788 }
8789 Ordering::Greater => break,
8790 Ordering::Equal => {
8791 if selection.end.column == snapshot.line_len(row) {
8792 if selection.is_empty() {
8793 selection.start.column -= suffix_len as u32;
8794 }
8795 selection.end.column -= suffix_len as u32;
8796 }
8797 break;
8798 }
8799 }
8800 }
8801 }
8802
8803 drop(snapshot);
8804 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8805
8806 let selections = this.selections.all::<Point>(cx);
8807 let selections_on_single_row = selections.windows(2).all(|selections| {
8808 selections[0].start.row == selections[1].start.row
8809 && selections[0].end.row == selections[1].end.row
8810 && selections[0].start.row == selections[0].end.row
8811 });
8812 let selections_selecting = selections
8813 .iter()
8814 .any(|selection| selection.start != selection.end);
8815 let advance_downwards = action.advance_downwards
8816 && selections_on_single_row
8817 && !selections_selecting
8818 && !matches!(this.mode, EditorMode::SingleLine { .. });
8819
8820 if advance_downwards {
8821 let snapshot = this.buffer.read(cx).snapshot(cx);
8822
8823 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8824 s.move_cursors_with(|display_snapshot, display_point, _| {
8825 let mut point = display_point.to_point(display_snapshot);
8826 point.row += 1;
8827 point = snapshot.clip_point(point, Bias::Left);
8828 let display_point = point.to_display_point(display_snapshot);
8829 let goal = SelectionGoal::HorizontalPosition(
8830 display_snapshot
8831 .x_for_display_point(display_point, text_layout_details)
8832 .into(),
8833 );
8834 (display_point, goal)
8835 })
8836 });
8837 }
8838 });
8839 }
8840
8841 pub fn select_enclosing_symbol(
8842 &mut self,
8843 _: &SelectEnclosingSymbol,
8844 cx: &mut ViewContext<Self>,
8845 ) {
8846 let buffer = self.buffer.read(cx).snapshot(cx);
8847 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8848
8849 fn update_selection(
8850 selection: &Selection<usize>,
8851 buffer_snap: &MultiBufferSnapshot,
8852 ) -> Option<Selection<usize>> {
8853 let cursor = selection.head();
8854 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8855 for symbol in symbols.iter().rev() {
8856 let start = symbol.range.start.to_offset(buffer_snap);
8857 let end = symbol.range.end.to_offset(buffer_snap);
8858 let new_range = start..end;
8859 if start < selection.start || end > selection.end {
8860 return Some(Selection {
8861 id: selection.id,
8862 start: new_range.start,
8863 end: new_range.end,
8864 goal: SelectionGoal::None,
8865 reversed: selection.reversed,
8866 });
8867 }
8868 }
8869 None
8870 }
8871
8872 let mut selected_larger_symbol = false;
8873 let new_selections = old_selections
8874 .iter()
8875 .map(|selection| match update_selection(selection, &buffer) {
8876 Some(new_selection) => {
8877 if new_selection.range() != selection.range() {
8878 selected_larger_symbol = true;
8879 }
8880 new_selection
8881 }
8882 None => selection.clone(),
8883 })
8884 .collect::<Vec<_>>();
8885
8886 if selected_larger_symbol {
8887 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8888 s.select(new_selections);
8889 });
8890 }
8891 }
8892
8893 pub fn select_larger_syntax_node(
8894 &mut self,
8895 _: &SelectLargerSyntaxNode,
8896 cx: &mut ViewContext<Self>,
8897 ) {
8898 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8899 let buffer = self.buffer.read(cx).snapshot(cx);
8900 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8901
8902 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8903 let mut selected_larger_node = false;
8904 let new_selections = old_selections
8905 .iter()
8906 .map(|selection| {
8907 let old_range = selection.start..selection.end;
8908 let mut new_range = old_range.clone();
8909 let mut new_node = None;
8910 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8911 {
8912 new_node = Some(node);
8913 new_range = containing_range;
8914 if !display_map.intersects_fold(new_range.start)
8915 && !display_map.intersects_fold(new_range.end)
8916 {
8917 break;
8918 }
8919 }
8920
8921 if let Some(node) = new_node {
8922 // Log the ancestor, to support using this action as a way to explore TreeSitter
8923 // nodes. Parent and grandparent are also logged because this operation will not
8924 // visit nodes that have the same range as their parent.
8925 log::info!("Node: {node:?}");
8926 let parent = node.parent();
8927 log::info!("Parent: {parent:?}");
8928 let grandparent = parent.and_then(|x| x.parent());
8929 log::info!("Grandparent: {grandparent:?}");
8930 }
8931
8932 selected_larger_node |= new_range != old_range;
8933 Selection {
8934 id: selection.id,
8935 start: new_range.start,
8936 end: new_range.end,
8937 goal: SelectionGoal::None,
8938 reversed: selection.reversed,
8939 }
8940 })
8941 .collect::<Vec<_>>();
8942
8943 if selected_larger_node {
8944 stack.push(old_selections);
8945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8946 s.select(new_selections);
8947 });
8948 }
8949 self.select_larger_syntax_node_stack = stack;
8950 }
8951
8952 pub fn select_smaller_syntax_node(
8953 &mut self,
8954 _: &SelectSmallerSyntaxNode,
8955 cx: &mut ViewContext<Self>,
8956 ) {
8957 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8958 if let Some(selections) = stack.pop() {
8959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8960 s.select(selections.to_vec());
8961 });
8962 }
8963 self.select_larger_syntax_node_stack = stack;
8964 }
8965
8966 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8967 if !EditorSettings::get_global(cx).gutter.runnables {
8968 self.clear_tasks();
8969 return Task::ready(());
8970 }
8971 let project = self.project.as_ref().map(Model::downgrade);
8972 cx.spawn(|this, mut cx| async move {
8973 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8974 let Some(project) = project.and_then(|p| p.upgrade()) else {
8975 return;
8976 };
8977 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8978 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8979 }) else {
8980 return;
8981 };
8982
8983 let hide_runnables = project
8984 .update(&mut cx, |project, cx| {
8985 // Do not display any test indicators in non-dev server remote projects.
8986 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8987 })
8988 .unwrap_or(true);
8989 if hide_runnables {
8990 return;
8991 }
8992 let new_rows =
8993 cx.background_executor()
8994 .spawn({
8995 let snapshot = display_snapshot.clone();
8996 async move {
8997 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8998 }
8999 })
9000 .await;
9001 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9002
9003 this.update(&mut cx, |this, _| {
9004 this.clear_tasks();
9005 for (key, value) in rows {
9006 this.insert_tasks(key, value);
9007 }
9008 })
9009 .ok();
9010 })
9011 }
9012 fn fetch_runnable_ranges(
9013 snapshot: &DisplaySnapshot,
9014 range: Range<Anchor>,
9015 ) -> Vec<language::RunnableRange> {
9016 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9017 }
9018
9019 fn runnable_rows(
9020 project: Model<Project>,
9021 snapshot: DisplaySnapshot,
9022 runnable_ranges: Vec<RunnableRange>,
9023 mut cx: AsyncWindowContext,
9024 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9025 runnable_ranges
9026 .into_iter()
9027 .filter_map(|mut runnable| {
9028 let tasks = cx
9029 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9030 .ok()?;
9031 if tasks.is_empty() {
9032 return None;
9033 }
9034
9035 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9036
9037 let row = snapshot
9038 .buffer_snapshot
9039 .buffer_line_for_row(MultiBufferRow(point.row))?
9040 .1
9041 .start
9042 .row;
9043
9044 let context_range =
9045 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9046 Some((
9047 (runnable.buffer_id, row),
9048 RunnableTasks {
9049 templates: tasks,
9050 offset: MultiBufferOffset(runnable.run_range.start),
9051 context_range,
9052 column: point.column,
9053 extra_variables: runnable.extra_captures,
9054 },
9055 ))
9056 })
9057 .collect()
9058 }
9059
9060 fn templates_with_tags(
9061 project: &Model<Project>,
9062 runnable: &mut Runnable,
9063 cx: &WindowContext,
9064 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9065 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9066 let (worktree_id, file) = project
9067 .buffer_for_id(runnable.buffer, cx)
9068 .and_then(|buffer| buffer.read(cx).file())
9069 .map(|file| (file.worktree_id(cx), file.clone()))
9070 .unzip();
9071
9072 (
9073 project.task_store().read(cx).task_inventory().cloned(),
9074 worktree_id,
9075 file,
9076 )
9077 });
9078
9079 let tags = mem::take(&mut runnable.tags);
9080 let mut tags: Vec<_> = tags
9081 .into_iter()
9082 .flat_map(|tag| {
9083 let tag = tag.0.clone();
9084 inventory
9085 .as_ref()
9086 .into_iter()
9087 .flat_map(|inventory| {
9088 inventory.read(cx).list_tasks(
9089 file.clone(),
9090 Some(runnable.language.clone()),
9091 worktree_id,
9092 cx,
9093 )
9094 })
9095 .filter(move |(_, template)| {
9096 template.tags.iter().any(|source_tag| source_tag == &tag)
9097 })
9098 })
9099 .sorted_by_key(|(kind, _)| kind.to_owned())
9100 .collect();
9101 if let Some((leading_tag_source, _)) = tags.first() {
9102 // Strongest source wins; if we have worktree tag binding, prefer that to
9103 // global and language bindings;
9104 // if we have a global binding, prefer that to language binding.
9105 let first_mismatch = tags
9106 .iter()
9107 .position(|(tag_source, _)| tag_source != leading_tag_source);
9108 if let Some(index) = first_mismatch {
9109 tags.truncate(index);
9110 }
9111 }
9112
9113 tags
9114 }
9115
9116 pub fn move_to_enclosing_bracket(
9117 &mut self,
9118 _: &MoveToEnclosingBracket,
9119 cx: &mut ViewContext<Self>,
9120 ) {
9121 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9122 s.move_offsets_with(|snapshot, selection| {
9123 let Some(enclosing_bracket_ranges) =
9124 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9125 else {
9126 return;
9127 };
9128
9129 let mut best_length = usize::MAX;
9130 let mut best_inside = false;
9131 let mut best_in_bracket_range = false;
9132 let mut best_destination = None;
9133 for (open, close) in enclosing_bracket_ranges {
9134 let close = close.to_inclusive();
9135 let length = close.end() - open.start;
9136 let inside = selection.start >= open.end && selection.end <= *close.start();
9137 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9138 || close.contains(&selection.head());
9139
9140 // If best is next to a bracket and current isn't, skip
9141 if !in_bracket_range && best_in_bracket_range {
9142 continue;
9143 }
9144
9145 // Prefer smaller lengths unless best is inside and current isn't
9146 if length > best_length && (best_inside || !inside) {
9147 continue;
9148 }
9149
9150 best_length = length;
9151 best_inside = inside;
9152 best_in_bracket_range = in_bracket_range;
9153 best_destination = Some(
9154 if close.contains(&selection.start) && close.contains(&selection.end) {
9155 if inside {
9156 open.end
9157 } else {
9158 open.start
9159 }
9160 } else if inside {
9161 *close.start()
9162 } else {
9163 *close.end()
9164 },
9165 );
9166 }
9167
9168 if let Some(destination) = best_destination {
9169 selection.collapse_to(destination, SelectionGoal::None);
9170 }
9171 })
9172 });
9173 }
9174
9175 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9176 self.end_selection(cx);
9177 self.selection_history.mode = SelectionHistoryMode::Undoing;
9178 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9179 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9180 self.select_next_state = entry.select_next_state;
9181 self.select_prev_state = entry.select_prev_state;
9182 self.add_selections_state = entry.add_selections_state;
9183 self.request_autoscroll(Autoscroll::newest(), cx);
9184 }
9185 self.selection_history.mode = SelectionHistoryMode::Normal;
9186 }
9187
9188 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9189 self.end_selection(cx);
9190 self.selection_history.mode = SelectionHistoryMode::Redoing;
9191 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9192 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9193 self.select_next_state = entry.select_next_state;
9194 self.select_prev_state = entry.select_prev_state;
9195 self.add_selections_state = entry.add_selections_state;
9196 self.request_autoscroll(Autoscroll::newest(), cx);
9197 }
9198 self.selection_history.mode = SelectionHistoryMode::Normal;
9199 }
9200
9201 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9202 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9203 }
9204
9205 pub fn expand_excerpts_down(
9206 &mut self,
9207 action: &ExpandExcerptsDown,
9208 cx: &mut ViewContext<Self>,
9209 ) {
9210 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9211 }
9212
9213 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9214 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9215 }
9216
9217 pub fn expand_excerpts_for_direction(
9218 &mut self,
9219 lines: u32,
9220 direction: ExpandExcerptDirection,
9221 cx: &mut ViewContext<Self>,
9222 ) {
9223 let selections = self.selections.disjoint_anchors();
9224
9225 let lines = if lines == 0 {
9226 EditorSettings::get_global(cx).expand_excerpt_lines
9227 } else {
9228 lines
9229 };
9230
9231 self.buffer.update(cx, |buffer, cx| {
9232 let snapshot = buffer.snapshot(cx);
9233 let mut excerpt_ids = selections
9234 .iter()
9235 .flat_map(|selection| {
9236 snapshot
9237 .excerpts_for_range(selection.range())
9238 .map(|excerpt| excerpt.id())
9239 })
9240 .collect::<Vec<_>>();
9241 excerpt_ids.sort();
9242 excerpt_ids.dedup();
9243 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9244 })
9245 }
9246
9247 pub fn expand_excerpt(
9248 &mut self,
9249 excerpt: ExcerptId,
9250 direction: ExpandExcerptDirection,
9251 cx: &mut ViewContext<Self>,
9252 ) {
9253 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9254 self.buffer.update(cx, |buffer, cx| {
9255 buffer.expand_excerpts([excerpt], lines, direction, cx)
9256 })
9257 }
9258
9259 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9260 self.go_to_diagnostic_impl(Direction::Next, cx)
9261 }
9262
9263 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9264 self.go_to_diagnostic_impl(Direction::Prev, cx)
9265 }
9266
9267 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9268 let buffer = self.buffer.read(cx).snapshot(cx);
9269 let selection = self.selections.newest::<usize>(cx);
9270
9271 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9272 if direction == Direction::Next {
9273 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9274 self.activate_diagnostics(popover.group_id(), cx);
9275 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9276 let primary_range_start = active_diagnostics.primary_range.start;
9277 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9278 let mut new_selection = s.newest_anchor().clone();
9279 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9280 s.select_anchors(vec![new_selection.clone()]);
9281 });
9282 self.refresh_inline_completion(false, true, cx);
9283 }
9284 return;
9285 }
9286 }
9287
9288 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9289 active_diagnostics
9290 .primary_range
9291 .to_offset(&buffer)
9292 .to_inclusive()
9293 });
9294 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9295 if active_primary_range.contains(&selection.head()) {
9296 *active_primary_range.start()
9297 } else {
9298 selection.head()
9299 }
9300 } else {
9301 selection.head()
9302 };
9303 let snapshot = self.snapshot(cx);
9304 loop {
9305 let diagnostics = if direction == Direction::Prev {
9306 buffer.diagnostics_in_range(0..search_start, true)
9307 } else {
9308 buffer.diagnostics_in_range(search_start..buffer.len(), false)
9309 }
9310 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9311 let search_start_anchor = buffer.anchor_after(search_start);
9312 let group = diagnostics
9313 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9314 // be sorted in a stable way
9315 // skip until we are at current active diagnostic, if it exists
9316 .skip_while(|entry| {
9317 let is_in_range = match direction {
9318 Direction::Prev => {
9319 entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
9320 }
9321 Direction::Next => {
9322 entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
9323 }
9324 };
9325 is_in_range
9326 && self
9327 .active_diagnostics
9328 .as_ref()
9329 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9330 })
9331 .find_map(|entry| {
9332 if entry.diagnostic.is_primary
9333 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9334 && !(entry.range.start == entry.range.end)
9335 // if we match with the active diagnostic, skip it
9336 && Some(entry.diagnostic.group_id)
9337 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9338 {
9339 Some((entry.range, entry.diagnostic.group_id))
9340 } else {
9341 None
9342 }
9343 });
9344
9345 if let Some((primary_range, group_id)) = group {
9346 self.activate_diagnostics(group_id, cx);
9347 let primary_range = primary_range.to_offset(&buffer);
9348 if self.active_diagnostics.is_some() {
9349 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9350 s.select(vec![Selection {
9351 id: selection.id,
9352 start: primary_range.start,
9353 end: primary_range.start,
9354 reversed: false,
9355 goal: SelectionGoal::None,
9356 }]);
9357 });
9358 self.refresh_inline_completion(false, true, cx);
9359 }
9360 break;
9361 } else {
9362 // Cycle around to the start of the buffer, potentially moving back to the start of
9363 // the currently active diagnostic.
9364 active_primary_range.take();
9365 if direction == Direction::Prev {
9366 if search_start == buffer.len() {
9367 break;
9368 } else {
9369 search_start = buffer.len();
9370 }
9371 } else if search_start == 0 {
9372 break;
9373 } else {
9374 search_start = 0;
9375 }
9376 }
9377 }
9378 }
9379
9380 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9381 let snapshot = self.snapshot(cx);
9382 let selection = self.selections.newest::<Point>(cx);
9383 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9384 }
9385
9386 fn go_to_hunk_after_position(
9387 &mut self,
9388 snapshot: &EditorSnapshot,
9389 position: Point,
9390 cx: &mut ViewContext<Editor>,
9391 ) -> Option<MultiBufferDiffHunk> {
9392 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9393 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9394 snapshot,
9395 position,
9396 ix > 0,
9397 snapshot.diff_map.diff_hunks_in_range(
9398 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9399 &snapshot.buffer_snapshot,
9400 ),
9401 cx,
9402 ) {
9403 return Some(hunk);
9404 }
9405 }
9406 None
9407 }
9408
9409 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9410 let snapshot = self.snapshot(cx);
9411 let selection = self.selections.newest::<Point>(cx);
9412 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9413 }
9414
9415 fn go_to_hunk_before_position(
9416 &mut self,
9417 snapshot: &EditorSnapshot,
9418 position: Point,
9419 cx: &mut ViewContext<Editor>,
9420 ) -> Option<MultiBufferDiffHunk> {
9421 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9422 .into_iter()
9423 .enumerate()
9424 {
9425 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9426 snapshot,
9427 position,
9428 ix > 0,
9429 snapshot
9430 .diff_map
9431 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9432 cx,
9433 ) {
9434 return Some(hunk);
9435 }
9436 }
9437 None
9438 }
9439
9440 fn go_to_next_hunk_in_direction(
9441 &mut self,
9442 snapshot: &DisplaySnapshot,
9443 initial_point: Point,
9444 is_wrapped: bool,
9445 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9446 cx: &mut ViewContext<Editor>,
9447 ) -> Option<MultiBufferDiffHunk> {
9448 let display_point = initial_point.to_display_point(snapshot);
9449 let mut hunks = hunks
9450 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9451 .filter(|(display_hunk, _)| {
9452 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9453 })
9454 .dedup();
9455
9456 if let Some((display_hunk, hunk)) = hunks.next() {
9457 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9458 let row = display_hunk.start_display_row();
9459 let point = DisplayPoint::new(row, 0);
9460 s.select_display_ranges([point..point]);
9461 });
9462
9463 Some(hunk)
9464 } else {
9465 None
9466 }
9467 }
9468
9469 pub fn go_to_definition(
9470 &mut self,
9471 _: &GoToDefinition,
9472 cx: &mut ViewContext<Self>,
9473 ) -> Task<Result<Navigated>> {
9474 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9475 cx.spawn(|editor, mut cx| async move {
9476 if definition.await? == Navigated::Yes {
9477 return Ok(Navigated::Yes);
9478 }
9479 match editor.update(&mut cx, |editor, cx| {
9480 editor.find_all_references(&FindAllReferences, cx)
9481 })? {
9482 Some(references) => references.await,
9483 None => Ok(Navigated::No),
9484 }
9485 })
9486 }
9487
9488 pub fn go_to_declaration(
9489 &mut self,
9490 _: &GoToDeclaration,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9494 }
9495
9496 pub fn go_to_declaration_split(
9497 &mut self,
9498 _: &GoToDeclaration,
9499 cx: &mut ViewContext<Self>,
9500 ) -> Task<Result<Navigated>> {
9501 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9502 }
9503
9504 pub fn go_to_implementation(
9505 &mut self,
9506 _: &GoToImplementation,
9507 cx: &mut ViewContext<Self>,
9508 ) -> Task<Result<Navigated>> {
9509 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9510 }
9511
9512 pub fn go_to_implementation_split(
9513 &mut self,
9514 _: &GoToImplementationSplit,
9515 cx: &mut ViewContext<Self>,
9516 ) -> Task<Result<Navigated>> {
9517 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9518 }
9519
9520 pub fn go_to_type_definition(
9521 &mut self,
9522 _: &GoToTypeDefinition,
9523 cx: &mut ViewContext<Self>,
9524 ) -> Task<Result<Navigated>> {
9525 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9526 }
9527
9528 pub fn go_to_definition_split(
9529 &mut self,
9530 _: &GoToDefinitionSplit,
9531 cx: &mut ViewContext<Self>,
9532 ) -> Task<Result<Navigated>> {
9533 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9534 }
9535
9536 pub fn go_to_type_definition_split(
9537 &mut self,
9538 _: &GoToTypeDefinitionSplit,
9539 cx: &mut ViewContext<Self>,
9540 ) -> Task<Result<Navigated>> {
9541 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9542 }
9543
9544 fn go_to_definition_of_kind(
9545 &mut self,
9546 kind: GotoDefinitionKind,
9547 split: bool,
9548 cx: &mut ViewContext<Self>,
9549 ) -> Task<Result<Navigated>> {
9550 let Some(provider) = self.semantics_provider.clone() else {
9551 return Task::ready(Ok(Navigated::No));
9552 };
9553 let head = self.selections.newest::<usize>(cx).head();
9554 let buffer = self.buffer.read(cx);
9555 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9556 text_anchor
9557 } else {
9558 return Task::ready(Ok(Navigated::No));
9559 };
9560
9561 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9562 return Task::ready(Ok(Navigated::No));
9563 };
9564
9565 cx.spawn(|editor, mut cx| async move {
9566 let definitions = definitions.await?;
9567 let navigated = editor
9568 .update(&mut cx, |editor, cx| {
9569 editor.navigate_to_hover_links(
9570 Some(kind),
9571 definitions
9572 .into_iter()
9573 .filter(|location| {
9574 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9575 })
9576 .map(HoverLink::Text)
9577 .collect::<Vec<_>>(),
9578 split,
9579 cx,
9580 )
9581 })?
9582 .await?;
9583 anyhow::Ok(navigated)
9584 })
9585 }
9586
9587 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9588 let selection = self.selections.newest_anchor();
9589 let head = selection.head();
9590 let tail = selection.tail();
9591
9592 let Some((buffer, start_position)) =
9593 self.buffer.read(cx).text_anchor_for_position(head, cx)
9594 else {
9595 return;
9596 };
9597
9598 let end_position = if head != tail {
9599 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9600 return;
9601 };
9602 Some(pos)
9603 } else {
9604 None
9605 };
9606
9607 let url_finder = cx.spawn(|editor, mut cx| async move {
9608 let url = if let Some(end_pos) = end_position {
9609 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9610 } else {
9611 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9612 };
9613
9614 if let Some(url) = url {
9615 editor.update(&mut cx, |_, cx| {
9616 cx.open_url(&url);
9617 })
9618 } else {
9619 Ok(())
9620 }
9621 });
9622
9623 url_finder.detach();
9624 }
9625
9626 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9627 let Some(workspace) = self.workspace() else {
9628 return;
9629 };
9630
9631 let position = self.selections.newest_anchor().head();
9632
9633 let Some((buffer, buffer_position)) =
9634 self.buffer.read(cx).text_anchor_for_position(position, cx)
9635 else {
9636 return;
9637 };
9638
9639 let project = self.project.clone();
9640
9641 cx.spawn(|_, mut cx| async move {
9642 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9643
9644 if let Some((_, path)) = result {
9645 workspace
9646 .update(&mut cx, |workspace, cx| {
9647 workspace.open_resolved_path(path, cx)
9648 })?
9649 .await?;
9650 }
9651 anyhow::Ok(())
9652 })
9653 .detach();
9654 }
9655
9656 pub(crate) fn navigate_to_hover_links(
9657 &mut self,
9658 kind: Option<GotoDefinitionKind>,
9659 mut definitions: Vec<HoverLink>,
9660 split: bool,
9661 cx: &mut ViewContext<Editor>,
9662 ) -> Task<Result<Navigated>> {
9663 // If there is one definition, just open it directly
9664 if definitions.len() == 1 {
9665 let definition = definitions.pop().unwrap();
9666
9667 enum TargetTaskResult {
9668 Location(Option<Location>),
9669 AlreadyNavigated,
9670 }
9671
9672 let target_task = match definition {
9673 HoverLink::Text(link) => {
9674 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9675 }
9676 HoverLink::InlayHint(lsp_location, server_id) => {
9677 let computation = self.compute_target_location(lsp_location, server_id, cx);
9678 cx.background_executor().spawn(async move {
9679 let location = computation.await?;
9680 Ok(TargetTaskResult::Location(location))
9681 })
9682 }
9683 HoverLink::Url(url) => {
9684 cx.open_url(&url);
9685 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9686 }
9687 HoverLink::File(path) => {
9688 if let Some(workspace) = self.workspace() {
9689 cx.spawn(|_, mut cx| async move {
9690 workspace
9691 .update(&mut cx, |workspace, cx| {
9692 workspace.open_resolved_path(path, cx)
9693 })?
9694 .await
9695 .map(|_| TargetTaskResult::AlreadyNavigated)
9696 })
9697 } else {
9698 Task::ready(Ok(TargetTaskResult::Location(None)))
9699 }
9700 }
9701 };
9702 cx.spawn(|editor, mut cx| async move {
9703 let target = match target_task.await.context("target resolution task")? {
9704 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9705 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9706 TargetTaskResult::Location(Some(target)) => target,
9707 };
9708
9709 editor.update(&mut cx, |editor, cx| {
9710 let Some(workspace) = editor.workspace() else {
9711 return Navigated::No;
9712 };
9713 let pane = workspace.read(cx).active_pane().clone();
9714
9715 let range = target.range.to_offset(target.buffer.read(cx));
9716 let range = editor.range_for_match(&range);
9717
9718 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9719 let buffer = target.buffer.read(cx);
9720 let range = check_multiline_range(buffer, range);
9721 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9722 s.select_ranges([range]);
9723 });
9724 } else {
9725 cx.window_context().defer(move |cx| {
9726 let target_editor: View<Self> =
9727 workspace.update(cx, |workspace, cx| {
9728 let pane = if split {
9729 workspace.adjacent_pane(cx)
9730 } else {
9731 workspace.active_pane().clone()
9732 };
9733
9734 workspace.open_project_item(
9735 pane,
9736 target.buffer.clone(),
9737 true,
9738 true,
9739 cx,
9740 )
9741 });
9742 target_editor.update(cx, |target_editor, cx| {
9743 // When selecting a definition in a different buffer, disable the nav history
9744 // to avoid creating a history entry at the previous cursor location.
9745 pane.update(cx, |pane, _| pane.disable_history());
9746 let buffer = target.buffer.read(cx);
9747 let range = check_multiline_range(buffer, range);
9748 target_editor.change_selections(
9749 Some(Autoscroll::focused()),
9750 cx,
9751 |s| {
9752 s.select_ranges([range]);
9753 },
9754 );
9755 pane.update(cx, |pane, _| pane.enable_history());
9756 });
9757 });
9758 }
9759 Navigated::Yes
9760 })
9761 })
9762 } else if !definitions.is_empty() {
9763 cx.spawn(|editor, mut cx| async move {
9764 let (title, location_tasks, workspace) = editor
9765 .update(&mut cx, |editor, cx| {
9766 let tab_kind = match kind {
9767 Some(GotoDefinitionKind::Implementation) => "Implementations",
9768 _ => "Definitions",
9769 };
9770 let title = definitions
9771 .iter()
9772 .find_map(|definition| match definition {
9773 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9774 let buffer = origin.buffer.read(cx);
9775 format!(
9776 "{} for {}",
9777 tab_kind,
9778 buffer
9779 .text_for_range(origin.range.clone())
9780 .collect::<String>()
9781 )
9782 }),
9783 HoverLink::InlayHint(_, _) => None,
9784 HoverLink::Url(_) => None,
9785 HoverLink::File(_) => None,
9786 })
9787 .unwrap_or(tab_kind.to_string());
9788 let location_tasks = definitions
9789 .into_iter()
9790 .map(|definition| match definition {
9791 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9792 HoverLink::InlayHint(lsp_location, server_id) => {
9793 editor.compute_target_location(lsp_location, server_id, cx)
9794 }
9795 HoverLink::Url(_) => Task::ready(Ok(None)),
9796 HoverLink::File(_) => Task::ready(Ok(None)),
9797 })
9798 .collect::<Vec<_>>();
9799 (title, location_tasks, editor.workspace().clone())
9800 })
9801 .context("location tasks preparation")?;
9802
9803 let locations = future::join_all(location_tasks)
9804 .await
9805 .into_iter()
9806 .filter_map(|location| location.transpose())
9807 .collect::<Result<_>>()
9808 .context("location tasks")?;
9809
9810 let Some(workspace) = workspace else {
9811 return Ok(Navigated::No);
9812 };
9813 let opened = workspace
9814 .update(&mut cx, |workspace, cx| {
9815 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9816 })
9817 .ok();
9818
9819 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9820 })
9821 } else {
9822 Task::ready(Ok(Navigated::No))
9823 }
9824 }
9825
9826 fn compute_target_location(
9827 &self,
9828 lsp_location: lsp::Location,
9829 server_id: LanguageServerId,
9830 cx: &mut ViewContext<Self>,
9831 ) -> Task<anyhow::Result<Option<Location>>> {
9832 let Some(project) = self.project.clone() else {
9833 return Task::ready(Ok(None));
9834 };
9835
9836 cx.spawn(move |editor, mut cx| async move {
9837 let location_task = editor.update(&mut cx, |_, cx| {
9838 project.update(cx, |project, cx| {
9839 let language_server_name = project
9840 .language_server_statuses(cx)
9841 .find(|(id, _)| server_id == *id)
9842 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9843 language_server_name.map(|language_server_name| {
9844 project.open_local_buffer_via_lsp(
9845 lsp_location.uri.clone(),
9846 server_id,
9847 language_server_name,
9848 cx,
9849 )
9850 })
9851 })
9852 })?;
9853 let location = match location_task {
9854 Some(task) => Some({
9855 let target_buffer_handle = task.await.context("open local buffer")?;
9856 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9857 let target_start = target_buffer
9858 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9859 let target_end = target_buffer
9860 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9861 target_buffer.anchor_after(target_start)
9862 ..target_buffer.anchor_before(target_end)
9863 })?;
9864 Location {
9865 buffer: target_buffer_handle,
9866 range,
9867 }
9868 }),
9869 None => None,
9870 };
9871 Ok(location)
9872 })
9873 }
9874
9875 pub fn find_all_references(
9876 &mut self,
9877 _: &FindAllReferences,
9878 cx: &mut ViewContext<Self>,
9879 ) -> Option<Task<Result<Navigated>>> {
9880 let selection = self.selections.newest::<usize>(cx);
9881 let multi_buffer = self.buffer.read(cx);
9882 let head = selection.head();
9883
9884 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9885 let head_anchor = multi_buffer_snapshot.anchor_at(
9886 head,
9887 if head < selection.tail() {
9888 Bias::Right
9889 } else {
9890 Bias::Left
9891 },
9892 );
9893
9894 match self
9895 .find_all_references_task_sources
9896 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9897 {
9898 Ok(_) => {
9899 log::info!(
9900 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9901 );
9902 return None;
9903 }
9904 Err(i) => {
9905 self.find_all_references_task_sources.insert(i, head_anchor);
9906 }
9907 }
9908
9909 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9910 let workspace = self.workspace()?;
9911 let project = workspace.read(cx).project().clone();
9912 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9913 Some(cx.spawn(|editor, mut cx| async move {
9914 let _cleanup = defer({
9915 let mut cx = cx.clone();
9916 move || {
9917 let _ = editor.update(&mut cx, |editor, _| {
9918 if let Ok(i) =
9919 editor
9920 .find_all_references_task_sources
9921 .binary_search_by(|anchor| {
9922 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9923 })
9924 {
9925 editor.find_all_references_task_sources.remove(i);
9926 }
9927 });
9928 }
9929 });
9930
9931 let locations = references.await?;
9932 if locations.is_empty() {
9933 return anyhow::Ok(Navigated::No);
9934 }
9935
9936 workspace.update(&mut cx, |workspace, cx| {
9937 let title = locations
9938 .first()
9939 .as_ref()
9940 .map(|location| {
9941 let buffer = location.buffer.read(cx);
9942 format!(
9943 "References to `{}`",
9944 buffer
9945 .text_for_range(location.range.clone())
9946 .collect::<String>()
9947 )
9948 })
9949 .unwrap();
9950 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9951 Navigated::Yes
9952 })
9953 }))
9954 }
9955
9956 /// Opens a multibuffer with the given project locations in it
9957 pub fn open_locations_in_multibuffer(
9958 workspace: &mut Workspace,
9959 mut locations: Vec<Location>,
9960 title: String,
9961 split: bool,
9962 cx: &mut ViewContext<Workspace>,
9963 ) {
9964 // If there are multiple definitions, open them in a multibuffer
9965 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9966 let mut locations = locations.into_iter().peekable();
9967 let mut ranges_to_highlight = Vec::new();
9968 let capability = workspace.project().read(cx).capability();
9969
9970 let excerpt_buffer = cx.new_model(|cx| {
9971 let mut multibuffer = MultiBuffer::new(capability);
9972 while let Some(location) = locations.next() {
9973 let buffer = location.buffer.read(cx);
9974 let mut ranges_for_buffer = Vec::new();
9975 let range = location.range.to_offset(buffer);
9976 ranges_for_buffer.push(range.clone());
9977
9978 while let Some(next_location) = locations.peek() {
9979 if next_location.buffer == location.buffer {
9980 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9981 locations.next();
9982 } else {
9983 break;
9984 }
9985 }
9986
9987 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9988 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9989 location.buffer.clone(),
9990 ranges_for_buffer,
9991 DEFAULT_MULTIBUFFER_CONTEXT,
9992 cx,
9993 ))
9994 }
9995
9996 multibuffer.with_title(title)
9997 });
9998
9999 let editor = cx.new_view(|cx| {
10000 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10001 });
10002 editor.update(cx, |editor, cx| {
10003 if let Some(first_range) = ranges_to_highlight.first() {
10004 editor.change_selections(None, cx, |selections| {
10005 selections.clear_disjoint();
10006 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10007 });
10008 }
10009 editor.highlight_background::<Self>(
10010 &ranges_to_highlight,
10011 |theme| theme.editor_highlighted_line_background,
10012 cx,
10013 );
10014 editor.register_buffers_with_language_servers(cx);
10015 });
10016
10017 let item = Box::new(editor);
10018 let item_id = item.item_id();
10019
10020 if split {
10021 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10022 } else {
10023 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10024 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10025 pane.close_current_preview_item(cx)
10026 } else {
10027 None
10028 }
10029 });
10030 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10031 }
10032 workspace.active_pane().update(cx, |pane, cx| {
10033 pane.set_preview_item_id(Some(item_id), cx);
10034 });
10035 }
10036
10037 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10038 use language::ToOffset as _;
10039
10040 let provider = self.semantics_provider.clone()?;
10041 let selection = self.selections.newest_anchor().clone();
10042 let (cursor_buffer, cursor_buffer_position) = self
10043 .buffer
10044 .read(cx)
10045 .text_anchor_for_position(selection.head(), cx)?;
10046 let (tail_buffer, cursor_buffer_position_end) = self
10047 .buffer
10048 .read(cx)
10049 .text_anchor_for_position(selection.tail(), cx)?;
10050 if tail_buffer != cursor_buffer {
10051 return None;
10052 }
10053
10054 let snapshot = cursor_buffer.read(cx).snapshot();
10055 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10056 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10057 let prepare_rename = provider
10058 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10059 .unwrap_or_else(|| Task::ready(Ok(None)));
10060 drop(snapshot);
10061
10062 Some(cx.spawn(|this, mut cx| async move {
10063 let rename_range = if let Some(range) = prepare_rename.await? {
10064 Some(range)
10065 } else {
10066 this.update(&mut cx, |this, cx| {
10067 let buffer = this.buffer.read(cx).snapshot(cx);
10068 let mut buffer_highlights = this
10069 .document_highlights_for_position(selection.head(), &buffer)
10070 .filter(|highlight| {
10071 highlight.start.excerpt_id == selection.head().excerpt_id
10072 && highlight.end.excerpt_id == selection.head().excerpt_id
10073 });
10074 buffer_highlights
10075 .next()
10076 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10077 })?
10078 };
10079 if let Some(rename_range) = rename_range {
10080 this.update(&mut cx, |this, cx| {
10081 let snapshot = cursor_buffer.read(cx).snapshot();
10082 let rename_buffer_range = rename_range.to_offset(&snapshot);
10083 let cursor_offset_in_rename_range =
10084 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10085 let cursor_offset_in_rename_range_end =
10086 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10087
10088 this.take_rename(false, cx);
10089 let buffer = this.buffer.read(cx).read(cx);
10090 let cursor_offset = selection.head().to_offset(&buffer);
10091 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10092 let rename_end = rename_start + rename_buffer_range.len();
10093 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10094 let mut old_highlight_id = None;
10095 let old_name: Arc<str> = buffer
10096 .chunks(rename_start..rename_end, true)
10097 .map(|chunk| {
10098 if old_highlight_id.is_none() {
10099 old_highlight_id = chunk.syntax_highlight_id;
10100 }
10101 chunk.text
10102 })
10103 .collect::<String>()
10104 .into();
10105
10106 drop(buffer);
10107
10108 // Position the selection in the rename editor so that it matches the current selection.
10109 this.show_local_selections = false;
10110 let rename_editor = cx.new_view(|cx| {
10111 let mut editor = Editor::single_line(cx);
10112 editor.buffer.update(cx, |buffer, cx| {
10113 buffer.edit([(0..0, old_name.clone())], None, cx)
10114 });
10115 let rename_selection_range = match cursor_offset_in_rename_range
10116 .cmp(&cursor_offset_in_rename_range_end)
10117 {
10118 Ordering::Equal => {
10119 editor.select_all(&SelectAll, cx);
10120 return editor;
10121 }
10122 Ordering::Less => {
10123 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10124 }
10125 Ordering::Greater => {
10126 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10127 }
10128 };
10129 if rename_selection_range.end > old_name.len() {
10130 editor.select_all(&SelectAll, cx);
10131 } else {
10132 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10133 s.select_ranges([rename_selection_range]);
10134 });
10135 }
10136 editor
10137 });
10138 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10139 if e == &EditorEvent::Focused {
10140 cx.emit(EditorEvent::FocusedIn)
10141 }
10142 })
10143 .detach();
10144
10145 let write_highlights =
10146 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10147 let read_highlights =
10148 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10149 let ranges = write_highlights
10150 .iter()
10151 .flat_map(|(_, ranges)| ranges.iter())
10152 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10153 .cloned()
10154 .collect();
10155
10156 this.highlight_text::<Rename>(
10157 ranges,
10158 HighlightStyle {
10159 fade_out: Some(0.6),
10160 ..Default::default()
10161 },
10162 cx,
10163 );
10164 let rename_focus_handle = rename_editor.focus_handle(cx);
10165 cx.focus(&rename_focus_handle);
10166 let block_id = this.insert_blocks(
10167 [BlockProperties {
10168 style: BlockStyle::Flex,
10169 placement: BlockPlacement::Below(range.start),
10170 height: 1,
10171 render: Arc::new({
10172 let rename_editor = rename_editor.clone();
10173 move |cx: &mut BlockContext| {
10174 let mut text_style = cx.editor_style.text.clone();
10175 if let Some(highlight_style) = old_highlight_id
10176 .and_then(|h| h.style(&cx.editor_style.syntax))
10177 {
10178 text_style = text_style.highlight(highlight_style);
10179 }
10180 div()
10181 .block_mouse_down()
10182 .pl(cx.anchor_x)
10183 .child(EditorElement::new(
10184 &rename_editor,
10185 EditorStyle {
10186 background: cx.theme().system().transparent,
10187 local_player: cx.editor_style.local_player,
10188 text: text_style,
10189 scrollbar_width: cx.editor_style.scrollbar_width,
10190 syntax: cx.editor_style.syntax.clone(),
10191 status: cx.editor_style.status.clone(),
10192 inlay_hints_style: HighlightStyle {
10193 font_weight: Some(FontWeight::BOLD),
10194 ..make_inlay_hints_style(cx)
10195 },
10196 inline_completion_styles: make_suggestion_styles(
10197 cx,
10198 ),
10199 ..EditorStyle::default()
10200 },
10201 ))
10202 .into_any_element()
10203 }
10204 }),
10205 priority: 0,
10206 }],
10207 Some(Autoscroll::fit()),
10208 cx,
10209 )[0];
10210 this.pending_rename = Some(RenameState {
10211 range,
10212 old_name,
10213 editor: rename_editor,
10214 block_id,
10215 });
10216 })?;
10217 }
10218
10219 Ok(())
10220 }))
10221 }
10222
10223 pub fn confirm_rename(
10224 &mut self,
10225 _: &ConfirmRename,
10226 cx: &mut ViewContext<Self>,
10227 ) -> Option<Task<Result<()>>> {
10228 let rename = self.take_rename(false, cx)?;
10229 let workspace = self.workspace()?.downgrade();
10230 let (buffer, start) = self
10231 .buffer
10232 .read(cx)
10233 .text_anchor_for_position(rename.range.start, cx)?;
10234 let (end_buffer, _) = self
10235 .buffer
10236 .read(cx)
10237 .text_anchor_for_position(rename.range.end, cx)?;
10238 if buffer != end_buffer {
10239 return None;
10240 }
10241
10242 let old_name = rename.old_name;
10243 let new_name = rename.editor.read(cx).text(cx);
10244
10245 let rename = self.semantics_provider.as_ref()?.perform_rename(
10246 &buffer,
10247 start,
10248 new_name.clone(),
10249 cx,
10250 )?;
10251
10252 Some(cx.spawn(|editor, mut cx| async move {
10253 let project_transaction = rename.await?;
10254 Self::open_project_transaction(
10255 &editor,
10256 workspace,
10257 project_transaction,
10258 format!("Rename: {} → {}", old_name, new_name),
10259 cx.clone(),
10260 )
10261 .await?;
10262
10263 editor.update(&mut cx, |editor, cx| {
10264 editor.refresh_document_highlights(cx);
10265 })?;
10266 Ok(())
10267 }))
10268 }
10269
10270 fn take_rename(
10271 &mut self,
10272 moving_cursor: bool,
10273 cx: &mut ViewContext<Self>,
10274 ) -> Option<RenameState> {
10275 let rename = self.pending_rename.take()?;
10276 if rename.editor.focus_handle(cx).is_focused(cx) {
10277 cx.focus(&self.focus_handle);
10278 }
10279
10280 self.remove_blocks(
10281 [rename.block_id].into_iter().collect(),
10282 Some(Autoscroll::fit()),
10283 cx,
10284 );
10285 self.clear_highlights::<Rename>(cx);
10286 self.show_local_selections = true;
10287
10288 if moving_cursor {
10289 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10290 editor.selections.newest::<usize>(cx).head()
10291 });
10292
10293 // Update the selection to match the position of the selection inside
10294 // the rename editor.
10295 let snapshot = self.buffer.read(cx).read(cx);
10296 let rename_range = rename.range.to_offset(&snapshot);
10297 let cursor_in_editor = snapshot
10298 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10299 .min(rename_range.end);
10300 drop(snapshot);
10301
10302 self.change_selections(None, cx, |s| {
10303 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10304 });
10305 } else {
10306 self.refresh_document_highlights(cx);
10307 }
10308
10309 Some(rename)
10310 }
10311
10312 pub fn pending_rename(&self) -> Option<&RenameState> {
10313 self.pending_rename.as_ref()
10314 }
10315
10316 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10317 let project = match &self.project {
10318 Some(project) => project.clone(),
10319 None => return None,
10320 };
10321
10322 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10323 }
10324
10325 fn format_selections(
10326 &mut self,
10327 _: &FormatSelections,
10328 cx: &mut ViewContext<Self>,
10329 ) -> Option<Task<Result<()>>> {
10330 let project = match &self.project {
10331 Some(project) => project.clone(),
10332 None => return None,
10333 };
10334
10335 let ranges = self
10336 .selections
10337 .all_adjusted(cx)
10338 .into_iter()
10339 .map(|selection| selection.range())
10340 .collect_vec();
10341
10342 Some(self.perform_format(
10343 project,
10344 FormatTrigger::Manual,
10345 FormatTarget::Ranges(ranges),
10346 cx,
10347 ))
10348 }
10349
10350 fn perform_format(
10351 &mut self,
10352 project: Model<Project>,
10353 trigger: FormatTrigger,
10354 target: FormatTarget,
10355 cx: &mut ViewContext<Self>,
10356 ) -> Task<Result<()>> {
10357 let buffer = self.buffer.clone();
10358 let (buffers, target) = match target {
10359 FormatTarget::Buffers => {
10360 let mut buffers = buffer.read(cx).all_buffers();
10361 if trigger == FormatTrigger::Save {
10362 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10363 }
10364 (buffers, LspFormatTarget::Buffers)
10365 }
10366 FormatTarget::Ranges(selection_ranges) => {
10367 let multi_buffer = buffer.read(cx);
10368 let snapshot = multi_buffer.read(cx);
10369 let mut buffers = HashSet::default();
10370 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10371 BTreeMap::new();
10372 for selection_range in selection_ranges {
10373 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10374 {
10375 let buffer_id = excerpt.buffer_id();
10376 let start = excerpt.buffer().anchor_before(buffer_range.start);
10377 let end = excerpt.buffer().anchor_after(buffer_range.end);
10378 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10379 buffer_id_to_ranges
10380 .entry(buffer_id)
10381 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10382 .or_insert_with(|| vec![start..end]);
10383 }
10384 }
10385 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10386 }
10387 };
10388
10389 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10390 let format = project.update(cx, |project, cx| {
10391 project.format(buffers, target, true, trigger, cx)
10392 });
10393
10394 cx.spawn(|_, mut cx| async move {
10395 let transaction = futures::select_biased! {
10396 () = timeout => {
10397 log::warn!("timed out waiting for formatting");
10398 None
10399 }
10400 transaction = format.log_err().fuse() => transaction,
10401 };
10402
10403 buffer
10404 .update(&mut cx, |buffer, cx| {
10405 if let Some(transaction) = transaction {
10406 if !buffer.is_singleton() {
10407 buffer.push_transaction(&transaction.0, cx);
10408 }
10409 }
10410
10411 cx.notify();
10412 })
10413 .ok();
10414
10415 Ok(())
10416 })
10417 }
10418
10419 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10420 if let Some(project) = self.project.clone() {
10421 self.buffer.update(cx, |multi_buffer, cx| {
10422 project.update(cx, |project, cx| {
10423 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10424 });
10425 })
10426 }
10427 }
10428
10429 fn cancel_language_server_work(
10430 &mut self,
10431 _: &actions::CancelLanguageServerWork,
10432 cx: &mut ViewContext<Self>,
10433 ) {
10434 if let Some(project) = self.project.clone() {
10435 self.buffer.update(cx, |multi_buffer, cx| {
10436 project.update(cx, |project, cx| {
10437 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10438 });
10439 })
10440 }
10441 }
10442
10443 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10444 cx.show_character_palette();
10445 }
10446
10447 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10448 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10449 let buffer = self.buffer.read(cx).snapshot(cx);
10450 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10451 let is_valid = buffer
10452 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10453 .any(|entry| {
10454 let range = entry.range.to_offset(&buffer);
10455 entry.diagnostic.is_primary
10456 && !range.is_empty()
10457 && range.start == primary_range_start
10458 && entry.diagnostic.message == active_diagnostics.primary_message
10459 });
10460
10461 if is_valid != active_diagnostics.is_valid {
10462 active_diagnostics.is_valid = is_valid;
10463 let mut new_styles = HashMap::default();
10464 for (block_id, diagnostic) in &active_diagnostics.blocks {
10465 new_styles.insert(
10466 *block_id,
10467 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10468 );
10469 }
10470 self.display_map.update(cx, |display_map, _cx| {
10471 display_map.replace_blocks(new_styles)
10472 });
10473 }
10474 }
10475 }
10476
10477 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10478 self.dismiss_diagnostics(cx);
10479 let snapshot = self.snapshot(cx);
10480 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10481 let buffer = self.buffer.read(cx).snapshot(cx);
10482
10483 let mut primary_range = None;
10484 let mut primary_message = None;
10485 let mut group_end = Point::zero();
10486 let diagnostic_group = buffer
10487 .diagnostic_group(group_id)
10488 .filter_map(|entry| {
10489 let start = entry.range.start.to_point(&buffer);
10490 let end = entry.range.end.to_point(&buffer);
10491 if snapshot.is_line_folded(MultiBufferRow(start.row))
10492 && (start.row == end.row
10493 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10494 {
10495 return None;
10496 }
10497 if end > group_end {
10498 group_end = end;
10499 }
10500 if entry.diagnostic.is_primary {
10501 primary_range = Some(entry.range.clone());
10502 primary_message = Some(entry.diagnostic.message.clone());
10503 }
10504 Some(entry)
10505 })
10506 .collect::<Vec<_>>();
10507 let primary_range = primary_range?;
10508 let primary_message = primary_message?;
10509
10510 let blocks = display_map
10511 .insert_blocks(
10512 diagnostic_group.iter().map(|entry| {
10513 let diagnostic = entry.diagnostic.clone();
10514 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10515 BlockProperties {
10516 style: BlockStyle::Fixed,
10517 placement: BlockPlacement::Below(
10518 buffer.anchor_after(entry.range.start),
10519 ),
10520 height: message_height,
10521 render: diagnostic_block_renderer(diagnostic, None, true, true),
10522 priority: 0,
10523 }
10524 }),
10525 cx,
10526 )
10527 .into_iter()
10528 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10529 .collect();
10530
10531 Some(ActiveDiagnosticGroup {
10532 primary_range,
10533 primary_message,
10534 group_id,
10535 blocks,
10536 is_valid: true,
10537 })
10538 });
10539 }
10540
10541 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10542 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10543 self.display_map.update(cx, |display_map, cx| {
10544 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10545 });
10546 cx.notify();
10547 }
10548 }
10549
10550 pub fn set_selections_from_remote(
10551 &mut self,
10552 selections: Vec<Selection<Anchor>>,
10553 pending_selection: Option<Selection<Anchor>>,
10554 cx: &mut ViewContext<Self>,
10555 ) {
10556 let old_cursor_position = self.selections.newest_anchor().head();
10557 self.selections.change_with(cx, |s| {
10558 s.select_anchors(selections);
10559 if let Some(pending_selection) = pending_selection {
10560 s.set_pending(pending_selection, SelectMode::Character);
10561 } else {
10562 s.clear_pending();
10563 }
10564 });
10565 self.selections_did_change(false, &old_cursor_position, true, cx);
10566 }
10567
10568 fn push_to_selection_history(&mut self) {
10569 self.selection_history.push(SelectionHistoryEntry {
10570 selections: self.selections.disjoint_anchors(),
10571 select_next_state: self.select_next_state.clone(),
10572 select_prev_state: self.select_prev_state.clone(),
10573 add_selections_state: self.add_selections_state.clone(),
10574 });
10575 }
10576
10577 pub fn transact(
10578 &mut self,
10579 cx: &mut ViewContext<Self>,
10580 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10581 ) -> Option<TransactionId> {
10582 self.start_transaction_at(Instant::now(), cx);
10583 update(self, cx);
10584 self.end_transaction_at(Instant::now(), cx)
10585 }
10586
10587 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10588 self.end_selection(cx);
10589 if let Some(tx_id) = self
10590 .buffer
10591 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10592 {
10593 self.selection_history
10594 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10595 cx.emit(EditorEvent::TransactionBegun {
10596 transaction_id: tx_id,
10597 })
10598 }
10599 }
10600
10601 pub fn end_transaction_at(
10602 &mut self,
10603 now: Instant,
10604 cx: &mut ViewContext<Self>,
10605 ) -> Option<TransactionId> {
10606 if let Some(transaction_id) = self
10607 .buffer
10608 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10609 {
10610 if let Some((_, end_selections)) =
10611 self.selection_history.transaction_mut(transaction_id)
10612 {
10613 *end_selections = Some(self.selections.disjoint_anchors());
10614 } else {
10615 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10616 }
10617
10618 cx.emit(EditorEvent::Edited { transaction_id });
10619 Some(transaction_id)
10620 } else {
10621 None
10622 }
10623 }
10624
10625 pub fn set_mark(&mut self, _: &actions::SetMark, cx: &mut ViewContext<Self>) {
10626 if self.selection_mark_mode {
10627 self.change_selections(None, cx, |s| {
10628 s.move_with(|_, sel| {
10629 sel.collapse_to(sel.head(), SelectionGoal::None);
10630 });
10631 })
10632 }
10633 self.selection_mark_mode = true;
10634 cx.notify();
10635 }
10636
10637 pub fn swap_selection_ends(
10638 &mut self,
10639 _: &actions::SwapSelectionEnds,
10640 cx: &mut ViewContext<Self>,
10641 ) {
10642 self.change_selections(None, cx, |s| {
10643 s.move_with(|_, sel| {
10644 if sel.start != sel.end {
10645 sel.reversed = !sel.reversed
10646 }
10647 });
10648 });
10649 cx.notify();
10650 }
10651
10652 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10653 if self.is_singleton(cx) {
10654 let selection = self.selections.newest::<Point>(cx);
10655
10656 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10657 let range = if selection.is_empty() {
10658 let point = selection.head().to_display_point(&display_map);
10659 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10660 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10661 .to_point(&display_map);
10662 start..end
10663 } else {
10664 selection.range()
10665 };
10666 if display_map.folds_in_range(range).next().is_some() {
10667 self.unfold_lines(&Default::default(), cx)
10668 } else {
10669 self.fold(&Default::default(), cx)
10670 }
10671 } else {
10672 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10673 let mut toggled_buffers = HashSet::default();
10674 for (_, buffer_snapshot, _) in
10675 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10676 {
10677 let buffer_id = buffer_snapshot.remote_id();
10678 if toggled_buffers.insert(buffer_id) {
10679 if self.buffer_folded(buffer_id, cx) {
10680 self.unfold_buffer(buffer_id, cx);
10681 } else {
10682 self.fold_buffer(buffer_id, cx);
10683 }
10684 }
10685 }
10686 }
10687 }
10688
10689 pub fn toggle_fold_recursive(
10690 &mut self,
10691 _: &actions::ToggleFoldRecursive,
10692 cx: &mut ViewContext<Self>,
10693 ) {
10694 let selection = self.selections.newest::<Point>(cx);
10695
10696 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10697 let range = if selection.is_empty() {
10698 let point = selection.head().to_display_point(&display_map);
10699 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10700 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10701 .to_point(&display_map);
10702 start..end
10703 } else {
10704 selection.range()
10705 };
10706 if display_map.folds_in_range(range).next().is_some() {
10707 self.unfold_recursive(&Default::default(), cx)
10708 } else {
10709 self.fold_recursive(&Default::default(), cx)
10710 }
10711 }
10712
10713 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10714 if self.is_singleton(cx) {
10715 let mut to_fold = Vec::new();
10716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10717 let selections = self.selections.all_adjusted(cx);
10718
10719 for selection in selections {
10720 let range = selection.range().sorted();
10721 let buffer_start_row = range.start.row;
10722
10723 if range.start.row != range.end.row {
10724 let mut found = false;
10725 let mut row = range.start.row;
10726 while row <= range.end.row {
10727 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10728 {
10729 found = true;
10730 row = crease.range().end.row + 1;
10731 to_fold.push(crease);
10732 } else {
10733 row += 1
10734 }
10735 }
10736 if found {
10737 continue;
10738 }
10739 }
10740
10741 for row in (0..=range.start.row).rev() {
10742 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10743 if crease.range().end.row >= buffer_start_row {
10744 to_fold.push(crease);
10745 if row <= range.start.row {
10746 break;
10747 }
10748 }
10749 }
10750 }
10751 }
10752
10753 self.fold_creases(to_fold, true, cx);
10754 } else {
10755 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10756 let mut folded_buffers = HashSet::default();
10757 for (_, buffer_snapshot, _) in
10758 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10759 {
10760 let buffer_id = buffer_snapshot.remote_id();
10761 if folded_buffers.insert(buffer_id) {
10762 self.fold_buffer(buffer_id, cx);
10763 }
10764 }
10765 }
10766 }
10767
10768 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10769 if !self.buffer.read(cx).is_singleton() {
10770 return;
10771 }
10772
10773 let fold_at_level = fold_at.level;
10774 let snapshot = self.buffer.read(cx).snapshot(cx);
10775 let mut to_fold = Vec::new();
10776 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10777
10778 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10779 while start_row < end_row {
10780 match self
10781 .snapshot(cx)
10782 .crease_for_buffer_row(MultiBufferRow(start_row))
10783 {
10784 Some(crease) => {
10785 let nested_start_row = crease.range().start.row + 1;
10786 let nested_end_row = crease.range().end.row;
10787
10788 if current_level < fold_at_level {
10789 stack.push((nested_start_row, nested_end_row, current_level + 1));
10790 } else if current_level == fold_at_level {
10791 to_fold.push(crease);
10792 }
10793
10794 start_row = nested_end_row + 1;
10795 }
10796 None => start_row += 1,
10797 }
10798 }
10799 }
10800
10801 self.fold_creases(to_fold, true, cx);
10802 }
10803
10804 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10805 if self.buffer.read(cx).is_singleton() {
10806 let mut fold_ranges = Vec::new();
10807 let snapshot = self.buffer.read(cx).snapshot(cx);
10808
10809 for row in 0..snapshot.max_row().0 {
10810 if let Some(foldable_range) =
10811 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10812 {
10813 fold_ranges.push(foldable_range);
10814 }
10815 }
10816
10817 self.fold_creases(fold_ranges, true, cx);
10818 } else {
10819 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10820 editor
10821 .update(&mut cx, |editor, cx| {
10822 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10823 editor.fold_buffer(buffer_id, cx);
10824 }
10825 })
10826 .ok();
10827 });
10828 }
10829 }
10830
10831 pub fn fold_function_bodies(
10832 &mut self,
10833 _: &actions::FoldFunctionBodies,
10834 cx: &mut ViewContext<Self>,
10835 ) {
10836 let snapshot = self.buffer.read(cx).snapshot(cx);
10837 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10838 return;
10839 };
10840 let creases = buffer
10841 .function_body_fold_ranges(0..buffer.len())
10842 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10843 .collect();
10844
10845 self.fold_creases(creases, true, cx);
10846 }
10847
10848 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10849 let mut to_fold = Vec::new();
10850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10851 let selections = self.selections.all_adjusted(cx);
10852
10853 for selection in selections {
10854 let range = selection.range().sorted();
10855 let buffer_start_row = range.start.row;
10856
10857 if range.start.row != range.end.row {
10858 let mut found = false;
10859 for row in range.start.row..=range.end.row {
10860 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10861 found = true;
10862 to_fold.push(crease);
10863 }
10864 }
10865 if found {
10866 continue;
10867 }
10868 }
10869
10870 for row in (0..=range.start.row).rev() {
10871 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10872 if crease.range().end.row >= buffer_start_row {
10873 to_fold.push(crease);
10874 } else {
10875 break;
10876 }
10877 }
10878 }
10879 }
10880
10881 self.fold_creases(to_fold, true, cx);
10882 }
10883
10884 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10885 let buffer_row = fold_at.buffer_row;
10886 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10887
10888 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10889 let autoscroll = self
10890 .selections
10891 .all::<Point>(cx)
10892 .iter()
10893 .any(|selection| crease.range().overlaps(&selection.range()));
10894
10895 self.fold_creases(vec![crease], autoscroll, cx);
10896 }
10897 }
10898
10899 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10900 if self.is_singleton(cx) {
10901 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10902 let buffer = &display_map.buffer_snapshot;
10903 let selections = self.selections.all::<Point>(cx);
10904 let ranges = selections
10905 .iter()
10906 .map(|s| {
10907 let range = s.display_range(&display_map).sorted();
10908 let mut start = range.start.to_point(&display_map);
10909 let mut end = range.end.to_point(&display_map);
10910 start.column = 0;
10911 end.column = buffer.line_len(MultiBufferRow(end.row));
10912 start..end
10913 })
10914 .collect::<Vec<_>>();
10915
10916 self.unfold_ranges(&ranges, true, true, cx);
10917 } else {
10918 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10919 let mut unfolded_buffers = HashSet::default();
10920 for (_, buffer_snapshot, _) in
10921 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10922 {
10923 let buffer_id = buffer_snapshot.remote_id();
10924 if unfolded_buffers.insert(buffer_id) {
10925 self.unfold_buffer(buffer_id, cx);
10926 }
10927 }
10928 }
10929 }
10930
10931 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10932 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10933 let selections = self.selections.all::<Point>(cx);
10934 let ranges = selections
10935 .iter()
10936 .map(|s| {
10937 let mut range = s.display_range(&display_map).sorted();
10938 *range.start.column_mut() = 0;
10939 *range.end.column_mut() = display_map.line_len(range.end.row());
10940 let start = range.start.to_point(&display_map);
10941 let end = range.end.to_point(&display_map);
10942 start..end
10943 })
10944 .collect::<Vec<_>>();
10945
10946 self.unfold_ranges(&ranges, true, true, cx);
10947 }
10948
10949 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10951
10952 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10953 ..Point::new(
10954 unfold_at.buffer_row.0,
10955 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10956 );
10957
10958 let autoscroll = self
10959 .selections
10960 .all::<Point>(cx)
10961 .iter()
10962 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10963
10964 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10965 }
10966
10967 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10968 if self.buffer.read(cx).is_singleton() {
10969 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10970 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10971 } else {
10972 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10973 editor
10974 .update(&mut cx, |editor, cx| {
10975 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10976 editor.unfold_buffer(buffer_id, cx);
10977 }
10978 })
10979 .ok();
10980 });
10981 }
10982 }
10983
10984 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10985 let selections = self.selections.all::<Point>(cx);
10986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10987 let line_mode = self.selections.line_mode;
10988 let ranges = selections
10989 .into_iter()
10990 .map(|s| {
10991 if line_mode {
10992 let start = Point::new(s.start.row, 0);
10993 let end = Point::new(
10994 s.end.row,
10995 display_map
10996 .buffer_snapshot
10997 .line_len(MultiBufferRow(s.end.row)),
10998 );
10999 Crease::simple(start..end, display_map.fold_placeholder.clone())
11000 } else {
11001 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11002 }
11003 })
11004 .collect::<Vec<_>>();
11005 self.fold_creases(ranges, true, cx);
11006 }
11007
11008 pub fn fold_ranges<T: ToOffset + Clone>(
11009 &mut self,
11010 ranges: Vec<Range<T>>,
11011 auto_scroll: bool,
11012 cx: &mut ViewContext<Self>,
11013 ) {
11014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11015 let ranges = ranges
11016 .into_iter()
11017 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11018 .collect::<Vec<_>>();
11019 self.fold_creases(ranges, auto_scroll, cx);
11020 }
11021
11022 pub fn fold_creases<T: ToOffset + Clone>(
11023 &mut self,
11024 creases: Vec<Crease<T>>,
11025 auto_scroll: bool,
11026 cx: &mut ViewContext<Self>,
11027 ) {
11028 if creases.is_empty() {
11029 return;
11030 }
11031
11032 let mut buffers_affected = HashSet::default();
11033 let multi_buffer = self.buffer().read(cx);
11034 for crease in &creases {
11035 if let Some((_, buffer, _)) =
11036 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11037 {
11038 buffers_affected.insert(buffer.read(cx).remote_id());
11039 };
11040 }
11041
11042 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11043
11044 if auto_scroll {
11045 self.request_autoscroll(Autoscroll::fit(), cx);
11046 }
11047
11048 for buffer_id in buffers_affected {
11049 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11050 }
11051
11052 cx.notify();
11053
11054 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11055 // Clear diagnostics block when folding a range that contains it.
11056 let snapshot = self.snapshot(cx);
11057 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11058 drop(snapshot);
11059 self.active_diagnostics = Some(active_diagnostics);
11060 self.dismiss_diagnostics(cx);
11061 } else {
11062 self.active_diagnostics = Some(active_diagnostics);
11063 }
11064 }
11065
11066 self.scrollbar_marker_state.dirty = true;
11067 }
11068
11069 /// Removes any folds whose ranges intersect any of the given ranges.
11070 pub fn unfold_ranges<T: ToOffset + Clone>(
11071 &mut self,
11072 ranges: &[Range<T>],
11073 inclusive: bool,
11074 auto_scroll: bool,
11075 cx: &mut ViewContext<Self>,
11076 ) {
11077 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11078 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11079 });
11080 }
11081
11082 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11083 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11084 return;
11085 }
11086 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11087 return;
11088 };
11089 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11090 self.display_map
11091 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11092 cx.emit(EditorEvent::BufferFoldToggled {
11093 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11094 folded: true,
11095 });
11096 cx.notify();
11097 }
11098
11099 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11100 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11101 return;
11102 }
11103 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11104 return;
11105 };
11106 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11107 self.display_map.update(cx, |display_map, cx| {
11108 display_map.unfold_buffer(buffer_id, cx);
11109 });
11110 cx.emit(EditorEvent::BufferFoldToggled {
11111 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11112 folded: false,
11113 });
11114 cx.notify();
11115 }
11116
11117 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11118 self.display_map.read(cx).buffer_folded(buffer)
11119 }
11120
11121 /// Removes any folds with the given ranges.
11122 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11123 &mut self,
11124 ranges: &[Range<T>],
11125 type_id: TypeId,
11126 auto_scroll: bool,
11127 cx: &mut ViewContext<Self>,
11128 ) {
11129 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11130 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11131 });
11132 }
11133
11134 fn remove_folds_with<T: ToOffset + Clone>(
11135 &mut self,
11136 ranges: &[Range<T>],
11137 auto_scroll: bool,
11138 cx: &mut ViewContext<Self>,
11139 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11140 ) {
11141 if ranges.is_empty() {
11142 return;
11143 }
11144
11145 let mut buffers_affected = HashSet::default();
11146 let multi_buffer = self.buffer().read(cx);
11147 for range in ranges {
11148 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11149 buffers_affected.insert(buffer.read(cx).remote_id());
11150 };
11151 }
11152
11153 self.display_map.update(cx, update);
11154
11155 if auto_scroll {
11156 self.request_autoscroll(Autoscroll::fit(), cx);
11157 }
11158
11159 for buffer_id in buffers_affected {
11160 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11161 }
11162
11163 cx.notify();
11164 self.scrollbar_marker_state.dirty = true;
11165 self.active_indent_guides_state.dirty = true;
11166 }
11167
11168 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11169 self.display_map.read(cx).fold_placeholder.clone()
11170 }
11171
11172 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11173 if hovered != self.gutter_hovered {
11174 self.gutter_hovered = hovered;
11175 cx.notify();
11176 }
11177 }
11178
11179 pub fn insert_blocks(
11180 &mut self,
11181 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11182 autoscroll: Option<Autoscroll>,
11183 cx: &mut ViewContext<Self>,
11184 ) -> Vec<CustomBlockId> {
11185 let blocks = self
11186 .display_map
11187 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11188 if let Some(autoscroll) = autoscroll {
11189 self.request_autoscroll(autoscroll, cx);
11190 }
11191 cx.notify();
11192 blocks
11193 }
11194
11195 pub fn resize_blocks(
11196 &mut self,
11197 heights: HashMap<CustomBlockId, u32>,
11198 autoscroll: Option<Autoscroll>,
11199 cx: &mut ViewContext<Self>,
11200 ) {
11201 self.display_map
11202 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11203 if let Some(autoscroll) = autoscroll {
11204 self.request_autoscroll(autoscroll, cx);
11205 }
11206 cx.notify();
11207 }
11208
11209 pub fn replace_blocks(
11210 &mut self,
11211 renderers: HashMap<CustomBlockId, RenderBlock>,
11212 autoscroll: Option<Autoscroll>,
11213 cx: &mut ViewContext<Self>,
11214 ) {
11215 self.display_map
11216 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11217 if let Some(autoscroll) = autoscroll {
11218 self.request_autoscroll(autoscroll, cx);
11219 }
11220 cx.notify();
11221 }
11222
11223 pub fn remove_blocks(
11224 &mut self,
11225 block_ids: HashSet<CustomBlockId>,
11226 autoscroll: Option<Autoscroll>,
11227 cx: &mut ViewContext<Self>,
11228 ) {
11229 self.display_map.update(cx, |display_map, cx| {
11230 display_map.remove_blocks(block_ids, cx)
11231 });
11232 if let Some(autoscroll) = autoscroll {
11233 self.request_autoscroll(autoscroll, cx);
11234 }
11235 cx.notify();
11236 }
11237
11238 pub fn row_for_block(
11239 &self,
11240 block_id: CustomBlockId,
11241 cx: &mut ViewContext<Self>,
11242 ) -> Option<DisplayRow> {
11243 self.display_map
11244 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11245 }
11246
11247 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11248 self.focused_block = Some(focused_block);
11249 }
11250
11251 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11252 self.focused_block.take()
11253 }
11254
11255 pub fn insert_creases(
11256 &mut self,
11257 creases: impl IntoIterator<Item = Crease<Anchor>>,
11258 cx: &mut ViewContext<Self>,
11259 ) -> Vec<CreaseId> {
11260 self.display_map
11261 .update(cx, |map, cx| map.insert_creases(creases, cx))
11262 }
11263
11264 pub fn remove_creases(
11265 &mut self,
11266 ids: impl IntoIterator<Item = CreaseId>,
11267 cx: &mut ViewContext<Self>,
11268 ) {
11269 self.display_map
11270 .update(cx, |map, cx| map.remove_creases(ids, cx));
11271 }
11272
11273 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11274 self.display_map
11275 .update(cx, |map, cx| map.snapshot(cx))
11276 .longest_row()
11277 }
11278
11279 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11280 self.display_map
11281 .update(cx, |map, cx| map.snapshot(cx))
11282 .max_point()
11283 }
11284
11285 pub fn text(&self, cx: &AppContext) -> String {
11286 self.buffer.read(cx).read(cx).text()
11287 }
11288
11289 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11290 let text = self.text(cx);
11291 let text = text.trim();
11292
11293 if text.is_empty() {
11294 return None;
11295 }
11296
11297 Some(text.to_string())
11298 }
11299
11300 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11301 self.transact(cx, |this, cx| {
11302 this.buffer
11303 .read(cx)
11304 .as_singleton()
11305 .expect("you can only call set_text on editors for singleton buffers")
11306 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11307 });
11308 }
11309
11310 pub fn display_text(&self, cx: &mut AppContext) -> String {
11311 self.display_map
11312 .update(cx, |map, cx| map.snapshot(cx))
11313 .text()
11314 }
11315
11316 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11317 let mut wrap_guides = smallvec::smallvec![];
11318
11319 if self.show_wrap_guides == Some(false) {
11320 return wrap_guides;
11321 }
11322
11323 let settings = self.buffer.read(cx).settings_at(0, cx);
11324 if settings.show_wrap_guides {
11325 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11326 wrap_guides.push((soft_wrap as usize, true));
11327 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11328 wrap_guides.push((soft_wrap as usize, true));
11329 }
11330 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11331 }
11332
11333 wrap_guides
11334 }
11335
11336 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11337 let settings = self.buffer.read(cx).settings_at(0, cx);
11338 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11339 match mode {
11340 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11341 SoftWrap::None
11342 }
11343 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11344 language_settings::SoftWrap::PreferredLineLength => {
11345 SoftWrap::Column(settings.preferred_line_length)
11346 }
11347 language_settings::SoftWrap::Bounded => {
11348 SoftWrap::Bounded(settings.preferred_line_length)
11349 }
11350 }
11351 }
11352
11353 pub fn set_soft_wrap_mode(
11354 &mut self,
11355 mode: language_settings::SoftWrap,
11356 cx: &mut ViewContext<Self>,
11357 ) {
11358 self.soft_wrap_mode_override = Some(mode);
11359 cx.notify();
11360 }
11361
11362 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11363 self.text_style_refinement = Some(style);
11364 }
11365
11366 /// called by the Element so we know what style we were most recently rendered with.
11367 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11368 let rem_size = cx.rem_size();
11369 self.display_map.update(cx, |map, cx| {
11370 map.set_font(
11371 style.text.font(),
11372 style.text.font_size.to_pixels(rem_size),
11373 cx,
11374 )
11375 });
11376 self.style = Some(style);
11377 }
11378
11379 pub fn style(&self) -> Option<&EditorStyle> {
11380 self.style.as_ref()
11381 }
11382
11383 // Called by the element. This method is not designed to be called outside of the editor
11384 // element's layout code because it does not notify when rewrapping is computed synchronously.
11385 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11386 self.display_map
11387 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11388 }
11389
11390 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11391 if self.soft_wrap_mode_override.is_some() {
11392 self.soft_wrap_mode_override.take();
11393 } else {
11394 let soft_wrap = match self.soft_wrap_mode(cx) {
11395 SoftWrap::GitDiff => return,
11396 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11397 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11398 language_settings::SoftWrap::None
11399 }
11400 };
11401 self.soft_wrap_mode_override = Some(soft_wrap);
11402 }
11403 cx.notify();
11404 }
11405
11406 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11407 let Some(workspace) = self.workspace() else {
11408 return;
11409 };
11410 let fs = workspace.read(cx).app_state().fs.clone();
11411 let current_show = TabBarSettings::get_global(cx).show;
11412 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11413 setting.show = Some(!current_show);
11414 });
11415 }
11416
11417 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11418 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11419 self.buffer
11420 .read(cx)
11421 .settings_at(0, cx)
11422 .indent_guides
11423 .enabled
11424 });
11425 self.show_indent_guides = Some(!currently_enabled);
11426 cx.notify();
11427 }
11428
11429 fn should_show_indent_guides(&self) -> Option<bool> {
11430 self.show_indent_guides
11431 }
11432
11433 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11434 let mut editor_settings = EditorSettings::get_global(cx).clone();
11435 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11436 EditorSettings::override_global(editor_settings, cx);
11437 }
11438
11439 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11440 self.use_relative_line_numbers
11441 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11442 }
11443
11444 pub fn toggle_relative_line_numbers(
11445 &mut self,
11446 _: &ToggleRelativeLineNumbers,
11447 cx: &mut ViewContext<Self>,
11448 ) {
11449 let is_relative = self.should_use_relative_line_numbers(cx);
11450 self.set_relative_line_number(Some(!is_relative), cx)
11451 }
11452
11453 pub fn set_relative_line_number(
11454 &mut self,
11455 is_relative: Option<bool>,
11456 cx: &mut ViewContext<Self>,
11457 ) {
11458 self.use_relative_line_numbers = is_relative;
11459 cx.notify();
11460 }
11461
11462 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11463 self.show_gutter = show_gutter;
11464 cx.notify();
11465 }
11466
11467 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11468 self.show_scrollbars = show_scrollbars;
11469 cx.notify();
11470 }
11471
11472 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11473 self.show_line_numbers = Some(show_line_numbers);
11474 cx.notify();
11475 }
11476
11477 pub fn set_show_git_diff_gutter(
11478 &mut self,
11479 show_git_diff_gutter: bool,
11480 cx: &mut ViewContext<Self>,
11481 ) {
11482 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11483 cx.notify();
11484 }
11485
11486 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11487 self.show_code_actions = Some(show_code_actions);
11488 cx.notify();
11489 }
11490
11491 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11492 self.show_runnables = Some(show_runnables);
11493 cx.notify();
11494 }
11495
11496 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11497 if self.display_map.read(cx).masked != masked {
11498 self.display_map.update(cx, |map, _| map.masked = masked);
11499 }
11500 cx.notify()
11501 }
11502
11503 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11504 self.show_wrap_guides = Some(show_wrap_guides);
11505 cx.notify();
11506 }
11507
11508 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11509 self.show_indent_guides = Some(show_indent_guides);
11510 cx.notify();
11511 }
11512
11513 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11514 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11515 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11516 if let Some(dir) = file.abs_path(cx).parent() {
11517 return Some(dir.to_owned());
11518 }
11519 }
11520
11521 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11522 return Some(project_path.path.to_path_buf());
11523 }
11524 }
11525
11526 None
11527 }
11528
11529 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11530 self.active_excerpt(cx)?
11531 .1
11532 .read(cx)
11533 .file()
11534 .and_then(|f| f.as_local())
11535 }
11536
11537 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11538 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11539 let project_path = buffer.read(cx).project_path(cx)?;
11540 let project = self.project.as_ref()?.read(cx);
11541 project.absolute_path(&project_path, cx)
11542 })
11543 }
11544
11545 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11546 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11547 let project_path = buffer.read(cx).project_path(cx)?;
11548 let project = self.project.as_ref()?.read(cx);
11549 let entry = project.entry_for_path(&project_path, cx)?;
11550 let path = entry.path.to_path_buf();
11551 Some(path)
11552 })
11553 }
11554
11555 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11556 if let Some(target) = self.target_file(cx) {
11557 cx.reveal_path(&target.abs_path(cx));
11558 }
11559 }
11560
11561 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11562 if let Some(path) = self.target_file_abs_path(cx) {
11563 if let Some(path) = path.to_str() {
11564 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11565 }
11566 }
11567 }
11568
11569 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11570 if let Some(path) = self.target_file_path(cx) {
11571 if let Some(path) = path.to_str() {
11572 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11573 }
11574 }
11575 }
11576
11577 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11578 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11579
11580 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11581 self.start_git_blame(true, cx);
11582 }
11583
11584 cx.notify();
11585 }
11586
11587 pub fn toggle_git_blame_inline(
11588 &mut self,
11589 _: &ToggleGitBlameInline,
11590 cx: &mut ViewContext<Self>,
11591 ) {
11592 self.toggle_git_blame_inline_internal(true, cx);
11593 cx.notify();
11594 }
11595
11596 pub fn git_blame_inline_enabled(&self) -> bool {
11597 self.git_blame_inline_enabled
11598 }
11599
11600 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11601 self.show_selection_menu = self
11602 .show_selection_menu
11603 .map(|show_selections_menu| !show_selections_menu)
11604 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11605
11606 cx.notify();
11607 }
11608
11609 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11610 self.show_selection_menu
11611 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11612 }
11613
11614 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11615 if let Some(project) = self.project.as_ref() {
11616 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11617 return;
11618 };
11619
11620 if buffer.read(cx).file().is_none() {
11621 return;
11622 }
11623
11624 let focused = self.focus_handle(cx).contains_focused(cx);
11625
11626 let project = project.clone();
11627 let blame =
11628 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11629 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11630 self.blame = Some(blame);
11631 }
11632 }
11633
11634 fn toggle_git_blame_inline_internal(
11635 &mut self,
11636 user_triggered: bool,
11637 cx: &mut ViewContext<Self>,
11638 ) {
11639 if self.git_blame_inline_enabled {
11640 self.git_blame_inline_enabled = false;
11641 self.show_git_blame_inline = false;
11642 self.show_git_blame_inline_delay_task.take();
11643 } else {
11644 self.git_blame_inline_enabled = true;
11645 self.start_git_blame_inline(user_triggered, cx);
11646 }
11647
11648 cx.notify();
11649 }
11650
11651 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11652 self.start_git_blame(user_triggered, cx);
11653
11654 if ProjectSettings::get_global(cx)
11655 .git
11656 .inline_blame_delay()
11657 .is_some()
11658 {
11659 self.start_inline_blame_timer(cx);
11660 } else {
11661 self.show_git_blame_inline = true
11662 }
11663 }
11664
11665 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11666 self.blame.as_ref()
11667 }
11668
11669 pub fn show_git_blame_gutter(&self) -> bool {
11670 self.show_git_blame_gutter
11671 }
11672
11673 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11674 self.show_git_blame_gutter && self.has_blame_entries(cx)
11675 }
11676
11677 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11678 self.show_git_blame_inline
11679 && self.focus_handle.is_focused(cx)
11680 && !self.newest_selection_head_on_empty_line(cx)
11681 && self.has_blame_entries(cx)
11682 }
11683
11684 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11685 self.blame()
11686 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11687 }
11688
11689 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11690 let cursor_anchor = self.selections.newest_anchor().head();
11691
11692 let snapshot = self.buffer.read(cx).snapshot(cx);
11693 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11694
11695 snapshot.line_len(buffer_row) == 0
11696 }
11697
11698 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11699 let buffer_and_selection = maybe!({
11700 let selection = self.selections.newest::<Point>(cx);
11701 let selection_range = selection.range();
11702
11703 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11704 (buffer, selection_range.start.row..selection_range.end.row)
11705 } else {
11706 let multi_buffer = self.buffer().read(cx);
11707 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11708 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11709
11710 let (excerpt, range) = if selection.reversed {
11711 buffer_ranges.first()
11712 } else {
11713 buffer_ranges.last()
11714 }?;
11715
11716 let snapshot = excerpt.buffer();
11717 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11718 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11719 (
11720 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11721 selection,
11722 )
11723 };
11724
11725 Some((buffer, selection))
11726 });
11727
11728 let Some((buffer, selection)) = buffer_and_selection else {
11729 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11730 };
11731
11732 let Some(project) = self.project.as_ref() else {
11733 return Task::ready(Err(anyhow!("editor does not have project")));
11734 };
11735
11736 project.update(cx, |project, cx| {
11737 project.get_permalink_to_line(&buffer, selection, cx)
11738 })
11739 }
11740
11741 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11742 let permalink_task = self.get_permalink_to_line(cx);
11743 let workspace = self.workspace();
11744
11745 cx.spawn(|_, mut cx| async move {
11746 match permalink_task.await {
11747 Ok(permalink) => {
11748 cx.update(|cx| {
11749 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11750 })
11751 .ok();
11752 }
11753 Err(err) => {
11754 let message = format!("Failed to copy permalink: {err}");
11755
11756 Err::<(), anyhow::Error>(err).log_err();
11757
11758 if let Some(workspace) = workspace {
11759 workspace
11760 .update(&mut cx, |workspace, cx| {
11761 struct CopyPermalinkToLine;
11762
11763 workspace.show_toast(
11764 Toast::new(
11765 NotificationId::unique::<CopyPermalinkToLine>(),
11766 message,
11767 ),
11768 cx,
11769 )
11770 })
11771 .ok();
11772 }
11773 }
11774 }
11775 })
11776 .detach();
11777 }
11778
11779 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11780 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11781 if let Some(file) = self.target_file(cx) {
11782 if let Some(path) = file.path().to_str() {
11783 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11784 }
11785 }
11786 }
11787
11788 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11789 let permalink_task = self.get_permalink_to_line(cx);
11790 let workspace = self.workspace();
11791
11792 cx.spawn(|_, mut cx| async move {
11793 match permalink_task.await {
11794 Ok(permalink) => {
11795 cx.update(|cx| {
11796 cx.open_url(permalink.as_ref());
11797 })
11798 .ok();
11799 }
11800 Err(err) => {
11801 let message = format!("Failed to open permalink: {err}");
11802
11803 Err::<(), anyhow::Error>(err).log_err();
11804
11805 if let Some(workspace) = workspace {
11806 workspace
11807 .update(&mut cx, |workspace, cx| {
11808 struct OpenPermalinkToLine;
11809
11810 workspace.show_toast(
11811 Toast::new(
11812 NotificationId::unique::<OpenPermalinkToLine>(),
11813 message,
11814 ),
11815 cx,
11816 )
11817 })
11818 .ok();
11819 }
11820 }
11821 }
11822 })
11823 .detach();
11824 }
11825
11826 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11827 self.insert_uuid(UuidVersion::V4, cx);
11828 }
11829
11830 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11831 self.insert_uuid(UuidVersion::V7, cx);
11832 }
11833
11834 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11835 self.transact(cx, |this, cx| {
11836 let edits = this
11837 .selections
11838 .all::<Point>(cx)
11839 .into_iter()
11840 .map(|selection| {
11841 let uuid = match version {
11842 UuidVersion::V4 => uuid::Uuid::new_v4(),
11843 UuidVersion::V7 => uuid::Uuid::now_v7(),
11844 };
11845
11846 (selection.range(), uuid.to_string())
11847 });
11848 this.edit(edits, cx);
11849 this.refresh_inline_completion(true, false, cx);
11850 });
11851 }
11852
11853 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11854 /// last highlight added will be used.
11855 ///
11856 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11857 pub fn highlight_rows<T: 'static>(
11858 &mut self,
11859 range: Range<Anchor>,
11860 color: Hsla,
11861 should_autoscroll: bool,
11862 cx: &mut ViewContext<Self>,
11863 ) {
11864 let snapshot = self.buffer().read(cx).snapshot(cx);
11865 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11866 let ix = row_highlights.binary_search_by(|highlight| {
11867 Ordering::Equal
11868 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11869 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11870 });
11871
11872 if let Err(mut ix) = ix {
11873 let index = post_inc(&mut self.highlight_order);
11874
11875 // If this range intersects with the preceding highlight, then merge it with
11876 // the preceding highlight. Otherwise insert a new highlight.
11877 let mut merged = false;
11878 if ix > 0 {
11879 let prev_highlight = &mut row_highlights[ix - 1];
11880 if prev_highlight
11881 .range
11882 .end
11883 .cmp(&range.start, &snapshot)
11884 .is_ge()
11885 {
11886 ix -= 1;
11887 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11888 prev_highlight.range.end = range.end;
11889 }
11890 merged = true;
11891 prev_highlight.index = index;
11892 prev_highlight.color = color;
11893 prev_highlight.should_autoscroll = should_autoscroll;
11894 }
11895 }
11896
11897 if !merged {
11898 row_highlights.insert(
11899 ix,
11900 RowHighlight {
11901 range: range.clone(),
11902 index,
11903 color,
11904 should_autoscroll,
11905 },
11906 );
11907 }
11908
11909 // If any of the following highlights intersect with this one, merge them.
11910 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11911 let highlight = &row_highlights[ix];
11912 if next_highlight
11913 .range
11914 .start
11915 .cmp(&highlight.range.end, &snapshot)
11916 .is_le()
11917 {
11918 if next_highlight
11919 .range
11920 .end
11921 .cmp(&highlight.range.end, &snapshot)
11922 .is_gt()
11923 {
11924 row_highlights[ix].range.end = next_highlight.range.end;
11925 }
11926 row_highlights.remove(ix + 1);
11927 } else {
11928 break;
11929 }
11930 }
11931 }
11932 }
11933
11934 /// Remove any highlighted row ranges of the given type that intersect the
11935 /// given ranges.
11936 pub fn remove_highlighted_rows<T: 'static>(
11937 &mut self,
11938 ranges_to_remove: Vec<Range<Anchor>>,
11939 cx: &mut ViewContext<Self>,
11940 ) {
11941 let snapshot = self.buffer().read(cx).snapshot(cx);
11942 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11943 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11944 row_highlights.retain(|highlight| {
11945 while let Some(range_to_remove) = ranges_to_remove.peek() {
11946 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11947 Ordering::Less | Ordering::Equal => {
11948 ranges_to_remove.next();
11949 }
11950 Ordering::Greater => {
11951 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11952 Ordering::Less | Ordering::Equal => {
11953 return false;
11954 }
11955 Ordering::Greater => break,
11956 }
11957 }
11958 }
11959 }
11960
11961 true
11962 })
11963 }
11964
11965 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11966 pub fn clear_row_highlights<T: 'static>(&mut self) {
11967 self.highlighted_rows.remove(&TypeId::of::<T>());
11968 }
11969
11970 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11971 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11972 self.highlighted_rows
11973 .get(&TypeId::of::<T>())
11974 .map_or(&[] as &[_], |vec| vec.as_slice())
11975 .iter()
11976 .map(|highlight| (highlight.range.clone(), highlight.color))
11977 }
11978
11979 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11980 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11981 /// Allows to ignore certain kinds of highlights.
11982 pub fn highlighted_display_rows(
11983 &mut self,
11984 cx: &mut WindowContext,
11985 ) -> BTreeMap<DisplayRow, Hsla> {
11986 let snapshot = self.snapshot(cx);
11987 let mut used_highlight_orders = HashMap::default();
11988 self.highlighted_rows
11989 .iter()
11990 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11991 .fold(
11992 BTreeMap::<DisplayRow, Hsla>::new(),
11993 |mut unique_rows, highlight| {
11994 let start = highlight.range.start.to_display_point(&snapshot);
11995 let end = highlight.range.end.to_display_point(&snapshot);
11996 let start_row = start.row().0;
11997 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11998 && end.column() == 0
11999 {
12000 end.row().0.saturating_sub(1)
12001 } else {
12002 end.row().0
12003 };
12004 for row in start_row..=end_row {
12005 let used_index =
12006 used_highlight_orders.entry(row).or_insert(highlight.index);
12007 if highlight.index >= *used_index {
12008 *used_index = highlight.index;
12009 unique_rows.insert(DisplayRow(row), highlight.color);
12010 }
12011 }
12012 unique_rows
12013 },
12014 )
12015 }
12016
12017 pub fn highlighted_display_row_for_autoscroll(
12018 &self,
12019 snapshot: &DisplaySnapshot,
12020 ) -> Option<DisplayRow> {
12021 self.highlighted_rows
12022 .values()
12023 .flat_map(|highlighted_rows| highlighted_rows.iter())
12024 .filter_map(|highlight| {
12025 if highlight.should_autoscroll {
12026 Some(highlight.range.start.to_display_point(snapshot).row())
12027 } else {
12028 None
12029 }
12030 })
12031 .min()
12032 }
12033
12034 pub fn set_search_within_ranges(
12035 &mut self,
12036 ranges: &[Range<Anchor>],
12037 cx: &mut ViewContext<Self>,
12038 ) {
12039 self.highlight_background::<SearchWithinRange>(
12040 ranges,
12041 |colors| colors.editor_document_highlight_read_background,
12042 cx,
12043 )
12044 }
12045
12046 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12047 self.breadcrumb_header = Some(new_header);
12048 }
12049
12050 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12051 self.clear_background_highlights::<SearchWithinRange>(cx);
12052 }
12053
12054 pub fn highlight_background<T: 'static>(
12055 &mut self,
12056 ranges: &[Range<Anchor>],
12057 color_fetcher: fn(&ThemeColors) -> Hsla,
12058 cx: &mut ViewContext<Self>,
12059 ) {
12060 self.background_highlights
12061 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12062 self.scrollbar_marker_state.dirty = true;
12063 cx.notify();
12064 }
12065
12066 pub fn clear_background_highlights<T: 'static>(
12067 &mut self,
12068 cx: &mut ViewContext<Self>,
12069 ) -> Option<BackgroundHighlight> {
12070 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12071 if !text_highlights.1.is_empty() {
12072 self.scrollbar_marker_state.dirty = true;
12073 cx.notify();
12074 }
12075 Some(text_highlights)
12076 }
12077
12078 pub fn highlight_gutter<T: 'static>(
12079 &mut self,
12080 ranges: &[Range<Anchor>],
12081 color_fetcher: fn(&AppContext) -> Hsla,
12082 cx: &mut ViewContext<Self>,
12083 ) {
12084 self.gutter_highlights
12085 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12086 cx.notify();
12087 }
12088
12089 pub fn clear_gutter_highlights<T: 'static>(
12090 &mut self,
12091 cx: &mut ViewContext<Self>,
12092 ) -> Option<GutterHighlight> {
12093 cx.notify();
12094 self.gutter_highlights.remove(&TypeId::of::<T>())
12095 }
12096
12097 #[cfg(feature = "test-support")]
12098 pub fn all_text_background_highlights(
12099 &mut self,
12100 cx: &mut ViewContext<Self>,
12101 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12102 let snapshot = self.snapshot(cx);
12103 let buffer = &snapshot.buffer_snapshot;
12104 let start = buffer.anchor_before(0);
12105 let end = buffer.anchor_after(buffer.len());
12106 let theme = cx.theme().colors();
12107 self.background_highlights_in_range(start..end, &snapshot, theme)
12108 }
12109
12110 #[cfg(feature = "test-support")]
12111 pub fn search_background_highlights(
12112 &mut self,
12113 cx: &mut ViewContext<Self>,
12114 ) -> Vec<Range<Point>> {
12115 let snapshot = self.buffer().read(cx).snapshot(cx);
12116
12117 let highlights = self
12118 .background_highlights
12119 .get(&TypeId::of::<items::BufferSearchHighlights>());
12120
12121 if let Some((_color, ranges)) = highlights {
12122 ranges
12123 .iter()
12124 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12125 .collect_vec()
12126 } else {
12127 vec![]
12128 }
12129 }
12130
12131 fn document_highlights_for_position<'a>(
12132 &'a self,
12133 position: Anchor,
12134 buffer: &'a MultiBufferSnapshot,
12135 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12136 let read_highlights = self
12137 .background_highlights
12138 .get(&TypeId::of::<DocumentHighlightRead>())
12139 .map(|h| &h.1);
12140 let write_highlights = self
12141 .background_highlights
12142 .get(&TypeId::of::<DocumentHighlightWrite>())
12143 .map(|h| &h.1);
12144 let left_position = position.bias_left(buffer);
12145 let right_position = position.bias_right(buffer);
12146 read_highlights
12147 .into_iter()
12148 .chain(write_highlights)
12149 .flat_map(move |ranges| {
12150 let start_ix = match ranges.binary_search_by(|probe| {
12151 let cmp = probe.end.cmp(&left_position, buffer);
12152 if cmp.is_ge() {
12153 Ordering::Greater
12154 } else {
12155 Ordering::Less
12156 }
12157 }) {
12158 Ok(i) | Err(i) => i,
12159 };
12160
12161 ranges[start_ix..]
12162 .iter()
12163 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12164 })
12165 }
12166
12167 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12168 self.background_highlights
12169 .get(&TypeId::of::<T>())
12170 .map_or(false, |(_, highlights)| !highlights.is_empty())
12171 }
12172
12173 pub fn background_highlights_in_range(
12174 &self,
12175 search_range: Range<Anchor>,
12176 display_snapshot: &DisplaySnapshot,
12177 theme: &ThemeColors,
12178 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12179 let mut results = Vec::new();
12180 for (color_fetcher, ranges) in self.background_highlights.values() {
12181 let color = color_fetcher(theme);
12182 let start_ix = match ranges.binary_search_by(|probe| {
12183 let cmp = probe
12184 .end
12185 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12186 if cmp.is_gt() {
12187 Ordering::Greater
12188 } else {
12189 Ordering::Less
12190 }
12191 }) {
12192 Ok(i) | Err(i) => i,
12193 };
12194 for range in &ranges[start_ix..] {
12195 if range
12196 .start
12197 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12198 .is_ge()
12199 {
12200 break;
12201 }
12202
12203 let start = range.start.to_display_point(display_snapshot);
12204 let end = range.end.to_display_point(display_snapshot);
12205 results.push((start..end, color))
12206 }
12207 }
12208 results
12209 }
12210
12211 pub fn background_highlight_row_ranges<T: 'static>(
12212 &self,
12213 search_range: Range<Anchor>,
12214 display_snapshot: &DisplaySnapshot,
12215 count: usize,
12216 ) -> Vec<RangeInclusive<DisplayPoint>> {
12217 let mut results = Vec::new();
12218 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12219 return vec![];
12220 };
12221
12222 let start_ix = match ranges.binary_search_by(|probe| {
12223 let cmp = probe
12224 .end
12225 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12226 if cmp.is_gt() {
12227 Ordering::Greater
12228 } else {
12229 Ordering::Less
12230 }
12231 }) {
12232 Ok(i) | Err(i) => i,
12233 };
12234 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12235 if let (Some(start_display), Some(end_display)) = (start, end) {
12236 results.push(
12237 start_display.to_display_point(display_snapshot)
12238 ..=end_display.to_display_point(display_snapshot),
12239 );
12240 }
12241 };
12242 let mut start_row: Option<Point> = None;
12243 let mut end_row: Option<Point> = None;
12244 if ranges.len() > count {
12245 return Vec::new();
12246 }
12247 for range in &ranges[start_ix..] {
12248 if range
12249 .start
12250 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12251 .is_ge()
12252 {
12253 break;
12254 }
12255 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12256 if let Some(current_row) = &end_row {
12257 if end.row == current_row.row {
12258 continue;
12259 }
12260 }
12261 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12262 if start_row.is_none() {
12263 assert_eq!(end_row, None);
12264 start_row = Some(start);
12265 end_row = Some(end);
12266 continue;
12267 }
12268 if let Some(current_end) = end_row.as_mut() {
12269 if start.row > current_end.row + 1 {
12270 push_region(start_row, end_row);
12271 start_row = Some(start);
12272 end_row = Some(end);
12273 } else {
12274 // Merge two hunks.
12275 *current_end = end;
12276 }
12277 } else {
12278 unreachable!();
12279 }
12280 }
12281 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12282 push_region(start_row, end_row);
12283 results
12284 }
12285
12286 pub fn gutter_highlights_in_range(
12287 &self,
12288 search_range: Range<Anchor>,
12289 display_snapshot: &DisplaySnapshot,
12290 cx: &AppContext,
12291 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12292 let mut results = Vec::new();
12293 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12294 let color = color_fetcher(cx);
12295 let start_ix = match ranges.binary_search_by(|probe| {
12296 let cmp = probe
12297 .end
12298 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12299 if cmp.is_gt() {
12300 Ordering::Greater
12301 } else {
12302 Ordering::Less
12303 }
12304 }) {
12305 Ok(i) | Err(i) => i,
12306 };
12307 for range in &ranges[start_ix..] {
12308 if range
12309 .start
12310 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12311 .is_ge()
12312 {
12313 break;
12314 }
12315
12316 let start = range.start.to_display_point(display_snapshot);
12317 let end = range.end.to_display_point(display_snapshot);
12318 results.push((start..end, color))
12319 }
12320 }
12321 results
12322 }
12323
12324 /// Get the text ranges corresponding to the redaction query
12325 pub fn redacted_ranges(
12326 &self,
12327 search_range: Range<Anchor>,
12328 display_snapshot: &DisplaySnapshot,
12329 cx: &WindowContext,
12330 ) -> Vec<Range<DisplayPoint>> {
12331 display_snapshot
12332 .buffer_snapshot
12333 .redacted_ranges(search_range, |file| {
12334 if let Some(file) = file {
12335 file.is_private()
12336 && EditorSettings::get(
12337 Some(SettingsLocation {
12338 worktree_id: file.worktree_id(cx),
12339 path: file.path().as_ref(),
12340 }),
12341 cx,
12342 )
12343 .redact_private_values
12344 } else {
12345 false
12346 }
12347 })
12348 .map(|range| {
12349 range.start.to_display_point(display_snapshot)
12350 ..range.end.to_display_point(display_snapshot)
12351 })
12352 .collect()
12353 }
12354
12355 pub fn highlight_text<T: 'static>(
12356 &mut self,
12357 ranges: Vec<Range<Anchor>>,
12358 style: HighlightStyle,
12359 cx: &mut ViewContext<Self>,
12360 ) {
12361 self.display_map.update(cx, |map, _| {
12362 map.highlight_text(TypeId::of::<T>(), ranges, style)
12363 });
12364 cx.notify();
12365 }
12366
12367 pub(crate) fn highlight_inlays<T: 'static>(
12368 &mut self,
12369 highlights: Vec<InlayHighlight>,
12370 style: HighlightStyle,
12371 cx: &mut ViewContext<Self>,
12372 ) {
12373 self.display_map.update(cx, |map, _| {
12374 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12375 });
12376 cx.notify();
12377 }
12378
12379 pub fn text_highlights<'a, T: 'static>(
12380 &'a self,
12381 cx: &'a AppContext,
12382 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12383 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12384 }
12385
12386 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12387 let cleared = self
12388 .display_map
12389 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12390 if cleared {
12391 cx.notify();
12392 }
12393 }
12394
12395 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12396 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12397 && self.focus_handle.is_focused(cx)
12398 }
12399
12400 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12401 self.show_cursor_when_unfocused = is_enabled;
12402 cx.notify();
12403 }
12404
12405 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12406 self.project
12407 .as_ref()
12408 .map(|project| project.read(cx).lsp_store())
12409 }
12410
12411 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12412 cx.notify();
12413 }
12414
12415 fn on_buffer_event(
12416 &mut self,
12417 multibuffer: Model<MultiBuffer>,
12418 event: &multi_buffer::Event,
12419 cx: &mut ViewContext<Self>,
12420 ) {
12421 match event {
12422 multi_buffer::Event::Edited {
12423 singleton_buffer_edited,
12424 edited_buffer: buffer_edited,
12425 } => {
12426 self.scrollbar_marker_state.dirty = true;
12427 self.active_indent_guides_state.dirty = true;
12428 self.refresh_active_diagnostics(cx);
12429 self.refresh_code_actions(cx);
12430 if self.has_active_inline_completion() {
12431 self.update_visible_inline_completion(cx);
12432 }
12433 if let Some(buffer) = buffer_edited {
12434 let buffer_id = buffer.read(cx).remote_id();
12435 if !self.registered_buffers.contains_key(&buffer_id) {
12436 if let Some(lsp_store) = self.lsp_store(cx) {
12437 lsp_store.update(cx, |lsp_store, cx| {
12438 self.registered_buffers.insert(
12439 buffer_id,
12440 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12441 );
12442 })
12443 }
12444 }
12445 }
12446 cx.emit(EditorEvent::BufferEdited);
12447 cx.emit(SearchEvent::MatchesInvalidated);
12448 if *singleton_buffer_edited {
12449 if let Some(project) = &self.project {
12450 let project = project.read(cx);
12451 #[allow(clippy::mutable_key_type)]
12452 let languages_affected = multibuffer
12453 .read(cx)
12454 .all_buffers()
12455 .into_iter()
12456 .filter_map(|buffer| {
12457 let buffer = buffer.read(cx);
12458 let language = buffer.language()?;
12459 if project.is_local()
12460 && project
12461 .language_servers_for_local_buffer(buffer, cx)
12462 .count()
12463 == 0
12464 {
12465 None
12466 } else {
12467 Some(language)
12468 }
12469 })
12470 .cloned()
12471 .collect::<HashSet<_>>();
12472 if !languages_affected.is_empty() {
12473 self.refresh_inlay_hints(
12474 InlayHintRefreshReason::BufferEdited(languages_affected),
12475 cx,
12476 );
12477 }
12478 }
12479 }
12480
12481 let Some(project) = &self.project else { return };
12482 let (telemetry, is_via_ssh) = {
12483 let project = project.read(cx);
12484 let telemetry = project.client().telemetry().clone();
12485 let is_via_ssh = project.is_via_ssh();
12486 (telemetry, is_via_ssh)
12487 };
12488 refresh_linked_ranges(self, cx);
12489 telemetry.log_edit_event("editor", is_via_ssh);
12490 }
12491 multi_buffer::Event::ExcerptsAdded {
12492 buffer,
12493 predecessor,
12494 excerpts,
12495 } => {
12496 self.tasks_update_task = Some(self.refresh_runnables(cx));
12497 let buffer_id = buffer.read(cx).remote_id();
12498 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12499 if let Some(project) = &self.project {
12500 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12501 }
12502 }
12503 cx.emit(EditorEvent::ExcerptsAdded {
12504 buffer: buffer.clone(),
12505 predecessor: *predecessor,
12506 excerpts: excerpts.clone(),
12507 });
12508 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12509 }
12510 multi_buffer::Event::ExcerptsRemoved { ids } => {
12511 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12512 let buffer = self.buffer.read(cx);
12513 self.registered_buffers
12514 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12515 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12516 }
12517 multi_buffer::Event::ExcerptsEdited { ids } => {
12518 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12519 }
12520 multi_buffer::Event::ExcerptsExpanded { ids } => {
12521 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12522 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12523 }
12524 multi_buffer::Event::Reparsed(buffer_id) => {
12525 self.tasks_update_task = Some(self.refresh_runnables(cx));
12526
12527 cx.emit(EditorEvent::Reparsed(*buffer_id));
12528 }
12529 multi_buffer::Event::LanguageChanged(buffer_id) => {
12530 linked_editing_ranges::refresh_linked_ranges(self, cx);
12531 cx.emit(EditorEvent::Reparsed(*buffer_id));
12532 cx.notify();
12533 }
12534 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12535 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12536 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12537 cx.emit(EditorEvent::TitleChanged)
12538 }
12539 // multi_buffer::Event::DiffBaseChanged => {
12540 // self.scrollbar_marker_state.dirty = true;
12541 // cx.emit(EditorEvent::DiffBaseChanged);
12542 // cx.notify();
12543 // }
12544 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12545 multi_buffer::Event::DiagnosticsUpdated => {
12546 self.refresh_active_diagnostics(cx);
12547 self.scrollbar_marker_state.dirty = true;
12548 cx.notify();
12549 }
12550 _ => {}
12551 };
12552 }
12553
12554 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12555 cx.notify();
12556 }
12557
12558 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12559 self.tasks_update_task = Some(self.refresh_runnables(cx));
12560 self.refresh_inline_completion(true, false, cx);
12561 self.refresh_inlay_hints(
12562 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12563 self.selections.newest_anchor().head(),
12564 &self.buffer.read(cx).snapshot(cx),
12565 cx,
12566 )),
12567 cx,
12568 );
12569
12570 let old_cursor_shape = self.cursor_shape;
12571
12572 {
12573 let editor_settings = EditorSettings::get_global(cx);
12574 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12575 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12576 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12577 }
12578
12579 if old_cursor_shape != self.cursor_shape {
12580 cx.emit(EditorEvent::CursorShapeChanged);
12581 }
12582
12583 let project_settings = ProjectSettings::get_global(cx);
12584 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12585
12586 if self.mode == EditorMode::Full {
12587 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12588 if self.git_blame_inline_enabled != inline_blame_enabled {
12589 self.toggle_git_blame_inline_internal(false, cx);
12590 }
12591 }
12592
12593 cx.notify();
12594 }
12595
12596 pub fn set_searchable(&mut self, searchable: bool) {
12597 self.searchable = searchable;
12598 }
12599
12600 pub fn searchable(&self) -> bool {
12601 self.searchable
12602 }
12603
12604 fn open_proposed_changes_editor(
12605 &mut self,
12606 _: &OpenProposedChangesEditor,
12607 cx: &mut ViewContext<Self>,
12608 ) {
12609 let Some(workspace) = self.workspace() else {
12610 cx.propagate();
12611 return;
12612 };
12613
12614 let selections = self.selections.all::<usize>(cx);
12615 let multi_buffer = self.buffer.read(cx);
12616 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12617 let mut new_selections_by_buffer = HashMap::default();
12618 for selection in selections {
12619 for (excerpt, range) in
12620 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12621 {
12622 let mut range = range.to_point(excerpt.buffer());
12623 range.start.column = 0;
12624 range.end.column = excerpt.buffer().line_len(range.end.row);
12625 new_selections_by_buffer
12626 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12627 .or_insert(Vec::new())
12628 .push(range)
12629 }
12630 }
12631
12632 let proposed_changes_buffers = new_selections_by_buffer
12633 .into_iter()
12634 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12635 .collect::<Vec<_>>();
12636 let proposed_changes_editor = cx.new_view(|cx| {
12637 ProposedChangesEditor::new(
12638 "Proposed changes",
12639 proposed_changes_buffers,
12640 self.project.clone(),
12641 cx,
12642 )
12643 });
12644
12645 cx.window_context().defer(move |cx| {
12646 workspace.update(cx, |workspace, cx| {
12647 workspace.active_pane().update(cx, |pane, cx| {
12648 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12649 });
12650 });
12651 });
12652 }
12653
12654 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12655 self.open_excerpts_common(None, true, cx)
12656 }
12657
12658 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12659 self.open_excerpts_common(None, false, cx)
12660 }
12661
12662 fn open_excerpts_common(
12663 &mut self,
12664 jump_data: Option<JumpData>,
12665 split: bool,
12666 cx: &mut ViewContext<Self>,
12667 ) {
12668 let Some(workspace) = self.workspace() else {
12669 cx.propagate();
12670 return;
12671 };
12672
12673 if self.buffer.read(cx).is_singleton() {
12674 cx.propagate();
12675 return;
12676 }
12677
12678 let mut new_selections_by_buffer = HashMap::default();
12679 match &jump_data {
12680 Some(JumpData::MultiBufferPoint {
12681 excerpt_id,
12682 position,
12683 anchor,
12684 line_offset_from_top,
12685 }) => {
12686 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12687 if let Some(buffer) = multi_buffer_snapshot
12688 .buffer_id_for_excerpt(*excerpt_id)
12689 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12690 {
12691 let buffer_snapshot = buffer.read(cx).snapshot();
12692 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12693 language::ToPoint::to_point(anchor, &buffer_snapshot)
12694 } else {
12695 buffer_snapshot.clip_point(*position, Bias::Left)
12696 };
12697 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12698 new_selections_by_buffer.insert(
12699 buffer,
12700 (
12701 vec![jump_to_offset..jump_to_offset],
12702 Some(*line_offset_from_top),
12703 ),
12704 );
12705 }
12706 }
12707 Some(JumpData::MultiBufferRow {
12708 row,
12709 line_offset_from_top,
12710 }) => {
12711 let point = MultiBufferPoint::new(row.0, 0);
12712 if let Some((buffer, buffer_point, _)) =
12713 self.buffer.read(cx).point_to_buffer_point(point, cx)
12714 {
12715 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12716 new_selections_by_buffer
12717 .entry(buffer)
12718 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12719 .0
12720 .push(buffer_offset..buffer_offset)
12721 }
12722 }
12723 None => {
12724 let selections = self.selections.all::<usize>(cx);
12725 let multi_buffer = self.buffer.read(cx);
12726 for selection in selections {
12727 for (excerpt, mut range) in multi_buffer
12728 .snapshot(cx)
12729 .range_to_buffer_ranges(selection.range())
12730 {
12731 // When editing branch buffers, jump to the corresponding location
12732 // in their base buffer.
12733 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12734 let buffer = buffer_handle.read(cx);
12735 if let Some(base_buffer) = buffer.base_buffer() {
12736 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12737 buffer_handle = base_buffer;
12738 }
12739
12740 if selection.reversed {
12741 mem::swap(&mut range.start, &mut range.end);
12742 }
12743 new_selections_by_buffer
12744 .entry(buffer_handle)
12745 .or_insert((Vec::new(), None))
12746 .0
12747 .push(range)
12748 }
12749 }
12750 }
12751 }
12752
12753 if new_selections_by_buffer.is_empty() {
12754 return;
12755 }
12756
12757 // We defer the pane interaction because we ourselves are a workspace item
12758 // and activating a new item causes the pane to call a method on us reentrantly,
12759 // which panics if we're on the stack.
12760 cx.window_context().defer(move |cx| {
12761 workspace.update(cx, |workspace, cx| {
12762 let pane = if split {
12763 workspace.adjacent_pane(cx)
12764 } else {
12765 workspace.active_pane().clone()
12766 };
12767
12768 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12769 let editor = buffer
12770 .read(cx)
12771 .file()
12772 .is_none()
12773 .then(|| {
12774 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12775 // so `workspace.open_project_item` will never find them, always opening a new editor.
12776 // Instead, we try to activate the existing editor in the pane first.
12777 let (editor, pane_item_index) =
12778 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12779 let editor = item.downcast::<Editor>()?;
12780 let singleton_buffer =
12781 editor.read(cx).buffer().read(cx).as_singleton()?;
12782 if singleton_buffer == buffer {
12783 Some((editor, i))
12784 } else {
12785 None
12786 }
12787 })?;
12788 pane.update(cx, |pane, cx| {
12789 pane.activate_item(pane_item_index, true, true, cx)
12790 });
12791 Some(editor)
12792 })
12793 .flatten()
12794 .unwrap_or_else(|| {
12795 workspace.open_project_item::<Self>(
12796 pane.clone(),
12797 buffer,
12798 true,
12799 true,
12800 cx,
12801 )
12802 });
12803
12804 editor.update(cx, |editor, cx| {
12805 let autoscroll = match scroll_offset {
12806 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12807 None => Autoscroll::newest(),
12808 };
12809 let nav_history = editor.nav_history.take();
12810 editor.change_selections(Some(autoscroll), cx, |s| {
12811 s.select_ranges(ranges);
12812 });
12813 editor.nav_history = nav_history;
12814 });
12815 }
12816 })
12817 });
12818 }
12819
12820 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12821 let snapshot = self.buffer.read(cx).read(cx);
12822 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12823 Some(
12824 ranges
12825 .iter()
12826 .map(move |range| {
12827 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12828 })
12829 .collect(),
12830 )
12831 }
12832
12833 fn selection_replacement_ranges(
12834 &self,
12835 range: Range<OffsetUtf16>,
12836 cx: &mut AppContext,
12837 ) -> Vec<Range<OffsetUtf16>> {
12838 let selections = self.selections.all::<OffsetUtf16>(cx);
12839 let newest_selection = selections
12840 .iter()
12841 .max_by_key(|selection| selection.id)
12842 .unwrap();
12843 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12844 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12845 let snapshot = self.buffer.read(cx).read(cx);
12846 selections
12847 .into_iter()
12848 .map(|mut selection| {
12849 selection.start.0 =
12850 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12851 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12852 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12853 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12854 })
12855 .collect()
12856 }
12857
12858 fn report_editor_event(
12859 &self,
12860 event_type: &'static str,
12861 file_extension: Option<String>,
12862 cx: &AppContext,
12863 ) {
12864 if cfg!(any(test, feature = "test-support")) {
12865 return;
12866 }
12867
12868 let Some(project) = &self.project else { return };
12869
12870 // If None, we are in a file without an extension
12871 let file = self
12872 .buffer
12873 .read(cx)
12874 .as_singleton()
12875 .and_then(|b| b.read(cx).file());
12876 let file_extension = file_extension.or(file
12877 .as_ref()
12878 .and_then(|file| Path::new(file.file_name(cx)).extension())
12879 .and_then(|e| e.to_str())
12880 .map(|a| a.to_string()));
12881
12882 let vim_mode = cx
12883 .global::<SettingsStore>()
12884 .raw_user_settings()
12885 .get("vim_mode")
12886 == Some(&serde_json::Value::Bool(true));
12887
12888 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12889 == language::language_settings::InlineCompletionProvider::Copilot;
12890 let copilot_enabled_for_language = self
12891 .buffer
12892 .read(cx)
12893 .settings_at(0, cx)
12894 .show_inline_completions;
12895
12896 let project = project.read(cx);
12897 telemetry::event!(
12898 event_type,
12899 file_extension,
12900 vim_mode,
12901 copilot_enabled,
12902 copilot_enabled_for_language,
12903 is_via_ssh = project.is_via_ssh(),
12904 );
12905 }
12906
12907 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12908 /// with each line being an array of {text, highlight} objects.
12909 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12910 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12911 return;
12912 };
12913
12914 #[derive(Serialize)]
12915 struct Chunk<'a> {
12916 text: String,
12917 highlight: Option<&'a str>,
12918 }
12919
12920 let snapshot = buffer.read(cx).snapshot();
12921 let range = self
12922 .selected_text_range(false, cx)
12923 .and_then(|selection| {
12924 if selection.range.is_empty() {
12925 None
12926 } else {
12927 Some(selection.range)
12928 }
12929 })
12930 .unwrap_or_else(|| 0..snapshot.len());
12931
12932 let chunks = snapshot.chunks(range, true);
12933 let mut lines = Vec::new();
12934 let mut line: VecDeque<Chunk> = VecDeque::new();
12935
12936 let Some(style) = self.style.as_ref() else {
12937 return;
12938 };
12939
12940 for chunk in chunks {
12941 let highlight = chunk
12942 .syntax_highlight_id
12943 .and_then(|id| id.name(&style.syntax));
12944 let mut chunk_lines = chunk.text.split('\n').peekable();
12945 while let Some(text) = chunk_lines.next() {
12946 let mut merged_with_last_token = false;
12947 if let Some(last_token) = line.back_mut() {
12948 if last_token.highlight == highlight {
12949 last_token.text.push_str(text);
12950 merged_with_last_token = true;
12951 }
12952 }
12953
12954 if !merged_with_last_token {
12955 line.push_back(Chunk {
12956 text: text.into(),
12957 highlight,
12958 });
12959 }
12960
12961 if chunk_lines.peek().is_some() {
12962 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12963 line.pop_front();
12964 }
12965 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12966 line.pop_back();
12967 }
12968
12969 lines.push(mem::take(&mut line));
12970 }
12971 }
12972 }
12973
12974 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12975 return;
12976 };
12977 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12978 }
12979
12980 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12981 self.request_autoscroll(Autoscroll::newest(), cx);
12982 let position = self.selections.newest_display(cx).start;
12983 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12984 }
12985
12986 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12987 &self.inlay_hint_cache
12988 }
12989
12990 pub fn replay_insert_event(
12991 &mut self,
12992 text: &str,
12993 relative_utf16_range: Option<Range<isize>>,
12994 cx: &mut ViewContext<Self>,
12995 ) {
12996 if !self.input_enabled {
12997 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12998 return;
12999 }
13000 if let Some(relative_utf16_range) = relative_utf16_range {
13001 let selections = self.selections.all::<OffsetUtf16>(cx);
13002 self.change_selections(None, cx, |s| {
13003 let new_ranges = selections.into_iter().map(|range| {
13004 let start = OffsetUtf16(
13005 range
13006 .head()
13007 .0
13008 .saturating_add_signed(relative_utf16_range.start),
13009 );
13010 let end = OffsetUtf16(
13011 range
13012 .head()
13013 .0
13014 .saturating_add_signed(relative_utf16_range.end),
13015 );
13016 start..end
13017 });
13018 s.select_ranges(new_ranges);
13019 });
13020 }
13021
13022 self.handle_input(text, cx);
13023 }
13024
13025 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13026 let Some(provider) = self.semantics_provider.as_ref() else {
13027 return false;
13028 };
13029
13030 let mut supports = false;
13031 self.buffer().read(cx).for_each_buffer(|buffer| {
13032 supports |= provider.supports_inlay_hints(buffer, cx);
13033 });
13034 supports
13035 }
13036
13037 pub fn focus(&self, cx: &mut WindowContext) {
13038 cx.focus(&self.focus_handle)
13039 }
13040
13041 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13042 self.focus_handle.is_focused(cx)
13043 }
13044
13045 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13046 cx.emit(EditorEvent::Focused);
13047
13048 if let Some(descendant) = self
13049 .last_focused_descendant
13050 .take()
13051 .and_then(|descendant| descendant.upgrade())
13052 {
13053 cx.focus(&descendant);
13054 } else {
13055 if let Some(blame) = self.blame.as_ref() {
13056 blame.update(cx, GitBlame::focus)
13057 }
13058
13059 self.blink_manager.update(cx, BlinkManager::enable);
13060 self.show_cursor_names(cx);
13061 self.buffer.update(cx, |buffer, cx| {
13062 buffer.finalize_last_transaction(cx);
13063 if self.leader_peer_id.is_none() {
13064 buffer.set_active_selections(
13065 &self.selections.disjoint_anchors(),
13066 self.selections.line_mode,
13067 self.cursor_shape,
13068 cx,
13069 );
13070 }
13071 });
13072 }
13073 }
13074
13075 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13076 cx.emit(EditorEvent::FocusedIn)
13077 }
13078
13079 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13080 if event.blurred != self.focus_handle {
13081 self.last_focused_descendant = Some(event.blurred);
13082 }
13083 }
13084
13085 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13086 self.blink_manager.update(cx, BlinkManager::disable);
13087 self.buffer
13088 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13089
13090 if let Some(blame) = self.blame.as_ref() {
13091 blame.update(cx, GitBlame::blur)
13092 }
13093 if !self.hover_state.focused(cx) {
13094 hide_hover(self, cx);
13095 }
13096
13097 self.hide_context_menu(cx);
13098 cx.emit(EditorEvent::Blurred);
13099 cx.notify();
13100 }
13101
13102 pub fn register_action<A: Action>(
13103 &mut self,
13104 listener: impl Fn(&A, &mut WindowContext) + 'static,
13105 ) -> Subscription {
13106 let id = self.next_editor_action_id.post_inc();
13107 let listener = Arc::new(listener);
13108 self.editor_actions.borrow_mut().insert(
13109 id,
13110 Box::new(move |cx| {
13111 let cx = cx.window_context();
13112 let listener = listener.clone();
13113 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13114 let action = action.downcast_ref().unwrap();
13115 if phase == DispatchPhase::Bubble {
13116 listener(action, cx)
13117 }
13118 })
13119 }),
13120 );
13121
13122 let editor_actions = self.editor_actions.clone();
13123 Subscription::new(move || {
13124 editor_actions.borrow_mut().remove(&id);
13125 })
13126 }
13127
13128 pub fn file_header_size(&self) -> u32 {
13129 FILE_HEADER_HEIGHT
13130 }
13131
13132 pub fn revert(
13133 &mut self,
13134 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13135 cx: &mut ViewContext<Self>,
13136 ) {
13137 self.buffer().update(cx, |multi_buffer, cx| {
13138 for (buffer_id, changes) in revert_changes {
13139 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13140 buffer.update(cx, |buffer, cx| {
13141 buffer.edit(
13142 changes.into_iter().map(|(range, text)| {
13143 (range, text.to_string().map(Arc::<str>::from))
13144 }),
13145 None,
13146 cx,
13147 );
13148 });
13149 }
13150 }
13151 });
13152 self.change_selections(None, cx, |selections| selections.refresh());
13153 }
13154
13155 pub fn to_pixel_point(
13156 &mut self,
13157 source: multi_buffer::Anchor,
13158 editor_snapshot: &EditorSnapshot,
13159 cx: &mut ViewContext<Self>,
13160 ) -> Option<gpui::Point<Pixels>> {
13161 let source_point = source.to_display_point(editor_snapshot);
13162 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13163 }
13164
13165 pub fn display_to_pixel_point(
13166 &self,
13167 source: DisplayPoint,
13168 editor_snapshot: &EditorSnapshot,
13169 cx: &WindowContext,
13170 ) -> Option<gpui::Point<Pixels>> {
13171 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13172 let text_layout_details = self.text_layout_details(cx);
13173 let scroll_top = text_layout_details
13174 .scroll_anchor
13175 .scroll_position(editor_snapshot)
13176 .y;
13177
13178 if source.row().as_f32() < scroll_top.floor() {
13179 return None;
13180 }
13181 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13182 let source_y = line_height * (source.row().as_f32() - scroll_top);
13183 Some(gpui::Point::new(source_x, source_y))
13184 }
13185
13186 pub fn has_active_completions_menu(&self) -> bool {
13187 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13188 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13189 })
13190 }
13191
13192 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13193 self.addons
13194 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13195 }
13196
13197 pub fn unregister_addon<T: Addon>(&mut self) {
13198 self.addons.remove(&std::any::TypeId::of::<T>());
13199 }
13200
13201 pub fn addon<T: Addon>(&self) -> Option<&T> {
13202 let type_id = std::any::TypeId::of::<T>();
13203 self.addons
13204 .get(&type_id)
13205 .and_then(|item| item.to_any().downcast_ref::<T>())
13206 }
13207
13208 pub fn add_change_set(
13209 &mut self,
13210 change_set: Model<BufferChangeSet>,
13211 cx: &mut ViewContext<Self>,
13212 ) {
13213 self.diff_map.add_change_set(change_set, cx);
13214 }
13215
13216 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13217 let text_layout_details = self.text_layout_details(cx);
13218 let style = &text_layout_details.editor_style;
13219 let font_id = cx.text_system().resolve_font(&style.text.font());
13220 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13221 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13222
13223 let em_width = cx
13224 .text_system()
13225 .typographic_bounds(font_id, font_size, 'm')
13226 .unwrap()
13227 .size
13228 .width;
13229
13230 gpui::Point::new(em_width, line_height)
13231 }
13232}
13233
13234fn get_unstaged_changes_for_buffers(
13235 project: &Model<Project>,
13236 buffers: impl IntoIterator<Item = Model<Buffer>>,
13237 cx: &mut ViewContext<Editor>,
13238) {
13239 let mut tasks = Vec::new();
13240 project.update(cx, |project, cx| {
13241 for buffer in buffers {
13242 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13243 }
13244 });
13245 cx.spawn(|this, mut cx| async move {
13246 let change_sets = futures::future::join_all(tasks).await;
13247 this.update(&mut cx, |this, cx| {
13248 for change_set in change_sets {
13249 if let Some(change_set) = change_set.log_err() {
13250 this.diff_map.add_change_set(change_set, cx);
13251 }
13252 }
13253 })
13254 .ok();
13255 })
13256 .detach();
13257}
13258
13259fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13260 let tab_size = tab_size.get() as usize;
13261 let mut width = offset;
13262
13263 for ch in text.chars() {
13264 width += if ch == '\t' {
13265 tab_size - (width % tab_size)
13266 } else {
13267 1
13268 };
13269 }
13270
13271 width - offset
13272}
13273
13274#[cfg(test)]
13275mod tests {
13276 use super::*;
13277
13278 #[test]
13279 fn test_string_size_with_expanded_tabs() {
13280 let nz = |val| NonZeroU32::new(val).unwrap();
13281 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13282 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13283 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13284 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13285 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13286 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13287 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13288 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13289 }
13290}
13291
13292/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13293struct WordBreakingTokenizer<'a> {
13294 input: &'a str,
13295}
13296
13297impl<'a> WordBreakingTokenizer<'a> {
13298 fn new(input: &'a str) -> Self {
13299 Self { input }
13300 }
13301}
13302
13303fn is_char_ideographic(ch: char) -> bool {
13304 use unicode_script::Script::*;
13305 use unicode_script::UnicodeScript;
13306 matches!(ch.script(), Han | Tangut | Yi)
13307}
13308
13309fn is_grapheme_ideographic(text: &str) -> bool {
13310 text.chars().any(is_char_ideographic)
13311}
13312
13313fn is_grapheme_whitespace(text: &str) -> bool {
13314 text.chars().any(|x| x.is_whitespace())
13315}
13316
13317fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13318 text.chars().next().map_or(false, |ch| {
13319 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13320 })
13321}
13322
13323#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13324struct WordBreakToken<'a> {
13325 token: &'a str,
13326 grapheme_len: usize,
13327 is_whitespace: bool,
13328}
13329
13330impl<'a> Iterator for WordBreakingTokenizer<'a> {
13331 /// Yields a span, the count of graphemes in the token, and whether it was
13332 /// whitespace. Note that it also breaks at word boundaries.
13333 type Item = WordBreakToken<'a>;
13334
13335 fn next(&mut self) -> Option<Self::Item> {
13336 use unicode_segmentation::UnicodeSegmentation;
13337 if self.input.is_empty() {
13338 return None;
13339 }
13340
13341 let mut iter = self.input.graphemes(true).peekable();
13342 let mut offset = 0;
13343 let mut graphemes = 0;
13344 if let Some(first_grapheme) = iter.next() {
13345 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13346 offset += first_grapheme.len();
13347 graphemes += 1;
13348 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13349 if let Some(grapheme) = iter.peek().copied() {
13350 if should_stay_with_preceding_ideograph(grapheme) {
13351 offset += grapheme.len();
13352 graphemes += 1;
13353 }
13354 }
13355 } else {
13356 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13357 let mut next_word_bound = words.peek().copied();
13358 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13359 next_word_bound = words.next();
13360 }
13361 while let Some(grapheme) = iter.peek().copied() {
13362 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13363 break;
13364 };
13365 if is_grapheme_whitespace(grapheme) != is_whitespace {
13366 break;
13367 };
13368 offset += grapheme.len();
13369 graphemes += 1;
13370 iter.next();
13371 }
13372 }
13373 let token = &self.input[..offset];
13374 self.input = &self.input[offset..];
13375 if is_whitespace {
13376 Some(WordBreakToken {
13377 token: " ",
13378 grapheme_len: 1,
13379 is_whitespace: true,
13380 })
13381 } else {
13382 Some(WordBreakToken {
13383 token,
13384 grapheme_len: graphemes,
13385 is_whitespace: false,
13386 })
13387 }
13388 } else {
13389 None
13390 }
13391 }
13392}
13393
13394#[test]
13395fn test_word_breaking_tokenizer() {
13396 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13397 ("", &[]),
13398 (" ", &[(" ", 1, true)]),
13399 ("Ʒ", &[("Ʒ", 1, false)]),
13400 ("Ǽ", &[("Ǽ", 1, false)]),
13401 ("⋑", &[("⋑", 1, false)]),
13402 ("⋑⋑", &[("⋑⋑", 2, false)]),
13403 (
13404 "原理,进而",
13405 &[
13406 ("原", 1, false),
13407 ("理,", 2, false),
13408 ("进", 1, false),
13409 ("而", 1, false),
13410 ],
13411 ),
13412 (
13413 "hello world",
13414 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13415 ),
13416 (
13417 "hello, world",
13418 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13419 ),
13420 (
13421 " hello world",
13422 &[
13423 (" ", 1, true),
13424 ("hello", 5, false),
13425 (" ", 1, true),
13426 ("world", 5, false),
13427 ],
13428 ),
13429 (
13430 "这是什么 \n 钢笔",
13431 &[
13432 ("这", 1, false),
13433 ("是", 1, false),
13434 ("什", 1, false),
13435 ("么", 1, false),
13436 (" ", 1, true),
13437 ("钢", 1, false),
13438 ("笔", 1, false),
13439 ],
13440 ),
13441 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13442 ];
13443
13444 for (input, result) in tests {
13445 assert_eq!(
13446 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13447 result
13448 .iter()
13449 .copied()
13450 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13451 token,
13452 grapheme_len,
13453 is_whitespace,
13454 })
13455 .collect::<Vec<_>>()
13456 );
13457 }
13458}
13459
13460fn wrap_with_prefix(
13461 line_prefix: String,
13462 unwrapped_text: String,
13463 wrap_column: usize,
13464 tab_size: NonZeroU32,
13465) -> String {
13466 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13467 let mut wrapped_text = String::new();
13468 let mut current_line = line_prefix.clone();
13469
13470 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13471 let mut current_line_len = line_prefix_len;
13472 for WordBreakToken {
13473 token,
13474 grapheme_len,
13475 is_whitespace,
13476 } in tokenizer
13477 {
13478 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13479 wrapped_text.push_str(current_line.trim_end());
13480 wrapped_text.push('\n');
13481 current_line.truncate(line_prefix.len());
13482 current_line_len = line_prefix_len;
13483 if !is_whitespace {
13484 current_line.push_str(token);
13485 current_line_len += grapheme_len;
13486 }
13487 } else if !is_whitespace {
13488 current_line.push_str(token);
13489 current_line_len += grapheme_len;
13490 } else if current_line_len != line_prefix_len {
13491 current_line.push(' ');
13492 current_line_len += 1;
13493 }
13494 }
13495
13496 if !current_line.is_empty() {
13497 wrapped_text.push_str(¤t_line);
13498 }
13499 wrapped_text
13500}
13501
13502#[test]
13503fn test_wrap_with_prefix() {
13504 assert_eq!(
13505 wrap_with_prefix(
13506 "# ".to_string(),
13507 "abcdefg".to_string(),
13508 4,
13509 NonZeroU32::new(4).unwrap()
13510 ),
13511 "# abcdefg"
13512 );
13513 assert_eq!(
13514 wrap_with_prefix(
13515 "".to_string(),
13516 "\thello world".to_string(),
13517 8,
13518 NonZeroU32::new(4).unwrap()
13519 ),
13520 "hello\nworld"
13521 );
13522 assert_eq!(
13523 wrap_with_prefix(
13524 "// ".to_string(),
13525 "xx \nyy zz aa bb cc".to_string(),
13526 12,
13527 NonZeroU32::new(4).unwrap()
13528 ),
13529 "// xx yy zz\n// aa bb cc"
13530 );
13531 assert_eq!(
13532 wrap_with_prefix(
13533 String::new(),
13534 "这是什么 \n 钢笔".to_string(),
13535 3,
13536 NonZeroU32::new(4).unwrap()
13537 ),
13538 "这是什\n么 钢\n笔"
13539 );
13540}
13541
13542fn hunks_for_selections(
13543 snapshot: &EditorSnapshot,
13544 selections: &[Selection<Point>],
13545) -> Vec<MultiBufferDiffHunk> {
13546 hunks_for_ranges(
13547 selections.iter().map(|selection| selection.range()),
13548 snapshot,
13549 )
13550}
13551
13552pub fn hunks_for_ranges(
13553 ranges: impl Iterator<Item = Range<Point>>,
13554 snapshot: &EditorSnapshot,
13555) -> Vec<MultiBufferDiffHunk> {
13556 let mut hunks = Vec::new();
13557 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13558 HashMap::default();
13559 for query_range in ranges {
13560 let query_rows =
13561 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13562 for hunk in snapshot.diff_map.diff_hunks_in_range(
13563 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13564 &snapshot.buffer_snapshot,
13565 ) {
13566 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13567 // when the caret is just above or just below the deleted hunk.
13568 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13569 let related_to_selection = if allow_adjacent {
13570 hunk.row_range.overlaps(&query_rows)
13571 || hunk.row_range.start == query_rows.end
13572 || hunk.row_range.end == query_rows.start
13573 } else {
13574 hunk.row_range.overlaps(&query_rows)
13575 };
13576 if related_to_selection {
13577 if !processed_buffer_rows
13578 .entry(hunk.buffer_id)
13579 .or_default()
13580 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13581 {
13582 continue;
13583 }
13584 hunks.push(hunk);
13585 }
13586 }
13587 }
13588
13589 hunks
13590}
13591
13592pub trait CollaborationHub {
13593 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13594 fn user_participant_indices<'a>(
13595 &self,
13596 cx: &'a AppContext,
13597 ) -> &'a HashMap<u64, ParticipantIndex>;
13598 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13599}
13600
13601impl CollaborationHub for Model<Project> {
13602 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13603 self.read(cx).collaborators()
13604 }
13605
13606 fn user_participant_indices<'a>(
13607 &self,
13608 cx: &'a AppContext,
13609 ) -> &'a HashMap<u64, ParticipantIndex> {
13610 self.read(cx).user_store().read(cx).participant_indices()
13611 }
13612
13613 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13614 let this = self.read(cx);
13615 let user_ids = this.collaborators().values().map(|c| c.user_id);
13616 this.user_store().read_with(cx, |user_store, cx| {
13617 user_store.participant_names(user_ids, cx)
13618 })
13619 }
13620}
13621
13622pub trait SemanticsProvider {
13623 fn hover(
13624 &self,
13625 buffer: &Model<Buffer>,
13626 position: text::Anchor,
13627 cx: &mut AppContext,
13628 ) -> Option<Task<Vec<project::Hover>>>;
13629
13630 fn inlay_hints(
13631 &self,
13632 buffer_handle: Model<Buffer>,
13633 range: Range<text::Anchor>,
13634 cx: &mut AppContext,
13635 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13636
13637 fn resolve_inlay_hint(
13638 &self,
13639 hint: InlayHint,
13640 buffer_handle: Model<Buffer>,
13641 server_id: LanguageServerId,
13642 cx: &mut AppContext,
13643 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13644
13645 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13646
13647 fn document_highlights(
13648 &self,
13649 buffer: &Model<Buffer>,
13650 position: text::Anchor,
13651 cx: &mut AppContext,
13652 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13653
13654 fn definitions(
13655 &self,
13656 buffer: &Model<Buffer>,
13657 position: text::Anchor,
13658 kind: GotoDefinitionKind,
13659 cx: &mut AppContext,
13660 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13661
13662 fn range_for_rename(
13663 &self,
13664 buffer: &Model<Buffer>,
13665 position: text::Anchor,
13666 cx: &mut AppContext,
13667 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13668
13669 fn perform_rename(
13670 &self,
13671 buffer: &Model<Buffer>,
13672 position: text::Anchor,
13673 new_name: String,
13674 cx: &mut AppContext,
13675 ) -> Option<Task<Result<ProjectTransaction>>>;
13676}
13677
13678pub trait CompletionProvider {
13679 fn completions(
13680 &self,
13681 buffer: &Model<Buffer>,
13682 buffer_position: text::Anchor,
13683 trigger: CompletionContext,
13684 cx: &mut ViewContext<Editor>,
13685 ) -> Task<Result<Vec<Completion>>>;
13686
13687 fn resolve_completions(
13688 &self,
13689 buffer: Model<Buffer>,
13690 completion_indices: Vec<usize>,
13691 completions: Rc<RefCell<Box<[Completion]>>>,
13692 cx: &mut ViewContext<Editor>,
13693 ) -> Task<Result<bool>>;
13694
13695 fn apply_additional_edits_for_completion(
13696 &self,
13697 _buffer: Model<Buffer>,
13698 _completions: Rc<RefCell<Box<[Completion]>>>,
13699 _completion_index: usize,
13700 _push_to_history: bool,
13701 _cx: &mut ViewContext<Editor>,
13702 ) -> Task<Result<Option<language::Transaction>>> {
13703 Task::ready(Ok(None))
13704 }
13705
13706 fn is_completion_trigger(
13707 &self,
13708 buffer: &Model<Buffer>,
13709 position: language::Anchor,
13710 text: &str,
13711 trigger_in_words: bool,
13712 cx: &mut ViewContext<Editor>,
13713 ) -> bool;
13714
13715 fn sort_completions(&self) -> bool {
13716 true
13717 }
13718}
13719
13720pub trait CodeActionProvider {
13721 fn id(&self) -> Arc<str>;
13722
13723 fn code_actions(
13724 &self,
13725 buffer: &Model<Buffer>,
13726 range: Range<text::Anchor>,
13727 cx: &mut WindowContext,
13728 ) -> Task<Result<Vec<CodeAction>>>;
13729
13730 fn apply_code_action(
13731 &self,
13732 buffer_handle: Model<Buffer>,
13733 action: CodeAction,
13734 excerpt_id: ExcerptId,
13735 push_to_history: bool,
13736 cx: &mut WindowContext,
13737 ) -> Task<Result<ProjectTransaction>>;
13738}
13739
13740impl CodeActionProvider for Model<Project> {
13741 fn id(&self) -> Arc<str> {
13742 "project".into()
13743 }
13744
13745 fn code_actions(
13746 &self,
13747 buffer: &Model<Buffer>,
13748 range: Range<text::Anchor>,
13749 cx: &mut WindowContext,
13750 ) -> Task<Result<Vec<CodeAction>>> {
13751 self.update(cx, |project, cx| {
13752 project.code_actions(buffer, range, None, cx)
13753 })
13754 }
13755
13756 fn apply_code_action(
13757 &self,
13758 buffer_handle: Model<Buffer>,
13759 action: CodeAction,
13760 _excerpt_id: ExcerptId,
13761 push_to_history: bool,
13762 cx: &mut WindowContext,
13763 ) -> Task<Result<ProjectTransaction>> {
13764 self.update(cx, |project, cx| {
13765 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13766 })
13767 }
13768}
13769
13770fn snippet_completions(
13771 project: &Project,
13772 buffer: &Model<Buffer>,
13773 buffer_position: text::Anchor,
13774 cx: &mut AppContext,
13775) -> Task<Result<Vec<Completion>>> {
13776 let language = buffer.read(cx).language_at(buffer_position);
13777 let language_name = language.as_ref().map(|language| language.lsp_id());
13778 let snippet_store = project.snippets().read(cx);
13779 let snippets = snippet_store.snippets_for(language_name, cx);
13780
13781 if snippets.is_empty() {
13782 return Task::ready(Ok(vec![]));
13783 }
13784 let snapshot = buffer.read(cx).text_snapshot();
13785 let chars: String = snapshot
13786 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13787 .collect();
13788
13789 let scope = language.map(|language| language.default_scope());
13790 let executor = cx.background_executor().clone();
13791
13792 cx.background_executor().spawn(async move {
13793 let classifier = CharClassifier::new(scope).for_completion(true);
13794 let mut last_word = chars
13795 .chars()
13796 .take_while(|c| classifier.is_word(*c))
13797 .collect::<String>();
13798 last_word = last_word.chars().rev().collect();
13799
13800 if last_word.is_empty() {
13801 return Ok(vec![]);
13802 }
13803
13804 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13805 let to_lsp = |point: &text::Anchor| {
13806 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13807 point_to_lsp(end)
13808 };
13809 let lsp_end = to_lsp(&buffer_position);
13810
13811 let candidates = snippets
13812 .iter()
13813 .enumerate()
13814 .flat_map(|(ix, snippet)| {
13815 snippet
13816 .prefix
13817 .iter()
13818 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13819 })
13820 .collect::<Vec<StringMatchCandidate>>();
13821
13822 let mut matches = fuzzy::match_strings(
13823 &candidates,
13824 &last_word,
13825 last_word.chars().any(|c| c.is_uppercase()),
13826 100,
13827 &Default::default(),
13828 executor,
13829 )
13830 .await;
13831
13832 // Remove all candidates where the query's start does not match the start of any word in the candidate
13833 if let Some(query_start) = last_word.chars().next() {
13834 matches.retain(|string_match| {
13835 split_words(&string_match.string).any(|word| {
13836 // Check that the first codepoint of the word as lowercase matches the first
13837 // codepoint of the query as lowercase
13838 word.chars()
13839 .flat_map(|codepoint| codepoint.to_lowercase())
13840 .zip(query_start.to_lowercase())
13841 .all(|(word_cp, query_cp)| word_cp == query_cp)
13842 })
13843 });
13844 }
13845
13846 let matched_strings = matches
13847 .into_iter()
13848 .map(|m| m.string)
13849 .collect::<HashSet<_>>();
13850
13851 let result: Vec<Completion> = snippets
13852 .into_iter()
13853 .filter_map(|snippet| {
13854 let matching_prefix = snippet
13855 .prefix
13856 .iter()
13857 .find(|prefix| matched_strings.contains(*prefix))?;
13858 let start = as_offset - last_word.len();
13859 let start = snapshot.anchor_before(start);
13860 let range = start..buffer_position;
13861 let lsp_start = to_lsp(&start);
13862 let lsp_range = lsp::Range {
13863 start: lsp_start,
13864 end: lsp_end,
13865 };
13866 Some(Completion {
13867 old_range: range,
13868 new_text: snippet.body.clone(),
13869 resolved: false,
13870 label: CodeLabel {
13871 text: matching_prefix.clone(),
13872 runs: vec![],
13873 filter_range: 0..matching_prefix.len(),
13874 },
13875 server_id: LanguageServerId(usize::MAX),
13876 documentation: snippet.description.clone().map(Documentation::SingleLine),
13877 lsp_completion: lsp::CompletionItem {
13878 label: snippet.prefix.first().unwrap().clone(),
13879 kind: Some(CompletionItemKind::SNIPPET),
13880 label_details: snippet.description.as_ref().map(|description| {
13881 lsp::CompletionItemLabelDetails {
13882 detail: Some(description.clone()),
13883 description: None,
13884 }
13885 }),
13886 insert_text_format: Some(InsertTextFormat::SNIPPET),
13887 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13888 lsp::InsertReplaceEdit {
13889 new_text: snippet.body.clone(),
13890 insert: lsp_range,
13891 replace: lsp_range,
13892 },
13893 )),
13894 filter_text: Some(snippet.body.clone()),
13895 sort_text: Some(char::MAX.to_string()),
13896 ..Default::default()
13897 },
13898 confirm: None,
13899 })
13900 })
13901 .collect();
13902
13903 Ok(result)
13904 })
13905}
13906
13907impl CompletionProvider for Model<Project> {
13908 fn completions(
13909 &self,
13910 buffer: &Model<Buffer>,
13911 buffer_position: text::Anchor,
13912 options: CompletionContext,
13913 cx: &mut ViewContext<Editor>,
13914 ) -> Task<Result<Vec<Completion>>> {
13915 self.update(cx, |project, cx| {
13916 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13917 let project_completions = project.completions(buffer, buffer_position, options, cx);
13918 cx.background_executor().spawn(async move {
13919 let mut completions = project_completions.await?;
13920 let snippets_completions = snippets.await?;
13921 completions.extend(snippets_completions);
13922 Ok(completions)
13923 })
13924 })
13925 }
13926
13927 fn resolve_completions(
13928 &self,
13929 buffer: Model<Buffer>,
13930 completion_indices: Vec<usize>,
13931 completions: Rc<RefCell<Box<[Completion]>>>,
13932 cx: &mut ViewContext<Editor>,
13933 ) -> Task<Result<bool>> {
13934 self.update(cx, |project, cx| {
13935 project.lsp_store().update(cx, |lsp_store, cx| {
13936 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13937 })
13938 })
13939 }
13940
13941 fn apply_additional_edits_for_completion(
13942 &self,
13943 buffer: Model<Buffer>,
13944 completions: Rc<RefCell<Box<[Completion]>>>,
13945 completion_index: usize,
13946 push_to_history: bool,
13947 cx: &mut ViewContext<Editor>,
13948 ) -> Task<Result<Option<language::Transaction>>> {
13949 self.update(cx, |project, cx| {
13950 project.lsp_store().update(cx, |lsp_store, cx| {
13951 lsp_store.apply_additional_edits_for_completion(
13952 buffer,
13953 completions,
13954 completion_index,
13955 push_to_history,
13956 cx,
13957 )
13958 })
13959 })
13960 }
13961
13962 fn is_completion_trigger(
13963 &self,
13964 buffer: &Model<Buffer>,
13965 position: language::Anchor,
13966 text: &str,
13967 trigger_in_words: bool,
13968 cx: &mut ViewContext<Editor>,
13969 ) -> bool {
13970 let mut chars = text.chars();
13971 let char = if let Some(char) = chars.next() {
13972 char
13973 } else {
13974 return false;
13975 };
13976 if chars.next().is_some() {
13977 return false;
13978 }
13979
13980 let buffer = buffer.read(cx);
13981 let snapshot = buffer.snapshot();
13982 if !snapshot.settings_at(position, cx).show_completions_on_input {
13983 return false;
13984 }
13985 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13986 if trigger_in_words && classifier.is_word(char) {
13987 return true;
13988 }
13989
13990 buffer.completion_triggers().contains(text)
13991 }
13992}
13993
13994impl SemanticsProvider for Model<Project> {
13995 fn hover(
13996 &self,
13997 buffer: &Model<Buffer>,
13998 position: text::Anchor,
13999 cx: &mut AppContext,
14000 ) -> Option<Task<Vec<project::Hover>>> {
14001 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14002 }
14003
14004 fn document_highlights(
14005 &self,
14006 buffer: &Model<Buffer>,
14007 position: text::Anchor,
14008 cx: &mut AppContext,
14009 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14010 Some(self.update(cx, |project, cx| {
14011 project.document_highlights(buffer, position, cx)
14012 }))
14013 }
14014
14015 fn definitions(
14016 &self,
14017 buffer: &Model<Buffer>,
14018 position: text::Anchor,
14019 kind: GotoDefinitionKind,
14020 cx: &mut AppContext,
14021 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14022 Some(self.update(cx, |project, cx| match kind {
14023 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14024 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14025 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14026 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14027 }))
14028 }
14029
14030 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14031 // TODO: make this work for remote projects
14032 self.read(cx)
14033 .language_servers_for_local_buffer(buffer.read(cx), cx)
14034 .any(
14035 |(_, server)| match server.capabilities().inlay_hint_provider {
14036 Some(lsp::OneOf::Left(enabled)) => enabled,
14037 Some(lsp::OneOf::Right(_)) => true,
14038 None => false,
14039 },
14040 )
14041 }
14042
14043 fn inlay_hints(
14044 &self,
14045 buffer_handle: Model<Buffer>,
14046 range: Range<text::Anchor>,
14047 cx: &mut AppContext,
14048 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14049 Some(self.update(cx, |project, cx| {
14050 project.inlay_hints(buffer_handle, range, cx)
14051 }))
14052 }
14053
14054 fn resolve_inlay_hint(
14055 &self,
14056 hint: InlayHint,
14057 buffer_handle: Model<Buffer>,
14058 server_id: LanguageServerId,
14059 cx: &mut AppContext,
14060 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14061 Some(self.update(cx, |project, cx| {
14062 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14063 }))
14064 }
14065
14066 fn range_for_rename(
14067 &self,
14068 buffer: &Model<Buffer>,
14069 position: text::Anchor,
14070 cx: &mut AppContext,
14071 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14072 Some(self.update(cx, |project, cx| {
14073 let buffer = buffer.clone();
14074 let task = project.prepare_rename(buffer.clone(), position, cx);
14075 cx.spawn(|_, mut cx| async move {
14076 Ok(match task.await? {
14077 PrepareRenameResponse::Success(range) => Some(range),
14078 PrepareRenameResponse::InvalidPosition => None,
14079 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14080 // Fallback on using TreeSitter info to determine identifier range
14081 buffer.update(&mut cx, |buffer, _| {
14082 let snapshot = buffer.snapshot();
14083 let (range, kind) = snapshot.surrounding_word(position);
14084 if kind != Some(CharKind::Word) {
14085 return None;
14086 }
14087 Some(
14088 snapshot.anchor_before(range.start)
14089 ..snapshot.anchor_after(range.end),
14090 )
14091 })?
14092 }
14093 })
14094 })
14095 }))
14096 }
14097
14098 fn perform_rename(
14099 &self,
14100 buffer: &Model<Buffer>,
14101 position: text::Anchor,
14102 new_name: String,
14103 cx: &mut AppContext,
14104 ) -> Option<Task<Result<ProjectTransaction>>> {
14105 Some(self.update(cx, |project, cx| {
14106 project.perform_rename(buffer.clone(), position, new_name, cx)
14107 }))
14108 }
14109}
14110
14111fn inlay_hint_settings(
14112 location: Anchor,
14113 snapshot: &MultiBufferSnapshot,
14114 cx: &mut ViewContext<Editor>,
14115) -> InlayHintSettings {
14116 let file = snapshot.file_at(location);
14117 let language = snapshot.language_at(location).map(|l| l.name());
14118 language_settings(language, file, cx).inlay_hints
14119}
14120
14121fn consume_contiguous_rows(
14122 contiguous_row_selections: &mut Vec<Selection<Point>>,
14123 selection: &Selection<Point>,
14124 display_map: &DisplaySnapshot,
14125 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14126) -> (MultiBufferRow, MultiBufferRow) {
14127 contiguous_row_selections.push(selection.clone());
14128 let start_row = MultiBufferRow(selection.start.row);
14129 let mut end_row = ending_row(selection, display_map);
14130
14131 while let Some(next_selection) = selections.peek() {
14132 if next_selection.start.row <= end_row.0 {
14133 end_row = ending_row(next_selection, display_map);
14134 contiguous_row_selections.push(selections.next().unwrap().clone());
14135 } else {
14136 break;
14137 }
14138 }
14139 (start_row, end_row)
14140}
14141
14142fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14143 if next_selection.end.column > 0 || next_selection.is_empty() {
14144 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14145 } else {
14146 MultiBufferRow(next_selection.end.row)
14147 }
14148}
14149
14150impl EditorSnapshot {
14151 pub fn remote_selections_in_range<'a>(
14152 &'a self,
14153 range: &'a Range<Anchor>,
14154 collaboration_hub: &dyn CollaborationHub,
14155 cx: &'a AppContext,
14156 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14157 let participant_names = collaboration_hub.user_names(cx);
14158 let participant_indices = collaboration_hub.user_participant_indices(cx);
14159 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14160 let collaborators_by_replica_id = collaborators_by_peer_id
14161 .iter()
14162 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14163 .collect::<HashMap<_, _>>();
14164 self.buffer_snapshot
14165 .selections_in_range(range, false)
14166 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14167 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14168 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14169 let user_name = participant_names.get(&collaborator.user_id).cloned();
14170 Some(RemoteSelection {
14171 replica_id,
14172 selection,
14173 cursor_shape,
14174 line_mode,
14175 participant_index,
14176 peer_id: collaborator.peer_id,
14177 user_name,
14178 })
14179 })
14180 }
14181
14182 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14183 self.display_snapshot.buffer_snapshot.language_at(position)
14184 }
14185
14186 pub fn is_focused(&self) -> bool {
14187 self.is_focused
14188 }
14189
14190 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14191 self.placeholder_text.as_ref()
14192 }
14193
14194 pub fn scroll_position(&self) -> gpui::Point<f32> {
14195 self.scroll_anchor.scroll_position(&self.display_snapshot)
14196 }
14197
14198 fn gutter_dimensions(
14199 &self,
14200 font_id: FontId,
14201 font_size: Pixels,
14202 em_width: Pixels,
14203 em_advance: Pixels,
14204 max_line_number_width: Pixels,
14205 cx: &AppContext,
14206 ) -> GutterDimensions {
14207 if !self.show_gutter {
14208 return GutterDimensions::default();
14209 }
14210 let descent = cx.text_system().descent(font_id, font_size);
14211
14212 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14213 matches!(
14214 ProjectSettings::get_global(cx).git.git_gutter,
14215 Some(GitGutterSetting::TrackedFiles)
14216 )
14217 });
14218 let gutter_settings = EditorSettings::get_global(cx).gutter;
14219 let show_line_numbers = self
14220 .show_line_numbers
14221 .unwrap_or(gutter_settings.line_numbers);
14222 let line_gutter_width = if show_line_numbers {
14223 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14224 let min_width_for_number_on_gutter = em_advance * 4.0;
14225 max_line_number_width.max(min_width_for_number_on_gutter)
14226 } else {
14227 0.0.into()
14228 };
14229
14230 let show_code_actions = self
14231 .show_code_actions
14232 .unwrap_or(gutter_settings.code_actions);
14233
14234 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14235
14236 let git_blame_entries_width =
14237 self.git_blame_gutter_max_author_length
14238 .map(|max_author_length| {
14239 // Length of the author name, but also space for the commit hash,
14240 // the spacing and the timestamp.
14241 let max_char_count = max_author_length
14242 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14243 + 7 // length of commit sha
14244 + 14 // length of max relative timestamp ("60 minutes ago")
14245 + 4; // gaps and margins
14246
14247 em_advance * max_char_count
14248 });
14249
14250 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14251 left_padding += if show_code_actions || show_runnables {
14252 em_width * 3.0
14253 } else if show_git_gutter && show_line_numbers {
14254 em_width * 2.0
14255 } else if show_git_gutter || show_line_numbers {
14256 em_width
14257 } else {
14258 px(0.)
14259 };
14260
14261 let right_padding = if gutter_settings.folds && show_line_numbers {
14262 em_width * 4.0
14263 } else if gutter_settings.folds {
14264 em_width * 3.0
14265 } else if show_line_numbers {
14266 em_width
14267 } else {
14268 px(0.)
14269 };
14270
14271 GutterDimensions {
14272 left_padding,
14273 right_padding,
14274 width: line_gutter_width + left_padding + right_padding,
14275 margin: -descent,
14276 git_blame_entries_width,
14277 }
14278 }
14279
14280 pub fn render_crease_toggle(
14281 &self,
14282 buffer_row: MultiBufferRow,
14283 row_contains_cursor: bool,
14284 editor: View<Editor>,
14285 cx: &mut WindowContext,
14286 ) -> Option<AnyElement> {
14287 let folded = self.is_line_folded(buffer_row);
14288 let mut is_foldable = false;
14289
14290 if let Some(crease) = self
14291 .crease_snapshot
14292 .query_row(buffer_row, &self.buffer_snapshot)
14293 {
14294 is_foldable = true;
14295 match crease {
14296 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14297 if let Some(render_toggle) = render_toggle {
14298 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14299 if folded {
14300 editor.update(cx, |editor, cx| {
14301 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14302 });
14303 } else {
14304 editor.update(cx, |editor, cx| {
14305 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14306 });
14307 }
14308 });
14309 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14310 }
14311 }
14312 }
14313 }
14314
14315 is_foldable |= self.starts_indent(buffer_row);
14316
14317 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14318 Some(
14319 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14320 .toggle_state(folded)
14321 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14322 if folded {
14323 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14324 } else {
14325 this.fold_at(&FoldAt { buffer_row }, cx);
14326 }
14327 }))
14328 .into_any_element(),
14329 )
14330 } else {
14331 None
14332 }
14333 }
14334
14335 pub fn render_crease_trailer(
14336 &self,
14337 buffer_row: MultiBufferRow,
14338 cx: &mut WindowContext,
14339 ) -> Option<AnyElement> {
14340 let folded = self.is_line_folded(buffer_row);
14341 if let Crease::Inline { render_trailer, .. } = self
14342 .crease_snapshot
14343 .query_row(buffer_row, &self.buffer_snapshot)?
14344 {
14345 let render_trailer = render_trailer.as_ref()?;
14346 Some(render_trailer(buffer_row, folded, cx))
14347 } else {
14348 None
14349 }
14350 }
14351}
14352
14353impl Deref for EditorSnapshot {
14354 type Target = DisplaySnapshot;
14355
14356 fn deref(&self) -> &Self::Target {
14357 &self.display_snapshot
14358 }
14359}
14360
14361#[derive(Clone, Debug, PartialEq, Eq)]
14362pub enum EditorEvent {
14363 InputIgnored {
14364 text: Arc<str>,
14365 },
14366 InputHandled {
14367 utf16_range_to_replace: Option<Range<isize>>,
14368 text: Arc<str>,
14369 },
14370 ExcerptsAdded {
14371 buffer: Model<Buffer>,
14372 predecessor: ExcerptId,
14373 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14374 },
14375 ExcerptsRemoved {
14376 ids: Vec<ExcerptId>,
14377 },
14378 BufferFoldToggled {
14379 ids: Vec<ExcerptId>,
14380 folded: bool,
14381 },
14382 ExcerptsEdited {
14383 ids: Vec<ExcerptId>,
14384 },
14385 ExcerptsExpanded {
14386 ids: Vec<ExcerptId>,
14387 },
14388 BufferEdited,
14389 Edited {
14390 transaction_id: clock::Lamport,
14391 },
14392 Reparsed(BufferId),
14393 Focused,
14394 FocusedIn,
14395 Blurred,
14396 DirtyChanged,
14397 Saved,
14398 TitleChanged,
14399 DiffBaseChanged,
14400 SelectionsChanged {
14401 local: bool,
14402 },
14403 ScrollPositionChanged {
14404 local: bool,
14405 autoscroll: bool,
14406 },
14407 Closed,
14408 TransactionUndone {
14409 transaction_id: clock::Lamport,
14410 },
14411 TransactionBegun {
14412 transaction_id: clock::Lamport,
14413 },
14414 Reloaded,
14415 CursorShapeChanged,
14416}
14417
14418impl EventEmitter<EditorEvent> for Editor {}
14419
14420impl FocusableView for Editor {
14421 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14422 self.focus_handle.clone()
14423 }
14424}
14425
14426impl Render for Editor {
14427 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14428 let settings = ThemeSettings::get_global(cx);
14429
14430 let mut text_style = match self.mode {
14431 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14432 color: cx.theme().colors().editor_foreground,
14433 font_family: settings.ui_font.family.clone(),
14434 font_features: settings.ui_font.features.clone(),
14435 font_fallbacks: settings.ui_font.fallbacks.clone(),
14436 font_size: rems(0.875).into(),
14437 font_weight: settings.ui_font.weight,
14438 line_height: relative(settings.buffer_line_height.value()),
14439 ..Default::default()
14440 },
14441 EditorMode::Full => TextStyle {
14442 color: cx.theme().colors().editor_foreground,
14443 font_family: settings.buffer_font.family.clone(),
14444 font_features: settings.buffer_font.features.clone(),
14445 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14446 font_size: settings.buffer_font_size().into(),
14447 font_weight: settings.buffer_font.weight,
14448 line_height: relative(settings.buffer_line_height.value()),
14449 ..Default::default()
14450 },
14451 };
14452 if let Some(text_style_refinement) = &self.text_style_refinement {
14453 text_style.refine(text_style_refinement)
14454 }
14455
14456 let background = match self.mode {
14457 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14458 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14459 EditorMode::Full => cx.theme().colors().editor_background,
14460 };
14461
14462 EditorElement::new(
14463 cx.view(),
14464 EditorStyle {
14465 background,
14466 local_player: cx.theme().players().local(),
14467 text: text_style,
14468 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14469 syntax: cx.theme().syntax().clone(),
14470 status: cx.theme().status().clone(),
14471 inlay_hints_style: make_inlay_hints_style(cx),
14472 inline_completion_styles: make_suggestion_styles(cx),
14473 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14474 },
14475 )
14476 }
14477}
14478
14479impl ViewInputHandler for Editor {
14480 fn text_for_range(
14481 &mut self,
14482 range_utf16: Range<usize>,
14483 adjusted_range: &mut Option<Range<usize>>,
14484 cx: &mut ViewContext<Self>,
14485 ) -> Option<String> {
14486 let snapshot = self.buffer.read(cx).read(cx);
14487 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14488 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14489 if (start.0..end.0) != range_utf16 {
14490 adjusted_range.replace(start.0..end.0);
14491 }
14492 Some(snapshot.text_for_range(start..end).collect())
14493 }
14494
14495 fn selected_text_range(
14496 &mut self,
14497 ignore_disabled_input: bool,
14498 cx: &mut ViewContext<Self>,
14499 ) -> Option<UTF16Selection> {
14500 // Prevent the IME menu from appearing when holding down an alphabetic key
14501 // while input is disabled.
14502 if !ignore_disabled_input && !self.input_enabled {
14503 return None;
14504 }
14505
14506 let selection = self.selections.newest::<OffsetUtf16>(cx);
14507 let range = selection.range();
14508
14509 Some(UTF16Selection {
14510 range: range.start.0..range.end.0,
14511 reversed: selection.reversed,
14512 })
14513 }
14514
14515 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14516 let snapshot = self.buffer.read(cx).read(cx);
14517 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14518 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14519 }
14520
14521 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14522 self.clear_highlights::<InputComposition>(cx);
14523 self.ime_transaction.take();
14524 }
14525
14526 fn replace_text_in_range(
14527 &mut self,
14528 range_utf16: Option<Range<usize>>,
14529 text: &str,
14530 cx: &mut ViewContext<Self>,
14531 ) {
14532 if !self.input_enabled {
14533 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14534 return;
14535 }
14536
14537 self.transact(cx, |this, cx| {
14538 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14539 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14540 Some(this.selection_replacement_ranges(range_utf16, cx))
14541 } else {
14542 this.marked_text_ranges(cx)
14543 };
14544
14545 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14546 let newest_selection_id = this.selections.newest_anchor().id;
14547 this.selections
14548 .all::<OffsetUtf16>(cx)
14549 .iter()
14550 .zip(ranges_to_replace.iter())
14551 .find_map(|(selection, range)| {
14552 if selection.id == newest_selection_id {
14553 Some(
14554 (range.start.0 as isize - selection.head().0 as isize)
14555 ..(range.end.0 as isize - selection.head().0 as isize),
14556 )
14557 } else {
14558 None
14559 }
14560 })
14561 });
14562
14563 cx.emit(EditorEvent::InputHandled {
14564 utf16_range_to_replace: range_to_replace,
14565 text: text.into(),
14566 });
14567
14568 if let Some(new_selected_ranges) = new_selected_ranges {
14569 this.change_selections(None, cx, |selections| {
14570 selections.select_ranges(new_selected_ranges)
14571 });
14572 this.backspace(&Default::default(), cx);
14573 }
14574
14575 this.handle_input(text, cx);
14576 });
14577
14578 if let Some(transaction) = self.ime_transaction {
14579 self.buffer.update(cx, |buffer, cx| {
14580 buffer.group_until_transaction(transaction, cx);
14581 });
14582 }
14583
14584 self.unmark_text(cx);
14585 }
14586
14587 fn replace_and_mark_text_in_range(
14588 &mut self,
14589 range_utf16: Option<Range<usize>>,
14590 text: &str,
14591 new_selected_range_utf16: Option<Range<usize>>,
14592 cx: &mut ViewContext<Self>,
14593 ) {
14594 if !self.input_enabled {
14595 return;
14596 }
14597
14598 let transaction = self.transact(cx, |this, cx| {
14599 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14600 let snapshot = this.buffer.read(cx).read(cx);
14601 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14602 for marked_range in &mut marked_ranges {
14603 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14604 marked_range.start.0 += relative_range_utf16.start;
14605 marked_range.start =
14606 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14607 marked_range.end =
14608 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14609 }
14610 }
14611 Some(marked_ranges)
14612 } else if let Some(range_utf16) = range_utf16 {
14613 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14614 Some(this.selection_replacement_ranges(range_utf16, cx))
14615 } else {
14616 None
14617 };
14618
14619 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14620 let newest_selection_id = this.selections.newest_anchor().id;
14621 this.selections
14622 .all::<OffsetUtf16>(cx)
14623 .iter()
14624 .zip(ranges_to_replace.iter())
14625 .find_map(|(selection, range)| {
14626 if selection.id == newest_selection_id {
14627 Some(
14628 (range.start.0 as isize - selection.head().0 as isize)
14629 ..(range.end.0 as isize - selection.head().0 as isize),
14630 )
14631 } else {
14632 None
14633 }
14634 })
14635 });
14636
14637 cx.emit(EditorEvent::InputHandled {
14638 utf16_range_to_replace: range_to_replace,
14639 text: text.into(),
14640 });
14641
14642 if let Some(ranges) = ranges_to_replace {
14643 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14644 }
14645
14646 let marked_ranges = {
14647 let snapshot = this.buffer.read(cx).read(cx);
14648 this.selections
14649 .disjoint_anchors()
14650 .iter()
14651 .map(|selection| {
14652 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14653 })
14654 .collect::<Vec<_>>()
14655 };
14656
14657 if text.is_empty() {
14658 this.unmark_text(cx);
14659 } else {
14660 this.highlight_text::<InputComposition>(
14661 marked_ranges.clone(),
14662 HighlightStyle {
14663 underline: Some(UnderlineStyle {
14664 thickness: px(1.),
14665 color: None,
14666 wavy: false,
14667 }),
14668 ..Default::default()
14669 },
14670 cx,
14671 );
14672 }
14673
14674 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14675 let use_autoclose = this.use_autoclose;
14676 let use_auto_surround = this.use_auto_surround;
14677 this.set_use_autoclose(false);
14678 this.set_use_auto_surround(false);
14679 this.handle_input(text, cx);
14680 this.set_use_autoclose(use_autoclose);
14681 this.set_use_auto_surround(use_auto_surround);
14682
14683 if let Some(new_selected_range) = new_selected_range_utf16 {
14684 let snapshot = this.buffer.read(cx).read(cx);
14685 let new_selected_ranges = marked_ranges
14686 .into_iter()
14687 .map(|marked_range| {
14688 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14689 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14690 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14691 snapshot.clip_offset_utf16(new_start, Bias::Left)
14692 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14693 })
14694 .collect::<Vec<_>>();
14695
14696 drop(snapshot);
14697 this.change_selections(None, cx, |selections| {
14698 selections.select_ranges(new_selected_ranges)
14699 });
14700 }
14701 });
14702
14703 self.ime_transaction = self.ime_transaction.or(transaction);
14704 if let Some(transaction) = self.ime_transaction {
14705 self.buffer.update(cx, |buffer, cx| {
14706 buffer.group_until_transaction(transaction, cx);
14707 });
14708 }
14709
14710 if self.text_highlights::<InputComposition>(cx).is_none() {
14711 self.ime_transaction.take();
14712 }
14713 }
14714
14715 fn bounds_for_range(
14716 &mut self,
14717 range_utf16: Range<usize>,
14718 element_bounds: gpui::Bounds<Pixels>,
14719 cx: &mut ViewContext<Self>,
14720 ) -> Option<gpui::Bounds<Pixels>> {
14721 let text_layout_details = self.text_layout_details(cx);
14722 let gpui::Point {
14723 x: em_width,
14724 y: line_height,
14725 } = self.character_size(cx);
14726
14727 let snapshot = self.snapshot(cx);
14728 let scroll_position = snapshot.scroll_position();
14729 let scroll_left = scroll_position.x * em_width;
14730
14731 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14732 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14733 + self.gutter_dimensions.width
14734 + self.gutter_dimensions.margin;
14735 let y = line_height * (start.row().as_f32() - scroll_position.y);
14736
14737 Some(Bounds {
14738 origin: element_bounds.origin + point(x, y),
14739 size: size(em_width, line_height),
14740 })
14741 }
14742}
14743
14744trait SelectionExt {
14745 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14746 fn spanned_rows(
14747 &self,
14748 include_end_if_at_line_start: bool,
14749 map: &DisplaySnapshot,
14750 ) -> Range<MultiBufferRow>;
14751}
14752
14753impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14754 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14755 let start = self
14756 .start
14757 .to_point(&map.buffer_snapshot)
14758 .to_display_point(map);
14759 let end = self
14760 .end
14761 .to_point(&map.buffer_snapshot)
14762 .to_display_point(map);
14763 if self.reversed {
14764 end..start
14765 } else {
14766 start..end
14767 }
14768 }
14769
14770 fn spanned_rows(
14771 &self,
14772 include_end_if_at_line_start: bool,
14773 map: &DisplaySnapshot,
14774 ) -> Range<MultiBufferRow> {
14775 let start = self.start.to_point(&map.buffer_snapshot);
14776 let mut end = self.end.to_point(&map.buffer_snapshot);
14777 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14778 end.row -= 1;
14779 }
14780
14781 let buffer_start = map.prev_line_boundary(start).0;
14782 let buffer_end = map.next_line_boundary(end).0;
14783 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14784 }
14785}
14786
14787impl<T: InvalidationRegion> InvalidationStack<T> {
14788 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14789 where
14790 S: Clone + ToOffset,
14791 {
14792 while let Some(region) = self.last() {
14793 let all_selections_inside_invalidation_ranges =
14794 if selections.len() == region.ranges().len() {
14795 selections
14796 .iter()
14797 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14798 .all(|(selection, invalidation_range)| {
14799 let head = selection.head().to_offset(buffer);
14800 invalidation_range.start <= head && invalidation_range.end >= head
14801 })
14802 } else {
14803 false
14804 };
14805
14806 if all_selections_inside_invalidation_ranges {
14807 break;
14808 } else {
14809 self.pop();
14810 }
14811 }
14812 }
14813}
14814
14815impl<T> Default for InvalidationStack<T> {
14816 fn default() -> Self {
14817 Self(Default::default())
14818 }
14819}
14820
14821impl<T> Deref for InvalidationStack<T> {
14822 type Target = Vec<T>;
14823
14824 fn deref(&self) -> &Self::Target {
14825 &self.0
14826 }
14827}
14828
14829impl<T> DerefMut for InvalidationStack<T> {
14830 fn deref_mut(&mut self) -> &mut Self::Target {
14831 &mut self.0
14832 }
14833}
14834
14835impl InvalidationRegion for SnippetState {
14836 fn ranges(&self) -> &[Range<Anchor>] {
14837 &self.ranges[self.active_index]
14838 }
14839}
14840
14841pub fn diagnostic_block_renderer(
14842 diagnostic: Diagnostic,
14843 max_message_rows: Option<u8>,
14844 allow_closing: bool,
14845 _is_valid: bool,
14846) -> RenderBlock {
14847 let (text_without_backticks, code_ranges) =
14848 highlight_diagnostic_message(&diagnostic, max_message_rows);
14849
14850 Arc::new(move |cx: &mut BlockContext| {
14851 let group_id: SharedString = cx.block_id.to_string().into();
14852
14853 let mut text_style = cx.text_style().clone();
14854 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14855 let theme_settings = ThemeSettings::get_global(cx);
14856 text_style.font_family = theme_settings.buffer_font.family.clone();
14857 text_style.font_style = theme_settings.buffer_font.style;
14858 text_style.font_features = theme_settings.buffer_font.features.clone();
14859 text_style.font_weight = theme_settings.buffer_font.weight;
14860
14861 let multi_line_diagnostic = diagnostic.message.contains('\n');
14862
14863 let buttons = |diagnostic: &Diagnostic| {
14864 if multi_line_diagnostic {
14865 v_flex()
14866 } else {
14867 h_flex()
14868 }
14869 .when(allow_closing, |div| {
14870 div.children(diagnostic.is_primary.then(|| {
14871 IconButton::new("close-block", IconName::XCircle)
14872 .icon_color(Color::Muted)
14873 .size(ButtonSize::Compact)
14874 .style(ButtonStyle::Transparent)
14875 .visible_on_hover(group_id.clone())
14876 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14877 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14878 }))
14879 })
14880 .child(
14881 IconButton::new("copy-block", IconName::Copy)
14882 .icon_color(Color::Muted)
14883 .size(ButtonSize::Compact)
14884 .style(ButtonStyle::Transparent)
14885 .visible_on_hover(group_id.clone())
14886 .on_click({
14887 let message = diagnostic.message.clone();
14888 move |_click, cx| {
14889 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14890 }
14891 })
14892 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14893 )
14894 };
14895
14896 let icon_size = buttons(&diagnostic)
14897 .into_any_element()
14898 .layout_as_root(AvailableSpace::min_size(), cx);
14899
14900 h_flex()
14901 .id(cx.block_id)
14902 .group(group_id.clone())
14903 .relative()
14904 .size_full()
14905 .block_mouse_down()
14906 .pl(cx.gutter_dimensions.width)
14907 .w(cx.max_width - cx.gutter_dimensions.full_width())
14908 .child(
14909 div()
14910 .flex()
14911 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14912 .flex_shrink(),
14913 )
14914 .child(buttons(&diagnostic))
14915 .child(div().flex().flex_shrink_0().child(
14916 StyledText::new(text_without_backticks.clone()).with_highlights(
14917 &text_style,
14918 code_ranges.iter().map(|range| {
14919 (
14920 range.clone(),
14921 HighlightStyle {
14922 font_weight: Some(FontWeight::BOLD),
14923 ..Default::default()
14924 },
14925 )
14926 }),
14927 ),
14928 ))
14929 .into_any_element()
14930 })
14931}
14932
14933fn inline_completion_edit_text(
14934 editor_snapshot: &EditorSnapshot,
14935 edits: &Vec<(Range<Anchor>, String)>,
14936 include_deletions: bool,
14937 cx: &WindowContext,
14938) -> InlineCompletionText {
14939 let edit_start = edits
14940 .first()
14941 .unwrap()
14942 .0
14943 .start
14944 .to_display_point(editor_snapshot);
14945
14946 let mut text = String::new();
14947 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14948 let mut highlights = Vec::new();
14949 for (old_range, new_text) in edits {
14950 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14951 text.extend(
14952 editor_snapshot
14953 .buffer_snapshot
14954 .chunks(offset..old_offset_range.start, false)
14955 .map(|chunk| chunk.text),
14956 );
14957 offset = old_offset_range.end;
14958
14959 let start = text.len();
14960 let color = if include_deletions && new_text.is_empty() {
14961 text.extend(
14962 editor_snapshot
14963 .buffer_snapshot
14964 .chunks(old_offset_range.start..offset, false)
14965 .map(|chunk| chunk.text),
14966 );
14967 cx.theme().status().deleted_background
14968 } else {
14969 text.push_str(new_text);
14970 cx.theme().status().created_background
14971 };
14972 let end = text.len();
14973
14974 highlights.push((
14975 start..end,
14976 HighlightStyle {
14977 background_color: Some(color),
14978 ..Default::default()
14979 },
14980 ));
14981 }
14982
14983 let edit_end = edits
14984 .last()
14985 .unwrap()
14986 .0
14987 .end
14988 .to_display_point(editor_snapshot);
14989 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14990 .to_offset(editor_snapshot, Bias::Right);
14991 text.extend(
14992 editor_snapshot
14993 .buffer_snapshot
14994 .chunks(offset..end_of_line, false)
14995 .map(|chunk| chunk.text),
14996 );
14997
14998 InlineCompletionText::Edit {
14999 text: text.into(),
15000 highlights,
15001 }
15002}
15003
15004pub fn highlight_diagnostic_message(
15005 diagnostic: &Diagnostic,
15006 mut max_message_rows: Option<u8>,
15007) -> (SharedString, Vec<Range<usize>>) {
15008 let mut text_without_backticks = String::new();
15009 let mut code_ranges = Vec::new();
15010
15011 if let Some(source) = &diagnostic.source {
15012 text_without_backticks.push_str(source);
15013 code_ranges.push(0..source.len());
15014 text_without_backticks.push_str(": ");
15015 }
15016
15017 let mut prev_offset = 0;
15018 let mut in_code_block = false;
15019 let has_row_limit = max_message_rows.is_some();
15020 let mut newline_indices = diagnostic
15021 .message
15022 .match_indices('\n')
15023 .filter(|_| has_row_limit)
15024 .map(|(ix, _)| ix)
15025 .fuse()
15026 .peekable();
15027
15028 for (quote_ix, _) in diagnostic
15029 .message
15030 .match_indices('`')
15031 .chain([(diagnostic.message.len(), "")])
15032 {
15033 let mut first_newline_ix = None;
15034 let mut last_newline_ix = None;
15035 while let Some(newline_ix) = newline_indices.peek() {
15036 if *newline_ix < quote_ix {
15037 if first_newline_ix.is_none() {
15038 first_newline_ix = Some(*newline_ix);
15039 }
15040 last_newline_ix = Some(*newline_ix);
15041
15042 if let Some(rows_left) = &mut max_message_rows {
15043 if *rows_left == 0 {
15044 break;
15045 } else {
15046 *rows_left -= 1;
15047 }
15048 }
15049 let _ = newline_indices.next();
15050 } else {
15051 break;
15052 }
15053 }
15054 let prev_len = text_without_backticks.len();
15055 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15056 text_without_backticks.push_str(new_text);
15057 if in_code_block {
15058 code_ranges.push(prev_len..text_without_backticks.len());
15059 }
15060 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15061 in_code_block = !in_code_block;
15062 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15063 text_without_backticks.push_str("...");
15064 break;
15065 }
15066 }
15067
15068 (text_without_backticks.into(), code_ranges)
15069}
15070
15071fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15072 match severity {
15073 DiagnosticSeverity::ERROR => colors.error,
15074 DiagnosticSeverity::WARNING => colors.warning,
15075 DiagnosticSeverity::INFORMATION => colors.info,
15076 DiagnosticSeverity::HINT => colors.info,
15077 _ => colors.ignored,
15078 }
15079}
15080
15081pub fn styled_runs_for_code_label<'a>(
15082 label: &'a CodeLabel,
15083 syntax_theme: &'a theme::SyntaxTheme,
15084) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15085 let fade_out = HighlightStyle {
15086 fade_out: Some(0.35),
15087 ..Default::default()
15088 };
15089
15090 let mut prev_end = label.filter_range.end;
15091 label
15092 .runs
15093 .iter()
15094 .enumerate()
15095 .flat_map(move |(ix, (range, highlight_id))| {
15096 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15097 style
15098 } else {
15099 return Default::default();
15100 };
15101 let mut muted_style = style;
15102 muted_style.highlight(fade_out);
15103
15104 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15105 if range.start >= label.filter_range.end {
15106 if range.start > prev_end {
15107 runs.push((prev_end..range.start, fade_out));
15108 }
15109 runs.push((range.clone(), muted_style));
15110 } else if range.end <= label.filter_range.end {
15111 runs.push((range.clone(), style));
15112 } else {
15113 runs.push((range.start..label.filter_range.end, style));
15114 runs.push((label.filter_range.end..range.end, muted_style));
15115 }
15116 prev_end = cmp::max(prev_end, range.end);
15117
15118 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15119 runs.push((prev_end..label.text.len(), fade_out));
15120 }
15121
15122 runs
15123 })
15124}
15125
15126pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15127 let mut prev_index = 0;
15128 let mut prev_codepoint: Option<char> = None;
15129 text.char_indices()
15130 .chain([(text.len(), '\0')])
15131 .filter_map(move |(index, codepoint)| {
15132 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15133 let is_boundary = index == text.len()
15134 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15135 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15136 if is_boundary {
15137 let chunk = &text[prev_index..index];
15138 prev_index = index;
15139 Some(chunk)
15140 } else {
15141 None
15142 }
15143 })
15144}
15145
15146pub trait RangeToAnchorExt: Sized {
15147 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15148
15149 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15150 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15151 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15152 }
15153}
15154
15155impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15156 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15157 let start_offset = self.start.to_offset(snapshot);
15158 let end_offset = self.end.to_offset(snapshot);
15159 if start_offset == end_offset {
15160 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15161 } else {
15162 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15163 }
15164 }
15165}
15166
15167pub trait RowExt {
15168 fn as_f32(&self) -> f32;
15169
15170 fn next_row(&self) -> Self;
15171
15172 fn previous_row(&self) -> Self;
15173
15174 fn minus(&self, other: Self) -> u32;
15175}
15176
15177impl RowExt for DisplayRow {
15178 fn as_f32(&self) -> f32 {
15179 self.0 as f32
15180 }
15181
15182 fn next_row(&self) -> Self {
15183 Self(self.0 + 1)
15184 }
15185
15186 fn previous_row(&self) -> Self {
15187 Self(self.0.saturating_sub(1))
15188 }
15189
15190 fn minus(&self, other: Self) -> u32 {
15191 self.0 - other.0
15192 }
15193}
15194
15195impl RowExt for MultiBufferRow {
15196 fn as_f32(&self) -> f32 {
15197 self.0 as f32
15198 }
15199
15200 fn next_row(&self) -> Self {
15201 Self(self.0 + 1)
15202 }
15203
15204 fn previous_row(&self) -> Self {
15205 Self(self.0.saturating_sub(1))
15206 }
15207
15208 fn minus(&self, other: Self) -> u32 {
15209 self.0 - other.0
15210 }
15211}
15212
15213trait RowRangeExt {
15214 type Row;
15215
15216 fn len(&self) -> usize;
15217
15218 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15219}
15220
15221impl RowRangeExt for Range<MultiBufferRow> {
15222 type Row = MultiBufferRow;
15223
15224 fn len(&self) -> usize {
15225 (self.end.0 - self.start.0) as usize
15226 }
15227
15228 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15229 (self.start.0..self.end.0).map(MultiBufferRow)
15230 }
15231}
15232
15233impl RowRangeExt for Range<DisplayRow> {
15234 type Row = DisplayRow;
15235
15236 fn len(&self) -> usize {
15237 (self.end.0 - self.start.0) as usize
15238 }
15239
15240 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15241 (self.start.0..self.end.0).map(DisplayRow)
15242 }
15243}
15244
15245fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15246 if hunk.diff_base_byte_range.is_empty() {
15247 DiffHunkStatus::Added
15248 } else if hunk.row_range.is_empty() {
15249 DiffHunkStatus::Removed
15250 } else {
15251 DiffHunkStatus::Modified
15252 }
15253}
15254
15255/// If select range has more than one line, we
15256/// just point the cursor to range.start.
15257fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15258 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15259 range
15260 } else {
15261 range.start..range.start
15262 }
15263}
15264pub struct KillRing(ClipboardItem);
15265impl Global for KillRing {}
15266
15267const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);