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 cx: &mut ViewContext<Editor>,
5250 ) -> Option<AnyElement> {
5251 self.context_menu.borrow().as_ref().and_then(|menu| {
5252 if menu.visible() {
5253 Some(menu.render(style, max_height_in_lines, cx))
5254 } else {
5255 None
5256 }
5257 })
5258 }
5259
5260 fn render_context_menu_aside(
5261 &self,
5262 style: &EditorStyle,
5263 max_size: Size<Pixels>,
5264 cx: &mut ViewContext<Editor>,
5265 ) -> Option<AnyElement> {
5266 self.context_menu.borrow().as_ref().and_then(|menu| {
5267 if menu.visible() {
5268 menu.render_aside(
5269 style,
5270 max_size,
5271 self.workspace.as_ref().map(|(w, _)| w.clone()),
5272 cx,
5273 )
5274 } else {
5275 None
5276 }
5277 })
5278 }
5279
5280 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5281 cx.notify();
5282 self.completion_tasks.clear();
5283 let context_menu = self.context_menu.borrow_mut().take();
5284 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5285 self.update_visible_inline_completion(cx);
5286 }
5287 context_menu
5288 }
5289
5290 fn show_snippet_choices(
5291 &mut self,
5292 choices: &Vec<String>,
5293 selection: Range<Anchor>,
5294 cx: &mut ViewContext<Self>,
5295 ) {
5296 if selection.start.buffer_id.is_none() {
5297 return;
5298 }
5299 let buffer_id = selection.start.buffer_id.unwrap();
5300 let buffer = self.buffer().read(cx).buffer(buffer_id);
5301 let id = post_inc(&mut self.next_completion_id);
5302
5303 if let Some(buffer) = buffer {
5304 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5305 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5306 ));
5307 }
5308 }
5309
5310 pub fn insert_snippet(
5311 &mut self,
5312 insertion_ranges: &[Range<usize>],
5313 snippet: Snippet,
5314 cx: &mut ViewContext<Self>,
5315 ) -> Result<()> {
5316 struct Tabstop<T> {
5317 is_end_tabstop: bool,
5318 ranges: Vec<Range<T>>,
5319 choices: Option<Vec<String>>,
5320 }
5321
5322 let tabstops = self.buffer.update(cx, |buffer, cx| {
5323 let snippet_text: Arc<str> = snippet.text.clone().into();
5324 buffer.edit(
5325 insertion_ranges
5326 .iter()
5327 .cloned()
5328 .map(|range| (range, snippet_text.clone())),
5329 Some(AutoindentMode::EachLine),
5330 cx,
5331 );
5332
5333 let snapshot = &*buffer.read(cx);
5334 let snippet = &snippet;
5335 snippet
5336 .tabstops
5337 .iter()
5338 .map(|tabstop| {
5339 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5340 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5341 });
5342 let mut tabstop_ranges = tabstop
5343 .ranges
5344 .iter()
5345 .flat_map(|tabstop_range| {
5346 let mut delta = 0_isize;
5347 insertion_ranges.iter().map(move |insertion_range| {
5348 let insertion_start = insertion_range.start as isize + delta;
5349 delta +=
5350 snippet.text.len() as isize - insertion_range.len() as isize;
5351
5352 let start = ((insertion_start + tabstop_range.start) as usize)
5353 .min(snapshot.len());
5354 let end = ((insertion_start + tabstop_range.end) as usize)
5355 .min(snapshot.len());
5356 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5357 })
5358 })
5359 .collect::<Vec<_>>();
5360 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5361
5362 Tabstop {
5363 is_end_tabstop,
5364 ranges: tabstop_ranges,
5365 choices: tabstop.choices.clone(),
5366 }
5367 })
5368 .collect::<Vec<_>>()
5369 });
5370 if let Some(tabstop) = tabstops.first() {
5371 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5372 s.select_ranges(tabstop.ranges.iter().cloned());
5373 });
5374
5375 if let Some(choices) = &tabstop.choices {
5376 if let Some(selection) = tabstop.ranges.first() {
5377 self.show_snippet_choices(choices, selection.clone(), cx)
5378 }
5379 }
5380
5381 // If we're already at the last tabstop and it's at the end of the snippet,
5382 // we're done, we don't need to keep the state around.
5383 if !tabstop.is_end_tabstop {
5384 let choices = tabstops
5385 .iter()
5386 .map(|tabstop| tabstop.choices.clone())
5387 .collect();
5388
5389 let ranges = tabstops
5390 .into_iter()
5391 .map(|tabstop| tabstop.ranges)
5392 .collect::<Vec<_>>();
5393
5394 self.snippet_stack.push(SnippetState {
5395 active_index: 0,
5396 ranges,
5397 choices,
5398 });
5399 }
5400
5401 // Check whether the just-entered snippet ends with an auto-closable bracket.
5402 if self.autoclose_regions.is_empty() {
5403 let snapshot = self.buffer.read(cx).snapshot(cx);
5404 for selection in &mut self.selections.all::<Point>(cx) {
5405 let selection_head = selection.head();
5406 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5407 continue;
5408 };
5409
5410 let mut bracket_pair = None;
5411 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5412 let prev_chars = snapshot
5413 .reversed_chars_at(selection_head)
5414 .collect::<String>();
5415 for (pair, enabled) in scope.brackets() {
5416 if enabled
5417 && pair.close
5418 && prev_chars.starts_with(pair.start.as_str())
5419 && next_chars.starts_with(pair.end.as_str())
5420 {
5421 bracket_pair = Some(pair.clone());
5422 break;
5423 }
5424 }
5425 if let Some(pair) = bracket_pair {
5426 let start = snapshot.anchor_after(selection_head);
5427 let end = snapshot.anchor_after(selection_head);
5428 self.autoclose_regions.push(AutocloseRegion {
5429 selection_id: selection.id,
5430 range: start..end,
5431 pair,
5432 });
5433 }
5434 }
5435 }
5436 }
5437 Ok(())
5438 }
5439
5440 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5441 self.move_to_snippet_tabstop(Bias::Right, cx)
5442 }
5443
5444 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5445 self.move_to_snippet_tabstop(Bias::Left, cx)
5446 }
5447
5448 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5449 if let Some(mut snippet) = self.snippet_stack.pop() {
5450 match bias {
5451 Bias::Left => {
5452 if snippet.active_index > 0 {
5453 snippet.active_index -= 1;
5454 } else {
5455 self.snippet_stack.push(snippet);
5456 return false;
5457 }
5458 }
5459 Bias::Right => {
5460 if snippet.active_index + 1 < snippet.ranges.len() {
5461 snippet.active_index += 1;
5462 } else {
5463 self.snippet_stack.push(snippet);
5464 return false;
5465 }
5466 }
5467 }
5468 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5469 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5470 s.select_anchor_ranges(current_ranges.iter().cloned())
5471 });
5472
5473 if let Some(choices) = &snippet.choices[snippet.active_index] {
5474 if let Some(selection) = current_ranges.first() {
5475 self.show_snippet_choices(&choices, selection.clone(), cx);
5476 }
5477 }
5478
5479 // If snippet state is not at the last tabstop, push it back on the stack
5480 if snippet.active_index + 1 < snippet.ranges.len() {
5481 self.snippet_stack.push(snippet);
5482 }
5483 return true;
5484 }
5485 }
5486
5487 false
5488 }
5489
5490 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5491 self.transact(cx, |this, cx| {
5492 this.select_all(&SelectAll, cx);
5493 this.insert("", cx);
5494 });
5495 }
5496
5497 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5498 self.transact(cx, |this, cx| {
5499 this.select_autoclose_pair(cx);
5500 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5501 if !this.linked_edit_ranges.is_empty() {
5502 let selections = this.selections.all::<MultiBufferPoint>(cx);
5503 let snapshot = this.buffer.read(cx).snapshot(cx);
5504
5505 for selection in selections.iter() {
5506 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5507 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5508 if selection_start.buffer_id != selection_end.buffer_id {
5509 continue;
5510 }
5511 if let Some(ranges) =
5512 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5513 {
5514 for (buffer, entries) in ranges {
5515 linked_ranges.entry(buffer).or_default().extend(entries);
5516 }
5517 }
5518 }
5519 }
5520
5521 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5522 if !this.selections.line_mode {
5523 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5524 for selection in &mut selections {
5525 if selection.is_empty() {
5526 let old_head = selection.head();
5527 let mut new_head =
5528 movement::left(&display_map, old_head.to_display_point(&display_map))
5529 .to_point(&display_map);
5530 if let Some((buffer, line_buffer_range)) = display_map
5531 .buffer_snapshot
5532 .buffer_line_for_row(MultiBufferRow(old_head.row))
5533 {
5534 let indent_size =
5535 buffer.indent_size_for_line(line_buffer_range.start.row);
5536 let indent_len = match indent_size.kind {
5537 IndentKind::Space => {
5538 buffer.settings_at(line_buffer_range.start, cx).tab_size
5539 }
5540 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5541 };
5542 if old_head.column <= indent_size.len && old_head.column > 0 {
5543 let indent_len = indent_len.get();
5544 new_head = cmp::min(
5545 new_head,
5546 MultiBufferPoint::new(
5547 old_head.row,
5548 ((old_head.column - 1) / indent_len) * indent_len,
5549 ),
5550 );
5551 }
5552 }
5553
5554 selection.set_head(new_head, SelectionGoal::None);
5555 }
5556 }
5557 }
5558
5559 this.signature_help_state.set_backspace_pressed(true);
5560 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5561 this.insert("", cx);
5562 let empty_str: Arc<str> = Arc::from("");
5563 for (buffer, edits) in linked_ranges {
5564 let snapshot = buffer.read(cx).snapshot();
5565 use text::ToPoint as TP;
5566
5567 let edits = edits
5568 .into_iter()
5569 .map(|range| {
5570 let end_point = TP::to_point(&range.end, &snapshot);
5571 let mut start_point = TP::to_point(&range.start, &snapshot);
5572
5573 if end_point == start_point {
5574 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5575 .saturating_sub(1);
5576 start_point =
5577 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5578 };
5579
5580 (start_point..end_point, empty_str.clone())
5581 })
5582 .sorted_by_key(|(range, _)| range.start)
5583 .collect::<Vec<_>>();
5584 buffer.update(cx, |this, cx| {
5585 this.edit(edits, None, cx);
5586 })
5587 }
5588 this.refresh_inline_completion(true, false, cx);
5589 linked_editing_ranges::refresh_linked_ranges(this, cx);
5590 });
5591 }
5592
5593 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5594 self.transact(cx, |this, cx| {
5595 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5596 let line_mode = s.line_mode;
5597 s.move_with(|map, selection| {
5598 if selection.is_empty() && !line_mode {
5599 let cursor = movement::right(map, selection.head());
5600 selection.end = cursor;
5601 selection.reversed = true;
5602 selection.goal = SelectionGoal::None;
5603 }
5604 })
5605 });
5606 this.insert("", cx);
5607 this.refresh_inline_completion(true, false, cx);
5608 });
5609 }
5610
5611 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5612 if self.move_to_prev_snippet_tabstop(cx) {
5613 return;
5614 }
5615
5616 self.outdent(&Outdent, cx);
5617 }
5618
5619 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5620 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5621 return;
5622 }
5623
5624 let mut selections = self.selections.all_adjusted(cx);
5625 let buffer = self.buffer.read(cx);
5626 let snapshot = buffer.snapshot(cx);
5627 let rows_iter = selections.iter().map(|s| s.head().row);
5628 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5629
5630 let mut edits = Vec::new();
5631 let mut prev_edited_row = 0;
5632 let mut row_delta = 0;
5633 for selection in &mut selections {
5634 if selection.start.row != prev_edited_row {
5635 row_delta = 0;
5636 }
5637 prev_edited_row = selection.end.row;
5638
5639 // If the selection is non-empty, then increase the indentation of the selected lines.
5640 if !selection.is_empty() {
5641 row_delta =
5642 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5643 continue;
5644 }
5645
5646 // If the selection is empty and the cursor is in the leading whitespace before the
5647 // suggested indentation, then auto-indent the line.
5648 let cursor = selection.head();
5649 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5650 if let Some(suggested_indent) =
5651 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5652 {
5653 if cursor.column < suggested_indent.len
5654 && cursor.column <= current_indent.len
5655 && current_indent.len <= suggested_indent.len
5656 {
5657 selection.start = Point::new(cursor.row, suggested_indent.len);
5658 selection.end = selection.start;
5659 if row_delta == 0 {
5660 edits.extend(Buffer::edit_for_indent_size_adjustment(
5661 cursor.row,
5662 current_indent,
5663 suggested_indent,
5664 ));
5665 row_delta = suggested_indent.len - current_indent.len;
5666 }
5667 continue;
5668 }
5669 }
5670
5671 // Otherwise, insert a hard or soft tab.
5672 let settings = buffer.settings_at(cursor, cx);
5673 let tab_size = if settings.hard_tabs {
5674 IndentSize::tab()
5675 } else {
5676 let tab_size = settings.tab_size.get();
5677 let char_column = snapshot
5678 .text_for_range(Point::new(cursor.row, 0)..cursor)
5679 .flat_map(str::chars)
5680 .count()
5681 + row_delta as usize;
5682 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5683 IndentSize::spaces(chars_to_next_tab_stop)
5684 };
5685 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5686 selection.end = selection.start;
5687 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5688 row_delta += tab_size.len;
5689 }
5690
5691 self.transact(cx, |this, cx| {
5692 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5693 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5694 this.refresh_inline_completion(true, false, cx);
5695 });
5696 }
5697
5698 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5699 if self.read_only(cx) {
5700 return;
5701 }
5702 let mut selections = self.selections.all::<Point>(cx);
5703 let mut prev_edited_row = 0;
5704 let mut row_delta = 0;
5705 let mut edits = Vec::new();
5706 let buffer = self.buffer.read(cx);
5707 let snapshot = buffer.snapshot(cx);
5708 for selection in &mut selections {
5709 if selection.start.row != prev_edited_row {
5710 row_delta = 0;
5711 }
5712 prev_edited_row = selection.end.row;
5713
5714 row_delta =
5715 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5716 }
5717
5718 self.transact(cx, |this, cx| {
5719 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5720 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5721 });
5722 }
5723
5724 fn indent_selection(
5725 buffer: &MultiBuffer,
5726 snapshot: &MultiBufferSnapshot,
5727 selection: &mut Selection<Point>,
5728 edits: &mut Vec<(Range<Point>, String)>,
5729 delta_for_start_row: u32,
5730 cx: &AppContext,
5731 ) -> u32 {
5732 let settings = buffer.settings_at(selection.start, cx);
5733 let tab_size = settings.tab_size.get();
5734 let indent_kind = if settings.hard_tabs {
5735 IndentKind::Tab
5736 } else {
5737 IndentKind::Space
5738 };
5739 let mut start_row = selection.start.row;
5740 let mut end_row = selection.end.row + 1;
5741
5742 // If a selection ends at the beginning of a line, don't indent
5743 // that last line.
5744 if selection.end.column == 0 && selection.end.row > selection.start.row {
5745 end_row -= 1;
5746 }
5747
5748 // Avoid re-indenting a row that has already been indented by a
5749 // previous selection, but still update this selection's column
5750 // to reflect that indentation.
5751 if delta_for_start_row > 0 {
5752 start_row += 1;
5753 selection.start.column += delta_for_start_row;
5754 if selection.end.row == selection.start.row {
5755 selection.end.column += delta_for_start_row;
5756 }
5757 }
5758
5759 let mut delta_for_end_row = 0;
5760 let has_multiple_rows = start_row + 1 != end_row;
5761 for row in start_row..end_row {
5762 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5763 let indent_delta = match (current_indent.kind, indent_kind) {
5764 (IndentKind::Space, IndentKind::Space) => {
5765 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5766 IndentSize::spaces(columns_to_next_tab_stop)
5767 }
5768 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5769 (_, IndentKind::Tab) => IndentSize::tab(),
5770 };
5771
5772 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5773 0
5774 } else {
5775 selection.start.column
5776 };
5777 let row_start = Point::new(row, start);
5778 edits.push((
5779 row_start..row_start,
5780 indent_delta.chars().collect::<String>(),
5781 ));
5782
5783 // Update this selection's endpoints to reflect the indentation.
5784 if row == selection.start.row {
5785 selection.start.column += indent_delta.len;
5786 }
5787 if row == selection.end.row {
5788 selection.end.column += indent_delta.len;
5789 delta_for_end_row = indent_delta.len;
5790 }
5791 }
5792
5793 if selection.start.row == selection.end.row {
5794 delta_for_start_row + delta_for_end_row
5795 } else {
5796 delta_for_end_row
5797 }
5798 }
5799
5800 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5801 if self.read_only(cx) {
5802 return;
5803 }
5804 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5805 let selections = self.selections.all::<Point>(cx);
5806 let mut deletion_ranges = Vec::new();
5807 let mut last_outdent = None;
5808 {
5809 let buffer = self.buffer.read(cx);
5810 let snapshot = buffer.snapshot(cx);
5811 for selection in &selections {
5812 let settings = buffer.settings_at(selection.start, cx);
5813 let tab_size = settings.tab_size.get();
5814 let mut rows = selection.spanned_rows(false, &display_map);
5815
5816 // Avoid re-outdenting a row that has already been outdented by a
5817 // previous selection.
5818 if let Some(last_row) = last_outdent {
5819 if last_row == rows.start {
5820 rows.start = rows.start.next_row();
5821 }
5822 }
5823 let has_multiple_rows = rows.len() > 1;
5824 for row in rows.iter_rows() {
5825 let indent_size = snapshot.indent_size_for_line(row);
5826 if indent_size.len > 0 {
5827 let deletion_len = match indent_size.kind {
5828 IndentKind::Space => {
5829 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5830 if columns_to_prev_tab_stop == 0 {
5831 tab_size
5832 } else {
5833 columns_to_prev_tab_stop
5834 }
5835 }
5836 IndentKind::Tab => 1,
5837 };
5838 let start = if has_multiple_rows
5839 || deletion_len > selection.start.column
5840 || indent_size.len < selection.start.column
5841 {
5842 0
5843 } else {
5844 selection.start.column - deletion_len
5845 };
5846 deletion_ranges.push(
5847 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5848 );
5849 last_outdent = Some(row);
5850 }
5851 }
5852 }
5853 }
5854
5855 self.transact(cx, |this, cx| {
5856 this.buffer.update(cx, |buffer, cx| {
5857 let empty_str: Arc<str> = Arc::default();
5858 buffer.edit(
5859 deletion_ranges
5860 .into_iter()
5861 .map(|range| (range, empty_str.clone())),
5862 None,
5863 cx,
5864 );
5865 });
5866 let selections = this.selections.all::<usize>(cx);
5867 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5868 });
5869 }
5870
5871 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5872 if self.read_only(cx) {
5873 return;
5874 }
5875 let selections = self
5876 .selections
5877 .all::<usize>(cx)
5878 .into_iter()
5879 .map(|s| s.range());
5880
5881 self.transact(cx, |this, cx| {
5882 this.buffer.update(cx, |buffer, cx| {
5883 buffer.autoindent_ranges(selections, cx);
5884 });
5885 let selections = this.selections.all::<usize>(cx);
5886 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5887 });
5888 }
5889
5890 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5891 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5892 let selections = self.selections.all::<Point>(cx);
5893
5894 let mut new_cursors = Vec::new();
5895 let mut edit_ranges = Vec::new();
5896 let mut selections = selections.iter().peekable();
5897 while let Some(selection) = selections.next() {
5898 let mut rows = selection.spanned_rows(false, &display_map);
5899 let goal_display_column = selection.head().to_display_point(&display_map).column();
5900
5901 // Accumulate contiguous regions of rows that we want to delete.
5902 while let Some(next_selection) = selections.peek() {
5903 let next_rows = next_selection.spanned_rows(false, &display_map);
5904 if next_rows.start <= rows.end {
5905 rows.end = next_rows.end;
5906 selections.next().unwrap();
5907 } else {
5908 break;
5909 }
5910 }
5911
5912 let buffer = &display_map.buffer_snapshot;
5913 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5914 let edit_end;
5915 let cursor_buffer_row;
5916 if buffer.max_point().row >= rows.end.0 {
5917 // If there's a line after the range, delete the \n from the end of the row range
5918 // and position the cursor on the next line.
5919 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5920 cursor_buffer_row = rows.end;
5921 } else {
5922 // If there isn't a line after the range, delete the \n from the line before the
5923 // start of the row range and position the cursor there.
5924 edit_start = edit_start.saturating_sub(1);
5925 edit_end = buffer.len();
5926 cursor_buffer_row = rows.start.previous_row();
5927 }
5928
5929 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5930 *cursor.column_mut() =
5931 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5932
5933 new_cursors.push((
5934 selection.id,
5935 buffer.anchor_after(cursor.to_point(&display_map)),
5936 ));
5937 edit_ranges.push(edit_start..edit_end);
5938 }
5939
5940 self.transact(cx, |this, cx| {
5941 let buffer = this.buffer.update(cx, |buffer, cx| {
5942 let empty_str: Arc<str> = Arc::default();
5943 buffer.edit(
5944 edit_ranges
5945 .into_iter()
5946 .map(|range| (range, empty_str.clone())),
5947 None,
5948 cx,
5949 );
5950 buffer.snapshot(cx)
5951 });
5952 let new_selections = new_cursors
5953 .into_iter()
5954 .map(|(id, cursor)| {
5955 let cursor = cursor.to_point(&buffer);
5956 Selection {
5957 id,
5958 start: cursor,
5959 end: cursor,
5960 reversed: false,
5961 goal: SelectionGoal::None,
5962 }
5963 })
5964 .collect();
5965
5966 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5967 s.select(new_selections);
5968 });
5969 });
5970 }
5971
5972 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5973 if self.read_only(cx) {
5974 return;
5975 }
5976 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5977 for selection in self.selections.all::<Point>(cx) {
5978 let start = MultiBufferRow(selection.start.row);
5979 // Treat single line selections as if they include the next line. Otherwise this action
5980 // would do nothing for single line selections individual cursors.
5981 let end = if selection.start.row == selection.end.row {
5982 MultiBufferRow(selection.start.row + 1)
5983 } else {
5984 MultiBufferRow(selection.end.row)
5985 };
5986
5987 if let Some(last_row_range) = row_ranges.last_mut() {
5988 if start <= last_row_range.end {
5989 last_row_range.end = end;
5990 continue;
5991 }
5992 }
5993 row_ranges.push(start..end);
5994 }
5995
5996 let snapshot = self.buffer.read(cx).snapshot(cx);
5997 let mut cursor_positions = Vec::new();
5998 for row_range in &row_ranges {
5999 let anchor = snapshot.anchor_before(Point::new(
6000 row_range.end.previous_row().0,
6001 snapshot.line_len(row_range.end.previous_row()),
6002 ));
6003 cursor_positions.push(anchor..anchor);
6004 }
6005
6006 self.transact(cx, |this, cx| {
6007 for row_range in row_ranges.into_iter().rev() {
6008 for row in row_range.iter_rows().rev() {
6009 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6010 let next_line_row = row.next_row();
6011 let indent = snapshot.indent_size_for_line(next_line_row);
6012 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6013
6014 let replace =
6015 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6016 " "
6017 } else {
6018 ""
6019 };
6020
6021 this.buffer.update(cx, |buffer, cx| {
6022 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6023 });
6024 }
6025 }
6026
6027 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6028 s.select_anchor_ranges(cursor_positions)
6029 });
6030 });
6031 }
6032
6033 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6034 self.join_lines_impl(true, cx);
6035 }
6036
6037 pub fn sort_lines_case_sensitive(
6038 &mut self,
6039 _: &SortLinesCaseSensitive,
6040 cx: &mut ViewContext<Self>,
6041 ) {
6042 self.manipulate_lines(cx, |lines| lines.sort())
6043 }
6044
6045 pub fn sort_lines_case_insensitive(
6046 &mut self,
6047 _: &SortLinesCaseInsensitive,
6048 cx: &mut ViewContext<Self>,
6049 ) {
6050 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6051 }
6052
6053 pub fn unique_lines_case_insensitive(
6054 &mut self,
6055 _: &UniqueLinesCaseInsensitive,
6056 cx: &mut ViewContext<Self>,
6057 ) {
6058 self.manipulate_lines(cx, |lines| {
6059 let mut seen = HashSet::default();
6060 lines.retain(|line| seen.insert(line.to_lowercase()));
6061 })
6062 }
6063
6064 pub fn unique_lines_case_sensitive(
6065 &mut self,
6066 _: &UniqueLinesCaseSensitive,
6067 cx: &mut ViewContext<Self>,
6068 ) {
6069 self.manipulate_lines(cx, |lines| {
6070 let mut seen = HashSet::default();
6071 lines.retain(|line| seen.insert(*line));
6072 })
6073 }
6074
6075 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6076 let mut revert_changes = HashMap::default();
6077 let snapshot = self.snapshot(cx);
6078 for hunk in hunks_for_ranges(
6079 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6080 &snapshot,
6081 ) {
6082 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6083 }
6084 if !revert_changes.is_empty() {
6085 self.transact(cx, |editor, cx| {
6086 editor.revert(revert_changes, cx);
6087 });
6088 }
6089 }
6090
6091 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6092 let Some(project) = self.project.clone() else {
6093 return;
6094 };
6095 self.reload(project, cx).detach_and_notify_err(cx);
6096 }
6097
6098 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6099 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6100 if !revert_changes.is_empty() {
6101 self.transact(cx, |editor, cx| {
6102 editor.revert(revert_changes, cx);
6103 });
6104 }
6105 }
6106
6107 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6108 let snapshot = self.buffer.read(cx).read(cx);
6109 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6110 drop(snapshot);
6111 let mut revert_changes = HashMap::default();
6112 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6113 if !revert_changes.is_empty() {
6114 self.revert(revert_changes, cx)
6115 }
6116 }
6117 }
6118
6119 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6120 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6121 let project_path = buffer.read(cx).project_path(cx)?;
6122 let project = self.project.as_ref()?.read(cx);
6123 let entry = project.entry_for_path(&project_path, cx)?;
6124 let parent = match &entry.canonical_path {
6125 Some(canonical_path) => canonical_path.to_path_buf(),
6126 None => project.absolute_path(&project_path, cx)?,
6127 }
6128 .parent()?
6129 .to_path_buf();
6130 Some(parent)
6131 }) {
6132 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6133 }
6134 }
6135
6136 fn gather_revert_changes(
6137 &mut self,
6138 selections: &[Selection<Point>],
6139 cx: &mut ViewContext<Editor>,
6140 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6141 let mut revert_changes = HashMap::default();
6142 let snapshot = self.snapshot(cx);
6143 for hunk in hunks_for_selections(&snapshot, selections) {
6144 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6145 }
6146 revert_changes
6147 }
6148
6149 pub fn prepare_revert_change(
6150 &mut self,
6151 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6152 hunk: &MultiBufferDiffHunk,
6153 cx: &AppContext,
6154 ) -> Option<()> {
6155 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6156 let buffer = buffer.read(cx);
6157 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6158 let original_text = change_set
6159 .read(cx)
6160 .base_text
6161 .as_ref()?
6162 .read(cx)
6163 .as_rope()
6164 .slice(hunk.diff_base_byte_range.clone());
6165 let buffer_snapshot = buffer.snapshot();
6166 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6167 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6168 probe
6169 .0
6170 .start
6171 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6172 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6173 }) {
6174 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6175 Some(())
6176 } else {
6177 None
6178 }
6179 }
6180
6181 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6182 self.manipulate_lines(cx, |lines| lines.reverse())
6183 }
6184
6185 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6186 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6187 }
6188
6189 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6190 where
6191 Fn: FnMut(&mut Vec<&str>),
6192 {
6193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6194 let buffer = self.buffer.read(cx).snapshot(cx);
6195
6196 let mut edits = Vec::new();
6197
6198 let selections = self.selections.all::<Point>(cx);
6199 let mut selections = selections.iter().peekable();
6200 let mut contiguous_row_selections = Vec::new();
6201 let mut new_selections = Vec::new();
6202 let mut added_lines = 0;
6203 let mut removed_lines = 0;
6204
6205 while let Some(selection) = selections.next() {
6206 let (start_row, end_row) = consume_contiguous_rows(
6207 &mut contiguous_row_selections,
6208 selection,
6209 &display_map,
6210 &mut selections,
6211 );
6212
6213 let start_point = Point::new(start_row.0, 0);
6214 let end_point = Point::new(
6215 end_row.previous_row().0,
6216 buffer.line_len(end_row.previous_row()),
6217 );
6218 let text = buffer
6219 .text_for_range(start_point..end_point)
6220 .collect::<String>();
6221
6222 let mut lines = text.split('\n').collect_vec();
6223
6224 let lines_before = lines.len();
6225 callback(&mut lines);
6226 let lines_after = lines.len();
6227
6228 edits.push((start_point..end_point, lines.join("\n")));
6229
6230 // Selections must change based on added and removed line count
6231 let start_row =
6232 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6233 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6234 new_selections.push(Selection {
6235 id: selection.id,
6236 start: start_row,
6237 end: end_row,
6238 goal: SelectionGoal::None,
6239 reversed: selection.reversed,
6240 });
6241
6242 if lines_after > lines_before {
6243 added_lines += lines_after - lines_before;
6244 } else if lines_before > lines_after {
6245 removed_lines += lines_before - lines_after;
6246 }
6247 }
6248
6249 self.transact(cx, |this, cx| {
6250 let buffer = this.buffer.update(cx, |buffer, cx| {
6251 buffer.edit(edits, None, cx);
6252 buffer.snapshot(cx)
6253 });
6254
6255 // Recalculate offsets on newly edited buffer
6256 let new_selections = new_selections
6257 .iter()
6258 .map(|s| {
6259 let start_point = Point::new(s.start.0, 0);
6260 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6261 Selection {
6262 id: s.id,
6263 start: buffer.point_to_offset(start_point),
6264 end: buffer.point_to_offset(end_point),
6265 goal: s.goal,
6266 reversed: s.reversed,
6267 }
6268 })
6269 .collect();
6270
6271 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6272 s.select(new_selections);
6273 });
6274
6275 this.request_autoscroll(Autoscroll::fit(), cx);
6276 });
6277 }
6278
6279 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6280 self.manipulate_text(cx, |text| text.to_uppercase())
6281 }
6282
6283 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6284 self.manipulate_text(cx, |text| text.to_lowercase())
6285 }
6286
6287 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6288 self.manipulate_text(cx, |text| {
6289 text.split('\n')
6290 .map(|line| line.to_case(Case::Title))
6291 .join("\n")
6292 })
6293 }
6294
6295 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6296 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6297 }
6298
6299 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6300 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6301 }
6302
6303 pub fn convert_to_upper_camel_case(
6304 &mut self,
6305 _: &ConvertToUpperCamelCase,
6306 cx: &mut ViewContext<Self>,
6307 ) {
6308 self.manipulate_text(cx, |text| {
6309 text.split('\n')
6310 .map(|line| line.to_case(Case::UpperCamel))
6311 .join("\n")
6312 })
6313 }
6314
6315 pub fn convert_to_lower_camel_case(
6316 &mut self,
6317 _: &ConvertToLowerCamelCase,
6318 cx: &mut ViewContext<Self>,
6319 ) {
6320 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6321 }
6322
6323 pub fn convert_to_opposite_case(
6324 &mut self,
6325 _: &ConvertToOppositeCase,
6326 cx: &mut ViewContext<Self>,
6327 ) {
6328 self.manipulate_text(cx, |text| {
6329 text.chars()
6330 .fold(String::with_capacity(text.len()), |mut t, c| {
6331 if c.is_uppercase() {
6332 t.extend(c.to_lowercase());
6333 } else {
6334 t.extend(c.to_uppercase());
6335 }
6336 t
6337 })
6338 })
6339 }
6340
6341 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6342 where
6343 Fn: FnMut(&str) -> String,
6344 {
6345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6346 let buffer = self.buffer.read(cx).snapshot(cx);
6347
6348 let mut new_selections = Vec::new();
6349 let mut edits = Vec::new();
6350 let mut selection_adjustment = 0i32;
6351
6352 for selection in self.selections.all::<usize>(cx) {
6353 let selection_is_empty = selection.is_empty();
6354
6355 let (start, end) = if selection_is_empty {
6356 let word_range = movement::surrounding_word(
6357 &display_map,
6358 selection.start.to_display_point(&display_map),
6359 );
6360 let start = word_range.start.to_offset(&display_map, Bias::Left);
6361 let end = word_range.end.to_offset(&display_map, Bias::Left);
6362 (start, end)
6363 } else {
6364 (selection.start, selection.end)
6365 };
6366
6367 let text = buffer.text_for_range(start..end).collect::<String>();
6368 let old_length = text.len() as i32;
6369 let text = callback(&text);
6370
6371 new_selections.push(Selection {
6372 start: (start as i32 - selection_adjustment) as usize,
6373 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6374 goal: SelectionGoal::None,
6375 ..selection
6376 });
6377
6378 selection_adjustment += old_length - text.len() as i32;
6379
6380 edits.push((start..end, text));
6381 }
6382
6383 self.transact(cx, |this, cx| {
6384 this.buffer.update(cx, |buffer, cx| {
6385 buffer.edit(edits, None, cx);
6386 });
6387
6388 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6389 s.select(new_selections);
6390 });
6391
6392 this.request_autoscroll(Autoscroll::fit(), cx);
6393 });
6394 }
6395
6396 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6397 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6398 let buffer = &display_map.buffer_snapshot;
6399 let selections = self.selections.all::<Point>(cx);
6400
6401 let mut edits = Vec::new();
6402 let mut selections_iter = selections.iter().peekable();
6403 while let Some(selection) = selections_iter.next() {
6404 let mut rows = selection.spanned_rows(false, &display_map);
6405 // duplicate line-wise
6406 if whole_lines || selection.start == selection.end {
6407 // Avoid duplicating the same lines twice.
6408 while let Some(next_selection) = selections_iter.peek() {
6409 let next_rows = next_selection.spanned_rows(false, &display_map);
6410 if next_rows.start < rows.end {
6411 rows.end = next_rows.end;
6412 selections_iter.next().unwrap();
6413 } else {
6414 break;
6415 }
6416 }
6417
6418 // Copy the text from the selected row region and splice it either at the start
6419 // or end of the region.
6420 let start = Point::new(rows.start.0, 0);
6421 let end = Point::new(
6422 rows.end.previous_row().0,
6423 buffer.line_len(rows.end.previous_row()),
6424 );
6425 let text = buffer
6426 .text_for_range(start..end)
6427 .chain(Some("\n"))
6428 .collect::<String>();
6429 let insert_location = if upwards {
6430 Point::new(rows.end.0, 0)
6431 } else {
6432 start
6433 };
6434 edits.push((insert_location..insert_location, text));
6435 } else {
6436 // duplicate character-wise
6437 let start = selection.start;
6438 let end = selection.end;
6439 let text = buffer.text_for_range(start..end).collect::<String>();
6440 edits.push((selection.end..selection.end, text));
6441 }
6442 }
6443
6444 self.transact(cx, |this, cx| {
6445 this.buffer.update(cx, |buffer, cx| {
6446 buffer.edit(edits, None, cx);
6447 });
6448
6449 this.request_autoscroll(Autoscroll::fit(), cx);
6450 });
6451 }
6452
6453 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6454 self.duplicate(true, true, cx);
6455 }
6456
6457 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6458 self.duplicate(false, true, cx);
6459 }
6460
6461 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6462 self.duplicate(false, false, cx);
6463 }
6464
6465 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6467 let buffer = self.buffer.read(cx).snapshot(cx);
6468
6469 let mut edits = Vec::new();
6470 let mut unfold_ranges = Vec::new();
6471 let mut refold_creases = Vec::new();
6472
6473 let selections = self.selections.all::<Point>(cx);
6474 let mut selections = selections.iter().peekable();
6475 let mut contiguous_row_selections = Vec::new();
6476 let mut new_selections = Vec::new();
6477
6478 while let Some(selection) = selections.next() {
6479 // Find all the selections that span a contiguous row range
6480 let (start_row, end_row) = consume_contiguous_rows(
6481 &mut contiguous_row_selections,
6482 selection,
6483 &display_map,
6484 &mut selections,
6485 );
6486
6487 // Move the text spanned by the row range to be before the line preceding the row range
6488 if start_row.0 > 0 {
6489 let range_to_move = Point::new(
6490 start_row.previous_row().0,
6491 buffer.line_len(start_row.previous_row()),
6492 )
6493 ..Point::new(
6494 end_row.previous_row().0,
6495 buffer.line_len(end_row.previous_row()),
6496 );
6497 let insertion_point = display_map
6498 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6499 .0;
6500
6501 // Don't move lines across excerpts
6502 if buffer
6503 .excerpt_boundaries_in_range((
6504 Bound::Excluded(insertion_point),
6505 Bound::Included(range_to_move.end),
6506 ))
6507 .next()
6508 .is_none()
6509 {
6510 let text = buffer
6511 .text_for_range(range_to_move.clone())
6512 .flat_map(|s| s.chars())
6513 .skip(1)
6514 .chain(['\n'])
6515 .collect::<String>();
6516
6517 edits.push((
6518 buffer.anchor_after(range_to_move.start)
6519 ..buffer.anchor_before(range_to_move.end),
6520 String::new(),
6521 ));
6522 let insertion_anchor = buffer.anchor_after(insertion_point);
6523 edits.push((insertion_anchor..insertion_anchor, text));
6524
6525 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6526
6527 // Move selections up
6528 new_selections.extend(contiguous_row_selections.drain(..).map(
6529 |mut selection| {
6530 selection.start.row -= row_delta;
6531 selection.end.row -= row_delta;
6532 selection
6533 },
6534 ));
6535
6536 // Move folds up
6537 unfold_ranges.push(range_to_move.clone());
6538 for fold in display_map.folds_in_range(
6539 buffer.anchor_before(range_to_move.start)
6540 ..buffer.anchor_after(range_to_move.end),
6541 ) {
6542 let mut start = fold.range.start.to_point(&buffer);
6543 let mut end = fold.range.end.to_point(&buffer);
6544 start.row -= row_delta;
6545 end.row -= row_delta;
6546 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6547 }
6548 }
6549 }
6550
6551 // If we didn't move line(s), preserve the existing selections
6552 new_selections.append(&mut contiguous_row_selections);
6553 }
6554
6555 self.transact(cx, |this, cx| {
6556 this.unfold_ranges(&unfold_ranges, true, true, cx);
6557 this.buffer.update(cx, |buffer, cx| {
6558 for (range, text) in edits {
6559 buffer.edit([(range, text)], None, cx);
6560 }
6561 });
6562 this.fold_creases(refold_creases, true, cx);
6563 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6564 s.select(new_selections);
6565 })
6566 });
6567 }
6568
6569 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6571 let buffer = self.buffer.read(cx).snapshot(cx);
6572
6573 let mut edits = Vec::new();
6574 let mut unfold_ranges = Vec::new();
6575 let mut refold_creases = Vec::new();
6576
6577 let selections = self.selections.all::<Point>(cx);
6578 let mut selections = selections.iter().peekable();
6579 let mut contiguous_row_selections = Vec::new();
6580 let mut new_selections = Vec::new();
6581
6582 while let Some(selection) = selections.next() {
6583 // Find all the selections that span a contiguous row range
6584 let (start_row, end_row) = consume_contiguous_rows(
6585 &mut contiguous_row_selections,
6586 selection,
6587 &display_map,
6588 &mut selections,
6589 );
6590
6591 // Move the text spanned by the row range to be after the last line of the row range
6592 if end_row.0 <= buffer.max_point().row {
6593 let range_to_move =
6594 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6595 let insertion_point = display_map
6596 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6597 .0;
6598
6599 // Don't move lines across excerpt boundaries
6600 if buffer
6601 .excerpt_boundaries_in_range((
6602 Bound::Excluded(range_to_move.start),
6603 Bound::Included(insertion_point),
6604 ))
6605 .next()
6606 .is_none()
6607 {
6608 let mut text = String::from("\n");
6609 text.extend(buffer.text_for_range(range_to_move.clone()));
6610 text.pop(); // Drop trailing newline
6611 edits.push((
6612 buffer.anchor_after(range_to_move.start)
6613 ..buffer.anchor_before(range_to_move.end),
6614 String::new(),
6615 ));
6616 let insertion_anchor = buffer.anchor_after(insertion_point);
6617 edits.push((insertion_anchor..insertion_anchor, text));
6618
6619 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6620
6621 // Move selections down
6622 new_selections.extend(contiguous_row_selections.drain(..).map(
6623 |mut selection| {
6624 selection.start.row += row_delta;
6625 selection.end.row += row_delta;
6626 selection
6627 },
6628 ));
6629
6630 // Move folds down
6631 unfold_ranges.push(range_to_move.clone());
6632 for fold in display_map.folds_in_range(
6633 buffer.anchor_before(range_to_move.start)
6634 ..buffer.anchor_after(range_to_move.end),
6635 ) {
6636 let mut start = fold.range.start.to_point(&buffer);
6637 let mut end = fold.range.end.to_point(&buffer);
6638 start.row += row_delta;
6639 end.row += row_delta;
6640 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6641 }
6642 }
6643 }
6644
6645 // If we didn't move line(s), preserve the existing selections
6646 new_selections.append(&mut contiguous_row_selections);
6647 }
6648
6649 self.transact(cx, |this, cx| {
6650 this.unfold_ranges(&unfold_ranges, true, true, cx);
6651 this.buffer.update(cx, |buffer, cx| {
6652 for (range, text) in edits {
6653 buffer.edit([(range, text)], None, cx);
6654 }
6655 });
6656 this.fold_creases(refold_creases, true, cx);
6657 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6658 });
6659 }
6660
6661 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6662 let text_layout_details = &self.text_layout_details(cx);
6663 self.transact(cx, |this, cx| {
6664 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6665 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6666 let line_mode = s.line_mode;
6667 s.move_with(|display_map, selection| {
6668 if !selection.is_empty() || line_mode {
6669 return;
6670 }
6671
6672 let mut head = selection.head();
6673 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6674 if head.column() == display_map.line_len(head.row()) {
6675 transpose_offset = display_map
6676 .buffer_snapshot
6677 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6678 }
6679
6680 if transpose_offset == 0 {
6681 return;
6682 }
6683
6684 *head.column_mut() += 1;
6685 head = display_map.clip_point(head, Bias::Right);
6686 let goal = SelectionGoal::HorizontalPosition(
6687 display_map
6688 .x_for_display_point(head, text_layout_details)
6689 .into(),
6690 );
6691 selection.collapse_to(head, goal);
6692
6693 let transpose_start = display_map
6694 .buffer_snapshot
6695 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6696 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6697 let transpose_end = display_map
6698 .buffer_snapshot
6699 .clip_offset(transpose_offset + 1, Bias::Right);
6700 if let Some(ch) =
6701 display_map.buffer_snapshot.chars_at(transpose_start).next()
6702 {
6703 edits.push((transpose_start..transpose_offset, String::new()));
6704 edits.push((transpose_end..transpose_end, ch.to_string()));
6705 }
6706 }
6707 });
6708 edits
6709 });
6710 this.buffer
6711 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6712 let selections = this.selections.all::<usize>(cx);
6713 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6714 s.select(selections);
6715 });
6716 });
6717 }
6718
6719 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6720 self.rewrap_impl(IsVimMode::No, cx)
6721 }
6722
6723 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6724 let buffer = self.buffer.read(cx).snapshot(cx);
6725 let selections = self.selections.all::<Point>(cx);
6726 let mut selections = selections.iter().peekable();
6727
6728 let mut edits = Vec::new();
6729 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6730
6731 while let Some(selection) = selections.next() {
6732 let mut start_row = selection.start.row;
6733 let mut end_row = selection.end.row;
6734
6735 // Skip selections that overlap with a range that has already been rewrapped.
6736 let selection_range = start_row..end_row;
6737 if rewrapped_row_ranges
6738 .iter()
6739 .any(|range| range.overlaps(&selection_range))
6740 {
6741 continue;
6742 }
6743
6744 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6745
6746 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6747 match language_scope.language_name().0.as_ref() {
6748 "Markdown" | "Plain Text" => {
6749 should_rewrap = true;
6750 }
6751 _ => {}
6752 }
6753 }
6754
6755 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6756
6757 // Since not all lines in the selection may be at the same indent
6758 // level, choose the indent size that is the most common between all
6759 // of the lines.
6760 //
6761 // If there is a tie, we use the deepest indent.
6762 let (indent_size, indent_end) = {
6763 let mut indent_size_occurrences = HashMap::default();
6764 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6765
6766 for row in start_row..=end_row {
6767 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6768 rows_by_indent_size.entry(indent).or_default().push(row);
6769 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6770 }
6771
6772 let indent_size = indent_size_occurrences
6773 .into_iter()
6774 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6775 .map(|(indent, _)| indent)
6776 .unwrap_or_default();
6777 let row = rows_by_indent_size[&indent_size][0];
6778 let indent_end = Point::new(row, indent_size.len);
6779
6780 (indent_size, indent_end)
6781 };
6782
6783 let mut line_prefix = indent_size.chars().collect::<String>();
6784
6785 if let Some(comment_prefix) =
6786 buffer
6787 .language_scope_at(selection.head())
6788 .and_then(|language| {
6789 language
6790 .line_comment_prefixes()
6791 .iter()
6792 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6793 .cloned()
6794 })
6795 {
6796 line_prefix.push_str(&comment_prefix);
6797 should_rewrap = true;
6798 }
6799
6800 if !should_rewrap {
6801 continue;
6802 }
6803
6804 if selection.is_empty() {
6805 'expand_upwards: while start_row > 0 {
6806 let prev_row = start_row - 1;
6807 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6808 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6809 {
6810 start_row = prev_row;
6811 } else {
6812 break 'expand_upwards;
6813 }
6814 }
6815
6816 'expand_downwards: while end_row < buffer.max_point().row {
6817 let next_row = end_row + 1;
6818 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6819 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6820 {
6821 end_row = next_row;
6822 } else {
6823 break 'expand_downwards;
6824 }
6825 }
6826 }
6827
6828 let start = Point::new(start_row, 0);
6829 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6830 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6831 let Some(lines_without_prefixes) = selection_text
6832 .lines()
6833 .map(|line| {
6834 line.strip_prefix(&line_prefix)
6835 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6836 .ok_or_else(|| {
6837 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6838 })
6839 })
6840 .collect::<Result<Vec<_>, _>>()
6841 .log_err()
6842 else {
6843 continue;
6844 };
6845
6846 let wrap_column = buffer
6847 .settings_at(Point::new(start_row, 0), cx)
6848 .preferred_line_length as usize;
6849 let wrapped_text = wrap_with_prefix(
6850 line_prefix,
6851 lines_without_prefixes.join(" "),
6852 wrap_column,
6853 tab_size,
6854 );
6855
6856 // TODO: should always use char-based diff while still supporting cursor behavior that
6857 // matches vim.
6858 let diff = match is_vim_mode {
6859 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6860 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6861 };
6862 let mut offset = start.to_offset(&buffer);
6863 let mut moved_since_edit = true;
6864
6865 for change in diff.iter_all_changes() {
6866 let value = change.value();
6867 match change.tag() {
6868 ChangeTag::Equal => {
6869 offset += value.len();
6870 moved_since_edit = true;
6871 }
6872 ChangeTag::Delete => {
6873 let start = buffer.anchor_after(offset);
6874 let end = buffer.anchor_before(offset + value.len());
6875
6876 if moved_since_edit {
6877 edits.push((start..end, String::new()));
6878 } else {
6879 edits.last_mut().unwrap().0.end = end;
6880 }
6881
6882 offset += value.len();
6883 moved_since_edit = false;
6884 }
6885 ChangeTag::Insert => {
6886 if moved_since_edit {
6887 let anchor = buffer.anchor_after(offset);
6888 edits.push((anchor..anchor, value.to_string()));
6889 } else {
6890 edits.last_mut().unwrap().1.push_str(value);
6891 }
6892
6893 moved_since_edit = false;
6894 }
6895 }
6896 }
6897
6898 rewrapped_row_ranges.push(start_row..=end_row);
6899 }
6900
6901 self.buffer
6902 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6903 }
6904
6905 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6906 let mut text = String::new();
6907 let buffer = self.buffer.read(cx).snapshot(cx);
6908 let mut selections = self.selections.all::<Point>(cx);
6909 let mut clipboard_selections = Vec::with_capacity(selections.len());
6910 {
6911 let max_point = buffer.max_point();
6912 let mut is_first = true;
6913 for selection in &mut selections {
6914 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6915 if is_entire_line {
6916 selection.start = Point::new(selection.start.row, 0);
6917 if !selection.is_empty() && selection.end.column == 0 {
6918 selection.end = cmp::min(max_point, selection.end);
6919 } else {
6920 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6921 }
6922 selection.goal = SelectionGoal::None;
6923 }
6924 if is_first {
6925 is_first = false;
6926 } else {
6927 text += "\n";
6928 }
6929 let mut len = 0;
6930 for chunk in buffer.text_for_range(selection.start..selection.end) {
6931 text.push_str(chunk);
6932 len += chunk.len();
6933 }
6934 clipboard_selections.push(ClipboardSelection {
6935 len,
6936 is_entire_line,
6937 first_line_indent: buffer
6938 .indent_size_for_line(MultiBufferRow(selection.start.row))
6939 .len,
6940 });
6941 }
6942 }
6943
6944 self.transact(cx, |this, cx| {
6945 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6946 s.select(selections);
6947 });
6948 this.insert("", cx);
6949 });
6950 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6951 }
6952
6953 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6954 let item = self.cut_common(cx);
6955 cx.write_to_clipboard(item);
6956 }
6957
6958 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6959 self.change_selections(None, cx, |s| {
6960 s.move_with(|snapshot, sel| {
6961 if sel.is_empty() {
6962 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6963 }
6964 });
6965 });
6966 let item = self.cut_common(cx);
6967 cx.set_global(KillRing(item))
6968 }
6969
6970 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6971 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6972 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6973 (kill_ring.text().to_string(), kill_ring.metadata_json())
6974 } else {
6975 return;
6976 }
6977 } else {
6978 return;
6979 };
6980 self.do_paste(&text, metadata, false, cx);
6981 }
6982
6983 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6984 let selections = self.selections.all::<Point>(cx);
6985 let buffer = self.buffer.read(cx).read(cx);
6986 let mut text = String::new();
6987
6988 let mut clipboard_selections = Vec::with_capacity(selections.len());
6989 {
6990 let max_point = buffer.max_point();
6991 let mut is_first = true;
6992 for selection in selections.iter() {
6993 let mut start = selection.start;
6994 let mut end = selection.end;
6995 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6996 if is_entire_line {
6997 start = Point::new(start.row, 0);
6998 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6999 }
7000 if is_first {
7001 is_first = false;
7002 } else {
7003 text += "\n";
7004 }
7005 let mut len = 0;
7006 for chunk in buffer.text_for_range(start..end) {
7007 text.push_str(chunk);
7008 len += chunk.len();
7009 }
7010 clipboard_selections.push(ClipboardSelection {
7011 len,
7012 is_entire_line,
7013 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7014 });
7015 }
7016 }
7017
7018 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7019 text,
7020 clipboard_selections,
7021 ));
7022 }
7023
7024 pub fn do_paste(
7025 &mut self,
7026 text: &String,
7027 clipboard_selections: Option<Vec<ClipboardSelection>>,
7028 handle_entire_lines: bool,
7029 cx: &mut ViewContext<Self>,
7030 ) {
7031 if self.read_only(cx) {
7032 return;
7033 }
7034
7035 let clipboard_text = Cow::Borrowed(text);
7036
7037 self.transact(cx, |this, cx| {
7038 if let Some(mut clipboard_selections) = clipboard_selections {
7039 let old_selections = this.selections.all::<usize>(cx);
7040 let all_selections_were_entire_line =
7041 clipboard_selections.iter().all(|s| s.is_entire_line);
7042 let first_selection_indent_column =
7043 clipboard_selections.first().map(|s| s.first_line_indent);
7044 if clipboard_selections.len() != old_selections.len() {
7045 clipboard_selections.drain(..);
7046 }
7047 let cursor_offset = this.selections.last::<usize>(cx).head();
7048 let mut auto_indent_on_paste = true;
7049
7050 this.buffer.update(cx, |buffer, cx| {
7051 let snapshot = buffer.read(cx);
7052 auto_indent_on_paste =
7053 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7054
7055 let mut start_offset = 0;
7056 let mut edits = Vec::new();
7057 let mut original_indent_columns = Vec::new();
7058 for (ix, selection) in old_selections.iter().enumerate() {
7059 let to_insert;
7060 let entire_line;
7061 let original_indent_column;
7062 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7063 let end_offset = start_offset + clipboard_selection.len;
7064 to_insert = &clipboard_text[start_offset..end_offset];
7065 entire_line = clipboard_selection.is_entire_line;
7066 start_offset = end_offset + 1;
7067 original_indent_column = Some(clipboard_selection.first_line_indent);
7068 } else {
7069 to_insert = clipboard_text.as_str();
7070 entire_line = all_selections_were_entire_line;
7071 original_indent_column = first_selection_indent_column
7072 }
7073
7074 // If the corresponding selection was empty when this slice of the
7075 // clipboard text was written, then the entire line containing the
7076 // selection was copied. If this selection is also currently empty,
7077 // then paste the line before the current line of the buffer.
7078 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7079 let column = selection.start.to_point(&snapshot).column as usize;
7080 let line_start = selection.start - column;
7081 line_start..line_start
7082 } else {
7083 selection.range()
7084 };
7085
7086 edits.push((range, to_insert));
7087 original_indent_columns.extend(original_indent_column);
7088 }
7089 drop(snapshot);
7090
7091 buffer.edit(
7092 edits,
7093 if auto_indent_on_paste {
7094 Some(AutoindentMode::Block {
7095 original_indent_columns,
7096 })
7097 } else {
7098 None
7099 },
7100 cx,
7101 );
7102 });
7103
7104 let selections = this.selections.all::<usize>(cx);
7105 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7106 } else {
7107 this.insert(&clipboard_text, cx);
7108 }
7109 });
7110 }
7111
7112 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7113 if let Some(item) = cx.read_from_clipboard() {
7114 let entries = item.entries();
7115
7116 match entries.first() {
7117 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7118 // of all the pasted entries.
7119 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7120 .do_paste(
7121 clipboard_string.text(),
7122 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7123 true,
7124 cx,
7125 ),
7126 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7127 }
7128 }
7129 }
7130
7131 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7132 if self.read_only(cx) {
7133 return;
7134 }
7135
7136 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7137 if let Some((selections, _)) =
7138 self.selection_history.transaction(transaction_id).cloned()
7139 {
7140 self.change_selections(None, cx, |s| {
7141 s.select_anchors(selections.to_vec());
7142 });
7143 }
7144 self.request_autoscroll(Autoscroll::fit(), cx);
7145 self.unmark_text(cx);
7146 self.refresh_inline_completion(true, false, cx);
7147 cx.emit(EditorEvent::Edited { transaction_id });
7148 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7149 }
7150 }
7151
7152 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7153 if self.read_only(cx) {
7154 return;
7155 }
7156
7157 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7158 if let Some((_, Some(selections))) =
7159 self.selection_history.transaction(transaction_id).cloned()
7160 {
7161 self.change_selections(None, cx, |s| {
7162 s.select_anchors(selections.to_vec());
7163 });
7164 }
7165 self.request_autoscroll(Autoscroll::fit(), cx);
7166 self.unmark_text(cx);
7167 self.refresh_inline_completion(true, false, cx);
7168 cx.emit(EditorEvent::Edited { transaction_id });
7169 }
7170 }
7171
7172 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7173 self.buffer
7174 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7175 }
7176
7177 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7178 self.buffer
7179 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7180 }
7181
7182 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7183 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7184 let line_mode = s.line_mode;
7185 s.move_with(|map, selection| {
7186 let cursor = if selection.is_empty() && !line_mode {
7187 movement::left(map, selection.start)
7188 } else {
7189 selection.start
7190 };
7191 selection.collapse_to(cursor, SelectionGoal::None);
7192 });
7193 })
7194 }
7195
7196 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7197 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7198 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7199 })
7200 }
7201
7202 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7203 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7204 let line_mode = s.line_mode;
7205 s.move_with(|map, selection| {
7206 let cursor = if selection.is_empty() && !line_mode {
7207 movement::right(map, selection.end)
7208 } else {
7209 selection.end
7210 };
7211 selection.collapse_to(cursor, SelectionGoal::None)
7212 });
7213 })
7214 }
7215
7216 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7217 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7218 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7219 })
7220 }
7221
7222 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7223 if self.take_rename(true, cx).is_some() {
7224 return;
7225 }
7226
7227 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7228 cx.propagate();
7229 return;
7230 }
7231
7232 let text_layout_details = &self.text_layout_details(cx);
7233 let selection_count = self.selections.count();
7234 let first_selection = self.selections.first_anchor();
7235
7236 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7237 let line_mode = s.line_mode;
7238 s.move_with(|map, selection| {
7239 if !selection.is_empty() && !line_mode {
7240 selection.goal = SelectionGoal::None;
7241 }
7242 let (cursor, goal) = movement::up(
7243 map,
7244 selection.start,
7245 selection.goal,
7246 false,
7247 text_layout_details,
7248 );
7249 selection.collapse_to(cursor, goal);
7250 });
7251 });
7252
7253 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7254 {
7255 cx.propagate();
7256 }
7257 }
7258
7259 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7260 if self.take_rename(true, cx).is_some() {
7261 return;
7262 }
7263
7264 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7265 cx.propagate();
7266 return;
7267 }
7268
7269 let text_layout_details = &self.text_layout_details(cx);
7270
7271 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7272 let line_mode = s.line_mode;
7273 s.move_with(|map, selection| {
7274 if !selection.is_empty() && !line_mode {
7275 selection.goal = SelectionGoal::None;
7276 }
7277 let (cursor, goal) = movement::up_by_rows(
7278 map,
7279 selection.start,
7280 action.lines,
7281 selection.goal,
7282 false,
7283 text_layout_details,
7284 );
7285 selection.collapse_to(cursor, goal);
7286 });
7287 })
7288 }
7289
7290 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7291 if self.take_rename(true, cx).is_some() {
7292 return;
7293 }
7294
7295 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7296 cx.propagate();
7297 return;
7298 }
7299
7300 let text_layout_details = &self.text_layout_details(cx);
7301
7302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7303 let line_mode = s.line_mode;
7304 s.move_with(|map, selection| {
7305 if !selection.is_empty() && !line_mode {
7306 selection.goal = SelectionGoal::None;
7307 }
7308 let (cursor, goal) = movement::down_by_rows(
7309 map,
7310 selection.start,
7311 action.lines,
7312 selection.goal,
7313 false,
7314 text_layout_details,
7315 );
7316 selection.collapse_to(cursor, goal);
7317 });
7318 })
7319 }
7320
7321 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7322 let text_layout_details = &self.text_layout_details(cx);
7323 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7324 s.move_heads_with(|map, head, goal| {
7325 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7326 })
7327 })
7328 }
7329
7330 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7331 let text_layout_details = &self.text_layout_details(cx);
7332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7333 s.move_heads_with(|map, head, goal| {
7334 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7335 })
7336 })
7337 }
7338
7339 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7340 let Some(row_count) = self.visible_row_count() else {
7341 return;
7342 };
7343
7344 let text_layout_details = &self.text_layout_details(cx);
7345
7346 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7347 s.move_heads_with(|map, head, goal| {
7348 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7349 })
7350 })
7351 }
7352
7353 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7354 if self.take_rename(true, cx).is_some() {
7355 return;
7356 }
7357
7358 if self
7359 .context_menu
7360 .borrow_mut()
7361 .as_mut()
7362 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7363 .unwrap_or(false)
7364 {
7365 return;
7366 }
7367
7368 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7369 cx.propagate();
7370 return;
7371 }
7372
7373 let Some(row_count) = self.visible_row_count() else {
7374 return;
7375 };
7376
7377 let autoscroll = if action.center_cursor {
7378 Autoscroll::center()
7379 } else {
7380 Autoscroll::fit()
7381 };
7382
7383 let text_layout_details = &self.text_layout_details(cx);
7384
7385 self.change_selections(Some(autoscroll), cx, |s| {
7386 let line_mode = s.line_mode;
7387 s.move_with(|map, selection| {
7388 if !selection.is_empty() && !line_mode {
7389 selection.goal = SelectionGoal::None;
7390 }
7391 let (cursor, goal) = movement::up_by_rows(
7392 map,
7393 selection.end,
7394 row_count,
7395 selection.goal,
7396 false,
7397 text_layout_details,
7398 );
7399 selection.collapse_to(cursor, goal);
7400 });
7401 });
7402 }
7403
7404 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7405 let text_layout_details = &self.text_layout_details(cx);
7406 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7407 s.move_heads_with(|map, head, goal| {
7408 movement::up(map, head, goal, false, text_layout_details)
7409 })
7410 })
7411 }
7412
7413 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7414 self.take_rename(true, cx);
7415
7416 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7417 cx.propagate();
7418 return;
7419 }
7420
7421 let text_layout_details = &self.text_layout_details(cx);
7422 let selection_count = self.selections.count();
7423 let first_selection = self.selections.first_anchor();
7424
7425 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7426 let line_mode = s.line_mode;
7427 s.move_with(|map, selection| {
7428 if !selection.is_empty() && !line_mode {
7429 selection.goal = SelectionGoal::None;
7430 }
7431 let (cursor, goal) = movement::down(
7432 map,
7433 selection.end,
7434 selection.goal,
7435 false,
7436 text_layout_details,
7437 );
7438 selection.collapse_to(cursor, goal);
7439 });
7440 });
7441
7442 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7443 {
7444 cx.propagate();
7445 }
7446 }
7447
7448 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7449 let Some(row_count) = self.visible_row_count() else {
7450 return;
7451 };
7452
7453 let text_layout_details = &self.text_layout_details(cx);
7454
7455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7456 s.move_heads_with(|map, head, goal| {
7457 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7458 })
7459 })
7460 }
7461
7462 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7463 if self.take_rename(true, cx).is_some() {
7464 return;
7465 }
7466
7467 if self
7468 .context_menu
7469 .borrow_mut()
7470 .as_mut()
7471 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7472 .unwrap_or(false)
7473 {
7474 return;
7475 }
7476
7477 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7478 cx.propagate();
7479 return;
7480 }
7481
7482 let Some(row_count) = self.visible_row_count() else {
7483 return;
7484 };
7485
7486 let autoscroll = if action.center_cursor {
7487 Autoscroll::center()
7488 } else {
7489 Autoscroll::fit()
7490 };
7491
7492 let text_layout_details = &self.text_layout_details(cx);
7493 self.change_selections(Some(autoscroll), cx, |s| {
7494 let line_mode = s.line_mode;
7495 s.move_with(|map, selection| {
7496 if !selection.is_empty() && !line_mode {
7497 selection.goal = SelectionGoal::None;
7498 }
7499 let (cursor, goal) = movement::down_by_rows(
7500 map,
7501 selection.end,
7502 row_count,
7503 selection.goal,
7504 false,
7505 text_layout_details,
7506 );
7507 selection.collapse_to(cursor, goal);
7508 });
7509 });
7510 }
7511
7512 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7513 let text_layout_details = &self.text_layout_details(cx);
7514 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7515 s.move_heads_with(|map, head, goal| {
7516 movement::down(map, head, goal, false, text_layout_details)
7517 })
7518 });
7519 }
7520
7521 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7522 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7523 context_menu.select_first(self.completion_provider.as_deref(), cx);
7524 }
7525 }
7526
7527 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7528 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7529 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7530 }
7531 }
7532
7533 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7534 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7535 context_menu.select_next(self.completion_provider.as_deref(), cx);
7536 }
7537 }
7538
7539 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7540 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7541 context_menu.select_last(self.completion_provider.as_deref(), cx);
7542 }
7543 }
7544
7545 pub fn move_to_previous_word_start(
7546 &mut self,
7547 _: &MoveToPreviousWordStart,
7548 cx: &mut ViewContext<Self>,
7549 ) {
7550 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7551 s.move_cursors_with(|map, head, _| {
7552 (
7553 movement::previous_word_start(map, head),
7554 SelectionGoal::None,
7555 )
7556 });
7557 })
7558 }
7559
7560 pub fn move_to_previous_subword_start(
7561 &mut self,
7562 _: &MoveToPreviousSubwordStart,
7563 cx: &mut ViewContext<Self>,
7564 ) {
7565 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7566 s.move_cursors_with(|map, head, _| {
7567 (
7568 movement::previous_subword_start(map, head),
7569 SelectionGoal::None,
7570 )
7571 });
7572 })
7573 }
7574
7575 pub fn select_to_previous_word_start(
7576 &mut self,
7577 _: &SelectToPreviousWordStart,
7578 cx: &mut ViewContext<Self>,
7579 ) {
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 s.move_heads_with(|map, head, _| {
7582 (
7583 movement::previous_word_start(map, head),
7584 SelectionGoal::None,
7585 )
7586 });
7587 })
7588 }
7589
7590 pub fn select_to_previous_subword_start(
7591 &mut self,
7592 _: &SelectToPreviousSubwordStart,
7593 cx: &mut ViewContext<Self>,
7594 ) {
7595 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7596 s.move_heads_with(|map, head, _| {
7597 (
7598 movement::previous_subword_start(map, head),
7599 SelectionGoal::None,
7600 )
7601 });
7602 })
7603 }
7604
7605 pub fn delete_to_previous_word_start(
7606 &mut self,
7607 action: &DeleteToPreviousWordStart,
7608 cx: &mut ViewContext<Self>,
7609 ) {
7610 self.transact(cx, |this, cx| {
7611 this.select_autoclose_pair(cx);
7612 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7613 let line_mode = s.line_mode;
7614 s.move_with(|map, selection| {
7615 if selection.is_empty() && !line_mode {
7616 let cursor = if action.ignore_newlines {
7617 movement::previous_word_start(map, selection.head())
7618 } else {
7619 movement::previous_word_start_or_newline(map, selection.head())
7620 };
7621 selection.set_head(cursor, SelectionGoal::None);
7622 }
7623 });
7624 });
7625 this.insert("", cx);
7626 });
7627 }
7628
7629 pub fn delete_to_previous_subword_start(
7630 &mut self,
7631 _: &DeleteToPreviousSubwordStart,
7632 cx: &mut ViewContext<Self>,
7633 ) {
7634 self.transact(cx, |this, cx| {
7635 this.select_autoclose_pair(cx);
7636 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7637 let line_mode = s.line_mode;
7638 s.move_with(|map, selection| {
7639 if selection.is_empty() && !line_mode {
7640 let cursor = movement::previous_subword_start(map, selection.head());
7641 selection.set_head(cursor, SelectionGoal::None);
7642 }
7643 });
7644 });
7645 this.insert("", cx);
7646 });
7647 }
7648
7649 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7651 s.move_cursors_with(|map, head, _| {
7652 (movement::next_word_end(map, head), SelectionGoal::None)
7653 });
7654 })
7655 }
7656
7657 pub fn move_to_next_subword_end(
7658 &mut self,
7659 _: &MoveToNextSubwordEnd,
7660 cx: &mut ViewContext<Self>,
7661 ) {
7662 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 s.move_cursors_with(|map, head, _| {
7664 (movement::next_subword_end(map, head), SelectionGoal::None)
7665 });
7666 })
7667 }
7668
7669 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7670 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7671 s.move_heads_with(|map, head, _| {
7672 (movement::next_word_end(map, head), SelectionGoal::None)
7673 });
7674 })
7675 }
7676
7677 pub fn select_to_next_subword_end(
7678 &mut self,
7679 _: &SelectToNextSubwordEnd,
7680 cx: &mut ViewContext<Self>,
7681 ) {
7682 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7683 s.move_heads_with(|map, head, _| {
7684 (movement::next_subword_end(map, head), SelectionGoal::None)
7685 });
7686 })
7687 }
7688
7689 pub fn delete_to_next_word_end(
7690 &mut self,
7691 action: &DeleteToNextWordEnd,
7692 cx: &mut ViewContext<Self>,
7693 ) {
7694 self.transact(cx, |this, cx| {
7695 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7696 let line_mode = s.line_mode;
7697 s.move_with(|map, selection| {
7698 if selection.is_empty() && !line_mode {
7699 let cursor = if action.ignore_newlines {
7700 movement::next_word_end(map, selection.head())
7701 } else {
7702 movement::next_word_end_or_newline(map, selection.head())
7703 };
7704 selection.set_head(cursor, SelectionGoal::None);
7705 }
7706 });
7707 });
7708 this.insert("", cx);
7709 });
7710 }
7711
7712 pub fn delete_to_next_subword_end(
7713 &mut self,
7714 _: &DeleteToNextSubwordEnd,
7715 cx: &mut ViewContext<Self>,
7716 ) {
7717 self.transact(cx, |this, cx| {
7718 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7719 s.move_with(|map, selection| {
7720 if selection.is_empty() {
7721 let cursor = movement::next_subword_end(map, selection.head());
7722 selection.set_head(cursor, SelectionGoal::None);
7723 }
7724 });
7725 });
7726 this.insert("", cx);
7727 });
7728 }
7729
7730 pub fn move_to_beginning_of_line(
7731 &mut self,
7732 action: &MoveToBeginningOfLine,
7733 cx: &mut ViewContext<Self>,
7734 ) {
7735 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7736 s.move_cursors_with(|map, head, _| {
7737 (
7738 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7739 SelectionGoal::None,
7740 )
7741 });
7742 })
7743 }
7744
7745 pub fn select_to_beginning_of_line(
7746 &mut self,
7747 action: &SelectToBeginningOfLine,
7748 cx: &mut ViewContext<Self>,
7749 ) {
7750 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 s.move_heads_with(|map, head, _| {
7752 (
7753 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7754 SelectionGoal::None,
7755 )
7756 });
7757 });
7758 }
7759
7760 pub fn delete_to_beginning_of_line(
7761 &mut self,
7762 _: &DeleteToBeginningOfLine,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 self.transact(cx, |this, cx| {
7766 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7767 s.move_with(|_, selection| {
7768 selection.reversed = true;
7769 });
7770 });
7771
7772 this.select_to_beginning_of_line(
7773 &SelectToBeginningOfLine {
7774 stop_at_soft_wraps: false,
7775 },
7776 cx,
7777 );
7778 this.backspace(&Backspace, cx);
7779 });
7780 }
7781
7782 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7783 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7784 s.move_cursors_with(|map, head, _| {
7785 (
7786 movement::line_end(map, head, action.stop_at_soft_wraps),
7787 SelectionGoal::None,
7788 )
7789 });
7790 })
7791 }
7792
7793 pub fn select_to_end_of_line(
7794 &mut self,
7795 action: &SelectToEndOfLine,
7796 cx: &mut ViewContext<Self>,
7797 ) {
7798 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7799 s.move_heads_with(|map, head, _| {
7800 (
7801 movement::line_end(map, head, action.stop_at_soft_wraps),
7802 SelectionGoal::None,
7803 )
7804 });
7805 })
7806 }
7807
7808 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7809 self.transact(cx, |this, cx| {
7810 this.select_to_end_of_line(
7811 &SelectToEndOfLine {
7812 stop_at_soft_wraps: false,
7813 },
7814 cx,
7815 );
7816 this.delete(&Delete, cx);
7817 });
7818 }
7819
7820 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7821 self.transact(cx, |this, cx| {
7822 this.select_to_end_of_line(
7823 &SelectToEndOfLine {
7824 stop_at_soft_wraps: false,
7825 },
7826 cx,
7827 );
7828 this.cut(&Cut, cx);
7829 });
7830 }
7831
7832 pub fn move_to_start_of_paragraph(
7833 &mut self,
7834 _: &MoveToStartOfParagraph,
7835 cx: &mut ViewContext<Self>,
7836 ) {
7837 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7838 cx.propagate();
7839 return;
7840 }
7841
7842 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7843 s.move_with(|map, selection| {
7844 selection.collapse_to(
7845 movement::start_of_paragraph(map, selection.head(), 1),
7846 SelectionGoal::None,
7847 )
7848 });
7849 })
7850 }
7851
7852 pub fn move_to_end_of_paragraph(
7853 &mut self,
7854 _: &MoveToEndOfParagraph,
7855 cx: &mut ViewContext<Self>,
7856 ) {
7857 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7858 cx.propagate();
7859 return;
7860 }
7861
7862 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7863 s.move_with(|map, selection| {
7864 selection.collapse_to(
7865 movement::end_of_paragraph(map, selection.head(), 1),
7866 SelectionGoal::None,
7867 )
7868 });
7869 })
7870 }
7871
7872 pub fn select_to_start_of_paragraph(
7873 &mut self,
7874 _: &SelectToStartOfParagraph,
7875 cx: &mut ViewContext<Self>,
7876 ) {
7877 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7878 cx.propagate();
7879 return;
7880 }
7881
7882 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7883 s.move_heads_with(|map, head, _| {
7884 (
7885 movement::start_of_paragraph(map, head, 1),
7886 SelectionGoal::None,
7887 )
7888 });
7889 })
7890 }
7891
7892 pub fn select_to_end_of_paragraph(
7893 &mut self,
7894 _: &SelectToEndOfParagraph,
7895 cx: &mut ViewContext<Self>,
7896 ) {
7897 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7898 cx.propagate();
7899 return;
7900 }
7901
7902 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7903 s.move_heads_with(|map, head, _| {
7904 (
7905 movement::end_of_paragraph(map, head, 1),
7906 SelectionGoal::None,
7907 )
7908 });
7909 })
7910 }
7911
7912 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7913 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7914 cx.propagate();
7915 return;
7916 }
7917
7918 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7919 s.select_ranges(vec![0..0]);
7920 });
7921 }
7922
7923 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7924 let mut selection = self.selections.last::<Point>(cx);
7925 selection.set_head(Point::zero(), SelectionGoal::None);
7926
7927 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7928 s.select(vec![selection]);
7929 });
7930 }
7931
7932 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7933 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7934 cx.propagate();
7935 return;
7936 }
7937
7938 let cursor = self.buffer.read(cx).read(cx).len();
7939 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7940 s.select_ranges(vec![cursor..cursor])
7941 });
7942 }
7943
7944 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7945 self.nav_history = nav_history;
7946 }
7947
7948 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7949 self.nav_history.as_ref()
7950 }
7951
7952 fn push_to_nav_history(
7953 &mut self,
7954 cursor_anchor: Anchor,
7955 new_position: Option<Point>,
7956 cx: &mut ViewContext<Self>,
7957 ) {
7958 if let Some(nav_history) = self.nav_history.as_mut() {
7959 let buffer = self.buffer.read(cx).read(cx);
7960 let cursor_position = cursor_anchor.to_point(&buffer);
7961 let scroll_state = self.scroll_manager.anchor();
7962 let scroll_top_row = scroll_state.top_row(&buffer);
7963 drop(buffer);
7964
7965 if let Some(new_position) = new_position {
7966 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7967 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7968 return;
7969 }
7970 }
7971
7972 nav_history.push(
7973 Some(NavigationData {
7974 cursor_anchor,
7975 cursor_position,
7976 scroll_anchor: scroll_state,
7977 scroll_top_row,
7978 }),
7979 cx,
7980 );
7981 }
7982 }
7983
7984 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7985 let buffer = self.buffer.read(cx).snapshot(cx);
7986 let mut selection = self.selections.first::<usize>(cx);
7987 selection.set_head(buffer.len(), SelectionGoal::None);
7988 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7989 s.select(vec![selection]);
7990 });
7991 }
7992
7993 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7994 let end = self.buffer.read(cx).read(cx).len();
7995 self.change_selections(None, cx, |s| {
7996 s.select_ranges(vec![0..end]);
7997 });
7998 }
7999
8000 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8001 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8002 let mut selections = self.selections.all::<Point>(cx);
8003 let max_point = display_map.buffer_snapshot.max_point();
8004 for selection in &mut selections {
8005 let rows = selection.spanned_rows(true, &display_map);
8006 selection.start = Point::new(rows.start.0, 0);
8007 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8008 selection.reversed = false;
8009 }
8010 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8011 s.select(selections);
8012 });
8013 }
8014
8015 pub fn split_selection_into_lines(
8016 &mut self,
8017 _: &SplitSelectionIntoLines,
8018 cx: &mut ViewContext<Self>,
8019 ) {
8020 let mut to_unfold = Vec::new();
8021 let mut new_selection_ranges = Vec::new();
8022 {
8023 let selections = self.selections.all::<Point>(cx);
8024 let buffer = self.buffer.read(cx).read(cx);
8025 for selection in selections {
8026 for row in selection.start.row..selection.end.row {
8027 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8028 new_selection_ranges.push(cursor..cursor);
8029 }
8030 new_selection_ranges.push(selection.end..selection.end);
8031 to_unfold.push(selection.start..selection.end);
8032 }
8033 }
8034 self.unfold_ranges(&to_unfold, true, true, cx);
8035 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8036 s.select_ranges(new_selection_ranges);
8037 });
8038 }
8039
8040 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8041 self.add_selection(true, cx);
8042 }
8043
8044 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8045 self.add_selection(false, cx);
8046 }
8047
8048 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8049 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8050 let mut selections = self.selections.all::<Point>(cx);
8051 let text_layout_details = self.text_layout_details(cx);
8052 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8053 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8054 let range = oldest_selection.display_range(&display_map).sorted();
8055
8056 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8057 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8058 let positions = start_x.min(end_x)..start_x.max(end_x);
8059
8060 selections.clear();
8061 let mut stack = Vec::new();
8062 for row in range.start.row().0..=range.end.row().0 {
8063 if let Some(selection) = self.selections.build_columnar_selection(
8064 &display_map,
8065 DisplayRow(row),
8066 &positions,
8067 oldest_selection.reversed,
8068 &text_layout_details,
8069 ) {
8070 stack.push(selection.id);
8071 selections.push(selection);
8072 }
8073 }
8074
8075 if above {
8076 stack.reverse();
8077 }
8078
8079 AddSelectionsState { above, stack }
8080 });
8081
8082 let last_added_selection = *state.stack.last().unwrap();
8083 let mut new_selections = Vec::new();
8084 if above == state.above {
8085 let end_row = if above {
8086 DisplayRow(0)
8087 } else {
8088 display_map.max_point().row()
8089 };
8090
8091 'outer: for selection in selections {
8092 if selection.id == last_added_selection {
8093 let range = selection.display_range(&display_map).sorted();
8094 debug_assert_eq!(range.start.row(), range.end.row());
8095 let mut row = range.start.row();
8096 let positions =
8097 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8098 px(start)..px(end)
8099 } else {
8100 let start_x =
8101 display_map.x_for_display_point(range.start, &text_layout_details);
8102 let end_x =
8103 display_map.x_for_display_point(range.end, &text_layout_details);
8104 start_x.min(end_x)..start_x.max(end_x)
8105 };
8106
8107 while row != end_row {
8108 if above {
8109 row.0 -= 1;
8110 } else {
8111 row.0 += 1;
8112 }
8113
8114 if let Some(new_selection) = self.selections.build_columnar_selection(
8115 &display_map,
8116 row,
8117 &positions,
8118 selection.reversed,
8119 &text_layout_details,
8120 ) {
8121 state.stack.push(new_selection.id);
8122 if above {
8123 new_selections.push(new_selection);
8124 new_selections.push(selection);
8125 } else {
8126 new_selections.push(selection);
8127 new_selections.push(new_selection);
8128 }
8129
8130 continue 'outer;
8131 }
8132 }
8133 }
8134
8135 new_selections.push(selection);
8136 }
8137 } else {
8138 new_selections = selections;
8139 new_selections.retain(|s| s.id != last_added_selection);
8140 state.stack.pop();
8141 }
8142
8143 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8144 s.select(new_selections);
8145 });
8146 if state.stack.len() > 1 {
8147 self.add_selections_state = Some(state);
8148 }
8149 }
8150
8151 pub fn select_next_match_internal(
8152 &mut self,
8153 display_map: &DisplaySnapshot,
8154 replace_newest: bool,
8155 autoscroll: Option<Autoscroll>,
8156 cx: &mut ViewContext<Self>,
8157 ) -> Result<()> {
8158 fn select_next_match_ranges(
8159 this: &mut Editor,
8160 range: Range<usize>,
8161 replace_newest: bool,
8162 auto_scroll: Option<Autoscroll>,
8163 cx: &mut ViewContext<Editor>,
8164 ) {
8165 this.unfold_ranges(&[range.clone()], false, true, cx);
8166 this.change_selections(auto_scroll, cx, |s| {
8167 if replace_newest {
8168 s.delete(s.newest_anchor().id);
8169 }
8170 s.insert_range(range.clone());
8171 });
8172 }
8173
8174 let buffer = &display_map.buffer_snapshot;
8175 let mut selections = self.selections.all::<usize>(cx);
8176 if let Some(mut select_next_state) = self.select_next_state.take() {
8177 let query = &select_next_state.query;
8178 if !select_next_state.done {
8179 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8180 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8181 let mut next_selected_range = None;
8182
8183 let bytes_after_last_selection =
8184 buffer.bytes_in_range(last_selection.end..buffer.len());
8185 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8186 let query_matches = query
8187 .stream_find_iter(bytes_after_last_selection)
8188 .map(|result| (last_selection.end, result))
8189 .chain(
8190 query
8191 .stream_find_iter(bytes_before_first_selection)
8192 .map(|result| (0, result)),
8193 );
8194
8195 for (start_offset, query_match) in query_matches {
8196 let query_match = query_match.unwrap(); // can only fail due to I/O
8197 let offset_range =
8198 start_offset + query_match.start()..start_offset + query_match.end();
8199 let display_range = offset_range.start.to_display_point(display_map)
8200 ..offset_range.end.to_display_point(display_map);
8201
8202 if !select_next_state.wordwise
8203 || (!movement::is_inside_word(display_map, display_range.start)
8204 && !movement::is_inside_word(display_map, display_range.end))
8205 {
8206 // TODO: This is n^2, because we might check all the selections
8207 if !selections
8208 .iter()
8209 .any(|selection| selection.range().overlaps(&offset_range))
8210 {
8211 next_selected_range = Some(offset_range);
8212 break;
8213 }
8214 }
8215 }
8216
8217 if let Some(next_selected_range) = next_selected_range {
8218 select_next_match_ranges(
8219 self,
8220 next_selected_range,
8221 replace_newest,
8222 autoscroll,
8223 cx,
8224 );
8225 } else {
8226 select_next_state.done = true;
8227 }
8228 }
8229
8230 self.select_next_state = Some(select_next_state);
8231 } else {
8232 let mut only_carets = true;
8233 let mut same_text_selected = true;
8234 let mut selected_text = None;
8235
8236 let mut selections_iter = selections.iter().peekable();
8237 while let Some(selection) = selections_iter.next() {
8238 if selection.start != selection.end {
8239 only_carets = false;
8240 }
8241
8242 if same_text_selected {
8243 if selected_text.is_none() {
8244 selected_text =
8245 Some(buffer.text_for_range(selection.range()).collect::<String>());
8246 }
8247
8248 if let Some(next_selection) = selections_iter.peek() {
8249 if next_selection.range().len() == selection.range().len() {
8250 let next_selected_text = buffer
8251 .text_for_range(next_selection.range())
8252 .collect::<String>();
8253 if Some(next_selected_text) != selected_text {
8254 same_text_selected = false;
8255 selected_text = None;
8256 }
8257 } else {
8258 same_text_selected = false;
8259 selected_text = None;
8260 }
8261 }
8262 }
8263 }
8264
8265 if only_carets {
8266 for selection in &mut selections {
8267 let word_range = movement::surrounding_word(
8268 display_map,
8269 selection.start.to_display_point(display_map),
8270 );
8271 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8272 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8273 selection.goal = SelectionGoal::None;
8274 selection.reversed = false;
8275 select_next_match_ranges(
8276 self,
8277 selection.start..selection.end,
8278 replace_newest,
8279 autoscroll,
8280 cx,
8281 );
8282 }
8283
8284 if selections.len() == 1 {
8285 let selection = selections
8286 .last()
8287 .expect("ensured that there's only one selection");
8288 let query = buffer
8289 .text_for_range(selection.start..selection.end)
8290 .collect::<String>();
8291 let is_empty = query.is_empty();
8292 let select_state = SelectNextState {
8293 query: AhoCorasick::new(&[query])?,
8294 wordwise: true,
8295 done: is_empty,
8296 };
8297 self.select_next_state = Some(select_state);
8298 } else {
8299 self.select_next_state = None;
8300 }
8301 } else if let Some(selected_text) = selected_text {
8302 self.select_next_state = Some(SelectNextState {
8303 query: AhoCorasick::new(&[selected_text])?,
8304 wordwise: false,
8305 done: false,
8306 });
8307 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8308 }
8309 }
8310 Ok(())
8311 }
8312
8313 pub fn select_all_matches(
8314 &mut self,
8315 _action: &SelectAllMatches,
8316 cx: &mut ViewContext<Self>,
8317 ) -> Result<()> {
8318 self.push_to_selection_history();
8319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8320
8321 self.select_next_match_internal(&display_map, false, None, cx)?;
8322 let Some(select_next_state) = self.select_next_state.as_mut() else {
8323 return Ok(());
8324 };
8325 if select_next_state.done {
8326 return Ok(());
8327 }
8328
8329 let mut new_selections = self.selections.all::<usize>(cx);
8330
8331 let buffer = &display_map.buffer_snapshot;
8332 let query_matches = select_next_state
8333 .query
8334 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8335
8336 for query_match in query_matches {
8337 let query_match = query_match.unwrap(); // can only fail due to I/O
8338 let offset_range = query_match.start()..query_match.end();
8339 let display_range = offset_range.start.to_display_point(&display_map)
8340 ..offset_range.end.to_display_point(&display_map);
8341
8342 if !select_next_state.wordwise
8343 || (!movement::is_inside_word(&display_map, display_range.start)
8344 && !movement::is_inside_word(&display_map, display_range.end))
8345 {
8346 self.selections.change_with(cx, |selections| {
8347 new_selections.push(Selection {
8348 id: selections.new_selection_id(),
8349 start: offset_range.start,
8350 end: offset_range.end,
8351 reversed: false,
8352 goal: SelectionGoal::None,
8353 });
8354 });
8355 }
8356 }
8357
8358 new_selections.sort_by_key(|selection| selection.start);
8359 let mut ix = 0;
8360 while ix + 1 < new_selections.len() {
8361 let current_selection = &new_selections[ix];
8362 let next_selection = &new_selections[ix + 1];
8363 if current_selection.range().overlaps(&next_selection.range()) {
8364 if current_selection.id < next_selection.id {
8365 new_selections.remove(ix + 1);
8366 } else {
8367 new_selections.remove(ix);
8368 }
8369 } else {
8370 ix += 1;
8371 }
8372 }
8373
8374 select_next_state.done = true;
8375 self.unfold_ranges(
8376 &new_selections
8377 .iter()
8378 .map(|selection| selection.range())
8379 .collect::<Vec<_>>(),
8380 false,
8381 false,
8382 cx,
8383 );
8384 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8385 selections.select(new_selections)
8386 });
8387
8388 Ok(())
8389 }
8390
8391 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8392 self.push_to_selection_history();
8393 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8394 self.select_next_match_internal(
8395 &display_map,
8396 action.replace_newest,
8397 Some(Autoscroll::newest()),
8398 cx,
8399 )?;
8400 Ok(())
8401 }
8402
8403 pub fn select_previous(
8404 &mut self,
8405 action: &SelectPrevious,
8406 cx: &mut ViewContext<Self>,
8407 ) -> Result<()> {
8408 self.push_to_selection_history();
8409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8410 let buffer = &display_map.buffer_snapshot;
8411 let mut selections = self.selections.all::<usize>(cx);
8412 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8413 let query = &select_prev_state.query;
8414 if !select_prev_state.done {
8415 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8416 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8417 let mut next_selected_range = None;
8418 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8419 let bytes_before_last_selection =
8420 buffer.reversed_bytes_in_range(0..last_selection.start);
8421 let bytes_after_first_selection =
8422 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8423 let query_matches = query
8424 .stream_find_iter(bytes_before_last_selection)
8425 .map(|result| (last_selection.start, result))
8426 .chain(
8427 query
8428 .stream_find_iter(bytes_after_first_selection)
8429 .map(|result| (buffer.len(), result)),
8430 );
8431 for (end_offset, query_match) in query_matches {
8432 let query_match = query_match.unwrap(); // can only fail due to I/O
8433 let offset_range =
8434 end_offset - query_match.end()..end_offset - query_match.start();
8435 let display_range = offset_range.start.to_display_point(&display_map)
8436 ..offset_range.end.to_display_point(&display_map);
8437
8438 if !select_prev_state.wordwise
8439 || (!movement::is_inside_word(&display_map, display_range.start)
8440 && !movement::is_inside_word(&display_map, display_range.end))
8441 {
8442 next_selected_range = Some(offset_range);
8443 break;
8444 }
8445 }
8446
8447 if let Some(next_selected_range) = next_selected_range {
8448 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8449 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8450 if action.replace_newest {
8451 s.delete(s.newest_anchor().id);
8452 }
8453 s.insert_range(next_selected_range);
8454 });
8455 } else {
8456 select_prev_state.done = true;
8457 }
8458 }
8459
8460 self.select_prev_state = Some(select_prev_state);
8461 } else {
8462 let mut only_carets = true;
8463 let mut same_text_selected = true;
8464 let mut selected_text = None;
8465
8466 let mut selections_iter = selections.iter().peekable();
8467 while let Some(selection) = selections_iter.next() {
8468 if selection.start != selection.end {
8469 only_carets = false;
8470 }
8471
8472 if same_text_selected {
8473 if selected_text.is_none() {
8474 selected_text =
8475 Some(buffer.text_for_range(selection.range()).collect::<String>());
8476 }
8477
8478 if let Some(next_selection) = selections_iter.peek() {
8479 if next_selection.range().len() == selection.range().len() {
8480 let next_selected_text = buffer
8481 .text_for_range(next_selection.range())
8482 .collect::<String>();
8483 if Some(next_selected_text) != selected_text {
8484 same_text_selected = false;
8485 selected_text = None;
8486 }
8487 } else {
8488 same_text_selected = false;
8489 selected_text = None;
8490 }
8491 }
8492 }
8493 }
8494
8495 if only_carets {
8496 for selection in &mut selections {
8497 let word_range = movement::surrounding_word(
8498 &display_map,
8499 selection.start.to_display_point(&display_map),
8500 );
8501 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8502 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8503 selection.goal = SelectionGoal::None;
8504 selection.reversed = false;
8505 }
8506 if selections.len() == 1 {
8507 let selection = selections
8508 .last()
8509 .expect("ensured that there's only one selection");
8510 let query = buffer
8511 .text_for_range(selection.start..selection.end)
8512 .collect::<String>();
8513 let is_empty = query.is_empty();
8514 let select_state = SelectNextState {
8515 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8516 wordwise: true,
8517 done: is_empty,
8518 };
8519 self.select_prev_state = Some(select_state);
8520 } else {
8521 self.select_prev_state = None;
8522 }
8523
8524 self.unfold_ranges(
8525 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8526 false,
8527 true,
8528 cx,
8529 );
8530 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8531 s.select(selections);
8532 });
8533 } else if let Some(selected_text) = selected_text {
8534 self.select_prev_state = Some(SelectNextState {
8535 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8536 wordwise: false,
8537 done: false,
8538 });
8539 self.select_previous(action, cx)?;
8540 }
8541 }
8542 Ok(())
8543 }
8544
8545 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8546 if self.read_only(cx) {
8547 return;
8548 }
8549 let text_layout_details = &self.text_layout_details(cx);
8550 self.transact(cx, |this, cx| {
8551 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8552 let mut edits = Vec::new();
8553 let mut selection_edit_ranges = Vec::new();
8554 let mut last_toggled_row = None;
8555 let snapshot = this.buffer.read(cx).read(cx);
8556 let empty_str: Arc<str> = Arc::default();
8557 let mut suffixes_inserted = Vec::new();
8558 let ignore_indent = action.ignore_indent;
8559
8560 fn comment_prefix_range(
8561 snapshot: &MultiBufferSnapshot,
8562 row: MultiBufferRow,
8563 comment_prefix: &str,
8564 comment_prefix_whitespace: &str,
8565 ignore_indent: bool,
8566 ) -> Range<Point> {
8567 let indent_size = if ignore_indent {
8568 0
8569 } else {
8570 snapshot.indent_size_for_line(row).len
8571 };
8572
8573 let start = Point::new(row.0, indent_size);
8574
8575 let mut line_bytes = snapshot
8576 .bytes_in_range(start..snapshot.max_point())
8577 .flatten()
8578 .copied();
8579
8580 // If this line currently begins with the line comment prefix, then record
8581 // the range containing the prefix.
8582 if line_bytes
8583 .by_ref()
8584 .take(comment_prefix.len())
8585 .eq(comment_prefix.bytes())
8586 {
8587 // Include any whitespace that matches the comment prefix.
8588 let matching_whitespace_len = line_bytes
8589 .zip(comment_prefix_whitespace.bytes())
8590 .take_while(|(a, b)| a == b)
8591 .count() as u32;
8592 let end = Point::new(
8593 start.row,
8594 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8595 );
8596 start..end
8597 } else {
8598 start..start
8599 }
8600 }
8601
8602 fn comment_suffix_range(
8603 snapshot: &MultiBufferSnapshot,
8604 row: MultiBufferRow,
8605 comment_suffix: &str,
8606 comment_suffix_has_leading_space: bool,
8607 ) -> Range<Point> {
8608 let end = Point::new(row.0, snapshot.line_len(row));
8609 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8610
8611 let mut line_end_bytes = snapshot
8612 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8613 .flatten()
8614 .copied();
8615
8616 let leading_space_len = if suffix_start_column > 0
8617 && line_end_bytes.next() == Some(b' ')
8618 && comment_suffix_has_leading_space
8619 {
8620 1
8621 } else {
8622 0
8623 };
8624
8625 // If this line currently begins with the line comment prefix, then record
8626 // the range containing the prefix.
8627 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8628 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8629 start..end
8630 } else {
8631 end..end
8632 }
8633 }
8634
8635 // TODO: Handle selections that cross excerpts
8636 for selection in &mut selections {
8637 let start_column = snapshot
8638 .indent_size_for_line(MultiBufferRow(selection.start.row))
8639 .len;
8640 let language = if let Some(language) =
8641 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8642 {
8643 language
8644 } else {
8645 continue;
8646 };
8647
8648 selection_edit_ranges.clear();
8649
8650 // If multiple selections contain a given row, avoid processing that
8651 // row more than once.
8652 let mut start_row = MultiBufferRow(selection.start.row);
8653 if last_toggled_row == Some(start_row) {
8654 start_row = start_row.next_row();
8655 }
8656 let end_row =
8657 if selection.end.row > selection.start.row && selection.end.column == 0 {
8658 MultiBufferRow(selection.end.row - 1)
8659 } else {
8660 MultiBufferRow(selection.end.row)
8661 };
8662 last_toggled_row = Some(end_row);
8663
8664 if start_row > end_row {
8665 continue;
8666 }
8667
8668 // If the language has line comments, toggle those.
8669 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8670
8671 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8672 if ignore_indent {
8673 full_comment_prefixes = full_comment_prefixes
8674 .into_iter()
8675 .map(|s| Arc::from(s.trim_end()))
8676 .collect();
8677 }
8678
8679 if !full_comment_prefixes.is_empty() {
8680 let first_prefix = full_comment_prefixes
8681 .first()
8682 .expect("prefixes is non-empty");
8683 let prefix_trimmed_lengths = full_comment_prefixes
8684 .iter()
8685 .map(|p| p.trim_end_matches(' ').len())
8686 .collect::<SmallVec<[usize; 4]>>();
8687
8688 let mut all_selection_lines_are_comments = true;
8689
8690 for row in start_row.0..=end_row.0 {
8691 let row = MultiBufferRow(row);
8692 if start_row < end_row && snapshot.is_line_blank(row) {
8693 continue;
8694 }
8695
8696 let prefix_range = full_comment_prefixes
8697 .iter()
8698 .zip(prefix_trimmed_lengths.iter().copied())
8699 .map(|(prefix, trimmed_prefix_len)| {
8700 comment_prefix_range(
8701 snapshot.deref(),
8702 row,
8703 &prefix[..trimmed_prefix_len],
8704 &prefix[trimmed_prefix_len..],
8705 ignore_indent,
8706 )
8707 })
8708 .max_by_key(|range| range.end.column - range.start.column)
8709 .expect("prefixes is non-empty");
8710
8711 if prefix_range.is_empty() {
8712 all_selection_lines_are_comments = false;
8713 }
8714
8715 selection_edit_ranges.push(prefix_range);
8716 }
8717
8718 if all_selection_lines_are_comments {
8719 edits.extend(
8720 selection_edit_ranges
8721 .iter()
8722 .cloned()
8723 .map(|range| (range, empty_str.clone())),
8724 );
8725 } else {
8726 let min_column = selection_edit_ranges
8727 .iter()
8728 .map(|range| range.start.column)
8729 .min()
8730 .unwrap_or(0);
8731 edits.extend(selection_edit_ranges.iter().map(|range| {
8732 let position = Point::new(range.start.row, min_column);
8733 (position..position, first_prefix.clone())
8734 }));
8735 }
8736 } else if let Some((full_comment_prefix, comment_suffix)) =
8737 language.block_comment_delimiters()
8738 {
8739 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8740 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8741 let prefix_range = comment_prefix_range(
8742 snapshot.deref(),
8743 start_row,
8744 comment_prefix,
8745 comment_prefix_whitespace,
8746 ignore_indent,
8747 );
8748 let suffix_range = comment_suffix_range(
8749 snapshot.deref(),
8750 end_row,
8751 comment_suffix.trim_start_matches(' '),
8752 comment_suffix.starts_with(' '),
8753 );
8754
8755 if prefix_range.is_empty() || suffix_range.is_empty() {
8756 edits.push((
8757 prefix_range.start..prefix_range.start,
8758 full_comment_prefix.clone(),
8759 ));
8760 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8761 suffixes_inserted.push((end_row, comment_suffix.len()));
8762 } else {
8763 edits.push((prefix_range, empty_str.clone()));
8764 edits.push((suffix_range, empty_str.clone()));
8765 }
8766 } else {
8767 continue;
8768 }
8769 }
8770
8771 drop(snapshot);
8772 this.buffer.update(cx, |buffer, cx| {
8773 buffer.edit(edits, None, cx);
8774 });
8775
8776 // Adjust selections so that they end before any comment suffixes that
8777 // were inserted.
8778 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8779 let mut selections = this.selections.all::<Point>(cx);
8780 let snapshot = this.buffer.read(cx).read(cx);
8781 for selection in &mut selections {
8782 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8783 match row.cmp(&MultiBufferRow(selection.end.row)) {
8784 Ordering::Less => {
8785 suffixes_inserted.next();
8786 continue;
8787 }
8788 Ordering::Greater => break,
8789 Ordering::Equal => {
8790 if selection.end.column == snapshot.line_len(row) {
8791 if selection.is_empty() {
8792 selection.start.column -= suffix_len as u32;
8793 }
8794 selection.end.column -= suffix_len as u32;
8795 }
8796 break;
8797 }
8798 }
8799 }
8800 }
8801
8802 drop(snapshot);
8803 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8804
8805 let selections = this.selections.all::<Point>(cx);
8806 let selections_on_single_row = selections.windows(2).all(|selections| {
8807 selections[0].start.row == selections[1].start.row
8808 && selections[0].end.row == selections[1].end.row
8809 && selections[0].start.row == selections[0].end.row
8810 });
8811 let selections_selecting = selections
8812 .iter()
8813 .any(|selection| selection.start != selection.end);
8814 let advance_downwards = action.advance_downwards
8815 && selections_on_single_row
8816 && !selections_selecting
8817 && !matches!(this.mode, EditorMode::SingleLine { .. });
8818
8819 if advance_downwards {
8820 let snapshot = this.buffer.read(cx).snapshot(cx);
8821
8822 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8823 s.move_cursors_with(|display_snapshot, display_point, _| {
8824 let mut point = display_point.to_point(display_snapshot);
8825 point.row += 1;
8826 point = snapshot.clip_point(point, Bias::Left);
8827 let display_point = point.to_display_point(display_snapshot);
8828 let goal = SelectionGoal::HorizontalPosition(
8829 display_snapshot
8830 .x_for_display_point(display_point, text_layout_details)
8831 .into(),
8832 );
8833 (display_point, goal)
8834 })
8835 });
8836 }
8837 });
8838 }
8839
8840 pub fn select_enclosing_symbol(
8841 &mut self,
8842 _: &SelectEnclosingSymbol,
8843 cx: &mut ViewContext<Self>,
8844 ) {
8845 let buffer = self.buffer.read(cx).snapshot(cx);
8846 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8847
8848 fn update_selection(
8849 selection: &Selection<usize>,
8850 buffer_snap: &MultiBufferSnapshot,
8851 ) -> Option<Selection<usize>> {
8852 let cursor = selection.head();
8853 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8854 for symbol in symbols.iter().rev() {
8855 let start = symbol.range.start.to_offset(buffer_snap);
8856 let end = symbol.range.end.to_offset(buffer_snap);
8857 let new_range = start..end;
8858 if start < selection.start || end > selection.end {
8859 return Some(Selection {
8860 id: selection.id,
8861 start: new_range.start,
8862 end: new_range.end,
8863 goal: SelectionGoal::None,
8864 reversed: selection.reversed,
8865 });
8866 }
8867 }
8868 None
8869 }
8870
8871 let mut selected_larger_symbol = false;
8872 let new_selections = old_selections
8873 .iter()
8874 .map(|selection| match update_selection(selection, &buffer) {
8875 Some(new_selection) => {
8876 if new_selection.range() != selection.range() {
8877 selected_larger_symbol = true;
8878 }
8879 new_selection
8880 }
8881 None => selection.clone(),
8882 })
8883 .collect::<Vec<_>>();
8884
8885 if selected_larger_symbol {
8886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8887 s.select(new_selections);
8888 });
8889 }
8890 }
8891
8892 pub fn select_larger_syntax_node(
8893 &mut self,
8894 _: &SelectLargerSyntaxNode,
8895 cx: &mut ViewContext<Self>,
8896 ) {
8897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8898 let buffer = self.buffer.read(cx).snapshot(cx);
8899 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8900
8901 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8902 let mut selected_larger_node = false;
8903 let new_selections = old_selections
8904 .iter()
8905 .map(|selection| {
8906 let old_range = selection.start..selection.end;
8907 let mut new_range = old_range.clone();
8908 let mut new_node = None;
8909 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8910 {
8911 new_node = Some(node);
8912 new_range = containing_range;
8913 if !display_map.intersects_fold(new_range.start)
8914 && !display_map.intersects_fold(new_range.end)
8915 {
8916 break;
8917 }
8918 }
8919
8920 if let Some(node) = new_node {
8921 // Log the ancestor, to support using this action as a way to explore TreeSitter
8922 // nodes. Parent and grandparent are also logged because this operation will not
8923 // visit nodes that have the same range as their parent.
8924 log::info!("Node: {node:?}");
8925 let parent = node.parent();
8926 log::info!("Parent: {parent:?}");
8927 let grandparent = parent.and_then(|x| x.parent());
8928 log::info!("Grandparent: {grandparent:?}");
8929 }
8930
8931 selected_larger_node |= new_range != old_range;
8932 Selection {
8933 id: selection.id,
8934 start: new_range.start,
8935 end: new_range.end,
8936 goal: SelectionGoal::None,
8937 reversed: selection.reversed,
8938 }
8939 })
8940 .collect::<Vec<_>>();
8941
8942 if selected_larger_node {
8943 stack.push(old_selections);
8944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8945 s.select(new_selections);
8946 });
8947 }
8948 self.select_larger_syntax_node_stack = stack;
8949 }
8950
8951 pub fn select_smaller_syntax_node(
8952 &mut self,
8953 _: &SelectSmallerSyntaxNode,
8954 cx: &mut ViewContext<Self>,
8955 ) {
8956 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8957 if let Some(selections) = stack.pop() {
8958 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8959 s.select(selections.to_vec());
8960 });
8961 }
8962 self.select_larger_syntax_node_stack = stack;
8963 }
8964
8965 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8966 if !EditorSettings::get_global(cx).gutter.runnables {
8967 self.clear_tasks();
8968 return Task::ready(());
8969 }
8970 let project = self.project.as_ref().map(Model::downgrade);
8971 cx.spawn(|this, mut cx| async move {
8972 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8973 let Some(project) = project.and_then(|p| p.upgrade()) else {
8974 return;
8975 };
8976 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8977 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8978 }) else {
8979 return;
8980 };
8981
8982 let hide_runnables = project
8983 .update(&mut cx, |project, cx| {
8984 // Do not display any test indicators in non-dev server remote projects.
8985 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8986 })
8987 .unwrap_or(true);
8988 if hide_runnables {
8989 return;
8990 }
8991 let new_rows =
8992 cx.background_executor()
8993 .spawn({
8994 let snapshot = display_snapshot.clone();
8995 async move {
8996 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8997 }
8998 })
8999 .await;
9000 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9001
9002 this.update(&mut cx, |this, _| {
9003 this.clear_tasks();
9004 for (key, value) in rows {
9005 this.insert_tasks(key, value);
9006 }
9007 })
9008 .ok();
9009 })
9010 }
9011 fn fetch_runnable_ranges(
9012 snapshot: &DisplaySnapshot,
9013 range: Range<Anchor>,
9014 ) -> Vec<language::RunnableRange> {
9015 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9016 }
9017
9018 fn runnable_rows(
9019 project: Model<Project>,
9020 snapshot: DisplaySnapshot,
9021 runnable_ranges: Vec<RunnableRange>,
9022 mut cx: AsyncWindowContext,
9023 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9024 runnable_ranges
9025 .into_iter()
9026 .filter_map(|mut runnable| {
9027 let tasks = cx
9028 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9029 .ok()?;
9030 if tasks.is_empty() {
9031 return None;
9032 }
9033
9034 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9035
9036 let row = snapshot
9037 .buffer_snapshot
9038 .buffer_line_for_row(MultiBufferRow(point.row))?
9039 .1
9040 .start
9041 .row;
9042
9043 let context_range =
9044 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9045 Some((
9046 (runnable.buffer_id, row),
9047 RunnableTasks {
9048 templates: tasks,
9049 offset: MultiBufferOffset(runnable.run_range.start),
9050 context_range,
9051 column: point.column,
9052 extra_variables: runnable.extra_captures,
9053 },
9054 ))
9055 })
9056 .collect()
9057 }
9058
9059 fn templates_with_tags(
9060 project: &Model<Project>,
9061 runnable: &mut Runnable,
9062 cx: &WindowContext,
9063 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9064 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9065 let (worktree_id, file) = project
9066 .buffer_for_id(runnable.buffer, cx)
9067 .and_then(|buffer| buffer.read(cx).file())
9068 .map(|file| (file.worktree_id(cx), file.clone()))
9069 .unzip();
9070
9071 (
9072 project.task_store().read(cx).task_inventory().cloned(),
9073 worktree_id,
9074 file,
9075 )
9076 });
9077
9078 let tags = mem::take(&mut runnable.tags);
9079 let mut tags: Vec<_> = tags
9080 .into_iter()
9081 .flat_map(|tag| {
9082 let tag = tag.0.clone();
9083 inventory
9084 .as_ref()
9085 .into_iter()
9086 .flat_map(|inventory| {
9087 inventory.read(cx).list_tasks(
9088 file.clone(),
9089 Some(runnable.language.clone()),
9090 worktree_id,
9091 cx,
9092 )
9093 })
9094 .filter(move |(_, template)| {
9095 template.tags.iter().any(|source_tag| source_tag == &tag)
9096 })
9097 })
9098 .sorted_by_key(|(kind, _)| kind.to_owned())
9099 .collect();
9100 if let Some((leading_tag_source, _)) = tags.first() {
9101 // Strongest source wins; if we have worktree tag binding, prefer that to
9102 // global and language bindings;
9103 // if we have a global binding, prefer that to language binding.
9104 let first_mismatch = tags
9105 .iter()
9106 .position(|(tag_source, _)| tag_source != leading_tag_source);
9107 if let Some(index) = first_mismatch {
9108 tags.truncate(index);
9109 }
9110 }
9111
9112 tags
9113 }
9114
9115 pub fn move_to_enclosing_bracket(
9116 &mut self,
9117 _: &MoveToEnclosingBracket,
9118 cx: &mut ViewContext<Self>,
9119 ) {
9120 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9121 s.move_offsets_with(|snapshot, selection| {
9122 let Some(enclosing_bracket_ranges) =
9123 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9124 else {
9125 return;
9126 };
9127
9128 let mut best_length = usize::MAX;
9129 let mut best_inside = false;
9130 let mut best_in_bracket_range = false;
9131 let mut best_destination = None;
9132 for (open, close) in enclosing_bracket_ranges {
9133 let close = close.to_inclusive();
9134 let length = close.end() - open.start;
9135 let inside = selection.start >= open.end && selection.end <= *close.start();
9136 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9137 || close.contains(&selection.head());
9138
9139 // If best is next to a bracket and current isn't, skip
9140 if !in_bracket_range && best_in_bracket_range {
9141 continue;
9142 }
9143
9144 // Prefer smaller lengths unless best is inside and current isn't
9145 if length > best_length && (best_inside || !inside) {
9146 continue;
9147 }
9148
9149 best_length = length;
9150 best_inside = inside;
9151 best_in_bracket_range = in_bracket_range;
9152 best_destination = Some(
9153 if close.contains(&selection.start) && close.contains(&selection.end) {
9154 if inside {
9155 open.end
9156 } else {
9157 open.start
9158 }
9159 } else if inside {
9160 *close.start()
9161 } else {
9162 *close.end()
9163 },
9164 );
9165 }
9166
9167 if let Some(destination) = best_destination {
9168 selection.collapse_to(destination, SelectionGoal::None);
9169 }
9170 })
9171 });
9172 }
9173
9174 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9175 self.end_selection(cx);
9176 self.selection_history.mode = SelectionHistoryMode::Undoing;
9177 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9178 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9179 self.select_next_state = entry.select_next_state;
9180 self.select_prev_state = entry.select_prev_state;
9181 self.add_selections_state = entry.add_selections_state;
9182 self.request_autoscroll(Autoscroll::newest(), cx);
9183 }
9184 self.selection_history.mode = SelectionHistoryMode::Normal;
9185 }
9186
9187 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9188 self.end_selection(cx);
9189 self.selection_history.mode = SelectionHistoryMode::Redoing;
9190 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9191 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9192 self.select_next_state = entry.select_next_state;
9193 self.select_prev_state = entry.select_prev_state;
9194 self.add_selections_state = entry.add_selections_state;
9195 self.request_autoscroll(Autoscroll::newest(), cx);
9196 }
9197 self.selection_history.mode = SelectionHistoryMode::Normal;
9198 }
9199
9200 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9201 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9202 }
9203
9204 pub fn expand_excerpts_down(
9205 &mut self,
9206 action: &ExpandExcerptsDown,
9207 cx: &mut ViewContext<Self>,
9208 ) {
9209 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9210 }
9211
9212 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9213 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9214 }
9215
9216 pub fn expand_excerpts_for_direction(
9217 &mut self,
9218 lines: u32,
9219 direction: ExpandExcerptDirection,
9220 cx: &mut ViewContext<Self>,
9221 ) {
9222 let selections = self.selections.disjoint_anchors();
9223
9224 let lines = if lines == 0 {
9225 EditorSettings::get_global(cx).expand_excerpt_lines
9226 } else {
9227 lines
9228 };
9229
9230 self.buffer.update(cx, |buffer, cx| {
9231 let snapshot = buffer.snapshot(cx);
9232 let mut excerpt_ids = selections
9233 .iter()
9234 .flat_map(|selection| {
9235 snapshot
9236 .excerpts_for_range(selection.range())
9237 .map(|excerpt| excerpt.id())
9238 })
9239 .collect::<Vec<_>>();
9240 excerpt_ids.sort();
9241 excerpt_ids.dedup();
9242 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9243 })
9244 }
9245
9246 pub fn expand_excerpt(
9247 &mut self,
9248 excerpt: ExcerptId,
9249 direction: ExpandExcerptDirection,
9250 cx: &mut ViewContext<Self>,
9251 ) {
9252 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9253 self.buffer.update(cx, |buffer, cx| {
9254 buffer.expand_excerpts([excerpt], lines, direction, cx)
9255 })
9256 }
9257
9258 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9259 self.go_to_diagnostic_impl(Direction::Next, cx)
9260 }
9261
9262 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9263 self.go_to_diagnostic_impl(Direction::Prev, cx)
9264 }
9265
9266 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9267 let buffer = self.buffer.read(cx).snapshot(cx);
9268 let selection = self.selections.newest::<usize>(cx);
9269
9270 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9271 if direction == Direction::Next {
9272 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9273 self.activate_diagnostics(popover.group_id(), cx);
9274 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9275 let primary_range_start = active_diagnostics.primary_range.start;
9276 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9277 let mut new_selection = s.newest_anchor().clone();
9278 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9279 s.select_anchors(vec![new_selection.clone()]);
9280 });
9281 self.refresh_inline_completion(false, true, cx);
9282 }
9283 return;
9284 }
9285 }
9286
9287 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9288 active_diagnostics
9289 .primary_range
9290 .to_offset(&buffer)
9291 .to_inclusive()
9292 });
9293 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9294 if active_primary_range.contains(&selection.head()) {
9295 *active_primary_range.start()
9296 } else {
9297 selection.head()
9298 }
9299 } else {
9300 selection.head()
9301 };
9302 let snapshot = self.snapshot(cx);
9303 loop {
9304 let diagnostics = if direction == Direction::Prev {
9305 buffer.diagnostics_in_range(0..search_start, true)
9306 } else {
9307 buffer.diagnostics_in_range(search_start..buffer.len(), false)
9308 }
9309 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9310 let search_start_anchor = buffer.anchor_after(search_start);
9311 let group = diagnostics
9312 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9313 // be sorted in a stable way
9314 // skip until we are at current active diagnostic, if it exists
9315 .skip_while(|entry| {
9316 let is_in_range = match direction {
9317 Direction::Prev => {
9318 entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
9319 }
9320 Direction::Next => {
9321 entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
9322 }
9323 };
9324 is_in_range
9325 && self
9326 .active_diagnostics
9327 .as_ref()
9328 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9329 })
9330 .find_map(|entry| {
9331 if entry.diagnostic.is_primary
9332 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9333 && !(entry.range.start == entry.range.end)
9334 // if we match with the active diagnostic, skip it
9335 && Some(entry.diagnostic.group_id)
9336 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9337 {
9338 Some((entry.range, entry.diagnostic.group_id))
9339 } else {
9340 None
9341 }
9342 });
9343
9344 if let Some((primary_range, group_id)) = group {
9345 self.activate_diagnostics(group_id, cx);
9346 let primary_range = primary_range.to_offset(&buffer);
9347 if self.active_diagnostics.is_some() {
9348 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9349 s.select(vec![Selection {
9350 id: selection.id,
9351 start: primary_range.start,
9352 end: primary_range.start,
9353 reversed: false,
9354 goal: SelectionGoal::None,
9355 }]);
9356 });
9357 self.refresh_inline_completion(false, true, cx);
9358 }
9359 break;
9360 } else {
9361 // Cycle around to the start of the buffer, potentially moving back to the start of
9362 // the currently active diagnostic.
9363 active_primary_range.take();
9364 if direction == Direction::Prev {
9365 if search_start == buffer.len() {
9366 break;
9367 } else {
9368 search_start = buffer.len();
9369 }
9370 } else if search_start == 0 {
9371 break;
9372 } else {
9373 search_start = 0;
9374 }
9375 }
9376 }
9377 }
9378
9379 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9380 let snapshot = self.snapshot(cx);
9381 let selection = self.selections.newest::<Point>(cx);
9382 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9383 }
9384
9385 fn go_to_hunk_after_position(
9386 &mut self,
9387 snapshot: &EditorSnapshot,
9388 position: Point,
9389 cx: &mut ViewContext<Editor>,
9390 ) -> Option<MultiBufferDiffHunk> {
9391 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9392 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9393 snapshot,
9394 position,
9395 ix > 0,
9396 snapshot.diff_map.diff_hunks_in_range(
9397 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9398 &snapshot.buffer_snapshot,
9399 ),
9400 cx,
9401 ) {
9402 return Some(hunk);
9403 }
9404 }
9405 None
9406 }
9407
9408 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9409 let snapshot = self.snapshot(cx);
9410 let selection = self.selections.newest::<Point>(cx);
9411 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9412 }
9413
9414 fn go_to_hunk_before_position(
9415 &mut self,
9416 snapshot: &EditorSnapshot,
9417 position: Point,
9418 cx: &mut ViewContext<Editor>,
9419 ) -> Option<MultiBufferDiffHunk> {
9420 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9421 .into_iter()
9422 .enumerate()
9423 {
9424 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9425 snapshot,
9426 position,
9427 ix > 0,
9428 snapshot
9429 .diff_map
9430 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9431 cx,
9432 ) {
9433 return Some(hunk);
9434 }
9435 }
9436 None
9437 }
9438
9439 fn go_to_next_hunk_in_direction(
9440 &mut self,
9441 snapshot: &DisplaySnapshot,
9442 initial_point: Point,
9443 is_wrapped: bool,
9444 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9445 cx: &mut ViewContext<Editor>,
9446 ) -> Option<MultiBufferDiffHunk> {
9447 let display_point = initial_point.to_display_point(snapshot);
9448 let mut hunks = hunks
9449 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9450 .filter(|(display_hunk, _)| {
9451 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9452 })
9453 .dedup();
9454
9455 if let Some((display_hunk, hunk)) = hunks.next() {
9456 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9457 let row = display_hunk.start_display_row();
9458 let point = DisplayPoint::new(row, 0);
9459 s.select_display_ranges([point..point]);
9460 });
9461
9462 Some(hunk)
9463 } else {
9464 None
9465 }
9466 }
9467
9468 pub fn go_to_definition(
9469 &mut self,
9470 _: &GoToDefinition,
9471 cx: &mut ViewContext<Self>,
9472 ) -> Task<Result<Navigated>> {
9473 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9474 cx.spawn(|editor, mut cx| async move {
9475 if definition.await? == Navigated::Yes {
9476 return Ok(Navigated::Yes);
9477 }
9478 match editor.update(&mut cx, |editor, cx| {
9479 editor.find_all_references(&FindAllReferences, cx)
9480 })? {
9481 Some(references) => references.await,
9482 None => Ok(Navigated::No),
9483 }
9484 })
9485 }
9486
9487 pub fn go_to_declaration(
9488 &mut self,
9489 _: &GoToDeclaration,
9490 cx: &mut ViewContext<Self>,
9491 ) -> Task<Result<Navigated>> {
9492 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9493 }
9494
9495 pub fn go_to_declaration_split(
9496 &mut self,
9497 _: &GoToDeclaration,
9498 cx: &mut ViewContext<Self>,
9499 ) -> Task<Result<Navigated>> {
9500 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9501 }
9502
9503 pub fn go_to_implementation(
9504 &mut self,
9505 _: &GoToImplementation,
9506 cx: &mut ViewContext<Self>,
9507 ) -> Task<Result<Navigated>> {
9508 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9509 }
9510
9511 pub fn go_to_implementation_split(
9512 &mut self,
9513 _: &GoToImplementationSplit,
9514 cx: &mut ViewContext<Self>,
9515 ) -> Task<Result<Navigated>> {
9516 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9517 }
9518
9519 pub fn go_to_type_definition(
9520 &mut self,
9521 _: &GoToTypeDefinition,
9522 cx: &mut ViewContext<Self>,
9523 ) -> Task<Result<Navigated>> {
9524 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9525 }
9526
9527 pub fn go_to_definition_split(
9528 &mut self,
9529 _: &GoToDefinitionSplit,
9530 cx: &mut ViewContext<Self>,
9531 ) -> Task<Result<Navigated>> {
9532 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9533 }
9534
9535 pub fn go_to_type_definition_split(
9536 &mut self,
9537 _: &GoToTypeDefinitionSplit,
9538 cx: &mut ViewContext<Self>,
9539 ) -> Task<Result<Navigated>> {
9540 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9541 }
9542
9543 fn go_to_definition_of_kind(
9544 &mut self,
9545 kind: GotoDefinitionKind,
9546 split: bool,
9547 cx: &mut ViewContext<Self>,
9548 ) -> Task<Result<Navigated>> {
9549 let Some(provider) = self.semantics_provider.clone() else {
9550 return Task::ready(Ok(Navigated::No));
9551 };
9552 let head = self.selections.newest::<usize>(cx).head();
9553 let buffer = self.buffer.read(cx);
9554 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9555 text_anchor
9556 } else {
9557 return Task::ready(Ok(Navigated::No));
9558 };
9559
9560 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9561 return Task::ready(Ok(Navigated::No));
9562 };
9563
9564 cx.spawn(|editor, mut cx| async move {
9565 let definitions = definitions.await?;
9566 let navigated = editor
9567 .update(&mut cx, |editor, cx| {
9568 editor.navigate_to_hover_links(
9569 Some(kind),
9570 definitions
9571 .into_iter()
9572 .filter(|location| {
9573 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9574 })
9575 .map(HoverLink::Text)
9576 .collect::<Vec<_>>(),
9577 split,
9578 cx,
9579 )
9580 })?
9581 .await?;
9582 anyhow::Ok(navigated)
9583 })
9584 }
9585
9586 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9587 let selection = self.selections.newest_anchor();
9588 let head = selection.head();
9589 let tail = selection.tail();
9590
9591 let Some((buffer, start_position)) =
9592 self.buffer.read(cx).text_anchor_for_position(head, cx)
9593 else {
9594 return;
9595 };
9596
9597 let end_position = if head != tail {
9598 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9599 return;
9600 };
9601 Some(pos)
9602 } else {
9603 None
9604 };
9605
9606 let url_finder = cx.spawn(|editor, mut cx| async move {
9607 let url = if let Some(end_pos) = end_position {
9608 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9609 } else {
9610 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9611 };
9612
9613 if let Some(url) = url {
9614 editor.update(&mut cx, |_, cx| {
9615 cx.open_url(&url);
9616 })
9617 } else {
9618 Ok(())
9619 }
9620 });
9621
9622 url_finder.detach();
9623 }
9624
9625 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9626 let Some(workspace) = self.workspace() else {
9627 return;
9628 };
9629
9630 let position = self.selections.newest_anchor().head();
9631
9632 let Some((buffer, buffer_position)) =
9633 self.buffer.read(cx).text_anchor_for_position(position, cx)
9634 else {
9635 return;
9636 };
9637
9638 let project = self.project.clone();
9639
9640 cx.spawn(|_, mut cx| async move {
9641 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9642
9643 if let Some((_, path)) = result {
9644 workspace
9645 .update(&mut cx, |workspace, cx| {
9646 workspace.open_resolved_path(path, cx)
9647 })?
9648 .await?;
9649 }
9650 anyhow::Ok(())
9651 })
9652 .detach();
9653 }
9654
9655 pub(crate) fn navigate_to_hover_links(
9656 &mut self,
9657 kind: Option<GotoDefinitionKind>,
9658 mut definitions: Vec<HoverLink>,
9659 split: bool,
9660 cx: &mut ViewContext<Editor>,
9661 ) -> Task<Result<Navigated>> {
9662 // If there is one definition, just open it directly
9663 if definitions.len() == 1 {
9664 let definition = definitions.pop().unwrap();
9665
9666 enum TargetTaskResult {
9667 Location(Option<Location>),
9668 AlreadyNavigated,
9669 }
9670
9671 let target_task = match definition {
9672 HoverLink::Text(link) => {
9673 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9674 }
9675 HoverLink::InlayHint(lsp_location, server_id) => {
9676 let computation = self.compute_target_location(lsp_location, server_id, cx);
9677 cx.background_executor().spawn(async move {
9678 let location = computation.await?;
9679 Ok(TargetTaskResult::Location(location))
9680 })
9681 }
9682 HoverLink::Url(url) => {
9683 cx.open_url(&url);
9684 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9685 }
9686 HoverLink::File(path) => {
9687 if let Some(workspace) = self.workspace() {
9688 cx.spawn(|_, mut cx| async move {
9689 workspace
9690 .update(&mut cx, |workspace, cx| {
9691 workspace.open_resolved_path(path, cx)
9692 })?
9693 .await
9694 .map(|_| TargetTaskResult::AlreadyNavigated)
9695 })
9696 } else {
9697 Task::ready(Ok(TargetTaskResult::Location(None)))
9698 }
9699 }
9700 };
9701 cx.spawn(|editor, mut cx| async move {
9702 let target = match target_task.await.context("target resolution task")? {
9703 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9704 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9705 TargetTaskResult::Location(Some(target)) => target,
9706 };
9707
9708 editor.update(&mut cx, |editor, cx| {
9709 let Some(workspace) = editor.workspace() else {
9710 return Navigated::No;
9711 };
9712 let pane = workspace.read(cx).active_pane().clone();
9713
9714 let range = target.range.to_offset(target.buffer.read(cx));
9715 let range = editor.range_for_match(&range);
9716
9717 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9718 let buffer = target.buffer.read(cx);
9719 let range = check_multiline_range(buffer, range);
9720 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9721 s.select_ranges([range]);
9722 });
9723 } else {
9724 cx.window_context().defer(move |cx| {
9725 let target_editor: View<Self> =
9726 workspace.update(cx, |workspace, cx| {
9727 let pane = if split {
9728 workspace.adjacent_pane(cx)
9729 } else {
9730 workspace.active_pane().clone()
9731 };
9732
9733 workspace.open_project_item(
9734 pane,
9735 target.buffer.clone(),
9736 true,
9737 true,
9738 cx,
9739 )
9740 });
9741 target_editor.update(cx, |target_editor, cx| {
9742 // When selecting a definition in a different buffer, disable the nav history
9743 // to avoid creating a history entry at the previous cursor location.
9744 pane.update(cx, |pane, _| pane.disable_history());
9745 let buffer = target.buffer.read(cx);
9746 let range = check_multiline_range(buffer, range);
9747 target_editor.change_selections(
9748 Some(Autoscroll::focused()),
9749 cx,
9750 |s| {
9751 s.select_ranges([range]);
9752 },
9753 );
9754 pane.update(cx, |pane, _| pane.enable_history());
9755 });
9756 });
9757 }
9758 Navigated::Yes
9759 })
9760 })
9761 } else if !definitions.is_empty() {
9762 cx.spawn(|editor, mut cx| async move {
9763 let (title, location_tasks, workspace) = editor
9764 .update(&mut cx, |editor, cx| {
9765 let tab_kind = match kind {
9766 Some(GotoDefinitionKind::Implementation) => "Implementations",
9767 _ => "Definitions",
9768 };
9769 let title = definitions
9770 .iter()
9771 .find_map(|definition| match definition {
9772 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9773 let buffer = origin.buffer.read(cx);
9774 format!(
9775 "{} for {}",
9776 tab_kind,
9777 buffer
9778 .text_for_range(origin.range.clone())
9779 .collect::<String>()
9780 )
9781 }),
9782 HoverLink::InlayHint(_, _) => None,
9783 HoverLink::Url(_) => None,
9784 HoverLink::File(_) => None,
9785 })
9786 .unwrap_or(tab_kind.to_string());
9787 let location_tasks = definitions
9788 .into_iter()
9789 .map(|definition| match definition {
9790 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9791 HoverLink::InlayHint(lsp_location, server_id) => {
9792 editor.compute_target_location(lsp_location, server_id, cx)
9793 }
9794 HoverLink::Url(_) => Task::ready(Ok(None)),
9795 HoverLink::File(_) => Task::ready(Ok(None)),
9796 })
9797 .collect::<Vec<_>>();
9798 (title, location_tasks, editor.workspace().clone())
9799 })
9800 .context("location tasks preparation")?;
9801
9802 let locations = future::join_all(location_tasks)
9803 .await
9804 .into_iter()
9805 .filter_map(|location| location.transpose())
9806 .collect::<Result<_>>()
9807 .context("location tasks")?;
9808
9809 let Some(workspace) = workspace else {
9810 return Ok(Navigated::No);
9811 };
9812 let opened = workspace
9813 .update(&mut cx, |workspace, cx| {
9814 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9815 })
9816 .ok();
9817
9818 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9819 })
9820 } else {
9821 Task::ready(Ok(Navigated::No))
9822 }
9823 }
9824
9825 fn compute_target_location(
9826 &self,
9827 lsp_location: lsp::Location,
9828 server_id: LanguageServerId,
9829 cx: &mut ViewContext<Self>,
9830 ) -> Task<anyhow::Result<Option<Location>>> {
9831 let Some(project) = self.project.clone() else {
9832 return Task::ready(Ok(None));
9833 };
9834
9835 cx.spawn(move |editor, mut cx| async move {
9836 let location_task = editor.update(&mut cx, |_, cx| {
9837 project.update(cx, |project, cx| {
9838 let language_server_name = project
9839 .language_server_statuses(cx)
9840 .find(|(id, _)| server_id == *id)
9841 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9842 language_server_name.map(|language_server_name| {
9843 project.open_local_buffer_via_lsp(
9844 lsp_location.uri.clone(),
9845 server_id,
9846 language_server_name,
9847 cx,
9848 )
9849 })
9850 })
9851 })?;
9852 let location = match location_task {
9853 Some(task) => Some({
9854 let target_buffer_handle = task.await.context("open local buffer")?;
9855 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9856 let target_start = target_buffer
9857 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9858 let target_end = target_buffer
9859 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9860 target_buffer.anchor_after(target_start)
9861 ..target_buffer.anchor_before(target_end)
9862 })?;
9863 Location {
9864 buffer: target_buffer_handle,
9865 range,
9866 }
9867 }),
9868 None => None,
9869 };
9870 Ok(location)
9871 })
9872 }
9873
9874 pub fn find_all_references(
9875 &mut self,
9876 _: &FindAllReferences,
9877 cx: &mut ViewContext<Self>,
9878 ) -> Option<Task<Result<Navigated>>> {
9879 let selection = self.selections.newest::<usize>(cx);
9880 let multi_buffer = self.buffer.read(cx);
9881 let head = selection.head();
9882
9883 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9884 let head_anchor = multi_buffer_snapshot.anchor_at(
9885 head,
9886 if head < selection.tail() {
9887 Bias::Right
9888 } else {
9889 Bias::Left
9890 },
9891 );
9892
9893 match self
9894 .find_all_references_task_sources
9895 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9896 {
9897 Ok(_) => {
9898 log::info!(
9899 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9900 );
9901 return None;
9902 }
9903 Err(i) => {
9904 self.find_all_references_task_sources.insert(i, head_anchor);
9905 }
9906 }
9907
9908 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9909 let workspace = self.workspace()?;
9910 let project = workspace.read(cx).project().clone();
9911 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9912 Some(cx.spawn(|editor, mut cx| async move {
9913 let _cleanup = defer({
9914 let mut cx = cx.clone();
9915 move || {
9916 let _ = editor.update(&mut cx, |editor, _| {
9917 if let Ok(i) =
9918 editor
9919 .find_all_references_task_sources
9920 .binary_search_by(|anchor| {
9921 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9922 })
9923 {
9924 editor.find_all_references_task_sources.remove(i);
9925 }
9926 });
9927 }
9928 });
9929
9930 let locations = references.await?;
9931 if locations.is_empty() {
9932 return anyhow::Ok(Navigated::No);
9933 }
9934
9935 workspace.update(&mut cx, |workspace, cx| {
9936 let title = locations
9937 .first()
9938 .as_ref()
9939 .map(|location| {
9940 let buffer = location.buffer.read(cx);
9941 format!(
9942 "References to `{}`",
9943 buffer
9944 .text_for_range(location.range.clone())
9945 .collect::<String>()
9946 )
9947 })
9948 .unwrap();
9949 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9950 Navigated::Yes
9951 })
9952 }))
9953 }
9954
9955 /// Opens a multibuffer with the given project locations in it
9956 pub fn open_locations_in_multibuffer(
9957 workspace: &mut Workspace,
9958 mut locations: Vec<Location>,
9959 title: String,
9960 split: bool,
9961 cx: &mut ViewContext<Workspace>,
9962 ) {
9963 // If there are multiple definitions, open them in a multibuffer
9964 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9965 let mut locations = locations.into_iter().peekable();
9966 let mut ranges_to_highlight = Vec::new();
9967 let capability = workspace.project().read(cx).capability();
9968
9969 let excerpt_buffer = cx.new_model(|cx| {
9970 let mut multibuffer = MultiBuffer::new(capability);
9971 while let Some(location) = locations.next() {
9972 let buffer = location.buffer.read(cx);
9973 let mut ranges_for_buffer = Vec::new();
9974 let range = location.range.to_offset(buffer);
9975 ranges_for_buffer.push(range.clone());
9976
9977 while let Some(next_location) = locations.peek() {
9978 if next_location.buffer == location.buffer {
9979 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9980 locations.next();
9981 } else {
9982 break;
9983 }
9984 }
9985
9986 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9987 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9988 location.buffer.clone(),
9989 ranges_for_buffer,
9990 DEFAULT_MULTIBUFFER_CONTEXT,
9991 cx,
9992 ))
9993 }
9994
9995 multibuffer.with_title(title)
9996 });
9997
9998 let editor = cx.new_view(|cx| {
9999 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10000 });
10001 editor.update(cx, |editor, cx| {
10002 if let Some(first_range) = ranges_to_highlight.first() {
10003 editor.change_selections(None, cx, |selections| {
10004 selections.clear_disjoint();
10005 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10006 });
10007 }
10008 editor.highlight_background::<Self>(
10009 &ranges_to_highlight,
10010 |theme| theme.editor_highlighted_line_background,
10011 cx,
10012 );
10013 editor.register_buffers_with_language_servers(cx);
10014 });
10015
10016 let item = Box::new(editor);
10017 let item_id = item.item_id();
10018
10019 if split {
10020 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10021 } else {
10022 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10023 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10024 pane.close_current_preview_item(cx)
10025 } else {
10026 None
10027 }
10028 });
10029 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10030 }
10031 workspace.active_pane().update(cx, |pane, cx| {
10032 pane.set_preview_item_id(Some(item_id), cx);
10033 });
10034 }
10035
10036 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10037 use language::ToOffset as _;
10038
10039 let provider = self.semantics_provider.clone()?;
10040 let selection = self.selections.newest_anchor().clone();
10041 let (cursor_buffer, cursor_buffer_position) = self
10042 .buffer
10043 .read(cx)
10044 .text_anchor_for_position(selection.head(), cx)?;
10045 let (tail_buffer, cursor_buffer_position_end) = self
10046 .buffer
10047 .read(cx)
10048 .text_anchor_for_position(selection.tail(), cx)?;
10049 if tail_buffer != cursor_buffer {
10050 return None;
10051 }
10052
10053 let snapshot = cursor_buffer.read(cx).snapshot();
10054 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10055 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10056 let prepare_rename = provider
10057 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10058 .unwrap_or_else(|| Task::ready(Ok(None)));
10059 drop(snapshot);
10060
10061 Some(cx.spawn(|this, mut cx| async move {
10062 let rename_range = if let Some(range) = prepare_rename.await? {
10063 Some(range)
10064 } else {
10065 this.update(&mut cx, |this, cx| {
10066 let buffer = this.buffer.read(cx).snapshot(cx);
10067 let mut buffer_highlights = this
10068 .document_highlights_for_position(selection.head(), &buffer)
10069 .filter(|highlight| {
10070 highlight.start.excerpt_id == selection.head().excerpt_id
10071 && highlight.end.excerpt_id == selection.head().excerpt_id
10072 });
10073 buffer_highlights
10074 .next()
10075 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10076 })?
10077 };
10078 if let Some(rename_range) = rename_range {
10079 this.update(&mut cx, |this, cx| {
10080 let snapshot = cursor_buffer.read(cx).snapshot();
10081 let rename_buffer_range = rename_range.to_offset(&snapshot);
10082 let cursor_offset_in_rename_range =
10083 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10084 let cursor_offset_in_rename_range_end =
10085 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10086
10087 this.take_rename(false, cx);
10088 let buffer = this.buffer.read(cx).read(cx);
10089 let cursor_offset = selection.head().to_offset(&buffer);
10090 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10091 let rename_end = rename_start + rename_buffer_range.len();
10092 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10093 let mut old_highlight_id = None;
10094 let old_name: Arc<str> = buffer
10095 .chunks(rename_start..rename_end, true)
10096 .map(|chunk| {
10097 if old_highlight_id.is_none() {
10098 old_highlight_id = chunk.syntax_highlight_id;
10099 }
10100 chunk.text
10101 })
10102 .collect::<String>()
10103 .into();
10104
10105 drop(buffer);
10106
10107 // Position the selection in the rename editor so that it matches the current selection.
10108 this.show_local_selections = false;
10109 let rename_editor = cx.new_view(|cx| {
10110 let mut editor = Editor::single_line(cx);
10111 editor.buffer.update(cx, |buffer, cx| {
10112 buffer.edit([(0..0, old_name.clone())], None, cx)
10113 });
10114 let rename_selection_range = match cursor_offset_in_rename_range
10115 .cmp(&cursor_offset_in_rename_range_end)
10116 {
10117 Ordering::Equal => {
10118 editor.select_all(&SelectAll, cx);
10119 return editor;
10120 }
10121 Ordering::Less => {
10122 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10123 }
10124 Ordering::Greater => {
10125 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10126 }
10127 };
10128 if rename_selection_range.end > old_name.len() {
10129 editor.select_all(&SelectAll, cx);
10130 } else {
10131 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10132 s.select_ranges([rename_selection_range]);
10133 });
10134 }
10135 editor
10136 });
10137 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10138 if e == &EditorEvent::Focused {
10139 cx.emit(EditorEvent::FocusedIn)
10140 }
10141 })
10142 .detach();
10143
10144 let write_highlights =
10145 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10146 let read_highlights =
10147 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10148 let ranges = write_highlights
10149 .iter()
10150 .flat_map(|(_, ranges)| ranges.iter())
10151 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10152 .cloned()
10153 .collect();
10154
10155 this.highlight_text::<Rename>(
10156 ranges,
10157 HighlightStyle {
10158 fade_out: Some(0.6),
10159 ..Default::default()
10160 },
10161 cx,
10162 );
10163 let rename_focus_handle = rename_editor.focus_handle(cx);
10164 cx.focus(&rename_focus_handle);
10165 let block_id = this.insert_blocks(
10166 [BlockProperties {
10167 style: BlockStyle::Flex,
10168 placement: BlockPlacement::Below(range.start),
10169 height: 1,
10170 render: Arc::new({
10171 let rename_editor = rename_editor.clone();
10172 move |cx: &mut BlockContext| {
10173 let mut text_style = cx.editor_style.text.clone();
10174 if let Some(highlight_style) = old_highlight_id
10175 .and_then(|h| h.style(&cx.editor_style.syntax))
10176 {
10177 text_style = text_style.highlight(highlight_style);
10178 }
10179 div()
10180 .block_mouse_down()
10181 .pl(cx.anchor_x)
10182 .child(EditorElement::new(
10183 &rename_editor,
10184 EditorStyle {
10185 background: cx.theme().system().transparent,
10186 local_player: cx.editor_style.local_player,
10187 text: text_style,
10188 scrollbar_width: cx.editor_style.scrollbar_width,
10189 syntax: cx.editor_style.syntax.clone(),
10190 status: cx.editor_style.status.clone(),
10191 inlay_hints_style: HighlightStyle {
10192 font_weight: Some(FontWeight::BOLD),
10193 ..make_inlay_hints_style(cx)
10194 },
10195 inline_completion_styles: make_suggestion_styles(
10196 cx,
10197 ),
10198 ..EditorStyle::default()
10199 },
10200 ))
10201 .into_any_element()
10202 }
10203 }),
10204 priority: 0,
10205 }],
10206 Some(Autoscroll::fit()),
10207 cx,
10208 )[0];
10209 this.pending_rename = Some(RenameState {
10210 range,
10211 old_name,
10212 editor: rename_editor,
10213 block_id,
10214 });
10215 })?;
10216 }
10217
10218 Ok(())
10219 }))
10220 }
10221
10222 pub fn confirm_rename(
10223 &mut self,
10224 _: &ConfirmRename,
10225 cx: &mut ViewContext<Self>,
10226 ) -> Option<Task<Result<()>>> {
10227 let rename = self.take_rename(false, cx)?;
10228 let workspace = self.workspace()?.downgrade();
10229 let (buffer, start) = self
10230 .buffer
10231 .read(cx)
10232 .text_anchor_for_position(rename.range.start, cx)?;
10233 let (end_buffer, _) = self
10234 .buffer
10235 .read(cx)
10236 .text_anchor_for_position(rename.range.end, cx)?;
10237 if buffer != end_buffer {
10238 return None;
10239 }
10240
10241 let old_name = rename.old_name;
10242 let new_name = rename.editor.read(cx).text(cx);
10243
10244 let rename = self.semantics_provider.as_ref()?.perform_rename(
10245 &buffer,
10246 start,
10247 new_name.clone(),
10248 cx,
10249 )?;
10250
10251 Some(cx.spawn(|editor, mut cx| async move {
10252 let project_transaction = rename.await?;
10253 Self::open_project_transaction(
10254 &editor,
10255 workspace,
10256 project_transaction,
10257 format!("Rename: {} → {}", old_name, new_name),
10258 cx.clone(),
10259 )
10260 .await?;
10261
10262 editor.update(&mut cx, |editor, cx| {
10263 editor.refresh_document_highlights(cx);
10264 })?;
10265 Ok(())
10266 }))
10267 }
10268
10269 fn take_rename(
10270 &mut self,
10271 moving_cursor: bool,
10272 cx: &mut ViewContext<Self>,
10273 ) -> Option<RenameState> {
10274 let rename = self.pending_rename.take()?;
10275 if rename.editor.focus_handle(cx).is_focused(cx) {
10276 cx.focus(&self.focus_handle);
10277 }
10278
10279 self.remove_blocks(
10280 [rename.block_id].into_iter().collect(),
10281 Some(Autoscroll::fit()),
10282 cx,
10283 );
10284 self.clear_highlights::<Rename>(cx);
10285 self.show_local_selections = true;
10286
10287 if moving_cursor {
10288 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10289 editor.selections.newest::<usize>(cx).head()
10290 });
10291
10292 // Update the selection to match the position of the selection inside
10293 // the rename editor.
10294 let snapshot = self.buffer.read(cx).read(cx);
10295 let rename_range = rename.range.to_offset(&snapshot);
10296 let cursor_in_editor = snapshot
10297 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10298 .min(rename_range.end);
10299 drop(snapshot);
10300
10301 self.change_selections(None, cx, |s| {
10302 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10303 });
10304 } else {
10305 self.refresh_document_highlights(cx);
10306 }
10307
10308 Some(rename)
10309 }
10310
10311 pub fn pending_rename(&self) -> Option<&RenameState> {
10312 self.pending_rename.as_ref()
10313 }
10314
10315 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10316 let project = match &self.project {
10317 Some(project) => project.clone(),
10318 None => return None,
10319 };
10320
10321 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10322 }
10323
10324 fn format_selections(
10325 &mut self,
10326 _: &FormatSelections,
10327 cx: &mut ViewContext<Self>,
10328 ) -> Option<Task<Result<()>>> {
10329 let project = match &self.project {
10330 Some(project) => project.clone(),
10331 None => return None,
10332 };
10333
10334 let ranges = self
10335 .selections
10336 .all_adjusted(cx)
10337 .into_iter()
10338 .map(|selection| selection.range())
10339 .collect_vec();
10340
10341 Some(self.perform_format(
10342 project,
10343 FormatTrigger::Manual,
10344 FormatTarget::Ranges(ranges),
10345 cx,
10346 ))
10347 }
10348
10349 fn perform_format(
10350 &mut self,
10351 project: Model<Project>,
10352 trigger: FormatTrigger,
10353 target: FormatTarget,
10354 cx: &mut ViewContext<Self>,
10355 ) -> Task<Result<()>> {
10356 let buffer = self.buffer.clone();
10357 let (buffers, target) = match target {
10358 FormatTarget::Buffers => {
10359 let mut buffers = buffer.read(cx).all_buffers();
10360 if trigger == FormatTrigger::Save {
10361 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10362 }
10363 (buffers, LspFormatTarget::Buffers)
10364 }
10365 FormatTarget::Ranges(selection_ranges) => {
10366 let multi_buffer = buffer.read(cx);
10367 let snapshot = multi_buffer.read(cx);
10368 let mut buffers = HashSet::default();
10369 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10370 BTreeMap::new();
10371 for selection_range in selection_ranges {
10372 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10373 {
10374 let buffer_id = excerpt.buffer_id();
10375 let start = excerpt.buffer().anchor_before(buffer_range.start);
10376 let end = excerpt.buffer().anchor_after(buffer_range.end);
10377 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10378 buffer_id_to_ranges
10379 .entry(buffer_id)
10380 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10381 .or_insert_with(|| vec![start..end]);
10382 }
10383 }
10384 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10385 }
10386 };
10387
10388 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10389 let format = project.update(cx, |project, cx| {
10390 project.format(buffers, target, true, trigger, cx)
10391 });
10392
10393 cx.spawn(|_, mut cx| async move {
10394 let transaction = futures::select_biased! {
10395 () = timeout => {
10396 log::warn!("timed out waiting for formatting");
10397 None
10398 }
10399 transaction = format.log_err().fuse() => transaction,
10400 };
10401
10402 buffer
10403 .update(&mut cx, |buffer, cx| {
10404 if let Some(transaction) = transaction {
10405 if !buffer.is_singleton() {
10406 buffer.push_transaction(&transaction.0, cx);
10407 }
10408 }
10409
10410 cx.notify();
10411 })
10412 .ok();
10413
10414 Ok(())
10415 })
10416 }
10417
10418 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10419 if let Some(project) = self.project.clone() {
10420 self.buffer.update(cx, |multi_buffer, cx| {
10421 project.update(cx, |project, cx| {
10422 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10423 });
10424 })
10425 }
10426 }
10427
10428 fn cancel_language_server_work(
10429 &mut self,
10430 _: &actions::CancelLanguageServerWork,
10431 cx: &mut ViewContext<Self>,
10432 ) {
10433 if let Some(project) = self.project.clone() {
10434 self.buffer.update(cx, |multi_buffer, cx| {
10435 project.update(cx, |project, cx| {
10436 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10437 });
10438 })
10439 }
10440 }
10441
10442 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10443 cx.show_character_palette();
10444 }
10445
10446 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10447 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10448 let buffer = self.buffer.read(cx).snapshot(cx);
10449 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10450 let is_valid = buffer
10451 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10452 .any(|entry| {
10453 let range = entry.range.to_offset(&buffer);
10454 entry.diagnostic.is_primary
10455 && !range.is_empty()
10456 && range.start == primary_range_start
10457 && entry.diagnostic.message == active_diagnostics.primary_message
10458 });
10459
10460 if is_valid != active_diagnostics.is_valid {
10461 active_diagnostics.is_valid = is_valid;
10462 let mut new_styles = HashMap::default();
10463 for (block_id, diagnostic) in &active_diagnostics.blocks {
10464 new_styles.insert(
10465 *block_id,
10466 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10467 );
10468 }
10469 self.display_map.update(cx, |display_map, _cx| {
10470 display_map.replace_blocks(new_styles)
10471 });
10472 }
10473 }
10474 }
10475
10476 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10477 self.dismiss_diagnostics(cx);
10478 let snapshot = self.snapshot(cx);
10479 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10480 let buffer = self.buffer.read(cx).snapshot(cx);
10481
10482 let mut primary_range = None;
10483 let mut primary_message = None;
10484 let mut group_end = Point::zero();
10485 let diagnostic_group = buffer
10486 .diagnostic_group(group_id)
10487 .filter_map(|entry| {
10488 let start = entry.range.start.to_point(&buffer);
10489 let end = entry.range.end.to_point(&buffer);
10490 if snapshot.is_line_folded(MultiBufferRow(start.row))
10491 && (start.row == end.row
10492 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10493 {
10494 return None;
10495 }
10496 if end > group_end {
10497 group_end = end;
10498 }
10499 if entry.diagnostic.is_primary {
10500 primary_range = Some(entry.range.clone());
10501 primary_message = Some(entry.diagnostic.message.clone());
10502 }
10503 Some(entry)
10504 })
10505 .collect::<Vec<_>>();
10506 let primary_range = primary_range?;
10507 let primary_message = primary_message?;
10508
10509 let blocks = display_map
10510 .insert_blocks(
10511 diagnostic_group.iter().map(|entry| {
10512 let diagnostic = entry.diagnostic.clone();
10513 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10514 BlockProperties {
10515 style: BlockStyle::Fixed,
10516 placement: BlockPlacement::Below(
10517 buffer.anchor_after(entry.range.start),
10518 ),
10519 height: message_height,
10520 render: diagnostic_block_renderer(diagnostic, None, true, true),
10521 priority: 0,
10522 }
10523 }),
10524 cx,
10525 )
10526 .into_iter()
10527 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10528 .collect();
10529
10530 Some(ActiveDiagnosticGroup {
10531 primary_range,
10532 primary_message,
10533 group_id,
10534 blocks,
10535 is_valid: true,
10536 })
10537 });
10538 }
10539
10540 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10541 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10542 self.display_map.update(cx, |display_map, cx| {
10543 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10544 });
10545 cx.notify();
10546 }
10547 }
10548
10549 pub fn set_selections_from_remote(
10550 &mut self,
10551 selections: Vec<Selection<Anchor>>,
10552 pending_selection: Option<Selection<Anchor>>,
10553 cx: &mut ViewContext<Self>,
10554 ) {
10555 let old_cursor_position = self.selections.newest_anchor().head();
10556 self.selections.change_with(cx, |s| {
10557 s.select_anchors(selections);
10558 if let Some(pending_selection) = pending_selection {
10559 s.set_pending(pending_selection, SelectMode::Character);
10560 } else {
10561 s.clear_pending();
10562 }
10563 });
10564 self.selections_did_change(false, &old_cursor_position, true, cx);
10565 }
10566
10567 fn push_to_selection_history(&mut self) {
10568 self.selection_history.push(SelectionHistoryEntry {
10569 selections: self.selections.disjoint_anchors(),
10570 select_next_state: self.select_next_state.clone(),
10571 select_prev_state: self.select_prev_state.clone(),
10572 add_selections_state: self.add_selections_state.clone(),
10573 });
10574 }
10575
10576 pub fn transact(
10577 &mut self,
10578 cx: &mut ViewContext<Self>,
10579 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10580 ) -> Option<TransactionId> {
10581 self.start_transaction_at(Instant::now(), cx);
10582 update(self, cx);
10583 self.end_transaction_at(Instant::now(), cx)
10584 }
10585
10586 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10587 self.end_selection(cx);
10588 if let Some(tx_id) = self
10589 .buffer
10590 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10591 {
10592 self.selection_history
10593 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10594 cx.emit(EditorEvent::TransactionBegun {
10595 transaction_id: tx_id,
10596 })
10597 }
10598 }
10599
10600 pub fn end_transaction_at(
10601 &mut self,
10602 now: Instant,
10603 cx: &mut ViewContext<Self>,
10604 ) -> Option<TransactionId> {
10605 if let Some(transaction_id) = self
10606 .buffer
10607 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10608 {
10609 if let Some((_, end_selections)) =
10610 self.selection_history.transaction_mut(transaction_id)
10611 {
10612 *end_selections = Some(self.selections.disjoint_anchors());
10613 } else {
10614 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10615 }
10616
10617 cx.emit(EditorEvent::Edited { transaction_id });
10618 Some(transaction_id)
10619 } else {
10620 None
10621 }
10622 }
10623
10624 pub fn set_mark(&mut self, _: &actions::SetMark, cx: &mut ViewContext<Self>) {
10625 if self.selection_mark_mode {
10626 self.change_selections(None, cx, |s| {
10627 s.move_with(|_, sel| {
10628 sel.collapse_to(sel.head(), SelectionGoal::None);
10629 });
10630 })
10631 }
10632 self.selection_mark_mode = true;
10633 cx.notify();
10634 }
10635
10636 pub fn exchange_mark(&mut self, _: &actions::ExchangeMark, cx: &mut ViewContext<Self>) {
10637 if self.selection_mark_mode {
10638 self.change_selections(None, cx, |s| {
10639 s.move_with(|_, sel| {
10640 if sel.start != sel.end {
10641 sel.reversed = !sel.reversed
10642 }
10643 });
10644 })
10645 }
10646 self.selection_mark_mode = true;
10647 cx.notify();
10648 }
10649
10650 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10651 if self.is_singleton(cx) {
10652 let selection = self.selections.newest::<Point>(cx);
10653
10654 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10655 let range = if selection.is_empty() {
10656 let point = selection.head().to_display_point(&display_map);
10657 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10658 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10659 .to_point(&display_map);
10660 start..end
10661 } else {
10662 selection.range()
10663 };
10664 if display_map.folds_in_range(range).next().is_some() {
10665 self.unfold_lines(&Default::default(), cx)
10666 } else {
10667 self.fold(&Default::default(), cx)
10668 }
10669 } else {
10670 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10671 let mut toggled_buffers = HashSet::default();
10672 for (_, buffer_snapshot, _) in
10673 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10674 {
10675 let buffer_id = buffer_snapshot.remote_id();
10676 if toggled_buffers.insert(buffer_id) {
10677 if self.buffer_folded(buffer_id, cx) {
10678 self.unfold_buffer(buffer_id, cx);
10679 } else {
10680 self.fold_buffer(buffer_id, cx);
10681 }
10682 }
10683 }
10684 }
10685 }
10686
10687 pub fn toggle_fold_recursive(
10688 &mut self,
10689 _: &actions::ToggleFoldRecursive,
10690 cx: &mut ViewContext<Self>,
10691 ) {
10692 let selection = self.selections.newest::<Point>(cx);
10693
10694 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10695 let range = if selection.is_empty() {
10696 let point = selection.head().to_display_point(&display_map);
10697 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10698 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10699 .to_point(&display_map);
10700 start..end
10701 } else {
10702 selection.range()
10703 };
10704 if display_map.folds_in_range(range).next().is_some() {
10705 self.unfold_recursive(&Default::default(), cx)
10706 } else {
10707 self.fold_recursive(&Default::default(), cx)
10708 }
10709 }
10710
10711 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10712 if self.is_singleton(cx) {
10713 let mut to_fold = Vec::new();
10714 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10715 let selections = self.selections.all_adjusted(cx);
10716
10717 for selection in selections {
10718 let range = selection.range().sorted();
10719 let buffer_start_row = range.start.row;
10720
10721 if range.start.row != range.end.row {
10722 let mut found = false;
10723 let mut row = range.start.row;
10724 while row <= range.end.row {
10725 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10726 {
10727 found = true;
10728 row = crease.range().end.row + 1;
10729 to_fold.push(crease);
10730 } else {
10731 row += 1
10732 }
10733 }
10734 if found {
10735 continue;
10736 }
10737 }
10738
10739 for row in (0..=range.start.row).rev() {
10740 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10741 if crease.range().end.row >= buffer_start_row {
10742 to_fold.push(crease);
10743 if row <= range.start.row {
10744 break;
10745 }
10746 }
10747 }
10748 }
10749 }
10750
10751 self.fold_creases(to_fold, true, cx);
10752 } else {
10753 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10754 let mut folded_buffers = HashSet::default();
10755 for (_, buffer_snapshot, _) in
10756 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10757 {
10758 let buffer_id = buffer_snapshot.remote_id();
10759 if folded_buffers.insert(buffer_id) {
10760 self.fold_buffer(buffer_id, cx);
10761 }
10762 }
10763 }
10764 }
10765
10766 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10767 if !self.buffer.read(cx).is_singleton() {
10768 return;
10769 }
10770
10771 let fold_at_level = fold_at.level;
10772 let snapshot = self.buffer.read(cx).snapshot(cx);
10773 let mut to_fold = Vec::new();
10774 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10775
10776 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10777 while start_row < end_row {
10778 match self
10779 .snapshot(cx)
10780 .crease_for_buffer_row(MultiBufferRow(start_row))
10781 {
10782 Some(crease) => {
10783 let nested_start_row = crease.range().start.row + 1;
10784 let nested_end_row = crease.range().end.row;
10785
10786 if current_level < fold_at_level {
10787 stack.push((nested_start_row, nested_end_row, current_level + 1));
10788 } else if current_level == fold_at_level {
10789 to_fold.push(crease);
10790 }
10791
10792 start_row = nested_end_row + 1;
10793 }
10794 None => start_row += 1,
10795 }
10796 }
10797 }
10798
10799 self.fold_creases(to_fold, true, cx);
10800 }
10801
10802 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10803 if self.buffer.read(cx).is_singleton() {
10804 let mut fold_ranges = Vec::new();
10805 let snapshot = self.buffer.read(cx).snapshot(cx);
10806
10807 for row in 0..snapshot.max_row().0 {
10808 if let Some(foldable_range) =
10809 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10810 {
10811 fold_ranges.push(foldable_range);
10812 }
10813 }
10814
10815 self.fold_creases(fold_ranges, true, cx);
10816 } else {
10817 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10818 editor
10819 .update(&mut cx, |editor, cx| {
10820 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10821 editor.fold_buffer(buffer_id, cx);
10822 }
10823 })
10824 .ok();
10825 });
10826 }
10827 }
10828
10829 pub fn fold_function_bodies(
10830 &mut self,
10831 _: &actions::FoldFunctionBodies,
10832 cx: &mut ViewContext<Self>,
10833 ) {
10834 let snapshot = self.buffer.read(cx).snapshot(cx);
10835 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10836 return;
10837 };
10838 let creases = buffer
10839 .function_body_fold_ranges(0..buffer.len())
10840 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10841 .collect();
10842
10843 self.fold_creases(creases, true, cx);
10844 }
10845
10846 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10847 let mut to_fold = Vec::new();
10848 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10849 let selections = self.selections.all_adjusted(cx);
10850
10851 for selection in selections {
10852 let range = selection.range().sorted();
10853 let buffer_start_row = range.start.row;
10854
10855 if range.start.row != range.end.row {
10856 let mut found = false;
10857 for row in range.start.row..=range.end.row {
10858 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10859 found = true;
10860 to_fold.push(crease);
10861 }
10862 }
10863 if found {
10864 continue;
10865 }
10866 }
10867
10868 for row in (0..=range.start.row).rev() {
10869 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10870 if crease.range().end.row >= buffer_start_row {
10871 to_fold.push(crease);
10872 } else {
10873 break;
10874 }
10875 }
10876 }
10877 }
10878
10879 self.fold_creases(to_fold, true, cx);
10880 }
10881
10882 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10883 let buffer_row = fold_at.buffer_row;
10884 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10885
10886 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10887 let autoscroll = self
10888 .selections
10889 .all::<Point>(cx)
10890 .iter()
10891 .any(|selection| crease.range().overlaps(&selection.range()));
10892
10893 self.fold_creases(vec![crease], autoscroll, cx);
10894 }
10895 }
10896
10897 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10898 if self.is_singleton(cx) {
10899 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10900 let buffer = &display_map.buffer_snapshot;
10901 let selections = self.selections.all::<Point>(cx);
10902 let ranges = selections
10903 .iter()
10904 .map(|s| {
10905 let range = s.display_range(&display_map).sorted();
10906 let mut start = range.start.to_point(&display_map);
10907 let mut end = range.end.to_point(&display_map);
10908 start.column = 0;
10909 end.column = buffer.line_len(MultiBufferRow(end.row));
10910 start..end
10911 })
10912 .collect::<Vec<_>>();
10913
10914 self.unfold_ranges(&ranges, true, true, cx);
10915 } else {
10916 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10917 let mut unfolded_buffers = HashSet::default();
10918 for (_, buffer_snapshot, _) in
10919 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10920 {
10921 let buffer_id = buffer_snapshot.remote_id();
10922 if unfolded_buffers.insert(buffer_id) {
10923 self.unfold_buffer(buffer_id, cx);
10924 }
10925 }
10926 }
10927 }
10928
10929 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10930 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10931 let selections = self.selections.all::<Point>(cx);
10932 let ranges = selections
10933 .iter()
10934 .map(|s| {
10935 let mut range = s.display_range(&display_map).sorted();
10936 *range.start.column_mut() = 0;
10937 *range.end.column_mut() = display_map.line_len(range.end.row());
10938 let start = range.start.to_point(&display_map);
10939 let end = range.end.to_point(&display_map);
10940 start..end
10941 })
10942 .collect::<Vec<_>>();
10943
10944 self.unfold_ranges(&ranges, true, true, cx);
10945 }
10946
10947 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10948 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10949
10950 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10951 ..Point::new(
10952 unfold_at.buffer_row.0,
10953 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10954 );
10955
10956 let autoscroll = self
10957 .selections
10958 .all::<Point>(cx)
10959 .iter()
10960 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10961
10962 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10963 }
10964
10965 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10966 if self.buffer.read(cx).is_singleton() {
10967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10968 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10969 } else {
10970 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10971 editor
10972 .update(&mut cx, |editor, cx| {
10973 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10974 editor.unfold_buffer(buffer_id, cx);
10975 }
10976 })
10977 .ok();
10978 });
10979 }
10980 }
10981
10982 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10983 let selections = self.selections.all::<Point>(cx);
10984 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10985 let line_mode = self.selections.line_mode;
10986 let ranges = selections
10987 .into_iter()
10988 .map(|s| {
10989 if line_mode {
10990 let start = Point::new(s.start.row, 0);
10991 let end = Point::new(
10992 s.end.row,
10993 display_map
10994 .buffer_snapshot
10995 .line_len(MultiBufferRow(s.end.row)),
10996 );
10997 Crease::simple(start..end, display_map.fold_placeholder.clone())
10998 } else {
10999 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11000 }
11001 })
11002 .collect::<Vec<_>>();
11003 self.fold_creases(ranges, true, cx);
11004 }
11005
11006 pub fn fold_ranges<T: ToOffset + Clone>(
11007 &mut self,
11008 ranges: Vec<Range<T>>,
11009 auto_scroll: bool,
11010 cx: &mut ViewContext<Self>,
11011 ) {
11012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11013 let ranges = ranges
11014 .into_iter()
11015 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11016 .collect::<Vec<_>>();
11017 self.fold_creases(ranges, auto_scroll, cx);
11018 }
11019
11020 pub fn fold_creases<T: ToOffset + Clone>(
11021 &mut self,
11022 creases: Vec<Crease<T>>,
11023 auto_scroll: bool,
11024 cx: &mut ViewContext<Self>,
11025 ) {
11026 if creases.is_empty() {
11027 return;
11028 }
11029
11030 let mut buffers_affected = HashSet::default();
11031 let multi_buffer = self.buffer().read(cx);
11032 for crease in &creases {
11033 if let Some((_, buffer, _)) =
11034 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11035 {
11036 buffers_affected.insert(buffer.read(cx).remote_id());
11037 };
11038 }
11039
11040 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11041
11042 if auto_scroll {
11043 self.request_autoscroll(Autoscroll::fit(), cx);
11044 }
11045
11046 for buffer_id in buffers_affected {
11047 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11048 }
11049
11050 cx.notify();
11051
11052 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11053 // Clear diagnostics block when folding a range that contains it.
11054 let snapshot = self.snapshot(cx);
11055 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11056 drop(snapshot);
11057 self.active_diagnostics = Some(active_diagnostics);
11058 self.dismiss_diagnostics(cx);
11059 } else {
11060 self.active_diagnostics = Some(active_diagnostics);
11061 }
11062 }
11063
11064 self.scrollbar_marker_state.dirty = true;
11065 }
11066
11067 /// Removes any folds whose ranges intersect any of the given ranges.
11068 pub fn unfold_ranges<T: ToOffset + Clone>(
11069 &mut self,
11070 ranges: &[Range<T>],
11071 inclusive: bool,
11072 auto_scroll: bool,
11073 cx: &mut ViewContext<Self>,
11074 ) {
11075 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11076 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11077 });
11078 }
11079
11080 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11081 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11082 return;
11083 }
11084 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11085 return;
11086 };
11087 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11088 self.display_map
11089 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11090 cx.emit(EditorEvent::BufferFoldToggled {
11091 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11092 folded: true,
11093 });
11094 cx.notify();
11095 }
11096
11097 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11098 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11099 return;
11100 }
11101 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11102 return;
11103 };
11104 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11105 self.display_map.update(cx, |display_map, cx| {
11106 display_map.unfold_buffer(buffer_id, cx);
11107 });
11108 cx.emit(EditorEvent::BufferFoldToggled {
11109 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11110 folded: false,
11111 });
11112 cx.notify();
11113 }
11114
11115 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11116 self.display_map.read(cx).buffer_folded(buffer)
11117 }
11118
11119 /// Removes any folds with the given ranges.
11120 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11121 &mut self,
11122 ranges: &[Range<T>],
11123 type_id: TypeId,
11124 auto_scroll: bool,
11125 cx: &mut ViewContext<Self>,
11126 ) {
11127 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11128 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11129 });
11130 }
11131
11132 fn remove_folds_with<T: ToOffset + Clone>(
11133 &mut self,
11134 ranges: &[Range<T>],
11135 auto_scroll: bool,
11136 cx: &mut ViewContext<Self>,
11137 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11138 ) {
11139 if ranges.is_empty() {
11140 return;
11141 }
11142
11143 let mut buffers_affected = HashSet::default();
11144 let multi_buffer = self.buffer().read(cx);
11145 for range in ranges {
11146 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11147 buffers_affected.insert(buffer.read(cx).remote_id());
11148 };
11149 }
11150
11151 self.display_map.update(cx, update);
11152
11153 if auto_scroll {
11154 self.request_autoscroll(Autoscroll::fit(), cx);
11155 }
11156
11157 for buffer_id in buffers_affected {
11158 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11159 }
11160
11161 cx.notify();
11162 self.scrollbar_marker_state.dirty = true;
11163 self.active_indent_guides_state.dirty = true;
11164 }
11165
11166 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11167 self.display_map.read(cx).fold_placeholder.clone()
11168 }
11169
11170 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11171 if hovered != self.gutter_hovered {
11172 self.gutter_hovered = hovered;
11173 cx.notify();
11174 }
11175 }
11176
11177 pub fn insert_blocks(
11178 &mut self,
11179 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11180 autoscroll: Option<Autoscroll>,
11181 cx: &mut ViewContext<Self>,
11182 ) -> Vec<CustomBlockId> {
11183 let blocks = self
11184 .display_map
11185 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11186 if let Some(autoscroll) = autoscroll {
11187 self.request_autoscroll(autoscroll, cx);
11188 }
11189 cx.notify();
11190 blocks
11191 }
11192
11193 pub fn resize_blocks(
11194 &mut self,
11195 heights: HashMap<CustomBlockId, u32>,
11196 autoscroll: Option<Autoscroll>,
11197 cx: &mut ViewContext<Self>,
11198 ) {
11199 self.display_map
11200 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11201 if let Some(autoscroll) = autoscroll {
11202 self.request_autoscroll(autoscroll, cx);
11203 }
11204 cx.notify();
11205 }
11206
11207 pub fn replace_blocks(
11208 &mut self,
11209 renderers: HashMap<CustomBlockId, RenderBlock>,
11210 autoscroll: Option<Autoscroll>,
11211 cx: &mut ViewContext<Self>,
11212 ) {
11213 self.display_map
11214 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11215 if let Some(autoscroll) = autoscroll {
11216 self.request_autoscroll(autoscroll, cx);
11217 }
11218 cx.notify();
11219 }
11220
11221 pub fn remove_blocks(
11222 &mut self,
11223 block_ids: HashSet<CustomBlockId>,
11224 autoscroll: Option<Autoscroll>,
11225 cx: &mut ViewContext<Self>,
11226 ) {
11227 self.display_map.update(cx, |display_map, cx| {
11228 display_map.remove_blocks(block_ids, cx)
11229 });
11230 if let Some(autoscroll) = autoscroll {
11231 self.request_autoscroll(autoscroll, cx);
11232 }
11233 cx.notify();
11234 }
11235
11236 pub fn row_for_block(
11237 &self,
11238 block_id: CustomBlockId,
11239 cx: &mut ViewContext<Self>,
11240 ) -> Option<DisplayRow> {
11241 self.display_map
11242 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11243 }
11244
11245 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11246 self.focused_block = Some(focused_block);
11247 }
11248
11249 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11250 self.focused_block.take()
11251 }
11252
11253 pub fn insert_creases(
11254 &mut self,
11255 creases: impl IntoIterator<Item = Crease<Anchor>>,
11256 cx: &mut ViewContext<Self>,
11257 ) -> Vec<CreaseId> {
11258 self.display_map
11259 .update(cx, |map, cx| map.insert_creases(creases, cx))
11260 }
11261
11262 pub fn remove_creases(
11263 &mut self,
11264 ids: impl IntoIterator<Item = CreaseId>,
11265 cx: &mut ViewContext<Self>,
11266 ) {
11267 self.display_map
11268 .update(cx, |map, cx| map.remove_creases(ids, cx));
11269 }
11270
11271 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11272 self.display_map
11273 .update(cx, |map, cx| map.snapshot(cx))
11274 .longest_row()
11275 }
11276
11277 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11278 self.display_map
11279 .update(cx, |map, cx| map.snapshot(cx))
11280 .max_point()
11281 }
11282
11283 pub fn text(&self, cx: &AppContext) -> String {
11284 self.buffer.read(cx).read(cx).text()
11285 }
11286
11287 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11288 let text = self.text(cx);
11289 let text = text.trim();
11290
11291 if text.is_empty() {
11292 return None;
11293 }
11294
11295 Some(text.to_string())
11296 }
11297
11298 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11299 self.transact(cx, |this, cx| {
11300 this.buffer
11301 .read(cx)
11302 .as_singleton()
11303 .expect("you can only call set_text on editors for singleton buffers")
11304 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11305 });
11306 }
11307
11308 pub fn display_text(&self, cx: &mut AppContext) -> String {
11309 self.display_map
11310 .update(cx, |map, cx| map.snapshot(cx))
11311 .text()
11312 }
11313
11314 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11315 let mut wrap_guides = smallvec::smallvec![];
11316
11317 if self.show_wrap_guides == Some(false) {
11318 return wrap_guides;
11319 }
11320
11321 let settings = self.buffer.read(cx).settings_at(0, cx);
11322 if settings.show_wrap_guides {
11323 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11324 wrap_guides.push((soft_wrap as usize, true));
11325 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11326 wrap_guides.push((soft_wrap as usize, true));
11327 }
11328 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11329 }
11330
11331 wrap_guides
11332 }
11333
11334 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11335 let settings = self.buffer.read(cx).settings_at(0, cx);
11336 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11337 match mode {
11338 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11339 SoftWrap::None
11340 }
11341 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11342 language_settings::SoftWrap::PreferredLineLength => {
11343 SoftWrap::Column(settings.preferred_line_length)
11344 }
11345 language_settings::SoftWrap::Bounded => {
11346 SoftWrap::Bounded(settings.preferred_line_length)
11347 }
11348 }
11349 }
11350
11351 pub fn set_soft_wrap_mode(
11352 &mut self,
11353 mode: language_settings::SoftWrap,
11354 cx: &mut ViewContext<Self>,
11355 ) {
11356 self.soft_wrap_mode_override = Some(mode);
11357 cx.notify();
11358 }
11359
11360 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11361 self.text_style_refinement = Some(style);
11362 }
11363
11364 /// called by the Element so we know what style we were most recently rendered with.
11365 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11366 let rem_size = cx.rem_size();
11367 self.display_map.update(cx, |map, cx| {
11368 map.set_font(
11369 style.text.font(),
11370 style.text.font_size.to_pixels(rem_size),
11371 cx,
11372 )
11373 });
11374 self.style = Some(style);
11375 }
11376
11377 pub fn style(&self) -> Option<&EditorStyle> {
11378 self.style.as_ref()
11379 }
11380
11381 // Called by the element. This method is not designed to be called outside of the editor
11382 // element's layout code because it does not notify when rewrapping is computed synchronously.
11383 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11384 self.display_map
11385 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11386 }
11387
11388 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11389 if self.soft_wrap_mode_override.is_some() {
11390 self.soft_wrap_mode_override.take();
11391 } else {
11392 let soft_wrap = match self.soft_wrap_mode(cx) {
11393 SoftWrap::GitDiff => return,
11394 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11395 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11396 language_settings::SoftWrap::None
11397 }
11398 };
11399 self.soft_wrap_mode_override = Some(soft_wrap);
11400 }
11401 cx.notify();
11402 }
11403
11404 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11405 let Some(workspace) = self.workspace() else {
11406 return;
11407 };
11408 let fs = workspace.read(cx).app_state().fs.clone();
11409 let current_show = TabBarSettings::get_global(cx).show;
11410 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11411 setting.show = Some(!current_show);
11412 });
11413 }
11414
11415 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11416 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11417 self.buffer
11418 .read(cx)
11419 .settings_at(0, cx)
11420 .indent_guides
11421 .enabled
11422 });
11423 self.show_indent_guides = Some(!currently_enabled);
11424 cx.notify();
11425 }
11426
11427 fn should_show_indent_guides(&self) -> Option<bool> {
11428 self.show_indent_guides
11429 }
11430
11431 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11432 let mut editor_settings = EditorSettings::get_global(cx).clone();
11433 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11434 EditorSettings::override_global(editor_settings, cx);
11435 }
11436
11437 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11438 self.use_relative_line_numbers
11439 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11440 }
11441
11442 pub fn toggle_relative_line_numbers(
11443 &mut self,
11444 _: &ToggleRelativeLineNumbers,
11445 cx: &mut ViewContext<Self>,
11446 ) {
11447 let is_relative = self.should_use_relative_line_numbers(cx);
11448 self.set_relative_line_number(Some(!is_relative), cx)
11449 }
11450
11451 pub fn set_relative_line_number(
11452 &mut self,
11453 is_relative: Option<bool>,
11454 cx: &mut ViewContext<Self>,
11455 ) {
11456 self.use_relative_line_numbers = is_relative;
11457 cx.notify();
11458 }
11459
11460 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11461 self.show_gutter = show_gutter;
11462 cx.notify();
11463 }
11464
11465 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11466 self.show_scrollbars = show_scrollbars;
11467 cx.notify();
11468 }
11469
11470 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11471 self.show_line_numbers = Some(show_line_numbers);
11472 cx.notify();
11473 }
11474
11475 pub fn set_show_git_diff_gutter(
11476 &mut self,
11477 show_git_diff_gutter: bool,
11478 cx: &mut ViewContext<Self>,
11479 ) {
11480 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11481 cx.notify();
11482 }
11483
11484 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11485 self.show_code_actions = Some(show_code_actions);
11486 cx.notify();
11487 }
11488
11489 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11490 self.show_runnables = Some(show_runnables);
11491 cx.notify();
11492 }
11493
11494 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11495 if self.display_map.read(cx).masked != masked {
11496 self.display_map.update(cx, |map, _| map.masked = masked);
11497 }
11498 cx.notify()
11499 }
11500
11501 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11502 self.show_wrap_guides = Some(show_wrap_guides);
11503 cx.notify();
11504 }
11505
11506 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11507 self.show_indent_guides = Some(show_indent_guides);
11508 cx.notify();
11509 }
11510
11511 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11512 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11513 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11514 if let Some(dir) = file.abs_path(cx).parent() {
11515 return Some(dir.to_owned());
11516 }
11517 }
11518
11519 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11520 return Some(project_path.path.to_path_buf());
11521 }
11522 }
11523
11524 None
11525 }
11526
11527 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11528 self.active_excerpt(cx)?
11529 .1
11530 .read(cx)
11531 .file()
11532 .and_then(|f| f.as_local())
11533 }
11534
11535 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11536 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11537 let project_path = buffer.read(cx).project_path(cx)?;
11538 let project = self.project.as_ref()?.read(cx);
11539 project.absolute_path(&project_path, cx)
11540 })
11541 }
11542
11543 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11544 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11545 let project_path = buffer.read(cx).project_path(cx)?;
11546 let project = self.project.as_ref()?.read(cx);
11547 let entry = project.entry_for_path(&project_path, cx)?;
11548 let path = entry.path.to_path_buf();
11549 Some(path)
11550 })
11551 }
11552
11553 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11554 if let Some(target) = self.target_file(cx) {
11555 cx.reveal_path(&target.abs_path(cx));
11556 }
11557 }
11558
11559 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11560 if let Some(path) = self.target_file_abs_path(cx) {
11561 if let Some(path) = path.to_str() {
11562 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11563 }
11564 }
11565 }
11566
11567 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11568 if let Some(path) = self.target_file_path(cx) {
11569 if let Some(path) = path.to_str() {
11570 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11571 }
11572 }
11573 }
11574
11575 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11576 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11577
11578 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11579 self.start_git_blame(true, cx);
11580 }
11581
11582 cx.notify();
11583 }
11584
11585 pub fn toggle_git_blame_inline(
11586 &mut self,
11587 _: &ToggleGitBlameInline,
11588 cx: &mut ViewContext<Self>,
11589 ) {
11590 self.toggle_git_blame_inline_internal(true, cx);
11591 cx.notify();
11592 }
11593
11594 pub fn git_blame_inline_enabled(&self) -> bool {
11595 self.git_blame_inline_enabled
11596 }
11597
11598 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11599 self.show_selection_menu = self
11600 .show_selection_menu
11601 .map(|show_selections_menu| !show_selections_menu)
11602 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11603
11604 cx.notify();
11605 }
11606
11607 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11608 self.show_selection_menu
11609 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11610 }
11611
11612 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11613 if let Some(project) = self.project.as_ref() {
11614 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11615 return;
11616 };
11617
11618 if buffer.read(cx).file().is_none() {
11619 return;
11620 }
11621
11622 let focused = self.focus_handle(cx).contains_focused(cx);
11623
11624 let project = project.clone();
11625 let blame =
11626 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11627 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11628 self.blame = Some(blame);
11629 }
11630 }
11631
11632 fn toggle_git_blame_inline_internal(
11633 &mut self,
11634 user_triggered: bool,
11635 cx: &mut ViewContext<Self>,
11636 ) {
11637 if self.git_blame_inline_enabled {
11638 self.git_blame_inline_enabled = false;
11639 self.show_git_blame_inline = false;
11640 self.show_git_blame_inline_delay_task.take();
11641 } else {
11642 self.git_blame_inline_enabled = true;
11643 self.start_git_blame_inline(user_triggered, cx);
11644 }
11645
11646 cx.notify();
11647 }
11648
11649 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11650 self.start_git_blame(user_triggered, cx);
11651
11652 if ProjectSettings::get_global(cx)
11653 .git
11654 .inline_blame_delay()
11655 .is_some()
11656 {
11657 self.start_inline_blame_timer(cx);
11658 } else {
11659 self.show_git_blame_inline = true
11660 }
11661 }
11662
11663 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11664 self.blame.as_ref()
11665 }
11666
11667 pub fn show_git_blame_gutter(&self) -> bool {
11668 self.show_git_blame_gutter
11669 }
11670
11671 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11672 self.show_git_blame_gutter && self.has_blame_entries(cx)
11673 }
11674
11675 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11676 self.show_git_blame_inline
11677 && self.focus_handle.is_focused(cx)
11678 && !self.newest_selection_head_on_empty_line(cx)
11679 && self.has_blame_entries(cx)
11680 }
11681
11682 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11683 self.blame()
11684 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11685 }
11686
11687 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11688 let cursor_anchor = self.selections.newest_anchor().head();
11689
11690 let snapshot = self.buffer.read(cx).snapshot(cx);
11691 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11692
11693 snapshot.line_len(buffer_row) == 0
11694 }
11695
11696 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11697 let buffer_and_selection = maybe!({
11698 let selection = self.selections.newest::<Point>(cx);
11699 let selection_range = selection.range();
11700
11701 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11702 (buffer, selection_range.start.row..selection_range.end.row)
11703 } else {
11704 let multi_buffer = self.buffer().read(cx);
11705 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11706 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11707
11708 let (excerpt, range) = if selection.reversed {
11709 buffer_ranges.first()
11710 } else {
11711 buffer_ranges.last()
11712 }?;
11713
11714 let snapshot = excerpt.buffer();
11715 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11716 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11717 (
11718 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11719 selection,
11720 )
11721 };
11722
11723 Some((buffer, selection))
11724 });
11725
11726 let Some((buffer, selection)) = buffer_and_selection else {
11727 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11728 };
11729
11730 let Some(project) = self.project.as_ref() else {
11731 return Task::ready(Err(anyhow!("editor does not have project")));
11732 };
11733
11734 project.update(cx, |project, cx| {
11735 project.get_permalink_to_line(&buffer, selection, cx)
11736 })
11737 }
11738
11739 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11740 let permalink_task = self.get_permalink_to_line(cx);
11741 let workspace = self.workspace();
11742
11743 cx.spawn(|_, mut cx| async move {
11744 match permalink_task.await {
11745 Ok(permalink) => {
11746 cx.update(|cx| {
11747 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11748 })
11749 .ok();
11750 }
11751 Err(err) => {
11752 let message = format!("Failed to copy permalink: {err}");
11753
11754 Err::<(), anyhow::Error>(err).log_err();
11755
11756 if let Some(workspace) = workspace {
11757 workspace
11758 .update(&mut cx, |workspace, cx| {
11759 struct CopyPermalinkToLine;
11760
11761 workspace.show_toast(
11762 Toast::new(
11763 NotificationId::unique::<CopyPermalinkToLine>(),
11764 message,
11765 ),
11766 cx,
11767 )
11768 })
11769 .ok();
11770 }
11771 }
11772 }
11773 })
11774 .detach();
11775 }
11776
11777 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11778 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11779 if let Some(file) = self.target_file(cx) {
11780 if let Some(path) = file.path().to_str() {
11781 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11782 }
11783 }
11784 }
11785
11786 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11787 let permalink_task = self.get_permalink_to_line(cx);
11788 let workspace = self.workspace();
11789
11790 cx.spawn(|_, mut cx| async move {
11791 match permalink_task.await {
11792 Ok(permalink) => {
11793 cx.update(|cx| {
11794 cx.open_url(permalink.as_ref());
11795 })
11796 .ok();
11797 }
11798 Err(err) => {
11799 let message = format!("Failed to open permalink: {err}");
11800
11801 Err::<(), anyhow::Error>(err).log_err();
11802
11803 if let Some(workspace) = workspace {
11804 workspace
11805 .update(&mut cx, |workspace, cx| {
11806 struct OpenPermalinkToLine;
11807
11808 workspace.show_toast(
11809 Toast::new(
11810 NotificationId::unique::<OpenPermalinkToLine>(),
11811 message,
11812 ),
11813 cx,
11814 )
11815 })
11816 .ok();
11817 }
11818 }
11819 }
11820 })
11821 .detach();
11822 }
11823
11824 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11825 self.insert_uuid(UuidVersion::V4, cx);
11826 }
11827
11828 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11829 self.insert_uuid(UuidVersion::V7, cx);
11830 }
11831
11832 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11833 self.transact(cx, |this, cx| {
11834 let edits = this
11835 .selections
11836 .all::<Point>(cx)
11837 .into_iter()
11838 .map(|selection| {
11839 let uuid = match version {
11840 UuidVersion::V4 => uuid::Uuid::new_v4(),
11841 UuidVersion::V7 => uuid::Uuid::now_v7(),
11842 };
11843
11844 (selection.range(), uuid.to_string())
11845 });
11846 this.edit(edits, cx);
11847 this.refresh_inline_completion(true, false, cx);
11848 });
11849 }
11850
11851 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11852 /// last highlight added will be used.
11853 ///
11854 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11855 pub fn highlight_rows<T: 'static>(
11856 &mut self,
11857 range: Range<Anchor>,
11858 color: Hsla,
11859 should_autoscroll: bool,
11860 cx: &mut ViewContext<Self>,
11861 ) {
11862 let snapshot = self.buffer().read(cx).snapshot(cx);
11863 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11864 let ix = row_highlights.binary_search_by(|highlight| {
11865 Ordering::Equal
11866 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11867 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11868 });
11869
11870 if let Err(mut ix) = ix {
11871 let index = post_inc(&mut self.highlight_order);
11872
11873 // If this range intersects with the preceding highlight, then merge it with
11874 // the preceding highlight. Otherwise insert a new highlight.
11875 let mut merged = false;
11876 if ix > 0 {
11877 let prev_highlight = &mut row_highlights[ix - 1];
11878 if prev_highlight
11879 .range
11880 .end
11881 .cmp(&range.start, &snapshot)
11882 .is_ge()
11883 {
11884 ix -= 1;
11885 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11886 prev_highlight.range.end = range.end;
11887 }
11888 merged = true;
11889 prev_highlight.index = index;
11890 prev_highlight.color = color;
11891 prev_highlight.should_autoscroll = should_autoscroll;
11892 }
11893 }
11894
11895 if !merged {
11896 row_highlights.insert(
11897 ix,
11898 RowHighlight {
11899 range: range.clone(),
11900 index,
11901 color,
11902 should_autoscroll,
11903 },
11904 );
11905 }
11906
11907 // If any of the following highlights intersect with this one, merge them.
11908 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11909 let highlight = &row_highlights[ix];
11910 if next_highlight
11911 .range
11912 .start
11913 .cmp(&highlight.range.end, &snapshot)
11914 .is_le()
11915 {
11916 if next_highlight
11917 .range
11918 .end
11919 .cmp(&highlight.range.end, &snapshot)
11920 .is_gt()
11921 {
11922 row_highlights[ix].range.end = next_highlight.range.end;
11923 }
11924 row_highlights.remove(ix + 1);
11925 } else {
11926 break;
11927 }
11928 }
11929 }
11930 }
11931
11932 /// Remove any highlighted row ranges of the given type that intersect the
11933 /// given ranges.
11934 pub fn remove_highlighted_rows<T: 'static>(
11935 &mut self,
11936 ranges_to_remove: Vec<Range<Anchor>>,
11937 cx: &mut ViewContext<Self>,
11938 ) {
11939 let snapshot = self.buffer().read(cx).snapshot(cx);
11940 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11941 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11942 row_highlights.retain(|highlight| {
11943 while let Some(range_to_remove) = ranges_to_remove.peek() {
11944 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11945 Ordering::Less | Ordering::Equal => {
11946 ranges_to_remove.next();
11947 }
11948 Ordering::Greater => {
11949 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11950 Ordering::Less | Ordering::Equal => {
11951 return false;
11952 }
11953 Ordering::Greater => break,
11954 }
11955 }
11956 }
11957 }
11958
11959 true
11960 })
11961 }
11962
11963 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11964 pub fn clear_row_highlights<T: 'static>(&mut self) {
11965 self.highlighted_rows.remove(&TypeId::of::<T>());
11966 }
11967
11968 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11969 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11970 self.highlighted_rows
11971 .get(&TypeId::of::<T>())
11972 .map_or(&[] as &[_], |vec| vec.as_slice())
11973 .iter()
11974 .map(|highlight| (highlight.range.clone(), highlight.color))
11975 }
11976
11977 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11978 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11979 /// Allows to ignore certain kinds of highlights.
11980 pub fn highlighted_display_rows(
11981 &mut self,
11982 cx: &mut WindowContext,
11983 ) -> BTreeMap<DisplayRow, Hsla> {
11984 let snapshot = self.snapshot(cx);
11985 let mut used_highlight_orders = HashMap::default();
11986 self.highlighted_rows
11987 .iter()
11988 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11989 .fold(
11990 BTreeMap::<DisplayRow, Hsla>::new(),
11991 |mut unique_rows, highlight| {
11992 let start = highlight.range.start.to_display_point(&snapshot);
11993 let end = highlight.range.end.to_display_point(&snapshot);
11994 let start_row = start.row().0;
11995 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11996 && end.column() == 0
11997 {
11998 end.row().0.saturating_sub(1)
11999 } else {
12000 end.row().0
12001 };
12002 for row in start_row..=end_row {
12003 let used_index =
12004 used_highlight_orders.entry(row).or_insert(highlight.index);
12005 if highlight.index >= *used_index {
12006 *used_index = highlight.index;
12007 unique_rows.insert(DisplayRow(row), highlight.color);
12008 }
12009 }
12010 unique_rows
12011 },
12012 )
12013 }
12014
12015 pub fn highlighted_display_row_for_autoscroll(
12016 &self,
12017 snapshot: &DisplaySnapshot,
12018 ) -> Option<DisplayRow> {
12019 self.highlighted_rows
12020 .values()
12021 .flat_map(|highlighted_rows| highlighted_rows.iter())
12022 .filter_map(|highlight| {
12023 if highlight.should_autoscroll {
12024 Some(highlight.range.start.to_display_point(snapshot).row())
12025 } else {
12026 None
12027 }
12028 })
12029 .min()
12030 }
12031
12032 pub fn set_search_within_ranges(
12033 &mut self,
12034 ranges: &[Range<Anchor>],
12035 cx: &mut ViewContext<Self>,
12036 ) {
12037 self.highlight_background::<SearchWithinRange>(
12038 ranges,
12039 |colors| colors.editor_document_highlight_read_background,
12040 cx,
12041 )
12042 }
12043
12044 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12045 self.breadcrumb_header = Some(new_header);
12046 }
12047
12048 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12049 self.clear_background_highlights::<SearchWithinRange>(cx);
12050 }
12051
12052 pub fn highlight_background<T: 'static>(
12053 &mut self,
12054 ranges: &[Range<Anchor>],
12055 color_fetcher: fn(&ThemeColors) -> Hsla,
12056 cx: &mut ViewContext<Self>,
12057 ) {
12058 self.background_highlights
12059 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12060 self.scrollbar_marker_state.dirty = true;
12061 cx.notify();
12062 }
12063
12064 pub fn clear_background_highlights<T: 'static>(
12065 &mut self,
12066 cx: &mut ViewContext<Self>,
12067 ) -> Option<BackgroundHighlight> {
12068 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12069 if !text_highlights.1.is_empty() {
12070 self.scrollbar_marker_state.dirty = true;
12071 cx.notify();
12072 }
12073 Some(text_highlights)
12074 }
12075
12076 pub fn highlight_gutter<T: 'static>(
12077 &mut self,
12078 ranges: &[Range<Anchor>],
12079 color_fetcher: fn(&AppContext) -> Hsla,
12080 cx: &mut ViewContext<Self>,
12081 ) {
12082 self.gutter_highlights
12083 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12084 cx.notify();
12085 }
12086
12087 pub fn clear_gutter_highlights<T: 'static>(
12088 &mut self,
12089 cx: &mut ViewContext<Self>,
12090 ) -> Option<GutterHighlight> {
12091 cx.notify();
12092 self.gutter_highlights.remove(&TypeId::of::<T>())
12093 }
12094
12095 #[cfg(feature = "test-support")]
12096 pub fn all_text_background_highlights(
12097 &mut self,
12098 cx: &mut ViewContext<Self>,
12099 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12100 let snapshot = self.snapshot(cx);
12101 let buffer = &snapshot.buffer_snapshot;
12102 let start = buffer.anchor_before(0);
12103 let end = buffer.anchor_after(buffer.len());
12104 let theme = cx.theme().colors();
12105 self.background_highlights_in_range(start..end, &snapshot, theme)
12106 }
12107
12108 #[cfg(feature = "test-support")]
12109 pub fn search_background_highlights(
12110 &mut self,
12111 cx: &mut ViewContext<Self>,
12112 ) -> Vec<Range<Point>> {
12113 let snapshot = self.buffer().read(cx).snapshot(cx);
12114
12115 let highlights = self
12116 .background_highlights
12117 .get(&TypeId::of::<items::BufferSearchHighlights>());
12118
12119 if let Some((_color, ranges)) = highlights {
12120 ranges
12121 .iter()
12122 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12123 .collect_vec()
12124 } else {
12125 vec![]
12126 }
12127 }
12128
12129 fn document_highlights_for_position<'a>(
12130 &'a self,
12131 position: Anchor,
12132 buffer: &'a MultiBufferSnapshot,
12133 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12134 let read_highlights = self
12135 .background_highlights
12136 .get(&TypeId::of::<DocumentHighlightRead>())
12137 .map(|h| &h.1);
12138 let write_highlights = self
12139 .background_highlights
12140 .get(&TypeId::of::<DocumentHighlightWrite>())
12141 .map(|h| &h.1);
12142 let left_position = position.bias_left(buffer);
12143 let right_position = position.bias_right(buffer);
12144 read_highlights
12145 .into_iter()
12146 .chain(write_highlights)
12147 .flat_map(move |ranges| {
12148 let start_ix = match ranges.binary_search_by(|probe| {
12149 let cmp = probe.end.cmp(&left_position, buffer);
12150 if cmp.is_ge() {
12151 Ordering::Greater
12152 } else {
12153 Ordering::Less
12154 }
12155 }) {
12156 Ok(i) | Err(i) => i,
12157 };
12158
12159 ranges[start_ix..]
12160 .iter()
12161 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12162 })
12163 }
12164
12165 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12166 self.background_highlights
12167 .get(&TypeId::of::<T>())
12168 .map_or(false, |(_, highlights)| !highlights.is_empty())
12169 }
12170
12171 pub fn background_highlights_in_range(
12172 &self,
12173 search_range: Range<Anchor>,
12174 display_snapshot: &DisplaySnapshot,
12175 theme: &ThemeColors,
12176 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12177 let mut results = Vec::new();
12178 for (color_fetcher, ranges) in self.background_highlights.values() {
12179 let color = color_fetcher(theme);
12180 let start_ix = match ranges.binary_search_by(|probe| {
12181 let cmp = probe
12182 .end
12183 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12184 if cmp.is_gt() {
12185 Ordering::Greater
12186 } else {
12187 Ordering::Less
12188 }
12189 }) {
12190 Ok(i) | Err(i) => i,
12191 };
12192 for range in &ranges[start_ix..] {
12193 if range
12194 .start
12195 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12196 .is_ge()
12197 {
12198 break;
12199 }
12200
12201 let start = range.start.to_display_point(display_snapshot);
12202 let end = range.end.to_display_point(display_snapshot);
12203 results.push((start..end, color))
12204 }
12205 }
12206 results
12207 }
12208
12209 pub fn background_highlight_row_ranges<T: 'static>(
12210 &self,
12211 search_range: Range<Anchor>,
12212 display_snapshot: &DisplaySnapshot,
12213 count: usize,
12214 ) -> Vec<RangeInclusive<DisplayPoint>> {
12215 let mut results = Vec::new();
12216 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12217 return vec![];
12218 };
12219
12220 let start_ix = match ranges.binary_search_by(|probe| {
12221 let cmp = probe
12222 .end
12223 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12224 if cmp.is_gt() {
12225 Ordering::Greater
12226 } else {
12227 Ordering::Less
12228 }
12229 }) {
12230 Ok(i) | Err(i) => i,
12231 };
12232 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12233 if let (Some(start_display), Some(end_display)) = (start, end) {
12234 results.push(
12235 start_display.to_display_point(display_snapshot)
12236 ..=end_display.to_display_point(display_snapshot),
12237 );
12238 }
12239 };
12240 let mut start_row: Option<Point> = None;
12241 let mut end_row: Option<Point> = None;
12242 if ranges.len() > count {
12243 return Vec::new();
12244 }
12245 for range in &ranges[start_ix..] {
12246 if range
12247 .start
12248 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12249 .is_ge()
12250 {
12251 break;
12252 }
12253 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12254 if let Some(current_row) = &end_row {
12255 if end.row == current_row.row {
12256 continue;
12257 }
12258 }
12259 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12260 if start_row.is_none() {
12261 assert_eq!(end_row, None);
12262 start_row = Some(start);
12263 end_row = Some(end);
12264 continue;
12265 }
12266 if let Some(current_end) = end_row.as_mut() {
12267 if start.row > current_end.row + 1 {
12268 push_region(start_row, end_row);
12269 start_row = Some(start);
12270 end_row = Some(end);
12271 } else {
12272 // Merge two hunks.
12273 *current_end = end;
12274 }
12275 } else {
12276 unreachable!();
12277 }
12278 }
12279 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12280 push_region(start_row, end_row);
12281 results
12282 }
12283
12284 pub fn gutter_highlights_in_range(
12285 &self,
12286 search_range: Range<Anchor>,
12287 display_snapshot: &DisplaySnapshot,
12288 cx: &AppContext,
12289 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12290 let mut results = Vec::new();
12291 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12292 let color = color_fetcher(cx);
12293 let start_ix = match ranges.binary_search_by(|probe| {
12294 let cmp = probe
12295 .end
12296 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12297 if cmp.is_gt() {
12298 Ordering::Greater
12299 } else {
12300 Ordering::Less
12301 }
12302 }) {
12303 Ok(i) | Err(i) => i,
12304 };
12305 for range in &ranges[start_ix..] {
12306 if range
12307 .start
12308 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12309 .is_ge()
12310 {
12311 break;
12312 }
12313
12314 let start = range.start.to_display_point(display_snapshot);
12315 let end = range.end.to_display_point(display_snapshot);
12316 results.push((start..end, color))
12317 }
12318 }
12319 results
12320 }
12321
12322 /// Get the text ranges corresponding to the redaction query
12323 pub fn redacted_ranges(
12324 &self,
12325 search_range: Range<Anchor>,
12326 display_snapshot: &DisplaySnapshot,
12327 cx: &WindowContext,
12328 ) -> Vec<Range<DisplayPoint>> {
12329 display_snapshot
12330 .buffer_snapshot
12331 .redacted_ranges(search_range, |file| {
12332 if let Some(file) = file {
12333 file.is_private()
12334 && EditorSettings::get(
12335 Some(SettingsLocation {
12336 worktree_id: file.worktree_id(cx),
12337 path: file.path().as_ref(),
12338 }),
12339 cx,
12340 )
12341 .redact_private_values
12342 } else {
12343 false
12344 }
12345 })
12346 .map(|range| {
12347 range.start.to_display_point(display_snapshot)
12348 ..range.end.to_display_point(display_snapshot)
12349 })
12350 .collect()
12351 }
12352
12353 pub fn highlight_text<T: 'static>(
12354 &mut self,
12355 ranges: Vec<Range<Anchor>>,
12356 style: HighlightStyle,
12357 cx: &mut ViewContext<Self>,
12358 ) {
12359 self.display_map.update(cx, |map, _| {
12360 map.highlight_text(TypeId::of::<T>(), ranges, style)
12361 });
12362 cx.notify();
12363 }
12364
12365 pub(crate) fn highlight_inlays<T: 'static>(
12366 &mut self,
12367 highlights: Vec<InlayHighlight>,
12368 style: HighlightStyle,
12369 cx: &mut ViewContext<Self>,
12370 ) {
12371 self.display_map.update(cx, |map, _| {
12372 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12373 });
12374 cx.notify();
12375 }
12376
12377 pub fn text_highlights<'a, T: 'static>(
12378 &'a self,
12379 cx: &'a AppContext,
12380 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12381 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12382 }
12383
12384 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12385 let cleared = self
12386 .display_map
12387 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12388 if cleared {
12389 cx.notify();
12390 }
12391 }
12392
12393 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12394 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12395 && self.focus_handle.is_focused(cx)
12396 }
12397
12398 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12399 self.show_cursor_when_unfocused = is_enabled;
12400 cx.notify();
12401 }
12402
12403 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12404 self.project
12405 .as_ref()
12406 .map(|project| project.read(cx).lsp_store())
12407 }
12408
12409 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12410 cx.notify();
12411 }
12412
12413 fn on_buffer_event(
12414 &mut self,
12415 multibuffer: Model<MultiBuffer>,
12416 event: &multi_buffer::Event,
12417 cx: &mut ViewContext<Self>,
12418 ) {
12419 match event {
12420 multi_buffer::Event::Edited {
12421 singleton_buffer_edited,
12422 edited_buffer: buffer_edited,
12423 } => {
12424 self.scrollbar_marker_state.dirty = true;
12425 self.active_indent_guides_state.dirty = true;
12426 self.refresh_active_diagnostics(cx);
12427 self.refresh_code_actions(cx);
12428 if self.has_active_inline_completion() {
12429 self.update_visible_inline_completion(cx);
12430 }
12431 if let Some(buffer) = buffer_edited {
12432 let buffer_id = buffer.read(cx).remote_id();
12433 if !self.registered_buffers.contains_key(&buffer_id) {
12434 if let Some(lsp_store) = self.lsp_store(cx) {
12435 lsp_store.update(cx, |lsp_store, cx| {
12436 self.registered_buffers.insert(
12437 buffer_id,
12438 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12439 );
12440 })
12441 }
12442 }
12443 }
12444 cx.emit(EditorEvent::BufferEdited);
12445 cx.emit(SearchEvent::MatchesInvalidated);
12446 if *singleton_buffer_edited {
12447 if let Some(project) = &self.project {
12448 let project = project.read(cx);
12449 #[allow(clippy::mutable_key_type)]
12450 let languages_affected = multibuffer
12451 .read(cx)
12452 .all_buffers()
12453 .into_iter()
12454 .filter_map(|buffer| {
12455 let buffer = buffer.read(cx);
12456 let language = buffer.language()?;
12457 if project.is_local()
12458 && project
12459 .language_servers_for_local_buffer(buffer, cx)
12460 .count()
12461 == 0
12462 {
12463 None
12464 } else {
12465 Some(language)
12466 }
12467 })
12468 .cloned()
12469 .collect::<HashSet<_>>();
12470 if !languages_affected.is_empty() {
12471 self.refresh_inlay_hints(
12472 InlayHintRefreshReason::BufferEdited(languages_affected),
12473 cx,
12474 );
12475 }
12476 }
12477 }
12478
12479 let Some(project) = &self.project else { return };
12480 let (telemetry, is_via_ssh) = {
12481 let project = project.read(cx);
12482 let telemetry = project.client().telemetry().clone();
12483 let is_via_ssh = project.is_via_ssh();
12484 (telemetry, is_via_ssh)
12485 };
12486 refresh_linked_ranges(self, cx);
12487 telemetry.log_edit_event("editor", is_via_ssh);
12488 }
12489 multi_buffer::Event::ExcerptsAdded {
12490 buffer,
12491 predecessor,
12492 excerpts,
12493 } => {
12494 self.tasks_update_task = Some(self.refresh_runnables(cx));
12495 let buffer_id = buffer.read(cx).remote_id();
12496 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12497 if let Some(project) = &self.project {
12498 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12499 }
12500 }
12501 cx.emit(EditorEvent::ExcerptsAdded {
12502 buffer: buffer.clone(),
12503 predecessor: *predecessor,
12504 excerpts: excerpts.clone(),
12505 });
12506 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12507 }
12508 multi_buffer::Event::ExcerptsRemoved { ids } => {
12509 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12510 let buffer = self.buffer.read(cx);
12511 self.registered_buffers
12512 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12513 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12514 }
12515 multi_buffer::Event::ExcerptsEdited { ids } => {
12516 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12517 }
12518 multi_buffer::Event::ExcerptsExpanded { ids } => {
12519 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12520 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12521 }
12522 multi_buffer::Event::Reparsed(buffer_id) => {
12523 self.tasks_update_task = Some(self.refresh_runnables(cx));
12524
12525 cx.emit(EditorEvent::Reparsed(*buffer_id));
12526 }
12527 multi_buffer::Event::LanguageChanged(buffer_id) => {
12528 linked_editing_ranges::refresh_linked_ranges(self, cx);
12529 cx.emit(EditorEvent::Reparsed(*buffer_id));
12530 cx.notify();
12531 }
12532 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12533 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12534 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12535 cx.emit(EditorEvent::TitleChanged)
12536 }
12537 // multi_buffer::Event::DiffBaseChanged => {
12538 // self.scrollbar_marker_state.dirty = true;
12539 // cx.emit(EditorEvent::DiffBaseChanged);
12540 // cx.notify();
12541 // }
12542 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12543 multi_buffer::Event::DiagnosticsUpdated => {
12544 self.refresh_active_diagnostics(cx);
12545 self.scrollbar_marker_state.dirty = true;
12546 cx.notify();
12547 }
12548 _ => {}
12549 };
12550 }
12551
12552 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12553 cx.notify();
12554 }
12555
12556 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12557 self.tasks_update_task = Some(self.refresh_runnables(cx));
12558 self.refresh_inline_completion(true, false, cx);
12559 self.refresh_inlay_hints(
12560 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12561 self.selections.newest_anchor().head(),
12562 &self.buffer.read(cx).snapshot(cx),
12563 cx,
12564 )),
12565 cx,
12566 );
12567
12568 let old_cursor_shape = self.cursor_shape;
12569
12570 {
12571 let editor_settings = EditorSettings::get_global(cx);
12572 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12573 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12574 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12575 }
12576
12577 if old_cursor_shape != self.cursor_shape {
12578 cx.emit(EditorEvent::CursorShapeChanged);
12579 }
12580
12581 let project_settings = ProjectSettings::get_global(cx);
12582 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12583
12584 if self.mode == EditorMode::Full {
12585 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12586 if self.git_blame_inline_enabled != inline_blame_enabled {
12587 self.toggle_git_blame_inline_internal(false, cx);
12588 }
12589 }
12590
12591 cx.notify();
12592 }
12593
12594 pub fn set_searchable(&mut self, searchable: bool) {
12595 self.searchable = searchable;
12596 }
12597
12598 pub fn searchable(&self) -> bool {
12599 self.searchable
12600 }
12601
12602 fn open_proposed_changes_editor(
12603 &mut self,
12604 _: &OpenProposedChangesEditor,
12605 cx: &mut ViewContext<Self>,
12606 ) {
12607 let Some(workspace) = self.workspace() else {
12608 cx.propagate();
12609 return;
12610 };
12611
12612 let selections = self.selections.all::<usize>(cx);
12613 let multi_buffer = self.buffer.read(cx);
12614 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12615 let mut new_selections_by_buffer = HashMap::default();
12616 for selection in selections {
12617 for (excerpt, range) in
12618 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12619 {
12620 let mut range = range.to_point(excerpt.buffer());
12621 range.start.column = 0;
12622 range.end.column = excerpt.buffer().line_len(range.end.row);
12623 new_selections_by_buffer
12624 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12625 .or_insert(Vec::new())
12626 .push(range)
12627 }
12628 }
12629
12630 let proposed_changes_buffers = new_selections_by_buffer
12631 .into_iter()
12632 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12633 .collect::<Vec<_>>();
12634 let proposed_changes_editor = cx.new_view(|cx| {
12635 ProposedChangesEditor::new(
12636 "Proposed changes",
12637 proposed_changes_buffers,
12638 self.project.clone(),
12639 cx,
12640 )
12641 });
12642
12643 cx.window_context().defer(move |cx| {
12644 workspace.update(cx, |workspace, cx| {
12645 workspace.active_pane().update(cx, |pane, cx| {
12646 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12647 });
12648 });
12649 });
12650 }
12651
12652 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12653 self.open_excerpts_common(None, true, cx)
12654 }
12655
12656 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12657 self.open_excerpts_common(None, false, cx)
12658 }
12659
12660 fn open_excerpts_common(
12661 &mut self,
12662 jump_data: Option<JumpData>,
12663 split: bool,
12664 cx: &mut ViewContext<Self>,
12665 ) {
12666 let Some(workspace) = self.workspace() else {
12667 cx.propagate();
12668 return;
12669 };
12670
12671 if self.buffer.read(cx).is_singleton() {
12672 cx.propagate();
12673 return;
12674 }
12675
12676 let mut new_selections_by_buffer = HashMap::default();
12677 match &jump_data {
12678 Some(JumpData::MultiBufferPoint {
12679 excerpt_id,
12680 position,
12681 anchor,
12682 line_offset_from_top,
12683 }) => {
12684 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12685 if let Some(buffer) = multi_buffer_snapshot
12686 .buffer_id_for_excerpt(*excerpt_id)
12687 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12688 {
12689 let buffer_snapshot = buffer.read(cx).snapshot();
12690 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12691 language::ToPoint::to_point(anchor, &buffer_snapshot)
12692 } else {
12693 buffer_snapshot.clip_point(*position, Bias::Left)
12694 };
12695 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12696 new_selections_by_buffer.insert(
12697 buffer,
12698 (
12699 vec![jump_to_offset..jump_to_offset],
12700 Some(*line_offset_from_top),
12701 ),
12702 );
12703 }
12704 }
12705 Some(JumpData::MultiBufferRow {
12706 row,
12707 line_offset_from_top,
12708 }) => {
12709 let point = MultiBufferPoint::new(row.0, 0);
12710 if let Some((buffer, buffer_point, _)) =
12711 self.buffer.read(cx).point_to_buffer_point(point, cx)
12712 {
12713 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12714 new_selections_by_buffer
12715 .entry(buffer)
12716 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12717 .0
12718 .push(buffer_offset..buffer_offset)
12719 }
12720 }
12721 None => {
12722 let selections = self.selections.all::<usize>(cx);
12723 let multi_buffer = self.buffer.read(cx);
12724 for selection in selections {
12725 for (excerpt, mut range) in multi_buffer
12726 .snapshot(cx)
12727 .range_to_buffer_ranges(selection.range())
12728 {
12729 // When editing branch buffers, jump to the corresponding location
12730 // in their base buffer.
12731 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12732 let buffer = buffer_handle.read(cx);
12733 if let Some(base_buffer) = buffer.base_buffer() {
12734 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12735 buffer_handle = base_buffer;
12736 }
12737
12738 if selection.reversed {
12739 mem::swap(&mut range.start, &mut range.end);
12740 }
12741 new_selections_by_buffer
12742 .entry(buffer_handle)
12743 .or_insert((Vec::new(), None))
12744 .0
12745 .push(range)
12746 }
12747 }
12748 }
12749 }
12750
12751 if new_selections_by_buffer.is_empty() {
12752 return;
12753 }
12754
12755 // We defer the pane interaction because we ourselves are a workspace item
12756 // and activating a new item causes the pane to call a method on us reentrantly,
12757 // which panics if we're on the stack.
12758 cx.window_context().defer(move |cx| {
12759 workspace.update(cx, |workspace, cx| {
12760 let pane = if split {
12761 workspace.adjacent_pane(cx)
12762 } else {
12763 workspace.active_pane().clone()
12764 };
12765
12766 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12767 let editor = buffer
12768 .read(cx)
12769 .file()
12770 .is_none()
12771 .then(|| {
12772 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12773 // so `workspace.open_project_item` will never find them, always opening a new editor.
12774 // Instead, we try to activate the existing editor in the pane first.
12775 let (editor, pane_item_index) =
12776 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12777 let editor = item.downcast::<Editor>()?;
12778 let singleton_buffer =
12779 editor.read(cx).buffer().read(cx).as_singleton()?;
12780 if singleton_buffer == buffer {
12781 Some((editor, i))
12782 } else {
12783 None
12784 }
12785 })?;
12786 pane.update(cx, |pane, cx| {
12787 pane.activate_item(pane_item_index, true, true, cx)
12788 });
12789 Some(editor)
12790 })
12791 .flatten()
12792 .unwrap_or_else(|| {
12793 workspace.open_project_item::<Self>(
12794 pane.clone(),
12795 buffer,
12796 true,
12797 true,
12798 cx,
12799 )
12800 });
12801
12802 editor.update(cx, |editor, cx| {
12803 let autoscroll = match scroll_offset {
12804 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12805 None => Autoscroll::newest(),
12806 };
12807 let nav_history = editor.nav_history.take();
12808 editor.change_selections(Some(autoscroll), cx, |s| {
12809 s.select_ranges(ranges);
12810 });
12811 editor.nav_history = nav_history;
12812 });
12813 }
12814 })
12815 });
12816 }
12817
12818 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12819 let snapshot = self.buffer.read(cx).read(cx);
12820 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12821 Some(
12822 ranges
12823 .iter()
12824 .map(move |range| {
12825 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12826 })
12827 .collect(),
12828 )
12829 }
12830
12831 fn selection_replacement_ranges(
12832 &self,
12833 range: Range<OffsetUtf16>,
12834 cx: &mut AppContext,
12835 ) -> Vec<Range<OffsetUtf16>> {
12836 let selections = self.selections.all::<OffsetUtf16>(cx);
12837 let newest_selection = selections
12838 .iter()
12839 .max_by_key(|selection| selection.id)
12840 .unwrap();
12841 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12842 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12843 let snapshot = self.buffer.read(cx).read(cx);
12844 selections
12845 .into_iter()
12846 .map(|mut selection| {
12847 selection.start.0 =
12848 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12849 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12850 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12851 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12852 })
12853 .collect()
12854 }
12855
12856 fn report_editor_event(
12857 &self,
12858 event_type: &'static str,
12859 file_extension: Option<String>,
12860 cx: &AppContext,
12861 ) {
12862 if cfg!(any(test, feature = "test-support")) {
12863 return;
12864 }
12865
12866 let Some(project) = &self.project else { return };
12867
12868 // If None, we are in a file without an extension
12869 let file = self
12870 .buffer
12871 .read(cx)
12872 .as_singleton()
12873 .and_then(|b| b.read(cx).file());
12874 let file_extension = file_extension.or(file
12875 .as_ref()
12876 .and_then(|file| Path::new(file.file_name(cx)).extension())
12877 .and_then(|e| e.to_str())
12878 .map(|a| a.to_string()));
12879
12880 let vim_mode = cx
12881 .global::<SettingsStore>()
12882 .raw_user_settings()
12883 .get("vim_mode")
12884 == Some(&serde_json::Value::Bool(true));
12885
12886 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12887 == language::language_settings::InlineCompletionProvider::Copilot;
12888 let copilot_enabled_for_language = self
12889 .buffer
12890 .read(cx)
12891 .settings_at(0, cx)
12892 .show_inline_completions;
12893
12894 let project = project.read(cx);
12895 telemetry::event!(
12896 event_type,
12897 file_extension,
12898 vim_mode,
12899 copilot_enabled,
12900 copilot_enabled_for_language,
12901 is_via_ssh = project.is_via_ssh(),
12902 );
12903 }
12904
12905 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12906 /// with each line being an array of {text, highlight} objects.
12907 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12908 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12909 return;
12910 };
12911
12912 #[derive(Serialize)]
12913 struct Chunk<'a> {
12914 text: String,
12915 highlight: Option<&'a str>,
12916 }
12917
12918 let snapshot = buffer.read(cx).snapshot();
12919 let range = self
12920 .selected_text_range(false, cx)
12921 .and_then(|selection| {
12922 if selection.range.is_empty() {
12923 None
12924 } else {
12925 Some(selection.range)
12926 }
12927 })
12928 .unwrap_or_else(|| 0..snapshot.len());
12929
12930 let chunks = snapshot.chunks(range, true);
12931 let mut lines = Vec::new();
12932 let mut line: VecDeque<Chunk> = VecDeque::new();
12933
12934 let Some(style) = self.style.as_ref() else {
12935 return;
12936 };
12937
12938 for chunk in chunks {
12939 let highlight = chunk
12940 .syntax_highlight_id
12941 .and_then(|id| id.name(&style.syntax));
12942 let mut chunk_lines = chunk.text.split('\n').peekable();
12943 while let Some(text) = chunk_lines.next() {
12944 let mut merged_with_last_token = false;
12945 if let Some(last_token) = line.back_mut() {
12946 if last_token.highlight == highlight {
12947 last_token.text.push_str(text);
12948 merged_with_last_token = true;
12949 }
12950 }
12951
12952 if !merged_with_last_token {
12953 line.push_back(Chunk {
12954 text: text.into(),
12955 highlight,
12956 });
12957 }
12958
12959 if chunk_lines.peek().is_some() {
12960 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12961 line.pop_front();
12962 }
12963 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12964 line.pop_back();
12965 }
12966
12967 lines.push(mem::take(&mut line));
12968 }
12969 }
12970 }
12971
12972 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12973 return;
12974 };
12975 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12976 }
12977
12978 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12979 self.request_autoscroll(Autoscroll::newest(), cx);
12980 let position = self.selections.newest_display(cx).start;
12981 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12982 }
12983
12984 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12985 &self.inlay_hint_cache
12986 }
12987
12988 pub fn replay_insert_event(
12989 &mut self,
12990 text: &str,
12991 relative_utf16_range: Option<Range<isize>>,
12992 cx: &mut ViewContext<Self>,
12993 ) {
12994 if !self.input_enabled {
12995 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12996 return;
12997 }
12998 if let Some(relative_utf16_range) = relative_utf16_range {
12999 let selections = self.selections.all::<OffsetUtf16>(cx);
13000 self.change_selections(None, cx, |s| {
13001 let new_ranges = selections.into_iter().map(|range| {
13002 let start = OffsetUtf16(
13003 range
13004 .head()
13005 .0
13006 .saturating_add_signed(relative_utf16_range.start),
13007 );
13008 let end = OffsetUtf16(
13009 range
13010 .head()
13011 .0
13012 .saturating_add_signed(relative_utf16_range.end),
13013 );
13014 start..end
13015 });
13016 s.select_ranges(new_ranges);
13017 });
13018 }
13019
13020 self.handle_input(text, cx);
13021 }
13022
13023 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13024 let Some(provider) = self.semantics_provider.as_ref() else {
13025 return false;
13026 };
13027
13028 let mut supports = false;
13029 self.buffer().read(cx).for_each_buffer(|buffer| {
13030 supports |= provider.supports_inlay_hints(buffer, cx);
13031 });
13032 supports
13033 }
13034
13035 pub fn focus(&self, cx: &mut WindowContext) {
13036 cx.focus(&self.focus_handle)
13037 }
13038
13039 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13040 self.focus_handle.is_focused(cx)
13041 }
13042
13043 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13044 cx.emit(EditorEvent::Focused);
13045
13046 if let Some(descendant) = self
13047 .last_focused_descendant
13048 .take()
13049 .and_then(|descendant| descendant.upgrade())
13050 {
13051 cx.focus(&descendant);
13052 } else {
13053 if let Some(blame) = self.blame.as_ref() {
13054 blame.update(cx, GitBlame::focus)
13055 }
13056
13057 self.blink_manager.update(cx, BlinkManager::enable);
13058 self.show_cursor_names(cx);
13059 self.buffer.update(cx, |buffer, cx| {
13060 buffer.finalize_last_transaction(cx);
13061 if self.leader_peer_id.is_none() {
13062 buffer.set_active_selections(
13063 &self.selections.disjoint_anchors(),
13064 self.selections.line_mode,
13065 self.cursor_shape,
13066 cx,
13067 );
13068 }
13069 });
13070 }
13071 }
13072
13073 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13074 cx.emit(EditorEvent::FocusedIn)
13075 }
13076
13077 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13078 if event.blurred != self.focus_handle {
13079 self.last_focused_descendant = Some(event.blurred);
13080 }
13081 }
13082
13083 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13084 self.blink_manager.update(cx, BlinkManager::disable);
13085 self.buffer
13086 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13087
13088 if let Some(blame) = self.blame.as_ref() {
13089 blame.update(cx, GitBlame::blur)
13090 }
13091 if !self.hover_state.focused(cx) {
13092 hide_hover(self, cx);
13093 }
13094
13095 self.hide_context_menu(cx);
13096 cx.emit(EditorEvent::Blurred);
13097 cx.notify();
13098 }
13099
13100 pub fn register_action<A: Action>(
13101 &mut self,
13102 listener: impl Fn(&A, &mut WindowContext) + 'static,
13103 ) -> Subscription {
13104 let id = self.next_editor_action_id.post_inc();
13105 let listener = Arc::new(listener);
13106 self.editor_actions.borrow_mut().insert(
13107 id,
13108 Box::new(move |cx| {
13109 let cx = cx.window_context();
13110 let listener = listener.clone();
13111 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13112 let action = action.downcast_ref().unwrap();
13113 if phase == DispatchPhase::Bubble {
13114 listener(action, cx)
13115 }
13116 })
13117 }),
13118 );
13119
13120 let editor_actions = self.editor_actions.clone();
13121 Subscription::new(move || {
13122 editor_actions.borrow_mut().remove(&id);
13123 })
13124 }
13125
13126 pub fn file_header_size(&self) -> u32 {
13127 FILE_HEADER_HEIGHT
13128 }
13129
13130 pub fn revert(
13131 &mut self,
13132 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13133 cx: &mut ViewContext<Self>,
13134 ) {
13135 self.buffer().update(cx, |multi_buffer, cx| {
13136 for (buffer_id, changes) in revert_changes {
13137 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13138 buffer.update(cx, |buffer, cx| {
13139 buffer.edit(
13140 changes.into_iter().map(|(range, text)| {
13141 (range, text.to_string().map(Arc::<str>::from))
13142 }),
13143 None,
13144 cx,
13145 );
13146 });
13147 }
13148 }
13149 });
13150 self.change_selections(None, cx, |selections| selections.refresh());
13151 }
13152
13153 pub fn to_pixel_point(
13154 &mut self,
13155 source: multi_buffer::Anchor,
13156 editor_snapshot: &EditorSnapshot,
13157 cx: &mut ViewContext<Self>,
13158 ) -> Option<gpui::Point<Pixels>> {
13159 let source_point = source.to_display_point(editor_snapshot);
13160 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13161 }
13162
13163 pub fn display_to_pixel_point(
13164 &self,
13165 source: DisplayPoint,
13166 editor_snapshot: &EditorSnapshot,
13167 cx: &WindowContext,
13168 ) -> Option<gpui::Point<Pixels>> {
13169 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13170 let text_layout_details = self.text_layout_details(cx);
13171 let scroll_top = text_layout_details
13172 .scroll_anchor
13173 .scroll_position(editor_snapshot)
13174 .y;
13175
13176 if source.row().as_f32() < scroll_top.floor() {
13177 return None;
13178 }
13179 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13180 let source_y = line_height * (source.row().as_f32() - scroll_top);
13181 Some(gpui::Point::new(source_x, source_y))
13182 }
13183
13184 pub fn has_active_completions_menu(&self) -> bool {
13185 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13186 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13187 })
13188 }
13189
13190 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13191 self.addons
13192 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13193 }
13194
13195 pub fn unregister_addon<T: Addon>(&mut self) {
13196 self.addons.remove(&std::any::TypeId::of::<T>());
13197 }
13198
13199 pub fn addon<T: Addon>(&self) -> Option<&T> {
13200 let type_id = std::any::TypeId::of::<T>();
13201 self.addons
13202 .get(&type_id)
13203 .and_then(|item| item.to_any().downcast_ref::<T>())
13204 }
13205
13206 pub fn add_change_set(
13207 &mut self,
13208 change_set: Model<BufferChangeSet>,
13209 cx: &mut ViewContext<Self>,
13210 ) {
13211 self.diff_map.add_change_set(change_set, cx);
13212 }
13213
13214 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13215 let text_layout_details = self.text_layout_details(cx);
13216 let style = &text_layout_details.editor_style;
13217 let font_id = cx.text_system().resolve_font(&style.text.font());
13218 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13219 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13220
13221 let em_width = cx
13222 .text_system()
13223 .typographic_bounds(font_id, font_size, 'm')
13224 .unwrap()
13225 .size
13226 .width;
13227
13228 gpui::Point::new(em_width, line_height)
13229 }
13230}
13231
13232fn get_unstaged_changes_for_buffers(
13233 project: &Model<Project>,
13234 buffers: impl IntoIterator<Item = Model<Buffer>>,
13235 cx: &mut ViewContext<Editor>,
13236) {
13237 let mut tasks = Vec::new();
13238 project.update(cx, |project, cx| {
13239 for buffer in buffers {
13240 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13241 }
13242 });
13243 cx.spawn(|this, mut cx| async move {
13244 let change_sets = futures::future::join_all(tasks).await;
13245 this.update(&mut cx, |this, cx| {
13246 for change_set in change_sets {
13247 if let Some(change_set) = change_set.log_err() {
13248 this.diff_map.add_change_set(change_set, cx);
13249 }
13250 }
13251 })
13252 .ok();
13253 })
13254 .detach();
13255}
13256
13257fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13258 let tab_size = tab_size.get() as usize;
13259 let mut width = offset;
13260
13261 for ch in text.chars() {
13262 width += if ch == '\t' {
13263 tab_size - (width % tab_size)
13264 } else {
13265 1
13266 };
13267 }
13268
13269 width - offset
13270}
13271
13272#[cfg(test)]
13273mod tests {
13274 use super::*;
13275
13276 #[test]
13277 fn test_string_size_with_expanded_tabs() {
13278 let nz = |val| NonZeroU32::new(val).unwrap();
13279 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13280 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13281 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13282 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13283 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13284 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13285 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13286 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13287 }
13288}
13289
13290/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13291struct WordBreakingTokenizer<'a> {
13292 input: &'a str,
13293}
13294
13295impl<'a> WordBreakingTokenizer<'a> {
13296 fn new(input: &'a str) -> Self {
13297 Self { input }
13298 }
13299}
13300
13301fn is_char_ideographic(ch: char) -> bool {
13302 use unicode_script::Script::*;
13303 use unicode_script::UnicodeScript;
13304 matches!(ch.script(), Han | Tangut | Yi)
13305}
13306
13307fn is_grapheme_ideographic(text: &str) -> bool {
13308 text.chars().any(is_char_ideographic)
13309}
13310
13311fn is_grapheme_whitespace(text: &str) -> bool {
13312 text.chars().any(|x| x.is_whitespace())
13313}
13314
13315fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13316 text.chars().next().map_or(false, |ch| {
13317 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13318 })
13319}
13320
13321#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13322struct WordBreakToken<'a> {
13323 token: &'a str,
13324 grapheme_len: usize,
13325 is_whitespace: bool,
13326}
13327
13328impl<'a> Iterator for WordBreakingTokenizer<'a> {
13329 /// Yields a span, the count of graphemes in the token, and whether it was
13330 /// whitespace. Note that it also breaks at word boundaries.
13331 type Item = WordBreakToken<'a>;
13332
13333 fn next(&mut self) -> Option<Self::Item> {
13334 use unicode_segmentation::UnicodeSegmentation;
13335 if self.input.is_empty() {
13336 return None;
13337 }
13338
13339 let mut iter = self.input.graphemes(true).peekable();
13340 let mut offset = 0;
13341 let mut graphemes = 0;
13342 if let Some(first_grapheme) = iter.next() {
13343 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13344 offset += first_grapheme.len();
13345 graphemes += 1;
13346 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13347 if let Some(grapheme) = iter.peek().copied() {
13348 if should_stay_with_preceding_ideograph(grapheme) {
13349 offset += grapheme.len();
13350 graphemes += 1;
13351 }
13352 }
13353 } else {
13354 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13355 let mut next_word_bound = words.peek().copied();
13356 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13357 next_word_bound = words.next();
13358 }
13359 while let Some(grapheme) = iter.peek().copied() {
13360 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13361 break;
13362 };
13363 if is_grapheme_whitespace(grapheme) != is_whitespace {
13364 break;
13365 };
13366 offset += grapheme.len();
13367 graphemes += 1;
13368 iter.next();
13369 }
13370 }
13371 let token = &self.input[..offset];
13372 self.input = &self.input[offset..];
13373 if is_whitespace {
13374 Some(WordBreakToken {
13375 token: " ",
13376 grapheme_len: 1,
13377 is_whitespace: true,
13378 })
13379 } else {
13380 Some(WordBreakToken {
13381 token,
13382 grapheme_len: graphemes,
13383 is_whitespace: false,
13384 })
13385 }
13386 } else {
13387 None
13388 }
13389 }
13390}
13391
13392#[test]
13393fn test_word_breaking_tokenizer() {
13394 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13395 ("", &[]),
13396 (" ", &[(" ", 1, true)]),
13397 ("Ʒ", &[("Ʒ", 1, false)]),
13398 ("Ǽ", &[("Ǽ", 1, false)]),
13399 ("⋑", &[("⋑", 1, false)]),
13400 ("⋑⋑", &[("⋑⋑", 2, false)]),
13401 (
13402 "原理,进而",
13403 &[
13404 ("原", 1, false),
13405 ("理,", 2, false),
13406 ("进", 1, false),
13407 ("而", 1, false),
13408 ],
13409 ),
13410 (
13411 "hello world",
13412 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13413 ),
13414 (
13415 "hello, world",
13416 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13417 ),
13418 (
13419 " hello world",
13420 &[
13421 (" ", 1, true),
13422 ("hello", 5, false),
13423 (" ", 1, true),
13424 ("world", 5, false),
13425 ],
13426 ),
13427 (
13428 "这是什么 \n 钢笔",
13429 &[
13430 ("这", 1, false),
13431 ("是", 1, false),
13432 ("什", 1, false),
13433 ("么", 1, false),
13434 (" ", 1, true),
13435 ("钢", 1, false),
13436 ("笔", 1, false),
13437 ],
13438 ),
13439 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13440 ];
13441
13442 for (input, result) in tests {
13443 assert_eq!(
13444 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13445 result
13446 .iter()
13447 .copied()
13448 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13449 token,
13450 grapheme_len,
13451 is_whitespace,
13452 })
13453 .collect::<Vec<_>>()
13454 );
13455 }
13456}
13457
13458fn wrap_with_prefix(
13459 line_prefix: String,
13460 unwrapped_text: String,
13461 wrap_column: usize,
13462 tab_size: NonZeroU32,
13463) -> String {
13464 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13465 let mut wrapped_text = String::new();
13466 let mut current_line = line_prefix.clone();
13467
13468 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13469 let mut current_line_len = line_prefix_len;
13470 for WordBreakToken {
13471 token,
13472 grapheme_len,
13473 is_whitespace,
13474 } in tokenizer
13475 {
13476 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13477 wrapped_text.push_str(current_line.trim_end());
13478 wrapped_text.push('\n');
13479 current_line.truncate(line_prefix.len());
13480 current_line_len = line_prefix_len;
13481 if !is_whitespace {
13482 current_line.push_str(token);
13483 current_line_len += grapheme_len;
13484 }
13485 } else if !is_whitespace {
13486 current_line.push_str(token);
13487 current_line_len += grapheme_len;
13488 } else if current_line_len != line_prefix_len {
13489 current_line.push(' ');
13490 current_line_len += 1;
13491 }
13492 }
13493
13494 if !current_line.is_empty() {
13495 wrapped_text.push_str(¤t_line);
13496 }
13497 wrapped_text
13498}
13499
13500#[test]
13501fn test_wrap_with_prefix() {
13502 assert_eq!(
13503 wrap_with_prefix(
13504 "# ".to_string(),
13505 "abcdefg".to_string(),
13506 4,
13507 NonZeroU32::new(4).unwrap()
13508 ),
13509 "# abcdefg"
13510 );
13511 assert_eq!(
13512 wrap_with_prefix(
13513 "".to_string(),
13514 "\thello world".to_string(),
13515 8,
13516 NonZeroU32::new(4).unwrap()
13517 ),
13518 "hello\nworld"
13519 );
13520 assert_eq!(
13521 wrap_with_prefix(
13522 "// ".to_string(),
13523 "xx \nyy zz aa bb cc".to_string(),
13524 12,
13525 NonZeroU32::new(4).unwrap()
13526 ),
13527 "// xx yy zz\n// aa bb cc"
13528 );
13529 assert_eq!(
13530 wrap_with_prefix(
13531 String::new(),
13532 "这是什么 \n 钢笔".to_string(),
13533 3,
13534 NonZeroU32::new(4).unwrap()
13535 ),
13536 "这是什\n么 钢\n笔"
13537 );
13538}
13539
13540fn hunks_for_selections(
13541 snapshot: &EditorSnapshot,
13542 selections: &[Selection<Point>],
13543) -> Vec<MultiBufferDiffHunk> {
13544 hunks_for_ranges(
13545 selections.iter().map(|selection| selection.range()),
13546 snapshot,
13547 )
13548}
13549
13550pub fn hunks_for_ranges(
13551 ranges: impl Iterator<Item = Range<Point>>,
13552 snapshot: &EditorSnapshot,
13553) -> Vec<MultiBufferDiffHunk> {
13554 let mut hunks = Vec::new();
13555 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13556 HashMap::default();
13557 for query_range in ranges {
13558 let query_rows =
13559 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13560 for hunk in snapshot.diff_map.diff_hunks_in_range(
13561 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13562 &snapshot.buffer_snapshot,
13563 ) {
13564 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13565 // when the caret is just above or just below the deleted hunk.
13566 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13567 let related_to_selection = if allow_adjacent {
13568 hunk.row_range.overlaps(&query_rows)
13569 || hunk.row_range.start == query_rows.end
13570 || hunk.row_range.end == query_rows.start
13571 } else {
13572 hunk.row_range.overlaps(&query_rows)
13573 };
13574 if related_to_selection {
13575 if !processed_buffer_rows
13576 .entry(hunk.buffer_id)
13577 .or_default()
13578 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13579 {
13580 continue;
13581 }
13582 hunks.push(hunk);
13583 }
13584 }
13585 }
13586
13587 hunks
13588}
13589
13590pub trait CollaborationHub {
13591 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13592 fn user_participant_indices<'a>(
13593 &self,
13594 cx: &'a AppContext,
13595 ) -> &'a HashMap<u64, ParticipantIndex>;
13596 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13597}
13598
13599impl CollaborationHub for Model<Project> {
13600 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13601 self.read(cx).collaborators()
13602 }
13603
13604 fn user_participant_indices<'a>(
13605 &self,
13606 cx: &'a AppContext,
13607 ) -> &'a HashMap<u64, ParticipantIndex> {
13608 self.read(cx).user_store().read(cx).participant_indices()
13609 }
13610
13611 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13612 let this = self.read(cx);
13613 let user_ids = this.collaborators().values().map(|c| c.user_id);
13614 this.user_store().read_with(cx, |user_store, cx| {
13615 user_store.participant_names(user_ids, cx)
13616 })
13617 }
13618}
13619
13620pub trait SemanticsProvider {
13621 fn hover(
13622 &self,
13623 buffer: &Model<Buffer>,
13624 position: text::Anchor,
13625 cx: &mut AppContext,
13626 ) -> Option<Task<Vec<project::Hover>>>;
13627
13628 fn inlay_hints(
13629 &self,
13630 buffer_handle: Model<Buffer>,
13631 range: Range<text::Anchor>,
13632 cx: &mut AppContext,
13633 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13634
13635 fn resolve_inlay_hint(
13636 &self,
13637 hint: InlayHint,
13638 buffer_handle: Model<Buffer>,
13639 server_id: LanguageServerId,
13640 cx: &mut AppContext,
13641 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13642
13643 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13644
13645 fn document_highlights(
13646 &self,
13647 buffer: &Model<Buffer>,
13648 position: text::Anchor,
13649 cx: &mut AppContext,
13650 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13651
13652 fn definitions(
13653 &self,
13654 buffer: &Model<Buffer>,
13655 position: text::Anchor,
13656 kind: GotoDefinitionKind,
13657 cx: &mut AppContext,
13658 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13659
13660 fn range_for_rename(
13661 &self,
13662 buffer: &Model<Buffer>,
13663 position: text::Anchor,
13664 cx: &mut AppContext,
13665 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13666
13667 fn perform_rename(
13668 &self,
13669 buffer: &Model<Buffer>,
13670 position: text::Anchor,
13671 new_name: String,
13672 cx: &mut AppContext,
13673 ) -> Option<Task<Result<ProjectTransaction>>>;
13674}
13675
13676pub trait CompletionProvider {
13677 fn completions(
13678 &self,
13679 buffer: &Model<Buffer>,
13680 buffer_position: text::Anchor,
13681 trigger: CompletionContext,
13682 cx: &mut ViewContext<Editor>,
13683 ) -> Task<Result<Vec<Completion>>>;
13684
13685 fn resolve_completions(
13686 &self,
13687 buffer: Model<Buffer>,
13688 completion_indices: Vec<usize>,
13689 completions: Rc<RefCell<Box<[Completion]>>>,
13690 cx: &mut ViewContext<Editor>,
13691 ) -> Task<Result<bool>>;
13692
13693 fn apply_additional_edits_for_completion(
13694 &self,
13695 _buffer: Model<Buffer>,
13696 _completions: Rc<RefCell<Box<[Completion]>>>,
13697 _completion_index: usize,
13698 _push_to_history: bool,
13699 _cx: &mut ViewContext<Editor>,
13700 ) -> Task<Result<Option<language::Transaction>>> {
13701 Task::ready(Ok(None))
13702 }
13703
13704 fn is_completion_trigger(
13705 &self,
13706 buffer: &Model<Buffer>,
13707 position: language::Anchor,
13708 text: &str,
13709 trigger_in_words: bool,
13710 cx: &mut ViewContext<Editor>,
13711 ) -> bool;
13712
13713 fn sort_completions(&self) -> bool {
13714 true
13715 }
13716}
13717
13718pub trait CodeActionProvider {
13719 fn id(&self) -> Arc<str>;
13720
13721 fn code_actions(
13722 &self,
13723 buffer: &Model<Buffer>,
13724 range: Range<text::Anchor>,
13725 cx: &mut WindowContext,
13726 ) -> Task<Result<Vec<CodeAction>>>;
13727
13728 fn apply_code_action(
13729 &self,
13730 buffer_handle: Model<Buffer>,
13731 action: CodeAction,
13732 excerpt_id: ExcerptId,
13733 push_to_history: bool,
13734 cx: &mut WindowContext,
13735 ) -> Task<Result<ProjectTransaction>>;
13736}
13737
13738impl CodeActionProvider for Model<Project> {
13739 fn id(&self) -> Arc<str> {
13740 "project".into()
13741 }
13742
13743 fn code_actions(
13744 &self,
13745 buffer: &Model<Buffer>,
13746 range: Range<text::Anchor>,
13747 cx: &mut WindowContext,
13748 ) -> Task<Result<Vec<CodeAction>>> {
13749 self.update(cx, |project, cx| {
13750 project.code_actions(buffer, range, None, cx)
13751 })
13752 }
13753
13754 fn apply_code_action(
13755 &self,
13756 buffer_handle: Model<Buffer>,
13757 action: CodeAction,
13758 _excerpt_id: ExcerptId,
13759 push_to_history: bool,
13760 cx: &mut WindowContext,
13761 ) -> Task<Result<ProjectTransaction>> {
13762 self.update(cx, |project, cx| {
13763 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13764 })
13765 }
13766}
13767
13768fn snippet_completions(
13769 project: &Project,
13770 buffer: &Model<Buffer>,
13771 buffer_position: text::Anchor,
13772 cx: &mut AppContext,
13773) -> Task<Result<Vec<Completion>>> {
13774 let language = buffer.read(cx).language_at(buffer_position);
13775 let language_name = language.as_ref().map(|language| language.lsp_id());
13776 let snippet_store = project.snippets().read(cx);
13777 let snippets = snippet_store.snippets_for(language_name, cx);
13778
13779 if snippets.is_empty() {
13780 return Task::ready(Ok(vec![]));
13781 }
13782 let snapshot = buffer.read(cx).text_snapshot();
13783 let chars: String = snapshot
13784 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13785 .collect();
13786
13787 let scope = language.map(|language| language.default_scope());
13788 let executor = cx.background_executor().clone();
13789
13790 cx.background_executor().spawn(async move {
13791 let classifier = CharClassifier::new(scope).for_completion(true);
13792 let mut last_word = chars
13793 .chars()
13794 .take_while(|c| classifier.is_word(*c))
13795 .collect::<String>();
13796 last_word = last_word.chars().rev().collect();
13797
13798 if last_word.is_empty() {
13799 return Ok(vec![]);
13800 }
13801
13802 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13803 let to_lsp = |point: &text::Anchor| {
13804 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13805 point_to_lsp(end)
13806 };
13807 let lsp_end = to_lsp(&buffer_position);
13808
13809 let candidates = snippets
13810 .iter()
13811 .enumerate()
13812 .flat_map(|(ix, snippet)| {
13813 snippet
13814 .prefix
13815 .iter()
13816 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13817 })
13818 .collect::<Vec<StringMatchCandidate>>();
13819
13820 let mut matches = fuzzy::match_strings(
13821 &candidates,
13822 &last_word,
13823 last_word.chars().any(|c| c.is_uppercase()),
13824 100,
13825 &Default::default(),
13826 executor,
13827 )
13828 .await;
13829
13830 // Remove all candidates where the query's start does not match the start of any word in the candidate
13831 if let Some(query_start) = last_word.chars().next() {
13832 matches.retain(|string_match| {
13833 split_words(&string_match.string).any(|word| {
13834 // Check that the first codepoint of the word as lowercase matches the first
13835 // codepoint of the query as lowercase
13836 word.chars()
13837 .flat_map(|codepoint| codepoint.to_lowercase())
13838 .zip(query_start.to_lowercase())
13839 .all(|(word_cp, query_cp)| word_cp == query_cp)
13840 })
13841 });
13842 }
13843
13844 let matched_strings = matches
13845 .into_iter()
13846 .map(|m| m.string)
13847 .collect::<HashSet<_>>();
13848
13849 let result: Vec<Completion> = snippets
13850 .into_iter()
13851 .filter_map(|snippet| {
13852 let matching_prefix = snippet
13853 .prefix
13854 .iter()
13855 .find(|prefix| matched_strings.contains(*prefix))?;
13856 let start = as_offset - last_word.len();
13857 let start = snapshot.anchor_before(start);
13858 let range = start..buffer_position;
13859 let lsp_start = to_lsp(&start);
13860 let lsp_range = lsp::Range {
13861 start: lsp_start,
13862 end: lsp_end,
13863 };
13864 Some(Completion {
13865 old_range: range,
13866 new_text: snippet.body.clone(),
13867 resolved: false,
13868 label: CodeLabel {
13869 text: matching_prefix.clone(),
13870 runs: vec![],
13871 filter_range: 0..matching_prefix.len(),
13872 },
13873 server_id: LanguageServerId(usize::MAX),
13874 documentation: snippet.description.clone().map(Documentation::SingleLine),
13875 lsp_completion: lsp::CompletionItem {
13876 label: snippet.prefix.first().unwrap().clone(),
13877 kind: Some(CompletionItemKind::SNIPPET),
13878 label_details: snippet.description.as_ref().map(|description| {
13879 lsp::CompletionItemLabelDetails {
13880 detail: Some(description.clone()),
13881 description: None,
13882 }
13883 }),
13884 insert_text_format: Some(InsertTextFormat::SNIPPET),
13885 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13886 lsp::InsertReplaceEdit {
13887 new_text: snippet.body.clone(),
13888 insert: lsp_range,
13889 replace: lsp_range,
13890 },
13891 )),
13892 filter_text: Some(snippet.body.clone()),
13893 sort_text: Some(char::MAX.to_string()),
13894 ..Default::default()
13895 },
13896 confirm: None,
13897 })
13898 })
13899 .collect();
13900
13901 Ok(result)
13902 })
13903}
13904
13905impl CompletionProvider for Model<Project> {
13906 fn completions(
13907 &self,
13908 buffer: &Model<Buffer>,
13909 buffer_position: text::Anchor,
13910 options: CompletionContext,
13911 cx: &mut ViewContext<Editor>,
13912 ) -> Task<Result<Vec<Completion>>> {
13913 self.update(cx, |project, cx| {
13914 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13915 let project_completions = project.completions(buffer, buffer_position, options, cx);
13916 cx.background_executor().spawn(async move {
13917 let mut completions = project_completions.await?;
13918 let snippets_completions = snippets.await?;
13919 completions.extend(snippets_completions);
13920 Ok(completions)
13921 })
13922 })
13923 }
13924
13925 fn resolve_completions(
13926 &self,
13927 buffer: Model<Buffer>,
13928 completion_indices: Vec<usize>,
13929 completions: Rc<RefCell<Box<[Completion]>>>,
13930 cx: &mut ViewContext<Editor>,
13931 ) -> Task<Result<bool>> {
13932 self.update(cx, |project, cx| {
13933 project.lsp_store().update(cx, |lsp_store, cx| {
13934 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13935 })
13936 })
13937 }
13938
13939 fn apply_additional_edits_for_completion(
13940 &self,
13941 buffer: Model<Buffer>,
13942 completions: Rc<RefCell<Box<[Completion]>>>,
13943 completion_index: usize,
13944 push_to_history: bool,
13945 cx: &mut ViewContext<Editor>,
13946 ) -> Task<Result<Option<language::Transaction>>> {
13947 self.update(cx, |project, cx| {
13948 project.lsp_store().update(cx, |lsp_store, cx| {
13949 lsp_store.apply_additional_edits_for_completion(
13950 buffer,
13951 completions,
13952 completion_index,
13953 push_to_history,
13954 cx,
13955 )
13956 })
13957 })
13958 }
13959
13960 fn is_completion_trigger(
13961 &self,
13962 buffer: &Model<Buffer>,
13963 position: language::Anchor,
13964 text: &str,
13965 trigger_in_words: bool,
13966 cx: &mut ViewContext<Editor>,
13967 ) -> bool {
13968 let mut chars = text.chars();
13969 let char = if let Some(char) = chars.next() {
13970 char
13971 } else {
13972 return false;
13973 };
13974 if chars.next().is_some() {
13975 return false;
13976 }
13977
13978 let buffer = buffer.read(cx);
13979 let snapshot = buffer.snapshot();
13980 if !snapshot.settings_at(position, cx).show_completions_on_input {
13981 return false;
13982 }
13983 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13984 if trigger_in_words && classifier.is_word(char) {
13985 return true;
13986 }
13987
13988 buffer.completion_triggers().contains(text)
13989 }
13990}
13991
13992impl SemanticsProvider for Model<Project> {
13993 fn hover(
13994 &self,
13995 buffer: &Model<Buffer>,
13996 position: text::Anchor,
13997 cx: &mut AppContext,
13998 ) -> Option<Task<Vec<project::Hover>>> {
13999 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14000 }
14001
14002 fn document_highlights(
14003 &self,
14004 buffer: &Model<Buffer>,
14005 position: text::Anchor,
14006 cx: &mut AppContext,
14007 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14008 Some(self.update(cx, |project, cx| {
14009 project.document_highlights(buffer, position, cx)
14010 }))
14011 }
14012
14013 fn definitions(
14014 &self,
14015 buffer: &Model<Buffer>,
14016 position: text::Anchor,
14017 kind: GotoDefinitionKind,
14018 cx: &mut AppContext,
14019 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14020 Some(self.update(cx, |project, cx| match kind {
14021 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14022 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14023 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14024 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14025 }))
14026 }
14027
14028 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14029 // TODO: make this work for remote projects
14030 self.read(cx)
14031 .language_servers_for_local_buffer(buffer.read(cx), cx)
14032 .any(
14033 |(_, server)| match server.capabilities().inlay_hint_provider {
14034 Some(lsp::OneOf::Left(enabled)) => enabled,
14035 Some(lsp::OneOf::Right(_)) => true,
14036 None => false,
14037 },
14038 )
14039 }
14040
14041 fn inlay_hints(
14042 &self,
14043 buffer_handle: Model<Buffer>,
14044 range: Range<text::Anchor>,
14045 cx: &mut AppContext,
14046 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14047 Some(self.update(cx, |project, cx| {
14048 project.inlay_hints(buffer_handle, range, cx)
14049 }))
14050 }
14051
14052 fn resolve_inlay_hint(
14053 &self,
14054 hint: InlayHint,
14055 buffer_handle: Model<Buffer>,
14056 server_id: LanguageServerId,
14057 cx: &mut AppContext,
14058 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14059 Some(self.update(cx, |project, cx| {
14060 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14061 }))
14062 }
14063
14064 fn range_for_rename(
14065 &self,
14066 buffer: &Model<Buffer>,
14067 position: text::Anchor,
14068 cx: &mut AppContext,
14069 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14070 Some(self.update(cx, |project, cx| {
14071 let buffer = buffer.clone();
14072 let task = project.prepare_rename(buffer.clone(), position, cx);
14073 cx.spawn(|_, mut cx| async move {
14074 Ok(match task.await? {
14075 PrepareRenameResponse::Success(range) => Some(range),
14076 PrepareRenameResponse::InvalidPosition => None,
14077 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14078 // Fallback on using TreeSitter info to determine identifier range
14079 buffer.update(&mut cx, |buffer, _| {
14080 let snapshot = buffer.snapshot();
14081 let (range, kind) = snapshot.surrounding_word(position);
14082 if kind != Some(CharKind::Word) {
14083 return None;
14084 }
14085 Some(
14086 snapshot.anchor_before(range.start)
14087 ..snapshot.anchor_after(range.end),
14088 )
14089 })?
14090 }
14091 })
14092 })
14093 }))
14094 }
14095
14096 fn perform_rename(
14097 &self,
14098 buffer: &Model<Buffer>,
14099 position: text::Anchor,
14100 new_name: String,
14101 cx: &mut AppContext,
14102 ) -> Option<Task<Result<ProjectTransaction>>> {
14103 Some(self.update(cx, |project, cx| {
14104 project.perform_rename(buffer.clone(), position, new_name, cx)
14105 }))
14106 }
14107}
14108
14109fn inlay_hint_settings(
14110 location: Anchor,
14111 snapshot: &MultiBufferSnapshot,
14112 cx: &mut ViewContext<Editor>,
14113) -> InlayHintSettings {
14114 let file = snapshot.file_at(location);
14115 let language = snapshot.language_at(location).map(|l| l.name());
14116 language_settings(language, file, cx).inlay_hints
14117}
14118
14119fn consume_contiguous_rows(
14120 contiguous_row_selections: &mut Vec<Selection<Point>>,
14121 selection: &Selection<Point>,
14122 display_map: &DisplaySnapshot,
14123 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14124) -> (MultiBufferRow, MultiBufferRow) {
14125 contiguous_row_selections.push(selection.clone());
14126 let start_row = MultiBufferRow(selection.start.row);
14127 let mut end_row = ending_row(selection, display_map);
14128
14129 while let Some(next_selection) = selections.peek() {
14130 if next_selection.start.row <= end_row.0 {
14131 end_row = ending_row(next_selection, display_map);
14132 contiguous_row_selections.push(selections.next().unwrap().clone());
14133 } else {
14134 break;
14135 }
14136 }
14137 (start_row, end_row)
14138}
14139
14140fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14141 if next_selection.end.column > 0 || next_selection.is_empty() {
14142 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14143 } else {
14144 MultiBufferRow(next_selection.end.row)
14145 }
14146}
14147
14148impl EditorSnapshot {
14149 pub fn remote_selections_in_range<'a>(
14150 &'a self,
14151 range: &'a Range<Anchor>,
14152 collaboration_hub: &dyn CollaborationHub,
14153 cx: &'a AppContext,
14154 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14155 let participant_names = collaboration_hub.user_names(cx);
14156 let participant_indices = collaboration_hub.user_participant_indices(cx);
14157 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14158 let collaborators_by_replica_id = collaborators_by_peer_id
14159 .iter()
14160 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14161 .collect::<HashMap<_, _>>();
14162 self.buffer_snapshot
14163 .selections_in_range(range, false)
14164 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14165 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14166 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14167 let user_name = participant_names.get(&collaborator.user_id).cloned();
14168 Some(RemoteSelection {
14169 replica_id,
14170 selection,
14171 cursor_shape,
14172 line_mode,
14173 participant_index,
14174 peer_id: collaborator.peer_id,
14175 user_name,
14176 })
14177 })
14178 }
14179
14180 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14181 self.display_snapshot.buffer_snapshot.language_at(position)
14182 }
14183
14184 pub fn is_focused(&self) -> bool {
14185 self.is_focused
14186 }
14187
14188 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14189 self.placeholder_text.as_ref()
14190 }
14191
14192 pub fn scroll_position(&self) -> gpui::Point<f32> {
14193 self.scroll_anchor.scroll_position(&self.display_snapshot)
14194 }
14195
14196 fn gutter_dimensions(
14197 &self,
14198 font_id: FontId,
14199 font_size: Pixels,
14200 em_width: Pixels,
14201 em_advance: Pixels,
14202 max_line_number_width: Pixels,
14203 cx: &AppContext,
14204 ) -> GutterDimensions {
14205 if !self.show_gutter {
14206 return GutterDimensions::default();
14207 }
14208 let descent = cx.text_system().descent(font_id, font_size);
14209
14210 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14211 matches!(
14212 ProjectSettings::get_global(cx).git.git_gutter,
14213 Some(GitGutterSetting::TrackedFiles)
14214 )
14215 });
14216 let gutter_settings = EditorSettings::get_global(cx).gutter;
14217 let show_line_numbers = self
14218 .show_line_numbers
14219 .unwrap_or(gutter_settings.line_numbers);
14220 let line_gutter_width = if show_line_numbers {
14221 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14222 let min_width_for_number_on_gutter = em_advance * 4.0;
14223 max_line_number_width.max(min_width_for_number_on_gutter)
14224 } else {
14225 0.0.into()
14226 };
14227
14228 let show_code_actions = self
14229 .show_code_actions
14230 .unwrap_or(gutter_settings.code_actions);
14231
14232 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14233
14234 let git_blame_entries_width =
14235 self.git_blame_gutter_max_author_length
14236 .map(|max_author_length| {
14237 // Length of the author name, but also space for the commit hash,
14238 // the spacing and the timestamp.
14239 let max_char_count = max_author_length
14240 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14241 + 7 // length of commit sha
14242 + 14 // length of max relative timestamp ("60 minutes ago")
14243 + 4; // gaps and margins
14244
14245 em_advance * max_char_count
14246 });
14247
14248 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14249 left_padding += if show_code_actions || show_runnables {
14250 em_width * 3.0
14251 } else if show_git_gutter && show_line_numbers {
14252 em_width * 2.0
14253 } else if show_git_gutter || show_line_numbers {
14254 em_width
14255 } else {
14256 px(0.)
14257 };
14258
14259 let right_padding = if gutter_settings.folds && show_line_numbers {
14260 em_width * 4.0
14261 } else if gutter_settings.folds {
14262 em_width * 3.0
14263 } else if show_line_numbers {
14264 em_width
14265 } else {
14266 px(0.)
14267 };
14268
14269 GutterDimensions {
14270 left_padding,
14271 right_padding,
14272 width: line_gutter_width + left_padding + right_padding,
14273 margin: -descent,
14274 git_blame_entries_width,
14275 }
14276 }
14277
14278 pub fn render_crease_toggle(
14279 &self,
14280 buffer_row: MultiBufferRow,
14281 row_contains_cursor: bool,
14282 editor: View<Editor>,
14283 cx: &mut WindowContext,
14284 ) -> Option<AnyElement> {
14285 let folded = self.is_line_folded(buffer_row);
14286 let mut is_foldable = false;
14287
14288 if let Some(crease) = self
14289 .crease_snapshot
14290 .query_row(buffer_row, &self.buffer_snapshot)
14291 {
14292 is_foldable = true;
14293 match crease {
14294 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14295 if let Some(render_toggle) = render_toggle {
14296 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14297 if folded {
14298 editor.update(cx, |editor, cx| {
14299 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14300 });
14301 } else {
14302 editor.update(cx, |editor, cx| {
14303 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14304 });
14305 }
14306 });
14307 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14308 }
14309 }
14310 }
14311 }
14312
14313 is_foldable |= self.starts_indent(buffer_row);
14314
14315 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14316 Some(
14317 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14318 .toggle_state(folded)
14319 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14320 if folded {
14321 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14322 } else {
14323 this.fold_at(&FoldAt { buffer_row }, cx);
14324 }
14325 }))
14326 .into_any_element(),
14327 )
14328 } else {
14329 None
14330 }
14331 }
14332
14333 pub fn render_crease_trailer(
14334 &self,
14335 buffer_row: MultiBufferRow,
14336 cx: &mut WindowContext,
14337 ) -> Option<AnyElement> {
14338 let folded = self.is_line_folded(buffer_row);
14339 if let Crease::Inline { render_trailer, .. } = self
14340 .crease_snapshot
14341 .query_row(buffer_row, &self.buffer_snapshot)?
14342 {
14343 let render_trailer = render_trailer.as_ref()?;
14344 Some(render_trailer(buffer_row, folded, cx))
14345 } else {
14346 None
14347 }
14348 }
14349}
14350
14351impl Deref for EditorSnapshot {
14352 type Target = DisplaySnapshot;
14353
14354 fn deref(&self) -> &Self::Target {
14355 &self.display_snapshot
14356 }
14357}
14358
14359#[derive(Clone, Debug, PartialEq, Eq)]
14360pub enum EditorEvent {
14361 InputIgnored {
14362 text: Arc<str>,
14363 },
14364 InputHandled {
14365 utf16_range_to_replace: Option<Range<isize>>,
14366 text: Arc<str>,
14367 },
14368 ExcerptsAdded {
14369 buffer: Model<Buffer>,
14370 predecessor: ExcerptId,
14371 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14372 },
14373 ExcerptsRemoved {
14374 ids: Vec<ExcerptId>,
14375 },
14376 BufferFoldToggled {
14377 ids: Vec<ExcerptId>,
14378 folded: bool,
14379 },
14380 ExcerptsEdited {
14381 ids: Vec<ExcerptId>,
14382 },
14383 ExcerptsExpanded {
14384 ids: Vec<ExcerptId>,
14385 },
14386 BufferEdited,
14387 Edited {
14388 transaction_id: clock::Lamport,
14389 },
14390 Reparsed(BufferId),
14391 Focused,
14392 FocusedIn,
14393 Blurred,
14394 DirtyChanged,
14395 Saved,
14396 TitleChanged,
14397 DiffBaseChanged,
14398 SelectionsChanged {
14399 local: bool,
14400 },
14401 ScrollPositionChanged {
14402 local: bool,
14403 autoscroll: bool,
14404 },
14405 Closed,
14406 TransactionUndone {
14407 transaction_id: clock::Lamport,
14408 },
14409 TransactionBegun {
14410 transaction_id: clock::Lamport,
14411 },
14412 Reloaded,
14413 CursorShapeChanged,
14414}
14415
14416impl EventEmitter<EditorEvent> for Editor {}
14417
14418impl FocusableView for Editor {
14419 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14420 self.focus_handle.clone()
14421 }
14422}
14423
14424impl Render for Editor {
14425 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14426 let settings = ThemeSettings::get_global(cx);
14427
14428 let mut text_style = match self.mode {
14429 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14430 color: cx.theme().colors().editor_foreground,
14431 font_family: settings.ui_font.family.clone(),
14432 font_features: settings.ui_font.features.clone(),
14433 font_fallbacks: settings.ui_font.fallbacks.clone(),
14434 font_size: rems(0.875).into(),
14435 font_weight: settings.ui_font.weight,
14436 line_height: relative(settings.buffer_line_height.value()),
14437 ..Default::default()
14438 },
14439 EditorMode::Full => TextStyle {
14440 color: cx.theme().colors().editor_foreground,
14441 font_family: settings.buffer_font.family.clone(),
14442 font_features: settings.buffer_font.features.clone(),
14443 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14444 font_size: settings.buffer_font_size().into(),
14445 font_weight: settings.buffer_font.weight,
14446 line_height: relative(settings.buffer_line_height.value()),
14447 ..Default::default()
14448 },
14449 };
14450 if let Some(text_style_refinement) = &self.text_style_refinement {
14451 text_style.refine(text_style_refinement)
14452 }
14453
14454 let background = match self.mode {
14455 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14456 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14457 EditorMode::Full => cx.theme().colors().editor_background,
14458 };
14459
14460 EditorElement::new(
14461 cx.view(),
14462 EditorStyle {
14463 background,
14464 local_player: cx.theme().players().local(),
14465 text: text_style,
14466 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14467 syntax: cx.theme().syntax().clone(),
14468 status: cx.theme().status().clone(),
14469 inlay_hints_style: make_inlay_hints_style(cx),
14470 inline_completion_styles: make_suggestion_styles(cx),
14471 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14472 },
14473 )
14474 }
14475}
14476
14477impl ViewInputHandler for Editor {
14478 fn text_for_range(
14479 &mut self,
14480 range_utf16: Range<usize>,
14481 adjusted_range: &mut Option<Range<usize>>,
14482 cx: &mut ViewContext<Self>,
14483 ) -> Option<String> {
14484 let snapshot = self.buffer.read(cx).read(cx);
14485 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14486 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14487 if (start.0..end.0) != range_utf16 {
14488 adjusted_range.replace(start.0..end.0);
14489 }
14490 Some(snapshot.text_for_range(start..end).collect())
14491 }
14492
14493 fn selected_text_range(
14494 &mut self,
14495 ignore_disabled_input: bool,
14496 cx: &mut ViewContext<Self>,
14497 ) -> Option<UTF16Selection> {
14498 // Prevent the IME menu from appearing when holding down an alphabetic key
14499 // while input is disabled.
14500 if !ignore_disabled_input && !self.input_enabled {
14501 return None;
14502 }
14503
14504 let selection = self.selections.newest::<OffsetUtf16>(cx);
14505 let range = selection.range();
14506
14507 Some(UTF16Selection {
14508 range: range.start.0..range.end.0,
14509 reversed: selection.reversed,
14510 })
14511 }
14512
14513 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14514 let snapshot = self.buffer.read(cx).read(cx);
14515 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14516 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14517 }
14518
14519 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14520 self.clear_highlights::<InputComposition>(cx);
14521 self.ime_transaction.take();
14522 }
14523
14524 fn replace_text_in_range(
14525 &mut self,
14526 range_utf16: Option<Range<usize>>,
14527 text: &str,
14528 cx: &mut ViewContext<Self>,
14529 ) {
14530 if !self.input_enabled {
14531 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14532 return;
14533 }
14534
14535 self.transact(cx, |this, cx| {
14536 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14537 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14538 Some(this.selection_replacement_ranges(range_utf16, cx))
14539 } else {
14540 this.marked_text_ranges(cx)
14541 };
14542
14543 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14544 let newest_selection_id = this.selections.newest_anchor().id;
14545 this.selections
14546 .all::<OffsetUtf16>(cx)
14547 .iter()
14548 .zip(ranges_to_replace.iter())
14549 .find_map(|(selection, range)| {
14550 if selection.id == newest_selection_id {
14551 Some(
14552 (range.start.0 as isize - selection.head().0 as isize)
14553 ..(range.end.0 as isize - selection.head().0 as isize),
14554 )
14555 } else {
14556 None
14557 }
14558 })
14559 });
14560
14561 cx.emit(EditorEvent::InputHandled {
14562 utf16_range_to_replace: range_to_replace,
14563 text: text.into(),
14564 });
14565
14566 if let Some(new_selected_ranges) = new_selected_ranges {
14567 this.change_selections(None, cx, |selections| {
14568 selections.select_ranges(new_selected_ranges)
14569 });
14570 this.backspace(&Default::default(), cx);
14571 }
14572
14573 this.handle_input(text, cx);
14574 });
14575
14576 if let Some(transaction) = self.ime_transaction {
14577 self.buffer.update(cx, |buffer, cx| {
14578 buffer.group_until_transaction(transaction, cx);
14579 });
14580 }
14581
14582 self.unmark_text(cx);
14583 }
14584
14585 fn replace_and_mark_text_in_range(
14586 &mut self,
14587 range_utf16: Option<Range<usize>>,
14588 text: &str,
14589 new_selected_range_utf16: Option<Range<usize>>,
14590 cx: &mut ViewContext<Self>,
14591 ) {
14592 if !self.input_enabled {
14593 return;
14594 }
14595
14596 let transaction = self.transact(cx, |this, cx| {
14597 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14598 let snapshot = this.buffer.read(cx).read(cx);
14599 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14600 for marked_range in &mut marked_ranges {
14601 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14602 marked_range.start.0 += relative_range_utf16.start;
14603 marked_range.start =
14604 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14605 marked_range.end =
14606 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14607 }
14608 }
14609 Some(marked_ranges)
14610 } else if let Some(range_utf16) = range_utf16 {
14611 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14612 Some(this.selection_replacement_ranges(range_utf16, cx))
14613 } else {
14614 None
14615 };
14616
14617 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14618 let newest_selection_id = this.selections.newest_anchor().id;
14619 this.selections
14620 .all::<OffsetUtf16>(cx)
14621 .iter()
14622 .zip(ranges_to_replace.iter())
14623 .find_map(|(selection, range)| {
14624 if selection.id == newest_selection_id {
14625 Some(
14626 (range.start.0 as isize - selection.head().0 as isize)
14627 ..(range.end.0 as isize - selection.head().0 as isize),
14628 )
14629 } else {
14630 None
14631 }
14632 })
14633 });
14634
14635 cx.emit(EditorEvent::InputHandled {
14636 utf16_range_to_replace: range_to_replace,
14637 text: text.into(),
14638 });
14639
14640 if let Some(ranges) = ranges_to_replace {
14641 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14642 }
14643
14644 let marked_ranges = {
14645 let snapshot = this.buffer.read(cx).read(cx);
14646 this.selections
14647 .disjoint_anchors()
14648 .iter()
14649 .map(|selection| {
14650 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14651 })
14652 .collect::<Vec<_>>()
14653 };
14654
14655 if text.is_empty() {
14656 this.unmark_text(cx);
14657 } else {
14658 this.highlight_text::<InputComposition>(
14659 marked_ranges.clone(),
14660 HighlightStyle {
14661 underline: Some(UnderlineStyle {
14662 thickness: px(1.),
14663 color: None,
14664 wavy: false,
14665 }),
14666 ..Default::default()
14667 },
14668 cx,
14669 );
14670 }
14671
14672 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14673 let use_autoclose = this.use_autoclose;
14674 let use_auto_surround = this.use_auto_surround;
14675 this.set_use_autoclose(false);
14676 this.set_use_auto_surround(false);
14677 this.handle_input(text, cx);
14678 this.set_use_autoclose(use_autoclose);
14679 this.set_use_auto_surround(use_auto_surround);
14680
14681 if let Some(new_selected_range) = new_selected_range_utf16 {
14682 let snapshot = this.buffer.read(cx).read(cx);
14683 let new_selected_ranges = marked_ranges
14684 .into_iter()
14685 .map(|marked_range| {
14686 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14687 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14688 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14689 snapshot.clip_offset_utf16(new_start, Bias::Left)
14690 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14691 })
14692 .collect::<Vec<_>>();
14693
14694 drop(snapshot);
14695 this.change_selections(None, cx, |selections| {
14696 selections.select_ranges(new_selected_ranges)
14697 });
14698 }
14699 });
14700
14701 self.ime_transaction = self.ime_transaction.or(transaction);
14702 if let Some(transaction) = self.ime_transaction {
14703 self.buffer.update(cx, |buffer, cx| {
14704 buffer.group_until_transaction(transaction, cx);
14705 });
14706 }
14707
14708 if self.text_highlights::<InputComposition>(cx).is_none() {
14709 self.ime_transaction.take();
14710 }
14711 }
14712
14713 fn bounds_for_range(
14714 &mut self,
14715 range_utf16: Range<usize>,
14716 element_bounds: gpui::Bounds<Pixels>,
14717 cx: &mut ViewContext<Self>,
14718 ) -> Option<gpui::Bounds<Pixels>> {
14719 let text_layout_details = self.text_layout_details(cx);
14720 let gpui::Point {
14721 x: em_width,
14722 y: line_height,
14723 } = self.character_size(cx);
14724
14725 let snapshot = self.snapshot(cx);
14726 let scroll_position = snapshot.scroll_position();
14727 let scroll_left = scroll_position.x * em_width;
14728
14729 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14730 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14731 + self.gutter_dimensions.width
14732 + self.gutter_dimensions.margin;
14733 let y = line_height * (start.row().as_f32() - scroll_position.y);
14734
14735 Some(Bounds {
14736 origin: element_bounds.origin + point(x, y),
14737 size: size(em_width, line_height),
14738 })
14739 }
14740}
14741
14742trait SelectionExt {
14743 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14744 fn spanned_rows(
14745 &self,
14746 include_end_if_at_line_start: bool,
14747 map: &DisplaySnapshot,
14748 ) -> Range<MultiBufferRow>;
14749}
14750
14751impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14752 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14753 let start = self
14754 .start
14755 .to_point(&map.buffer_snapshot)
14756 .to_display_point(map);
14757 let end = self
14758 .end
14759 .to_point(&map.buffer_snapshot)
14760 .to_display_point(map);
14761 if self.reversed {
14762 end..start
14763 } else {
14764 start..end
14765 }
14766 }
14767
14768 fn spanned_rows(
14769 &self,
14770 include_end_if_at_line_start: bool,
14771 map: &DisplaySnapshot,
14772 ) -> Range<MultiBufferRow> {
14773 let start = self.start.to_point(&map.buffer_snapshot);
14774 let mut end = self.end.to_point(&map.buffer_snapshot);
14775 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14776 end.row -= 1;
14777 }
14778
14779 let buffer_start = map.prev_line_boundary(start).0;
14780 let buffer_end = map.next_line_boundary(end).0;
14781 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14782 }
14783}
14784
14785impl<T: InvalidationRegion> InvalidationStack<T> {
14786 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14787 where
14788 S: Clone + ToOffset,
14789 {
14790 while let Some(region) = self.last() {
14791 let all_selections_inside_invalidation_ranges =
14792 if selections.len() == region.ranges().len() {
14793 selections
14794 .iter()
14795 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14796 .all(|(selection, invalidation_range)| {
14797 let head = selection.head().to_offset(buffer);
14798 invalidation_range.start <= head && invalidation_range.end >= head
14799 })
14800 } else {
14801 false
14802 };
14803
14804 if all_selections_inside_invalidation_ranges {
14805 break;
14806 } else {
14807 self.pop();
14808 }
14809 }
14810 }
14811}
14812
14813impl<T> Default for InvalidationStack<T> {
14814 fn default() -> Self {
14815 Self(Default::default())
14816 }
14817}
14818
14819impl<T> Deref for InvalidationStack<T> {
14820 type Target = Vec<T>;
14821
14822 fn deref(&self) -> &Self::Target {
14823 &self.0
14824 }
14825}
14826
14827impl<T> DerefMut for InvalidationStack<T> {
14828 fn deref_mut(&mut self) -> &mut Self::Target {
14829 &mut self.0
14830 }
14831}
14832
14833impl InvalidationRegion for SnippetState {
14834 fn ranges(&self) -> &[Range<Anchor>] {
14835 &self.ranges[self.active_index]
14836 }
14837}
14838
14839pub fn diagnostic_block_renderer(
14840 diagnostic: Diagnostic,
14841 max_message_rows: Option<u8>,
14842 allow_closing: bool,
14843 _is_valid: bool,
14844) -> RenderBlock {
14845 let (text_without_backticks, code_ranges) =
14846 highlight_diagnostic_message(&diagnostic, max_message_rows);
14847
14848 Arc::new(move |cx: &mut BlockContext| {
14849 let group_id: SharedString = cx.block_id.to_string().into();
14850
14851 let mut text_style = cx.text_style().clone();
14852 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14853 let theme_settings = ThemeSettings::get_global(cx);
14854 text_style.font_family = theme_settings.buffer_font.family.clone();
14855 text_style.font_style = theme_settings.buffer_font.style;
14856 text_style.font_features = theme_settings.buffer_font.features.clone();
14857 text_style.font_weight = theme_settings.buffer_font.weight;
14858
14859 let multi_line_diagnostic = diagnostic.message.contains('\n');
14860
14861 let buttons = |diagnostic: &Diagnostic| {
14862 if multi_line_diagnostic {
14863 v_flex()
14864 } else {
14865 h_flex()
14866 }
14867 .when(allow_closing, |div| {
14868 div.children(diagnostic.is_primary.then(|| {
14869 IconButton::new("close-block", IconName::XCircle)
14870 .icon_color(Color::Muted)
14871 .size(ButtonSize::Compact)
14872 .style(ButtonStyle::Transparent)
14873 .visible_on_hover(group_id.clone())
14874 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14875 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14876 }))
14877 })
14878 .child(
14879 IconButton::new("copy-block", IconName::Copy)
14880 .icon_color(Color::Muted)
14881 .size(ButtonSize::Compact)
14882 .style(ButtonStyle::Transparent)
14883 .visible_on_hover(group_id.clone())
14884 .on_click({
14885 let message = diagnostic.message.clone();
14886 move |_click, cx| {
14887 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14888 }
14889 })
14890 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14891 )
14892 };
14893
14894 let icon_size = buttons(&diagnostic)
14895 .into_any_element()
14896 .layout_as_root(AvailableSpace::min_size(), cx);
14897
14898 h_flex()
14899 .id(cx.block_id)
14900 .group(group_id.clone())
14901 .relative()
14902 .size_full()
14903 .block_mouse_down()
14904 .pl(cx.gutter_dimensions.width)
14905 .w(cx.max_width - cx.gutter_dimensions.full_width())
14906 .child(
14907 div()
14908 .flex()
14909 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14910 .flex_shrink(),
14911 )
14912 .child(buttons(&diagnostic))
14913 .child(div().flex().flex_shrink_0().child(
14914 StyledText::new(text_without_backticks.clone()).with_highlights(
14915 &text_style,
14916 code_ranges.iter().map(|range| {
14917 (
14918 range.clone(),
14919 HighlightStyle {
14920 font_weight: Some(FontWeight::BOLD),
14921 ..Default::default()
14922 },
14923 )
14924 }),
14925 ),
14926 ))
14927 .into_any_element()
14928 })
14929}
14930
14931fn inline_completion_edit_text(
14932 editor_snapshot: &EditorSnapshot,
14933 edits: &Vec<(Range<Anchor>, String)>,
14934 include_deletions: bool,
14935 cx: &WindowContext,
14936) -> InlineCompletionText {
14937 let edit_start = edits
14938 .first()
14939 .unwrap()
14940 .0
14941 .start
14942 .to_display_point(editor_snapshot);
14943
14944 let mut text = String::new();
14945 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14946 let mut highlights = Vec::new();
14947 for (old_range, new_text) in edits {
14948 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14949 text.extend(
14950 editor_snapshot
14951 .buffer_snapshot
14952 .chunks(offset..old_offset_range.start, false)
14953 .map(|chunk| chunk.text),
14954 );
14955 offset = old_offset_range.end;
14956
14957 let start = text.len();
14958 let color = if include_deletions && new_text.is_empty() {
14959 text.extend(
14960 editor_snapshot
14961 .buffer_snapshot
14962 .chunks(old_offset_range.start..offset, false)
14963 .map(|chunk| chunk.text),
14964 );
14965 cx.theme().status().deleted_background
14966 } else {
14967 text.push_str(new_text);
14968 cx.theme().status().created_background
14969 };
14970 let end = text.len();
14971
14972 highlights.push((
14973 start..end,
14974 HighlightStyle {
14975 background_color: Some(color),
14976 ..Default::default()
14977 },
14978 ));
14979 }
14980
14981 let edit_end = edits
14982 .last()
14983 .unwrap()
14984 .0
14985 .end
14986 .to_display_point(editor_snapshot);
14987 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14988 .to_offset(editor_snapshot, Bias::Right);
14989 text.extend(
14990 editor_snapshot
14991 .buffer_snapshot
14992 .chunks(offset..end_of_line, false)
14993 .map(|chunk| chunk.text),
14994 );
14995
14996 InlineCompletionText::Edit {
14997 text: text.into(),
14998 highlights,
14999 }
15000}
15001
15002pub fn highlight_diagnostic_message(
15003 diagnostic: &Diagnostic,
15004 mut max_message_rows: Option<u8>,
15005) -> (SharedString, Vec<Range<usize>>) {
15006 let mut text_without_backticks = String::new();
15007 let mut code_ranges = Vec::new();
15008
15009 if let Some(source) = &diagnostic.source {
15010 text_without_backticks.push_str(source);
15011 code_ranges.push(0..source.len());
15012 text_without_backticks.push_str(": ");
15013 }
15014
15015 let mut prev_offset = 0;
15016 let mut in_code_block = false;
15017 let has_row_limit = max_message_rows.is_some();
15018 let mut newline_indices = diagnostic
15019 .message
15020 .match_indices('\n')
15021 .filter(|_| has_row_limit)
15022 .map(|(ix, _)| ix)
15023 .fuse()
15024 .peekable();
15025
15026 for (quote_ix, _) in diagnostic
15027 .message
15028 .match_indices('`')
15029 .chain([(diagnostic.message.len(), "")])
15030 {
15031 let mut first_newline_ix = None;
15032 let mut last_newline_ix = None;
15033 while let Some(newline_ix) = newline_indices.peek() {
15034 if *newline_ix < quote_ix {
15035 if first_newline_ix.is_none() {
15036 first_newline_ix = Some(*newline_ix);
15037 }
15038 last_newline_ix = Some(*newline_ix);
15039
15040 if let Some(rows_left) = &mut max_message_rows {
15041 if *rows_left == 0 {
15042 break;
15043 } else {
15044 *rows_left -= 1;
15045 }
15046 }
15047 let _ = newline_indices.next();
15048 } else {
15049 break;
15050 }
15051 }
15052 let prev_len = text_without_backticks.len();
15053 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15054 text_without_backticks.push_str(new_text);
15055 if in_code_block {
15056 code_ranges.push(prev_len..text_without_backticks.len());
15057 }
15058 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15059 in_code_block = !in_code_block;
15060 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15061 text_without_backticks.push_str("...");
15062 break;
15063 }
15064 }
15065
15066 (text_without_backticks.into(), code_ranges)
15067}
15068
15069fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15070 match severity {
15071 DiagnosticSeverity::ERROR => colors.error,
15072 DiagnosticSeverity::WARNING => colors.warning,
15073 DiagnosticSeverity::INFORMATION => colors.info,
15074 DiagnosticSeverity::HINT => colors.info,
15075 _ => colors.ignored,
15076 }
15077}
15078
15079pub fn styled_runs_for_code_label<'a>(
15080 label: &'a CodeLabel,
15081 syntax_theme: &'a theme::SyntaxTheme,
15082) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15083 let fade_out = HighlightStyle {
15084 fade_out: Some(0.35),
15085 ..Default::default()
15086 };
15087
15088 let mut prev_end = label.filter_range.end;
15089 label
15090 .runs
15091 .iter()
15092 .enumerate()
15093 .flat_map(move |(ix, (range, highlight_id))| {
15094 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15095 style
15096 } else {
15097 return Default::default();
15098 };
15099 let mut muted_style = style;
15100 muted_style.highlight(fade_out);
15101
15102 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15103 if range.start >= label.filter_range.end {
15104 if range.start > prev_end {
15105 runs.push((prev_end..range.start, fade_out));
15106 }
15107 runs.push((range.clone(), muted_style));
15108 } else if range.end <= label.filter_range.end {
15109 runs.push((range.clone(), style));
15110 } else {
15111 runs.push((range.start..label.filter_range.end, style));
15112 runs.push((label.filter_range.end..range.end, muted_style));
15113 }
15114 prev_end = cmp::max(prev_end, range.end);
15115
15116 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15117 runs.push((prev_end..label.text.len(), fade_out));
15118 }
15119
15120 runs
15121 })
15122}
15123
15124pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15125 let mut prev_index = 0;
15126 let mut prev_codepoint: Option<char> = None;
15127 text.char_indices()
15128 .chain([(text.len(), '\0')])
15129 .filter_map(move |(index, codepoint)| {
15130 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15131 let is_boundary = index == text.len()
15132 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15133 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15134 if is_boundary {
15135 let chunk = &text[prev_index..index];
15136 prev_index = index;
15137 Some(chunk)
15138 } else {
15139 None
15140 }
15141 })
15142}
15143
15144pub trait RangeToAnchorExt: Sized {
15145 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15146
15147 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15148 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15149 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15150 }
15151}
15152
15153impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15154 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15155 let start_offset = self.start.to_offset(snapshot);
15156 let end_offset = self.end.to_offset(snapshot);
15157 if start_offset == end_offset {
15158 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15159 } else {
15160 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15161 }
15162 }
15163}
15164
15165pub trait RowExt {
15166 fn as_f32(&self) -> f32;
15167
15168 fn next_row(&self) -> Self;
15169
15170 fn previous_row(&self) -> Self;
15171
15172 fn minus(&self, other: Self) -> u32;
15173}
15174
15175impl RowExt for DisplayRow {
15176 fn as_f32(&self) -> f32 {
15177 self.0 as f32
15178 }
15179
15180 fn next_row(&self) -> Self {
15181 Self(self.0 + 1)
15182 }
15183
15184 fn previous_row(&self) -> Self {
15185 Self(self.0.saturating_sub(1))
15186 }
15187
15188 fn minus(&self, other: Self) -> u32 {
15189 self.0 - other.0
15190 }
15191}
15192
15193impl RowExt for MultiBufferRow {
15194 fn as_f32(&self) -> f32 {
15195 self.0 as f32
15196 }
15197
15198 fn next_row(&self) -> Self {
15199 Self(self.0 + 1)
15200 }
15201
15202 fn previous_row(&self) -> Self {
15203 Self(self.0.saturating_sub(1))
15204 }
15205
15206 fn minus(&self, other: Self) -> u32 {
15207 self.0 - other.0
15208 }
15209}
15210
15211trait RowRangeExt {
15212 type Row;
15213
15214 fn len(&self) -> usize;
15215
15216 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15217}
15218
15219impl RowRangeExt for Range<MultiBufferRow> {
15220 type Row = MultiBufferRow;
15221
15222 fn len(&self) -> usize {
15223 (self.end.0 - self.start.0) as usize
15224 }
15225
15226 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15227 (self.start.0..self.end.0).map(MultiBufferRow)
15228 }
15229}
15230
15231impl RowRangeExt for Range<DisplayRow> {
15232 type Row = DisplayRow;
15233
15234 fn len(&self) -> usize {
15235 (self.end.0 - self.start.0) as usize
15236 }
15237
15238 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15239 (self.start.0..self.end.0).map(DisplayRow)
15240 }
15241}
15242
15243fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15244 if hunk.diff_base_byte_range.is_empty() {
15245 DiffHunkStatus::Added
15246 } else if hunk.row_range.is_empty() {
15247 DiffHunkStatus::Removed
15248 } else {
15249 DiffHunkStatus::Modified
15250 }
15251}
15252
15253/// If select range has more than one line, we
15254/// just point the cursor to range.start.
15255fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15256 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15257 range
15258 } else {
15259 range.start..range.start
15260 }
15261}
15262pub struct KillRing(ClipboardItem);
15263impl Global for KillRing {}
15264
15265const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);