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 swap_selection_ends(
10637 &mut self,
10638 _: &actions::SwapSelectionEnds,
10639 cx: &mut ViewContext<Self>,
10640 ) {
10641 self.change_selections(None, cx, |s| {
10642 s.move_with(|_, sel| {
10643 if sel.start != sel.end {
10644 sel.reversed = !sel.reversed
10645 }
10646 });
10647 });
10648 cx.notify();
10649 }
10650
10651 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10652 if self.is_singleton(cx) {
10653 let selection = self.selections.newest::<Point>(cx);
10654
10655 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10656 let range = if selection.is_empty() {
10657 let point = selection.head().to_display_point(&display_map);
10658 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10659 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10660 .to_point(&display_map);
10661 start..end
10662 } else {
10663 selection.range()
10664 };
10665 if display_map.folds_in_range(range).next().is_some() {
10666 self.unfold_lines(&Default::default(), cx)
10667 } else {
10668 self.fold(&Default::default(), cx)
10669 }
10670 } else {
10671 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10672 let mut toggled_buffers = HashSet::default();
10673 for (_, buffer_snapshot, _) in
10674 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10675 {
10676 let buffer_id = buffer_snapshot.remote_id();
10677 if toggled_buffers.insert(buffer_id) {
10678 if self.buffer_folded(buffer_id, cx) {
10679 self.unfold_buffer(buffer_id, cx);
10680 } else {
10681 self.fold_buffer(buffer_id, cx);
10682 }
10683 }
10684 }
10685 }
10686 }
10687
10688 pub fn toggle_fold_recursive(
10689 &mut self,
10690 _: &actions::ToggleFoldRecursive,
10691 cx: &mut ViewContext<Self>,
10692 ) {
10693 let selection = self.selections.newest::<Point>(cx);
10694
10695 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10696 let range = if selection.is_empty() {
10697 let point = selection.head().to_display_point(&display_map);
10698 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10699 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10700 .to_point(&display_map);
10701 start..end
10702 } else {
10703 selection.range()
10704 };
10705 if display_map.folds_in_range(range).next().is_some() {
10706 self.unfold_recursive(&Default::default(), cx)
10707 } else {
10708 self.fold_recursive(&Default::default(), cx)
10709 }
10710 }
10711
10712 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10713 if self.is_singleton(cx) {
10714 let mut to_fold = Vec::new();
10715 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10716 let selections = self.selections.all_adjusted(cx);
10717
10718 for selection in selections {
10719 let range = selection.range().sorted();
10720 let buffer_start_row = range.start.row;
10721
10722 if range.start.row != range.end.row {
10723 let mut found = false;
10724 let mut row = range.start.row;
10725 while row <= range.end.row {
10726 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10727 {
10728 found = true;
10729 row = crease.range().end.row + 1;
10730 to_fold.push(crease);
10731 } else {
10732 row += 1
10733 }
10734 }
10735 if found {
10736 continue;
10737 }
10738 }
10739
10740 for row in (0..=range.start.row).rev() {
10741 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10742 if crease.range().end.row >= buffer_start_row {
10743 to_fold.push(crease);
10744 if row <= range.start.row {
10745 break;
10746 }
10747 }
10748 }
10749 }
10750 }
10751
10752 self.fold_creases(to_fold, true, cx);
10753 } else {
10754 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10755 let mut folded_buffers = HashSet::default();
10756 for (_, buffer_snapshot, _) in
10757 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10758 {
10759 let buffer_id = buffer_snapshot.remote_id();
10760 if folded_buffers.insert(buffer_id) {
10761 self.fold_buffer(buffer_id, cx);
10762 }
10763 }
10764 }
10765 }
10766
10767 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10768 if !self.buffer.read(cx).is_singleton() {
10769 return;
10770 }
10771
10772 let fold_at_level = fold_at.level;
10773 let snapshot = self.buffer.read(cx).snapshot(cx);
10774 let mut to_fold = Vec::new();
10775 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10776
10777 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10778 while start_row < end_row {
10779 match self
10780 .snapshot(cx)
10781 .crease_for_buffer_row(MultiBufferRow(start_row))
10782 {
10783 Some(crease) => {
10784 let nested_start_row = crease.range().start.row + 1;
10785 let nested_end_row = crease.range().end.row;
10786
10787 if current_level < fold_at_level {
10788 stack.push((nested_start_row, nested_end_row, current_level + 1));
10789 } else if current_level == fold_at_level {
10790 to_fold.push(crease);
10791 }
10792
10793 start_row = nested_end_row + 1;
10794 }
10795 None => start_row += 1,
10796 }
10797 }
10798 }
10799
10800 self.fold_creases(to_fold, true, cx);
10801 }
10802
10803 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10804 if self.buffer.read(cx).is_singleton() {
10805 let mut fold_ranges = Vec::new();
10806 let snapshot = self.buffer.read(cx).snapshot(cx);
10807
10808 for row in 0..snapshot.max_row().0 {
10809 if let Some(foldable_range) =
10810 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10811 {
10812 fold_ranges.push(foldable_range);
10813 }
10814 }
10815
10816 self.fold_creases(fold_ranges, true, cx);
10817 } else {
10818 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10819 editor
10820 .update(&mut cx, |editor, cx| {
10821 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10822 editor.fold_buffer(buffer_id, cx);
10823 }
10824 })
10825 .ok();
10826 });
10827 }
10828 }
10829
10830 pub fn fold_function_bodies(
10831 &mut self,
10832 _: &actions::FoldFunctionBodies,
10833 cx: &mut ViewContext<Self>,
10834 ) {
10835 let snapshot = self.buffer.read(cx).snapshot(cx);
10836 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10837 return;
10838 };
10839 let creases = buffer
10840 .function_body_fold_ranges(0..buffer.len())
10841 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10842 .collect();
10843
10844 self.fold_creases(creases, true, cx);
10845 }
10846
10847 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10848 let mut to_fold = Vec::new();
10849 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10850 let selections = self.selections.all_adjusted(cx);
10851
10852 for selection in selections {
10853 let range = selection.range().sorted();
10854 let buffer_start_row = range.start.row;
10855
10856 if range.start.row != range.end.row {
10857 let mut found = false;
10858 for row in range.start.row..=range.end.row {
10859 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10860 found = true;
10861 to_fold.push(crease);
10862 }
10863 }
10864 if found {
10865 continue;
10866 }
10867 }
10868
10869 for row in (0..=range.start.row).rev() {
10870 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10871 if crease.range().end.row >= buffer_start_row {
10872 to_fold.push(crease);
10873 } else {
10874 break;
10875 }
10876 }
10877 }
10878 }
10879
10880 self.fold_creases(to_fold, true, cx);
10881 }
10882
10883 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10884 let buffer_row = fold_at.buffer_row;
10885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10886
10887 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10888 let autoscroll = self
10889 .selections
10890 .all::<Point>(cx)
10891 .iter()
10892 .any(|selection| crease.range().overlaps(&selection.range()));
10893
10894 self.fold_creases(vec![crease], autoscroll, cx);
10895 }
10896 }
10897
10898 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10899 if self.is_singleton(cx) {
10900 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10901 let buffer = &display_map.buffer_snapshot;
10902 let selections = self.selections.all::<Point>(cx);
10903 let ranges = selections
10904 .iter()
10905 .map(|s| {
10906 let range = s.display_range(&display_map).sorted();
10907 let mut start = range.start.to_point(&display_map);
10908 let mut end = range.end.to_point(&display_map);
10909 start.column = 0;
10910 end.column = buffer.line_len(MultiBufferRow(end.row));
10911 start..end
10912 })
10913 .collect::<Vec<_>>();
10914
10915 self.unfold_ranges(&ranges, true, true, cx);
10916 } else {
10917 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10918 let mut unfolded_buffers = HashSet::default();
10919 for (_, buffer_snapshot, _) in
10920 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10921 {
10922 let buffer_id = buffer_snapshot.remote_id();
10923 if unfolded_buffers.insert(buffer_id) {
10924 self.unfold_buffer(buffer_id, cx);
10925 }
10926 }
10927 }
10928 }
10929
10930 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10932 let selections = self.selections.all::<Point>(cx);
10933 let ranges = selections
10934 .iter()
10935 .map(|s| {
10936 let mut range = s.display_range(&display_map).sorted();
10937 *range.start.column_mut() = 0;
10938 *range.end.column_mut() = display_map.line_len(range.end.row());
10939 let start = range.start.to_point(&display_map);
10940 let end = range.end.to_point(&display_map);
10941 start..end
10942 })
10943 .collect::<Vec<_>>();
10944
10945 self.unfold_ranges(&ranges, true, true, cx);
10946 }
10947
10948 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10950
10951 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10952 ..Point::new(
10953 unfold_at.buffer_row.0,
10954 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10955 );
10956
10957 let autoscroll = self
10958 .selections
10959 .all::<Point>(cx)
10960 .iter()
10961 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10962
10963 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10964 }
10965
10966 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10967 if self.buffer.read(cx).is_singleton() {
10968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10969 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10970 } else {
10971 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10972 editor
10973 .update(&mut cx, |editor, cx| {
10974 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10975 editor.unfold_buffer(buffer_id, cx);
10976 }
10977 })
10978 .ok();
10979 });
10980 }
10981 }
10982
10983 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10984 let selections = self.selections.all::<Point>(cx);
10985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10986 let line_mode = self.selections.line_mode;
10987 let ranges = selections
10988 .into_iter()
10989 .map(|s| {
10990 if line_mode {
10991 let start = Point::new(s.start.row, 0);
10992 let end = Point::new(
10993 s.end.row,
10994 display_map
10995 .buffer_snapshot
10996 .line_len(MultiBufferRow(s.end.row)),
10997 );
10998 Crease::simple(start..end, display_map.fold_placeholder.clone())
10999 } else {
11000 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11001 }
11002 })
11003 .collect::<Vec<_>>();
11004 self.fold_creases(ranges, true, cx);
11005 }
11006
11007 pub fn fold_ranges<T: ToOffset + Clone>(
11008 &mut self,
11009 ranges: Vec<Range<T>>,
11010 auto_scroll: bool,
11011 cx: &mut ViewContext<Self>,
11012 ) {
11013 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11014 let ranges = ranges
11015 .into_iter()
11016 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11017 .collect::<Vec<_>>();
11018 self.fold_creases(ranges, auto_scroll, cx);
11019 }
11020
11021 pub fn fold_creases<T: ToOffset + Clone>(
11022 &mut self,
11023 creases: Vec<Crease<T>>,
11024 auto_scroll: bool,
11025 cx: &mut ViewContext<Self>,
11026 ) {
11027 if creases.is_empty() {
11028 return;
11029 }
11030
11031 let mut buffers_affected = HashSet::default();
11032 let multi_buffer = self.buffer().read(cx);
11033 for crease in &creases {
11034 if let Some((_, buffer, _)) =
11035 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11036 {
11037 buffers_affected.insert(buffer.read(cx).remote_id());
11038 };
11039 }
11040
11041 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11042
11043 if auto_scroll {
11044 self.request_autoscroll(Autoscroll::fit(), cx);
11045 }
11046
11047 for buffer_id in buffers_affected {
11048 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11049 }
11050
11051 cx.notify();
11052
11053 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11054 // Clear diagnostics block when folding a range that contains it.
11055 let snapshot = self.snapshot(cx);
11056 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11057 drop(snapshot);
11058 self.active_diagnostics = Some(active_diagnostics);
11059 self.dismiss_diagnostics(cx);
11060 } else {
11061 self.active_diagnostics = Some(active_diagnostics);
11062 }
11063 }
11064
11065 self.scrollbar_marker_state.dirty = true;
11066 }
11067
11068 /// Removes any folds whose ranges intersect any of the given ranges.
11069 pub fn unfold_ranges<T: ToOffset + Clone>(
11070 &mut self,
11071 ranges: &[Range<T>],
11072 inclusive: bool,
11073 auto_scroll: bool,
11074 cx: &mut ViewContext<Self>,
11075 ) {
11076 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11077 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11078 });
11079 }
11080
11081 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11082 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11083 return;
11084 }
11085 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11086 return;
11087 };
11088 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11089 self.display_map
11090 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11091 cx.emit(EditorEvent::BufferFoldToggled {
11092 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11093 folded: true,
11094 });
11095 cx.notify();
11096 }
11097
11098 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11099 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11100 return;
11101 }
11102 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11103 return;
11104 };
11105 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11106 self.display_map.update(cx, |display_map, cx| {
11107 display_map.unfold_buffer(buffer_id, cx);
11108 });
11109 cx.emit(EditorEvent::BufferFoldToggled {
11110 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11111 folded: false,
11112 });
11113 cx.notify();
11114 }
11115
11116 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11117 self.display_map.read(cx).buffer_folded(buffer)
11118 }
11119
11120 /// Removes any folds with the given ranges.
11121 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11122 &mut self,
11123 ranges: &[Range<T>],
11124 type_id: TypeId,
11125 auto_scroll: bool,
11126 cx: &mut ViewContext<Self>,
11127 ) {
11128 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11129 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11130 });
11131 }
11132
11133 fn remove_folds_with<T: ToOffset + Clone>(
11134 &mut self,
11135 ranges: &[Range<T>],
11136 auto_scroll: bool,
11137 cx: &mut ViewContext<Self>,
11138 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11139 ) {
11140 if ranges.is_empty() {
11141 return;
11142 }
11143
11144 let mut buffers_affected = HashSet::default();
11145 let multi_buffer = self.buffer().read(cx);
11146 for range in ranges {
11147 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11148 buffers_affected.insert(buffer.read(cx).remote_id());
11149 };
11150 }
11151
11152 self.display_map.update(cx, update);
11153
11154 if auto_scroll {
11155 self.request_autoscroll(Autoscroll::fit(), cx);
11156 }
11157
11158 for buffer_id in buffers_affected {
11159 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11160 }
11161
11162 cx.notify();
11163 self.scrollbar_marker_state.dirty = true;
11164 self.active_indent_guides_state.dirty = true;
11165 }
11166
11167 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11168 self.display_map.read(cx).fold_placeholder.clone()
11169 }
11170
11171 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11172 if hovered != self.gutter_hovered {
11173 self.gutter_hovered = hovered;
11174 cx.notify();
11175 }
11176 }
11177
11178 pub fn insert_blocks(
11179 &mut self,
11180 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11181 autoscroll: Option<Autoscroll>,
11182 cx: &mut ViewContext<Self>,
11183 ) -> Vec<CustomBlockId> {
11184 let blocks = self
11185 .display_map
11186 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11187 if let Some(autoscroll) = autoscroll {
11188 self.request_autoscroll(autoscroll, cx);
11189 }
11190 cx.notify();
11191 blocks
11192 }
11193
11194 pub fn resize_blocks(
11195 &mut self,
11196 heights: HashMap<CustomBlockId, u32>,
11197 autoscroll: Option<Autoscroll>,
11198 cx: &mut ViewContext<Self>,
11199 ) {
11200 self.display_map
11201 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11202 if let Some(autoscroll) = autoscroll {
11203 self.request_autoscroll(autoscroll, cx);
11204 }
11205 cx.notify();
11206 }
11207
11208 pub fn replace_blocks(
11209 &mut self,
11210 renderers: HashMap<CustomBlockId, RenderBlock>,
11211 autoscroll: Option<Autoscroll>,
11212 cx: &mut ViewContext<Self>,
11213 ) {
11214 self.display_map
11215 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11216 if let Some(autoscroll) = autoscroll {
11217 self.request_autoscroll(autoscroll, cx);
11218 }
11219 cx.notify();
11220 }
11221
11222 pub fn remove_blocks(
11223 &mut self,
11224 block_ids: HashSet<CustomBlockId>,
11225 autoscroll: Option<Autoscroll>,
11226 cx: &mut ViewContext<Self>,
11227 ) {
11228 self.display_map.update(cx, |display_map, cx| {
11229 display_map.remove_blocks(block_ids, cx)
11230 });
11231 if let Some(autoscroll) = autoscroll {
11232 self.request_autoscroll(autoscroll, cx);
11233 }
11234 cx.notify();
11235 }
11236
11237 pub fn row_for_block(
11238 &self,
11239 block_id: CustomBlockId,
11240 cx: &mut ViewContext<Self>,
11241 ) -> Option<DisplayRow> {
11242 self.display_map
11243 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11244 }
11245
11246 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11247 self.focused_block = Some(focused_block);
11248 }
11249
11250 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11251 self.focused_block.take()
11252 }
11253
11254 pub fn insert_creases(
11255 &mut self,
11256 creases: impl IntoIterator<Item = Crease<Anchor>>,
11257 cx: &mut ViewContext<Self>,
11258 ) -> Vec<CreaseId> {
11259 self.display_map
11260 .update(cx, |map, cx| map.insert_creases(creases, cx))
11261 }
11262
11263 pub fn remove_creases(
11264 &mut self,
11265 ids: impl IntoIterator<Item = CreaseId>,
11266 cx: &mut ViewContext<Self>,
11267 ) {
11268 self.display_map
11269 .update(cx, |map, cx| map.remove_creases(ids, cx));
11270 }
11271
11272 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11273 self.display_map
11274 .update(cx, |map, cx| map.snapshot(cx))
11275 .longest_row()
11276 }
11277
11278 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11279 self.display_map
11280 .update(cx, |map, cx| map.snapshot(cx))
11281 .max_point()
11282 }
11283
11284 pub fn text(&self, cx: &AppContext) -> String {
11285 self.buffer.read(cx).read(cx).text()
11286 }
11287
11288 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11289 let text = self.text(cx);
11290 let text = text.trim();
11291
11292 if text.is_empty() {
11293 return None;
11294 }
11295
11296 Some(text.to_string())
11297 }
11298
11299 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11300 self.transact(cx, |this, cx| {
11301 this.buffer
11302 .read(cx)
11303 .as_singleton()
11304 .expect("you can only call set_text on editors for singleton buffers")
11305 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11306 });
11307 }
11308
11309 pub fn display_text(&self, cx: &mut AppContext) -> String {
11310 self.display_map
11311 .update(cx, |map, cx| map.snapshot(cx))
11312 .text()
11313 }
11314
11315 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11316 let mut wrap_guides = smallvec::smallvec![];
11317
11318 if self.show_wrap_guides == Some(false) {
11319 return wrap_guides;
11320 }
11321
11322 let settings = self.buffer.read(cx).settings_at(0, cx);
11323 if settings.show_wrap_guides {
11324 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11325 wrap_guides.push((soft_wrap as usize, true));
11326 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11327 wrap_guides.push((soft_wrap as usize, true));
11328 }
11329 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11330 }
11331
11332 wrap_guides
11333 }
11334
11335 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11336 let settings = self.buffer.read(cx).settings_at(0, cx);
11337 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11338 match mode {
11339 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11340 SoftWrap::None
11341 }
11342 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11343 language_settings::SoftWrap::PreferredLineLength => {
11344 SoftWrap::Column(settings.preferred_line_length)
11345 }
11346 language_settings::SoftWrap::Bounded => {
11347 SoftWrap::Bounded(settings.preferred_line_length)
11348 }
11349 }
11350 }
11351
11352 pub fn set_soft_wrap_mode(
11353 &mut self,
11354 mode: language_settings::SoftWrap,
11355 cx: &mut ViewContext<Self>,
11356 ) {
11357 self.soft_wrap_mode_override = Some(mode);
11358 cx.notify();
11359 }
11360
11361 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11362 self.text_style_refinement = Some(style);
11363 }
11364
11365 /// called by the Element so we know what style we were most recently rendered with.
11366 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11367 let rem_size = cx.rem_size();
11368 self.display_map.update(cx, |map, cx| {
11369 map.set_font(
11370 style.text.font(),
11371 style.text.font_size.to_pixels(rem_size),
11372 cx,
11373 )
11374 });
11375 self.style = Some(style);
11376 }
11377
11378 pub fn style(&self) -> Option<&EditorStyle> {
11379 self.style.as_ref()
11380 }
11381
11382 // Called by the element. This method is not designed to be called outside of the editor
11383 // element's layout code because it does not notify when rewrapping is computed synchronously.
11384 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11385 self.display_map
11386 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11387 }
11388
11389 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11390 if self.soft_wrap_mode_override.is_some() {
11391 self.soft_wrap_mode_override.take();
11392 } else {
11393 let soft_wrap = match self.soft_wrap_mode(cx) {
11394 SoftWrap::GitDiff => return,
11395 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11396 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11397 language_settings::SoftWrap::None
11398 }
11399 };
11400 self.soft_wrap_mode_override = Some(soft_wrap);
11401 }
11402 cx.notify();
11403 }
11404
11405 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11406 let Some(workspace) = self.workspace() else {
11407 return;
11408 };
11409 let fs = workspace.read(cx).app_state().fs.clone();
11410 let current_show = TabBarSettings::get_global(cx).show;
11411 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11412 setting.show = Some(!current_show);
11413 });
11414 }
11415
11416 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11417 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11418 self.buffer
11419 .read(cx)
11420 .settings_at(0, cx)
11421 .indent_guides
11422 .enabled
11423 });
11424 self.show_indent_guides = Some(!currently_enabled);
11425 cx.notify();
11426 }
11427
11428 fn should_show_indent_guides(&self) -> Option<bool> {
11429 self.show_indent_guides
11430 }
11431
11432 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11433 let mut editor_settings = EditorSettings::get_global(cx).clone();
11434 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11435 EditorSettings::override_global(editor_settings, cx);
11436 }
11437
11438 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11439 self.use_relative_line_numbers
11440 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11441 }
11442
11443 pub fn toggle_relative_line_numbers(
11444 &mut self,
11445 _: &ToggleRelativeLineNumbers,
11446 cx: &mut ViewContext<Self>,
11447 ) {
11448 let is_relative = self.should_use_relative_line_numbers(cx);
11449 self.set_relative_line_number(Some(!is_relative), cx)
11450 }
11451
11452 pub fn set_relative_line_number(
11453 &mut self,
11454 is_relative: Option<bool>,
11455 cx: &mut ViewContext<Self>,
11456 ) {
11457 self.use_relative_line_numbers = is_relative;
11458 cx.notify();
11459 }
11460
11461 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11462 self.show_gutter = show_gutter;
11463 cx.notify();
11464 }
11465
11466 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11467 self.show_scrollbars = show_scrollbars;
11468 cx.notify();
11469 }
11470
11471 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11472 self.show_line_numbers = Some(show_line_numbers);
11473 cx.notify();
11474 }
11475
11476 pub fn set_show_git_diff_gutter(
11477 &mut self,
11478 show_git_diff_gutter: bool,
11479 cx: &mut ViewContext<Self>,
11480 ) {
11481 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11482 cx.notify();
11483 }
11484
11485 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11486 self.show_code_actions = Some(show_code_actions);
11487 cx.notify();
11488 }
11489
11490 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11491 self.show_runnables = Some(show_runnables);
11492 cx.notify();
11493 }
11494
11495 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11496 if self.display_map.read(cx).masked != masked {
11497 self.display_map.update(cx, |map, _| map.masked = masked);
11498 }
11499 cx.notify()
11500 }
11501
11502 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11503 self.show_wrap_guides = Some(show_wrap_guides);
11504 cx.notify();
11505 }
11506
11507 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11508 self.show_indent_guides = Some(show_indent_guides);
11509 cx.notify();
11510 }
11511
11512 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11513 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11514 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11515 if let Some(dir) = file.abs_path(cx).parent() {
11516 return Some(dir.to_owned());
11517 }
11518 }
11519
11520 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11521 return Some(project_path.path.to_path_buf());
11522 }
11523 }
11524
11525 None
11526 }
11527
11528 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11529 self.active_excerpt(cx)?
11530 .1
11531 .read(cx)
11532 .file()
11533 .and_then(|f| f.as_local())
11534 }
11535
11536 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11537 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11538 let project_path = buffer.read(cx).project_path(cx)?;
11539 let project = self.project.as_ref()?.read(cx);
11540 project.absolute_path(&project_path, cx)
11541 })
11542 }
11543
11544 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11545 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11546 let project_path = buffer.read(cx).project_path(cx)?;
11547 let project = self.project.as_ref()?.read(cx);
11548 let entry = project.entry_for_path(&project_path, cx)?;
11549 let path = entry.path.to_path_buf();
11550 Some(path)
11551 })
11552 }
11553
11554 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11555 if let Some(target) = self.target_file(cx) {
11556 cx.reveal_path(&target.abs_path(cx));
11557 }
11558 }
11559
11560 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11561 if let Some(path) = self.target_file_abs_path(cx) {
11562 if let Some(path) = path.to_str() {
11563 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11564 }
11565 }
11566 }
11567
11568 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11569 if let Some(path) = self.target_file_path(cx) {
11570 if let Some(path) = path.to_str() {
11571 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11572 }
11573 }
11574 }
11575
11576 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11577 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11578
11579 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11580 self.start_git_blame(true, cx);
11581 }
11582
11583 cx.notify();
11584 }
11585
11586 pub fn toggle_git_blame_inline(
11587 &mut self,
11588 _: &ToggleGitBlameInline,
11589 cx: &mut ViewContext<Self>,
11590 ) {
11591 self.toggle_git_blame_inline_internal(true, cx);
11592 cx.notify();
11593 }
11594
11595 pub fn git_blame_inline_enabled(&self) -> bool {
11596 self.git_blame_inline_enabled
11597 }
11598
11599 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11600 self.show_selection_menu = self
11601 .show_selection_menu
11602 .map(|show_selections_menu| !show_selections_menu)
11603 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11604
11605 cx.notify();
11606 }
11607
11608 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11609 self.show_selection_menu
11610 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11611 }
11612
11613 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11614 if let Some(project) = self.project.as_ref() {
11615 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11616 return;
11617 };
11618
11619 if buffer.read(cx).file().is_none() {
11620 return;
11621 }
11622
11623 let focused = self.focus_handle(cx).contains_focused(cx);
11624
11625 let project = project.clone();
11626 let blame =
11627 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11628 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11629 self.blame = Some(blame);
11630 }
11631 }
11632
11633 fn toggle_git_blame_inline_internal(
11634 &mut self,
11635 user_triggered: bool,
11636 cx: &mut ViewContext<Self>,
11637 ) {
11638 if self.git_blame_inline_enabled {
11639 self.git_blame_inline_enabled = false;
11640 self.show_git_blame_inline = false;
11641 self.show_git_blame_inline_delay_task.take();
11642 } else {
11643 self.git_blame_inline_enabled = true;
11644 self.start_git_blame_inline(user_triggered, cx);
11645 }
11646
11647 cx.notify();
11648 }
11649
11650 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11651 self.start_git_blame(user_triggered, cx);
11652
11653 if ProjectSettings::get_global(cx)
11654 .git
11655 .inline_blame_delay()
11656 .is_some()
11657 {
11658 self.start_inline_blame_timer(cx);
11659 } else {
11660 self.show_git_blame_inline = true
11661 }
11662 }
11663
11664 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11665 self.blame.as_ref()
11666 }
11667
11668 pub fn show_git_blame_gutter(&self) -> bool {
11669 self.show_git_blame_gutter
11670 }
11671
11672 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11673 self.show_git_blame_gutter && self.has_blame_entries(cx)
11674 }
11675
11676 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11677 self.show_git_blame_inline
11678 && self.focus_handle.is_focused(cx)
11679 && !self.newest_selection_head_on_empty_line(cx)
11680 && self.has_blame_entries(cx)
11681 }
11682
11683 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11684 self.blame()
11685 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11686 }
11687
11688 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11689 let cursor_anchor = self.selections.newest_anchor().head();
11690
11691 let snapshot = self.buffer.read(cx).snapshot(cx);
11692 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11693
11694 snapshot.line_len(buffer_row) == 0
11695 }
11696
11697 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11698 let buffer_and_selection = maybe!({
11699 let selection = self.selections.newest::<Point>(cx);
11700 let selection_range = selection.range();
11701
11702 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11703 (buffer, selection_range.start.row..selection_range.end.row)
11704 } else {
11705 let multi_buffer = self.buffer().read(cx);
11706 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11707 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11708
11709 let (excerpt, range) = if selection.reversed {
11710 buffer_ranges.first()
11711 } else {
11712 buffer_ranges.last()
11713 }?;
11714
11715 let snapshot = excerpt.buffer();
11716 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11717 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11718 (
11719 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11720 selection,
11721 )
11722 };
11723
11724 Some((buffer, selection))
11725 });
11726
11727 let Some((buffer, selection)) = buffer_and_selection else {
11728 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11729 };
11730
11731 let Some(project) = self.project.as_ref() else {
11732 return Task::ready(Err(anyhow!("editor does not have project")));
11733 };
11734
11735 project.update(cx, |project, cx| {
11736 project.get_permalink_to_line(&buffer, selection, cx)
11737 })
11738 }
11739
11740 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11741 let permalink_task = self.get_permalink_to_line(cx);
11742 let workspace = self.workspace();
11743
11744 cx.spawn(|_, mut cx| async move {
11745 match permalink_task.await {
11746 Ok(permalink) => {
11747 cx.update(|cx| {
11748 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11749 })
11750 .ok();
11751 }
11752 Err(err) => {
11753 let message = format!("Failed to copy permalink: {err}");
11754
11755 Err::<(), anyhow::Error>(err).log_err();
11756
11757 if let Some(workspace) = workspace {
11758 workspace
11759 .update(&mut cx, |workspace, cx| {
11760 struct CopyPermalinkToLine;
11761
11762 workspace.show_toast(
11763 Toast::new(
11764 NotificationId::unique::<CopyPermalinkToLine>(),
11765 message,
11766 ),
11767 cx,
11768 )
11769 })
11770 .ok();
11771 }
11772 }
11773 }
11774 })
11775 .detach();
11776 }
11777
11778 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11779 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11780 if let Some(file) = self.target_file(cx) {
11781 if let Some(path) = file.path().to_str() {
11782 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11783 }
11784 }
11785 }
11786
11787 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11788 let permalink_task = self.get_permalink_to_line(cx);
11789 let workspace = self.workspace();
11790
11791 cx.spawn(|_, mut cx| async move {
11792 match permalink_task.await {
11793 Ok(permalink) => {
11794 cx.update(|cx| {
11795 cx.open_url(permalink.as_ref());
11796 })
11797 .ok();
11798 }
11799 Err(err) => {
11800 let message = format!("Failed to open permalink: {err}");
11801
11802 Err::<(), anyhow::Error>(err).log_err();
11803
11804 if let Some(workspace) = workspace {
11805 workspace
11806 .update(&mut cx, |workspace, cx| {
11807 struct OpenPermalinkToLine;
11808
11809 workspace.show_toast(
11810 Toast::new(
11811 NotificationId::unique::<OpenPermalinkToLine>(),
11812 message,
11813 ),
11814 cx,
11815 )
11816 })
11817 .ok();
11818 }
11819 }
11820 }
11821 })
11822 .detach();
11823 }
11824
11825 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11826 self.insert_uuid(UuidVersion::V4, cx);
11827 }
11828
11829 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11830 self.insert_uuid(UuidVersion::V7, cx);
11831 }
11832
11833 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11834 self.transact(cx, |this, cx| {
11835 let edits = this
11836 .selections
11837 .all::<Point>(cx)
11838 .into_iter()
11839 .map(|selection| {
11840 let uuid = match version {
11841 UuidVersion::V4 => uuid::Uuid::new_v4(),
11842 UuidVersion::V7 => uuid::Uuid::now_v7(),
11843 };
11844
11845 (selection.range(), uuid.to_string())
11846 });
11847 this.edit(edits, cx);
11848 this.refresh_inline_completion(true, false, cx);
11849 });
11850 }
11851
11852 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11853 /// last highlight added will be used.
11854 ///
11855 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11856 pub fn highlight_rows<T: 'static>(
11857 &mut self,
11858 range: Range<Anchor>,
11859 color: Hsla,
11860 should_autoscroll: bool,
11861 cx: &mut ViewContext<Self>,
11862 ) {
11863 let snapshot = self.buffer().read(cx).snapshot(cx);
11864 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11865 let ix = row_highlights.binary_search_by(|highlight| {
11866 Ordering::Equal
11867 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11868 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11869 });
11870
11871 if let Err(mut ix) = ix {
11872 let index = post_inc(&mut self.highlight_order);
11873
11874 // If this range intersects with the preceding highlight, then merge it with
11875 // the preceding highlight. Otherwise insert a new highlight.
11876 let mut merged = false;
11877 if ix > 0 {
11878 let prev_highlight = &mut row_highlights[ix - 1];
11879 if prev_highlight
11880 .range
11881 .end
11882 .cmp(&range.start, &snapshot)
11883 .is_ge()
11884 {
11885 ix -= 1;
11886 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11887 prev_highlight.range.end = range.end;
11888 }
11889 merged = true;
11890 prev_highlight.index = index;
11891 prev_highlight.color = color;
11892 prev_highlight.should_autoscroll = should_autoscroll;
11893 }
11894 }
11895
11896 if !merged {
11897 row_highlights.insert(
11898 ix,
11899 RowHighlight {
11900 range: range.clone(),
11901 index,
11902 color,
11903 should_autoscroll,
11904 },
11905 );
11906 }
11907
11908 // If any of the following highlights intersect with this one, merge them.
11909 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11910 let highlight = &row_highlights[ix];
11911 if next_highlight
11912 .range
11913 .start
11914 .cmp(&highlight.range.end, &snapshot)
11915 .is_le()
11916 {
11917 if next_highlight
11918 .range
11919 .end
11920 .cmp(&highlight.range.end, &snapshot)
11921 .is_gt()
11922 {
11923 row_highlights[ix].range.end = next_highlight.range.end;
11924 }
11925 row_highlights.remove(ix + 1);
11926 } else {
11927 break;
11928 }
11929 }
11930 }
11931 }
11932
11933 /// Remove any highlighted row ranges of the given type that intersect the
11934 /// given ranges.
11935 pub fn remove_highlighted_rows<T: 'static>(
11936 &mut self,
11937 ranges_to_remove: Vec<Range<Anchor>>,
11938 cx: &mut ViewContext<Self>,
11939 ) {
11940 let snapshot = self.buffer().read(cx).snapshot(cx);
11941 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11942 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11943 row_highlights.retain(|highlight| {
11944 while let Some(range_to_remove) = ranges_to_remove.peek() {
11945 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11946 Ordering::Less | Ordering::Equal => {
11947 ranges_to_remove.next();
11948 }
11949 Ordering::Greater => {
11950 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11951 Ordering::Less | Ordering::Equal => {
11952 return false;
11953 }
11954 Ordering::Greater => break,
11955 }
11956 }
11957 }
11958 }
11959
11960 true
11961 })
11962 }
11963
11964 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11965 pub fn clear_row_highlights<T: 'static>(&mut self) {
11966 self.highlighted_rows.remove(&TypeId::of::<T>());
11967 }
11968
11969 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11970 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11971 self.highlighted_rows
11972 .get(&TypeId::of::<T>())
11973 .map_or(&[] as &[_], |vec| vec.as_slice())
11974 .iter()
11975 .map(|highlight| (highlight.range.clone(), highlight.color))
11976 }
11977
11978 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11979 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11980 /// Allows to ignore certain kinds of highlights.
11981 pub fn highlighted_display_rows(
11982 &mut self,
11983 cx: &mut WindowContext,
11984 ) -> BTreeMap<DisplayRow, Hsla> {
11985 let snapshot = self.snapshot(cx);
11986 let mut used_highlight_orders = HashMap::default();
11987 self.highlighted_rows
11988 .iter()
11989 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11990 .fold(
11991 BTreeMap::<DisplayRow, Hsla>::new(),
11992 |mut unique_rows, highlight| {
11993 let start = highlight.range.start.to_display_point(&snapshot);
11994 let end = highlight.range.end.to_display_point(&snapshot);
11995 let start_row = start.row().0;
11996 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11997 && end.column() == 0
11998 {
11999 end.row().0.saturating_sub(1)
12000 } else {
12001 end.row().0
12002 };
12003 for row in start_row..=end_row {
12004 let used_index =
12005 used_highlight_orders.entry(row).or_insert(highlight.index);
12006 if highlight.index >= *used_index {
12007 *used_index = highlight.index;
12008 unique_rows.insert(DisplayRow(row), highlight.color);
12009 }
12010 }
12011 unique_rows
12012 },
12013 )
12014 }
12015
12016 pub fn highlighted_display_row_for_autoscroll(
12017 &self,
12018 snapshot: &DisplaySnapshot,
12019 ) -> Option<DisplayRow> {
12020 self.highlighted_rows
12021 .values()
12022 .flat_map(|highlighted_rows| highlighted_rows.iter())
12023 .filter_map(|highlight| {
12024 if highlight.should_autoscroll {
12025 Some(highlight.range.start.to_display_point(snapshot).row())
12026 } else {
12027 None
12028 }
12029 })
12030 .min()
12031 }
12032
12033 pub fn set_search_within_ranges(
12034 &mut self,
12035 ranges: &[Range<Anchor>],
12036 cx: &mut ViewContext<Self>,
12037 ) {
12038 self.highlight_background::<SearchWithinRange>(
12039 ranges,
12040 |colors| colors.editor_document_highlight_read_background,
12041 cx,
12042 )
12043 }
12044
12045 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12046 self.breadcrumb_header = Some(new_header);
12047 }
12048
12049 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12050 self.clear_background_highlights::<SearchWithinRange>(cx);
12051 }
12052
12053 pub fn highlight_background<T: 'static>(
12054 &mut self,
12055 ranges: &[Range<Anchor>],
12056 color_fetcher: fn(&ThemeColors) -> Hsla,
12057 cx: &mut ViewContext<Self>,
12058 ) {
12059 self.background_highlights
12060 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12061 self.scrollbar_marker_state.dirty = true;
12062 cx.notify();
12063 }
12064
12065 pub fn clear_background_highlights<T: 'static>(
12066 &mut self,
12067 cx: &mut ViewContext<Self>,
12068 ) -> Option<BackgroundHighlight> {
12069 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12070 if !text_highlights.1.is_empty() {
12071 self.scrollbar_marker_state.dirty = true;
12072 cx.notify();
12073 }
12074 Some(text_highlights)
12075 }
12076
12077 pub fn highlight_gutter<T: 'static>(
12078 &mut self,
12079 ranges: &[Range<Anchor>],
12080 color_fetcher: fn(&AppContext) -> Hsla,
12081 cx: &mut ViewContext<Self>,
12082 ) {
12083 self.gutter_highlights
12084 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12085 cx.notify();
12086 }
12087
12088 pub fn clear_gutter_highlights<T: 'static>(
12089 &mut self,
12090 cx: &mut ViewContext<Self>,
12091 ) -> Option<GutterHighlight> {
12092 cx.notify();
12093 self.gutter_highlights.remove(&TypeId::of::<T>())
12094 }
12095
12096 #[cfg(feature = "test-support")]
12097 pub fn all_text_background_highlights(
12098 &mut self,
12099 cx: &mut ViewContext<Self>,
12100 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12101 let snapshot = self.snapshot(cx);
12102 let buffer = &snapshot.buffer_snapshot;
12103 let start = buffer.anchor_before(0);
12104 let end = buffer.anchor_after(buffer.len());
12105 let theme = cx.theme().colors();
12106 self.background_highlights_in_range(start..end, &snapshot, theme)
12107 }
12108
12109 #[cfg(feature = "test-support")]
12110 pub fn search_background_highlights(
12111 &mut self,
12112 cx: &mut ViewContext<Self>,
12113 ) -> Vec<Range<Point>> {
12114 let snapshot = self.buffer().read(cx).snapshot(cx);
12115
12116 let highlights = self
12117 .background_highlights
12118 .get(&TypeId::of::<items::BufferSearchHighlights>());
12119
12120 if let Some((_color, ranges)) = highlights {
12121 ranges
12122 .iter()
12123 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12124 .collect_vec()
12125 } else {
12126 vec![]
12127 }
12128 }
12129
12130 fn document_highlights_for_position<'a>(
12131 &'a self,
12132 position: Anchor,
12133 buffer: &'a MultiBufferSnapshot,
12134 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12135 let read_highlights = self
12136 .background_highlights
12137 .get(&TypeId::of::<DocumentHighlightRead>())
12138 .map(|h| &h.1);
12139 let write_highlights = self
12140 .background_highlights
12141 .get(&TypeId::of::<DocumentHighlightWrite>())
12142 .map(|h| &h.1);
12143 let left_position = position.bias_left(buffer);
12144 let right_position = position.bias_right(buffer);
12145 read_highlights
12146 .into_iter()
12147 .chain(write_highlights)
12148 .flat_map(move |ranges| {
12149 let start_ix = match ranges.binary_search_by(|probe| {
12150 let cmp = probe.end.cmp(&left_position, buffer);
12151 if cmp.is_ge() {
12152 Ordering::Greater
12153 } else {
12154 Ordering::Less
12155 }
12156 }) {
12157 Ok(i) | Err(i) => i,
12158 };
12159
12160 ranges[start_ix..]
12161 .iter()
12162 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12163 })
12164 }
12165
12166 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12167 self.background_highlights
12168 .get(&TypeId::of::<T>())
12169 .map_or(false, |(_, highlights)| !highlights.is_empty())
12170 }
12171
12172 pub fn background_highlights_in_range(
12173 &self,
12174 search_range: Range<Anchor>,
12175 display_snapshot: &DisplaySnapshot,
12176 theme: &ThemeColors,
12177 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12178 let mut results = Vec::new();
12179 for (color_fetcher, ranges) in self.background_highlights.values() {
12180 let color = color_fetcher(theme);
12181 let start_ix = match ranges.binary_search_by(|probe| {
12182 let cmp = probe
12183 .end
12184 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12185 if cmp.is_gt() {
12186 Ordering::Greater
12187 } else {
12188 Ordering::Less
12189 }
12190 }) {
12191 Ok(i) | Err(i) => i,
12192 };
12193 for range in &ranges[start_ix..] {
12194 if range
12195 .start
12196 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12197 .is_ge()
12198 {
12199 break;
12200 }
12201
12202 let start = range.start.to_display_point(display_snapshot);
12203 let end = range.end.to_display_point(display_snapshot);
12204 results.push((start..end, color))
12205 }
12206 }
12207 results
12208 }
12209
12210 pub fn background_highlight_row_ranges<T: 'static>(
12211 &self,
12212 search_range: Range<Anchor>,
12213 display_snapshot: &DisplaySnapshot,
12214 count: usize,
12215 ) -> Vec<RangeInclusive<DisplayPoint>> {
12216 let mut results = Vec::new();
12217 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12218 return vec![];
12219 };
12220
12221 let start_ix = match ranges.binary_search_by(|probe| {
12222 let cmp = probe
12223 .end
12224 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12225 if cmp.is_gt() {
12226 Ordering::Greater
12227 } else {
12228 Ordering::Less
12229 }
12230 }) {
12231 Ok(i) | Err(i) => i,
12232 };
12233 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12234 if let (Some(start_display), Some(end_display)) = (start, end) {
12235 results.push(
12236 start_display.to_display_point(display_snapshot)
12237 ..=end_display.to_display_point(display_snapshot),
12238 );
12239 }
12240 };
12241 let mut start_row: Option<Point> = None;
12242 let mut end_row: Option<Point> = None;
12243 if ranges.len() > count {
12244 return Vec::new();
12245 }
12246 for range in &ranges[start_ix..] {
12247 if range
12248 .start
12249 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12250 .is_ge()
12251 {
12252 break;
12253 }
12254 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12255 if let Some(current_row) = &end_row {
12256 if end.row == current_row.row {
12257 continue;
12258 }
12259 }
12260 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12261 if start_row.is_none() {
12262 assert_eq!(end_row, None);
12263 start_row = Some(start);
12264 end_row = Some(end);
12265 continue;
12266 }
12267 if let Some(current_end) = end_row.as_mut() {
12268 if start.row > current_end.row + 1 {
12269 push_region(start_row, end_row);
12270 start_row = Some(start);
12271 end_row = Some(end);
12272 } else {
12273 // Merge two hunks.
12274 *current_end = end;
12275 }
12276 } else {
12277 unreachable!();
12278 }
12279 }
12280 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12281 push_region(start_row, end_row);
12282 results
12283 }
12284
12285 pub fn gutter_highlights_in_range(
12286 &self,
12287 search_range: Range<Anchor>,
12288 display_snapshot: &DisplaySnapshot,
12289 cx: &AppContext,
12290 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12291 let mut results = Vec::new();
12292 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12293 let color = color_fetcher(cx);
12294 let start_ix = match ranges.binary_search_by(|probe| {
12295 let cmp = probe
12296 .end
12297 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12298 if cmp.is_gt() {
12299 Ordering::Greater
12300 } else {
12301 Ordering::Less
12302 }
12303 }) {
12304 Ok(i) | Err(i) => i,
12305 };
12306 for range in &ranges[start_ix..] {
12307 if range
12308 .start
12309 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12310 .is_ge()
12311 {
12312 break;
12313 }
12314
12315 let start = range.start.to_display_point(display_snapshot);
12316 let end = range.end.to_display_point(display_snapshot);
12317 results.push((start..end, color))
12318 }
12319 }
12320 results
12321 }
12322
12323 /// Get the text ranges corresponding to the redaction query
12324 pub fn redacted_ranges(
12325 &self,
12326 search_range: Range<Anchor>,
12327 display_snapshot: &DisplaySnapshot,
12328 cx: &WindowContext,
12329 ) -> Vec<Range<DisplayPoint>> {
12330 display_snapshot
12331 .buffer_snapshot
12332 .redacted_ranges(search_range, |file| {
12333 if let Some(file) = file {
12334 file.is_private()
12335 && EditorSettings::get(
12336 Some(SettingsLocation {
12337 worktree_id: file.worktree_id(cx),
12338 path: file.path().as_ref(),
12339 }),
12340 cx,
12341 )
12342 .redact_private_values
12343 } else {
12344 false
12345 }
12346 })
12347 .map(|range| {
12348 range.start.to_display_point(display_snapshot)
12349 ..range.end.to_display_point(display_snapshot)
12350 })
12351 .collect()
12352 }
12353
12354 pub fn highlight_text<T: 'static>(
12355 &mut self,
12356 ranges: Vec<Range<Anchor>>,
12357 style: HighlightStyle,
12358 cx: &mut ViewContext<Self>,
12359 ) {
12360 self.display_map.update(cx, |map, _| {
12361 map.highlight_text(TypeId::of::<T>(), ranges, style)
12362 });
12363 cx.notify();
12364 }
12365
12366 pub(crate) fn highlight_inlays<T: 'static>(
12367 &mut self,
12368 highlights: Vec<InlayHighlight>,
12369 style: HighlightStyle,
12370 cx: &mut ViewContext<Self>,
12371 ) {
12372 self.display_map.update(cx, |map, _| {
12373 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12374 });
12375 cx.notify();
12376 }
12377
12378 pub fn text_highlights<'a, T: 'static>(
12379 &'a self,
12380 cx: &'a AppContext,
12381 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12382 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12383 }
12384
12385 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12386 let cleared = self
12387 .display_map
12388 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12389 if cleared {
12390 cx.notify();
12391 }
12392 }
12393
12394 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12395 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12396 && self.focus_handle.is_focused(cx)
12397 }
12398
12399 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12400 self.show_cursor_when_unfocused = is_enabled;
12401 cx.notify();
12402 }
12403
12404 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12405 self.project
12406 .as_ref()
12407 .map(|project| project.read(cx).lsp_store())
12408 }
12409
12410 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12411 cx.notify();
12412 }
12413
12414 fn on_buffer_event(
12415 &mut self,
12416 multibuffer: Model<MultiBuffer>,
12417 event: &multi_buffer::Event,
12418 cx: &mut ViewContext<Self>,
12419 ) {
12420 match event {
12421 multi_buffer::Event::Edited {
12422 singleton_buffer_edited,
12423 edited_buffer: buffer_edited,
12424 } => {
12425 self.scrollbar_marker_state.dirty = true;
12426 self.active_indent_guides_state.dirty = true;
12427 self.refresh_active_diagnostics(cx);
12428 self.refresh_code_actions(cx);
12429 if self.has_active_inline_completion() {
12430 self.update_visible_inline_completion(cx);
12431 }
12432 if let Some(buffer) = buffer_edited {
12433 let buffer_id = buffer.read(cx).remote_id();
12434 if !self.registered_buffers.contains_key(&buffer_id) {
12435 if let Some(lsp_store) = self.lsp_store(cx) {
12436 lsp_store.update(cx, |lsp_store, cx| {
12437 self.registered_buffers.insert(
12438 buffer_id,
12439 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12440 );
12441 })
12442 }
12443 }
12444 }
12445 cx.emit(EditorEvent::BufferEdited);
12446 cx.emit(SearchEvent::MatchesInvalidated);
12447 if *singleton_buffer_edited {
12448 if let Some(project) = &self.project {
12449 let project = project.read(cx);
12450 #[allow(clippy::mutable_key_type)]
12451 let languages_affected = multibuffer
12452 .read(cx)
12453 .all_buffers()
12454 .into_iter()
12455 .filter_map(|buffer| {
12456 let buffer = buffer.read(cx);
12457 let language = buffer.language()?;
12458 if project.is_local()
12459 && project
12460 .language_servers_for_local_buffer(buffer, cx)
12461 .count()
12462 == 0
12463 {
12464 None
12465 } else {
12466 Some(language)
12467 }
12468 })
12469 .cloned()
12470 .collect::<HashSet<_>>();
12471 if !languages_affected.is_empty() {
12472 self.refresh_inlay_hints(
12473 InlayHintRefreshReason::BufferEdited(languages_affected),
12474 cx,
12475 );
12476 }
12477 }
12478 }
12479
12480 let Some(project) = &self.project else { return };
12481 let (telemetry, is_via_ssh) = {
12482 let project = project.read(cx);
12483 let telemetry = project.client().telemetry().clone();
12484 let is_via_ssh = project.is_via_ssh();
12485 (telemetry, is_via_ssh)
12486 };
12487 refresh_linked_ranges(self, cx);
12488 telemetry.log_edit_event("editor", is_via_ssh);
12489 }
12490 multi_buffer::Event::ExcerptsAdded {
12491 buffer,
12492 predecessor,
12493 excerpts,
12494 } => {
12495 self.tasks_update_task = Some(self.refresh_runnables(cx));
12496 let buffer_id = buffer.read(cx).remote_id();
12497 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12498 if let Some(project) = &self.project {
12499 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12500 }
12501 }
12502 cx.emit(EditorEvent::ExcerptsAdded {
12503 buffer: buffer.clone(),
12504 predecessor: *predecessor,
12505 excerpts: excerpts.clone(),
12506 });
12507 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12508 }
12509 multi_buffer::Event::ExcerptsRemoved { ids } => {
12510 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12511 let buffer = self.buffer.read(cx);
12512 self.registered_buffers
12513 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12514 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12515 }
12516 multi_buffer::Event::ExcerptsEdited { ids } => {
12517 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12518 }
12519 multi_buffer::Event::ExcerptsExpanded { ids } => {
12520 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12521 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12522 }
12523 multi_buffer::Event::Reparsed(buffer_id) => {
12524 self.tasks_update_task = Some(self.refresh_runnables(cx));
12525
12526 cx.emit(EditorEvent::Reparsed(*buffer_id));
12527 }
12528 multi_buffer::Event::LanguageChanged(buffer_id) => {
12529 linked_editing_ranges::refresh_linked_ranges(self, cx);
12530 cx.emit(EditorEvent::Reparsed(*buffer_id));
12531 cx.notify();
12532 }
12533 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12534 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12535 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12536 cx.emit(EditorEvent::TitleChanged)
12537 }
12538 // multi_buffer::Event::DiffBaseChanged => {
12539 // self.scrollbar_marker_state.dirty = true;
12540 // cx.emit(EditorEvent::DiffBaseChanged);
12541 // cx.notify();
12542 // }
12543 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12544 multi_buffer::Event::DiagnosticsUpdated => {
12545 self.refresh_active_diagnostics(cx);
12546 self.scrollbar_marker_state.dirty = true;
12547 cx.notify();
12548 }
12549 _ => {}
12550 };
12551 }
12552
12553 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12554 cx.notify();
12555 }
12556
12557 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12558 self.tasks_update_task = Some(self.refresh_runnables(cx));
12559 self.refresh_inline_completion(true, false, cx);
12560 self.refresh_inlay_hints(
12561 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12562 self.selections.newest_anchor().head(),
12563 &self.buffer.read(cx).snapshot(cx),
12564 cx,
12565 )),
12566 cx,
12567 );
12568
12569 let old_cursor_shape = self.cursor_shape;
12570
12571 {
12572 let editor_settings = EditorSettings::get_global(cx);
12573 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12574 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12575 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12576 }
12577
12578 if old_cursor_shape != self.cursor_shape {
12579 cx.emit(EditorEvent::CursorShapeChanged);
12580 }
12581
12582 let project_settings = ProjectSettings::get_global(cx);
12583 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12584
12585 if self.mode == EditorMode::Full {
12586 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12587 if self.git_blame_inline_enabled != inline_blame_enabled {
12588 self.toggle_git_blame_inline_internal(false, cx);
12589 }
12590 }
12591
12592 cx.notify();
12593 }
12594
12595 pub fn set_searchable(&mut self, searchable: bool) {
12596 self.searchable = searchable;
12597 }
12598
12599 pub fn searchable(&self) -> bool {
12600 self.searchable
12601 }
12602
12603 fn open_proposed_changes_editor(
12604 &mut self,
12605 _: &OpenProposedChangesEditor,
12606 cx: &mut ViewContext<Self>,
12607 ) {
12608 let Some(workspace) = self.workspace() else {
12609 cx.propagate();
12610 return;
12611 };
12612
12613 let selections = self.selections.all::<usize>(cx);
12614 let multi_buffer = self.buffer.read(cx);
12615 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12616 let mut new_selections_by_buffer = HashMap::default();
12617 for selection in selections {
12618 for (excerpt, range) in
12619 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12620 {
12621 let mut range = range.to_point(excerpt.buffer());
12622 range.start.column = 0;
12623 range.end.column = excerpt.buffer().line_len(range.end.row);
12624 new_selections_by_buffer
12625 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12626 .or_insert(Vec::new())
12627 .push(range)
12628 }
12629 }
12630
12631 let proposed_changes_buffers = new_selections_by_buffer
12632 .into_iter()
12633 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12634 .collect::<Vec<_>>();
12635 let proposed_changes_editor = cx.new_view(|cx| {
12636 ProposedChangesEditor::new(
12637 "Proposed changes",
12638 proposed_changes_buffers,
12639 self.project.clone(),
12640 cx,
12641 )
12642 });
12643
12644 cx.window_context().defer(move |cx| {
12645 workspace.update(cx, |workspace, cx| {
12646 workspace.active_pane().update(cx, |pane, cx| {
12647 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12648 });
12649 });
12650 });
12651 }
12652
12653 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12654 self.open_excerpts_common(None, true, cx)
12655 }
12656
12657 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12658 self.open_excerpts_common(None, false, cx)
12659 }
12660
12661 fn open_excerpts_common(
12662 &mut self,
12663 jump_data: Option<JumpData>,
12664 split: bool,
12665 cx: &mut ViewContext<Self>,
12666 ) {
12667 let Some(workspace) = self.workspace() else {
12668 cx.propagate();
12669 return;
12670 };
12671
12672 if self.buffer.read(cx).is_singleton() {
12673 cx.propagate();
12674 return;
12675 }
12676
12677 let mut new_selections_by_buffer = HashMap::default();
12678 match &jump_data {
12679 Some(JumpData::MultiBufferPoint {
12680 excerpt_id,
12681 position,
12682 anchor,
12683 line_offset_from_top,
12684 }) => {
12685 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12686 if let Some(buffer) = multi_buffer_snapshot
12687 .buffer_id_for_excerpt(*excerpt_id)
12688 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12689 {
12690 let buffer_snapshot = buffer.read(cx).snapshot();
12691 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12692 language::ToPoint::to_point(anchor, &buffer_snapshot)
12693 } else {
12694 buffer_snapshot.clip_point(*position, Bias::Left)
12695 };
12696 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12697 new_selections_by_buffer.insert(
12698 buffer,
12699 (
12700 vec![jump_to_offset..jump_to_offset],
12701 Some(*line_offset_from_top),
12702 ),
12703 );
12704 }
12705 }
12706 Some(JumpData::MultiBufferRow {
12707 row,
12708 line_offset_from_top,
12709 }) => {
12710 let point = MultiBufferPoint::new(row.0, 0);
12711 if let Some((buffer, buffer_point, _)) =
12712 self.buffer.read(cx).point_to_buffer_point(point, cx)
12713 {
12714 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12715 new_selections_by_buffer
12716 .entry(buffer)
12717 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12718 .0
12719 .push(buffer_offset..buffer_offset)
12720 }
12721 }
12722 None => {
12723 let selections = self.selections.all::<usize>(cx);
12724 let multi_buffer = self.buffer.read(cx);
12725 for selection in selections {
12726 for (excerpt, mut range) in multi_buffer
12727 .snapshot(cx)
12728 .range_to_buffer_ranges(selection.range())
12729 {
12730 // When editing branch buffers, jump to the corresponding location
12731 // in their base buffer.
12732 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12733 let buffer = buffer_handle.read(cx);
12734 if let Some(base_buffer) = buffer.base_buffer() {
12735 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12736 buffer_handle = base_buffer;
12737 }
12738
12739 if selection.reversed {
12740 mem::swap(&mut range.start, &mut range.end);
12741 }
12742 new_selections_by_buffer
12743 .entry(buffer_handle)
12744 .or_insert((Vec::new(), None))
12745 .0
12746 .push(range)
12747 }
12748 }
12749 }
12750 }
12751
12752 if new_selections_by_buffer.is_empty() {
12753 return;
12754 }
12755
12756 // We defer the pane interaction because we ourselves are a workspace item
12757 // and activating a new item causes the pane to call a method on us reentrantly,
12758 // which panics if we're on the stack.
12759 cx.window_context().defer(move |cx| {
12760 workspace.update(cx, |workspace, cx| {
12761 let pane = if split {
12762 workspace.adjacent_pane(cx)
12763 } else {
12764 workspace.active_pane().clone()
12765 };
12766
12767 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12768 let editor = buffer
12769 .read(cx)
12770 .file()
12771 .is_none()
12772 .then(|| {
12773 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12774 // so `workspace.open_project_item` will never find them, always opening a new editor.
12775 // Instead, we try to activate the existing editor in the pane first.
12776 let (editor, pane_item_index) =
12777 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12778 let editor = item.downcast::<Editor>()?;
12779 let singleton_buffer =
12780 editor.read(cx).buffer().read(cx).as_singleton()?;
12781 if singleton_buffer == buffer {
12782 Some((editor, i))
12783 } else {
12784 None
12785 }
12786 })?;
12787 pane.update(cx, |pane, cx| {
12788 pane.activate_item(pane_item_index, true, true, cx)
12789 });
12790 Some(editor)
12791 })
12792 .flatten()
12793 .unwrap_or_else(|| {
12794 workspace.open_project_item::<Self>(
12795 pane.clone(),
12796 buffer,
12797 true,
12798 true,
12799 cx,
12800 )
12801 });
12802
12803 editor.update(cx, |editor, cx| {
12804 let autoscroll = match scroll_offset {
12805 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12806 None => Autoscroll::newest(),
12807 };
12808 let nav_history = editor.nav_history.take();
12809 editor.change_selections(Some(autoscroll), cx, |s| {
12810 s.select_ranges(ranges);
12811 });
12812 editor.nav_history = nav_history;
12813 });
12814 }
12815 })
12816 });
12817 }
12818
12819 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12820 let snapshot = self.buffer.read(cx).read(cx);
12821 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12822 Some(
12823 ranges
12824 .iter()
12825 .map(move |range| {
12826 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12827 })
12828 .collect(),
12829 )
12830 }
12831
12832 fn selection_replacement_ranges(
12833 &self,
12834 range: Range<OffsetUtf16>,
12835 cx: &mut AppContext,
12836 ) -> Vec<Range<OffsetUtf16>> {
12837 let selections = self.selections.all::<OffsetUtf16>(cx);
12838 let newest_selection = selections
12839 .iter()
12840 .max_by_key(|selection| selection.id)
12841 .unwrap();
12842 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12843 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12844 let snapshot = self.buffer.read(cx).read(cx);
12845 selections
12846 .into_iter()
12847 .map(|mut selection| {
12848 selection.start.0 =
12849 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12850 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12851 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12852 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12853 })
12854 .collect()
12855 }
12856
12857 fn report_editor_event(
12858 &self,
12859 event_type: &'static str,
12860 file_extension: Option<String>,
12861 cx: &AppContext,
12862 ) {
12863 if cfg!(any(test, feature = "test-support")) {
12864 return;
12865 }
12866
12867 let Some(project) = &self.project else { return };
12868
12869 // If None, we are in a file without an extension
12870 let file = self
12871 .buffer
12872 .read(cx)
12873 .as_singleton()
12874 .and_then(|b| b.read(cx).file());
12875 let file_extension = file_extension.or(file
12876 .as_ref()
12877 .and_then(|file| Path::new(file.file_name(cx)).extension())
12878 .and_then(|e| e.to_str())
12879 .map(|a| a.to_string()));
12880
12881 let vim_mode = cx
12882 .global::<SettingsStore>()
12883 .raw_user_settings()
12884 .get("vim_mode")
12885 == Some(&serde_json::Value::Bool(true));
12886
12887 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12888 == language::language_settings::InlineCompletionProvider::Copilot;
12889 let copilot_enabled_for_language = self
12890 .buffer
12891 .read(cx)
12892 .settings_at(0, cx)
12893 .show_inline_completions;
12894
12895 let project = project.read(cx);
12896 telemetry::event!(
12897 event_type,
12898 file_extension,
12899 vim_mode,
12900 copilot_enabled,
12901 copilot_enabled_for_language,
12902 is_via_ssh = project.is_via_ssh(),
12903 );
12904 }
12905
12906 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12907 /// with each line being an array of {text, highlight} objects.
12908 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12909 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12910 return;
12911 };
12912
12913 #[derive(Serialize)]
12914 struct Chunk<'a> {
12915 text: String,
12916 highlight: Option<&'a str>,
12917 }
12918
12919 let snapshot = buffer.read(cx).snapshot();
12920 let range = self
12921 .selected_text_range(false, cx)
12922 .and_then(|selection| {
12923 if selection.range.is_empty() {
12924 None
12925 } else {
12926 Some(selection.range)
12927 }
12928 })
12929 .unwrap_or_else(|| 0..snapshot.len());
12930
12931 let chunks = snapshot.chunks(range, true);
12932 let mut lines = Vec::new();
12933 let mut line: VecDeque<Chunk> = VecDeque::new();
12934
12935 let Some(style) = self.style.as_ref() else {
12936 return;
12937 };
12938
12939 for chunk in chunks {
12940 let highlight = chunk
12941 .syntax_highlight_id
12942 .and_then(|id| id.name(&style.syntax));
12943 let mut chunk_lines = chunk.text.split('\n').peekable();
12944 while let Some(text) = chunk_lines.next() {
12945 let mut merged_with_last_token = false;
12946 if let Some(last_token) = line.back_mut() {
12947 if last_token.highlight == highlight {
12948 last_token.text.push_str(text);
12949 merged_with_last_token = true;
12950 }
12951 }
12952
12953 if !merged_with_last_token {
12954 line.push_back(Chunk {
12955 text: text.into(),
12956 highlight,
12957 });
12958 }
12959
12960 if chunk_lines.peek().is_some() {
12961 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12962 line.pop_front();
12963 }
12964 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12965 line.pop_back();
12966 }
12967
12968 lines.push(mem::take(&mut line));
12969 }
12970 }
12971 }
12972
12973 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12974 return;
12975 };
12976 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12977 }
12978
12979 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12980 self.request_autoscroll(Autoscroll::newest(), cx);
12981 let position = self.selections.newest_display(cx).start;
12982 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12983 }
12984
12985 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12986 &self.inlay_hint_cache
12987 }
12988
12989 pub fn replay_insert_event(
12990 &mut self,
12991 text: &str,
12992 relative_utf16_range: Option<Range<isize>>,
12993 cx: &mut ViewContext<Self>,
12994 ) {
12995 if !self.input_enabled {
12996 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12997 return;
12998 }
12999 if let Some(relative_utf16_range) = relative_utf16_range {
13000 let selections = self.selections.all::<OffsetUtf16>(cx);
13001 self.change_selections(None, cx, |s| {
13002 let new_ranges = selections.into_iter().map(|range| {
13003 let start = OffsetUtf16(
13004 range
13005 .head()
13006 .0
13007 .saturating_add_signed(relative_utf16_range.start),
13008 );
13009 let end = OffsetUtf16(
13010 range
13011 .head()
13012 .0
13013 .saturating_add_signed(relative_utf16_range.end),
13014 );
13015 start..end
13016 });
13017 s.select_ranges(new_ranges);
13018 });
13019 }
13020
13021 self.handle_input(text, cx);
13022 }
13023
13024 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13025 let Some(provider) = self.semantics_provider.as_ref() else {
13026 return false;
13027 };
13028
13029 let mut supports = false;
13030 self.buffer().read(cx).for_each_buffer(|buffer| {
13031 supports |= provider.supports_inlay_hints(buffer, cx);
13032 });
13033 supports
13034 }
13035
13036 pub fn focus(&self, cx: &mut WindowContext) {
13037 cx.focus(&self.focus_handle)
13038 }
13039
13040 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13041 self.focus_handle.is_focused(cx)
13042 }
13043
13044 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13045 cx.emit(EditorEvent::Focused);
13046
13047 if let Some(descendant) = self
13048 .last_focused_descendant
13049 .take()
13050 .and_then(|descendant| descendant.upgrade())
13051 {
13052 cx.focus(&descendant);
13053 } else {
13054 if let Some(blame) = self.blame.as_ref() {
13055 blame.update(cx, GitBlame::focus)
13056 }
13057
13058 self.blink_manager.update(cx, BlinkManager::enable);
13059 self.show_cursor_names(cx);
13060 self.buffer.update(cx, |buffer, cx| {
13061 buffer.finalize_last_transaction(cx);
13062 if self.leader_peer_id.is_none() {
13063 buffer.set_active_selections(
13064 &self.selections.disjoint_anchors(),
13065 self.selections.line_mode,
13066 self.cursor_shape,
13067 cx,
13068 );
13069 }
13070 });
13071 }
13072 }
13073
13074 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13075 cx.emit(EditorEvent::FocusedIn)
13076 }
13077
13078 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13079 if event.blurred != self.focus_handle {
13080 self.last_focused_descendant = Some(event.blurred);
13081 }
13082 }
13083
13084 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13085 self.blink_manager.update(cx, BlinkManager::disable);
13086 self.buffer
13087 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13088
13089 if let Some(blame) = self.blame.as_ref() {
13090 blame.update(cx, GitBlame::blur)
13091 }
13092 if !self.hover_state.focused(cx) {
13093 hide_hover(self, cx);
13094 }
13095
13096 self.hide_context_menu(cx);
13097 cx.emit(EditorEvent::Blurred);
13098 cx.notify();
13099 }
13100
13101 pub fn register_action<A: Action>(
13102 &mut self,
13103 listener: impl Fn(&A, &mut WindowContext) + 'static,
13104 ) -> Subscription {
13105 let id = self.next_editor_action_id.post_inc();
13106 let listener = Arc::new(listener);
13107 self.editor_actions.borrow_mut().insert(
13108 id,
13109 Box::new(move |cx| {
13110 let cx = cx.window_context();
13111 let listener = listener.clone();
13112 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13113 let action = action.downcast_ref().unwrap();
13114 if phase == DispatchPhase::Bubble {
13115 listener(action, cx)
13116 }
13117 })
13118 }),
13119 );
13120
13121 let editor_actions = self.editor_actions.clone();
13122 Subscription::new(move || {
13123 editor_actions.borrow_mut().remove(&id);
13124 })
13125 }
13126
13127 pub fn file_header_size(&self) -> u32 {
13128 FILE_HEADER_HEIGHT
13129 }
13130
13131 pub fn revert(
13132 &mut self,
13133 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13134 cx: &mut ViewContext<Self>,
13135 ) {
13136 self.buffer().update(cx, |multi_buffer, cx| {
13137 for (buffer_id, changes) in revert_changes {
13138 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13139 buffer.update(cx, |buffer, cx| {
13140 buffer.edit(
13141 changes.into_iter().map(|(range, text)| {
13142 (range, text.to_string().map(Arc::<str>::from))
13143 }),
13144 None,
13145 cx,
13146 );
13147 });
13148 }
13149 }
13150 });
13151 self.change_selections(None, cx, |selections| selections.refresh());
13152 }
13153
13154 pub fn to_pixel_point(
13155 &mut self,
13156 source: multi_buffer::Anchor,
13157 editor_snapshot: &EditorSnapshot,
13158 cx: &mut ViewContext<Self>,
13159 ) -> Option<gpui::Point<Pixels>> {
13160 let source_point = source.to_display_point(editor_snapshot);
13161 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13162 }
13163
13164 pub fn display_to_pixel_point(
13165 &self,
13166 source: DisplayPoint,
13167 editor_snapshot: &EditorSnapshot,
13168 cx: &WindowContext,
13169 ) -> Option<gpui::Point<Pixels>> {
13170 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13171 let text_layout_details = self.text_layout_details(cx);
13172 let scroll_top = text_layout_details
13173 .scroll_anchor
13174 .scroll_position(editor_snapshot)
13175 .y;
13176
13177 if source.row().as_f32() < scroll_top.floor() {
13178 return None;
13179 }
13180 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13181 let source_y = line_height * (source.row().as_f32() - scroll_top);
13182 Some(gpui::Point::new(source_x, source_y))
13183 }
13184
13185 pub fn has_active_completions_menu(&self) -> bool {
13186 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13187 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13188 })
13189 }
13190
13191 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13192 self.addons
13193 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13194 }
13195
13196 pub fn unregister_addon<T: Addon>(&mut self) {
13197 self.addons.remove(&std::any::TypeId::of::<T>());
13198 }
13199
13200 pub fn addon<T: Addon>(&self) -> Option<&T> {
13201 let type_id = std::any::TypeId::of::<T>();
13202 self.addons
13203 .get(&type_id)
13204 .and_then(|item| item.to_any().downcast_ref::<T>())
13205 }
13206
13207 pub fn add_change_set(
13208 &mut self,
13209 change_set: Model<BufferChangeSet>,
13210 cx: &mut ViewContext<Self>,
13211 ) {
13212 self.diff_map.add_change_set(change_set, cx);
13213 }
13214
13215 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13216 let text_layout_details = self.text_layout_details(cx);
13217 let style = &text_layout_details.editor_style;
13218 let font_id = cx.text_system().resolve_font(&style.text.font());
13219 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13220 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13221
13222 let em_width = cx
13223 .text_system()
13224 .typographic_bounds(font_id, font_size, 'm')
13225 .unwrap()
13226 .size
13227 .width;
13228
13229 gpui::Point::new(em_width, line_height)
13230 }
13231}
13232
13233fn get_unstaged_changes_for_buffers(
13234 project: &Model<Project>,
13235 buffers: impl IntoIterator<Item = Model<Buffer>>,
13236 cx: &mut ViewContext<Editor>,
13237) {
13238 let mut tasks = Vec::new();
13239 project.update(cx, |project, cx| {
13240 for buffer in buffers {
13241 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13242 }
13243 });
13244 cx.spawn(|this, mut cx| async move {
13245 let change_sets = futures::future::join_all(tasks).await;
13246 this.update(&mut cx, |this, cx| {
13247 for change_set in change_sets {
13248 if let Some(change_set) = change_set.log_err() {
13249 this.diff_map.add_change_set(change_set, cx);
13250 }
13251 }
13252 })
13253 .ok();
13254 })
13255 .detach();
13256}
13257
13258fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13259 let tab_size = tab_size.get() as usize;
13260 let mut width = offset;
13261
13262 for ch in text.chars() {
13263 width += if ch == '\t' {
13264 tab_size - (width % tab_size)
13265 } else {
13266 1
13267 };
13268 }
13269
13270 width - offset
13271}
13272
13273#[cfg(test)]
13274mod tests {
13275 use super::*;
13276
13277 #[test]
13278 fn test_string_size_with_expanded_tabs() {
13279 let nz = |val| NonZeroU32::new(val).unwrap();
13280 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13281 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13282 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13283 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13284 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13285 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13286 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13287 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13288 }
13289}
13290
13291/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13292struct WordBreakingTokenizer<'a> {
13293 input: &'a str,
13294}
13295
13296impl<'a> WordBreakingTokenizer<'a> {
13297 fn new(input: &'a str) -> Self {
13298 Self { input }
13299 }
13300}
13301
13302fn is_char_ideographic(ch: char) -> bool {
13303 use unicode_script::Script::*;
13304 use unicode_script::UnicodeScript;
13305 matches!(ch.script(), Han | Tangut | Yi)
13306}
13307
13308fn is_grapheme_ideographic(text: &str) -> bool {
13309 text.chars().any(is_char_ideographic)
13310}
13311
13312fn is_grapheme_whitespace(text: &str) -> bool {
13313 text.chars().any(|x| x.is_whitespace())
13314}
13315
13316fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13317 text.chars().next().map_or(false, |ch| {
13318 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13319 })
13320}
13321
13322#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13323struct WordBreakToken<'a> {
13324 token: &'a str,
13325 grapheme_len: usize,
13326 is_whitespace: bool,
13327}
13328
13329impl<'a> Iterator for WordBreakingTokenizer<'a> {
13330 /// Yields a span, the count of graphemes in the token, and whether it was
13331 /// whitespace. Note that it also breaks at word boundaries.
13332 type Item = WordBreakToken<'a>;
13333
13334 fn next(&mut self) -> Option<Self::Item> {
13335 use unicode_segmentation::UnicodeSegmentation;
13336 if self.input.is_empty() {
13337 return None;
13338 }
13339
13340 let mut iter = self.input.graphemes(true).peekable();
13341 let mut offset = 0;
13342 let mut graphemes = 0;
13343 if let Some(first_grapheme) = iter.next() {
13344 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13345 offset += first_grapheme.len();
13346 graphemes += 1;
13347 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13348 if let Some(grapheme) = iter.peek().copied() {
13349 if should_stay_with_preceding_ideograph(grapheme) {
13350 offset += grapheme.len();
13351 graphemes += 1;
13352 }
13353 }
13354 } else {
13355 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13356 let mut next_word_bound = words.peek().copied();
13357 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13358 next_word_bound = words.next();
13359 }
13360 while let Some(grapheme) = iter.peek().copied() {
13361 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13362 break;
13363 };
13364 if is_grapheme_whitespace(grapheme) != is_whitespace {
13365 break;
13366 };
13367 offset += grapheme.len();
13368 graphemes += 1;
13369 iter.next();
13370 }
13371 }
13372 let token = &self.input[..offset];
13373 self.input = &self.input[offset..];
13374 if is_whitespace {
13375 Some(WordBreakToken {
13376 token: " ",
13377 grapheme_len: 1,
13378 is_whitespace: true,
13379 })
13380 } else {
13381 Some(WordBreakToken {
13382 token,
13383 grapheme_len: graphemes,
13384 is_whitespace: false,
13385 })
13386 }
13387 } else {
13388 None
13389 }
13390 }
13391}
13392
13393#[test]
13394fn test_word_breaking_tokenizer() {
13395 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13396 ("", &[]),
13397 (" ", &[(" ", 1, true)]),
13398 ("Ʒ", &[("Ʒ", 1, false)]),
13399 ("Ǽ", &[("Ǽ", 1, false)]),
13400 ("⋑", &[("⋑", 1, false)]),
13401 ("⋑⋑", &[("⋑⋑", 2, false)]),
13402 (
13403 "原理,进而",
13404 &[
13405 ("原", 1, false),
13406 ("理,", 2, false),
13407 ("进", 1, false),
13408 ("而", 1, false),
13409 ],
13410 ),
13411 (
13412 "hello world",
13413 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13414 ),
13415 (
13416 "hello, world",
13417 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13418 ),
13419 (
13420 " hello world",
13421 &[
13422 (" ", 1, true),
13423 ("hello", 5, false),
13424 (" ", 1, true),
13425 ("world", 5, false),
13426 ],
13427 ),
13428 (
13429 "这是什么 \n 钢笔",
13430 &[
13431 ("这", 1, false),
13432 ("是", 1, false),
13433 ("什", 1, false),
13434 ("么", 1, false),
13435 (" ", 1, true),
13436 ("钢", 1, false),
13437 ("笔", 1, false),
13438 ],
13439 ),
13440 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13441 ];
13442
13443 for (input, result) in tests {
13444 assert_eq!(
13445 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13446 result
13447 .iter()
13448 .copied()
13449 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13450 token,
13451 grapheme_len,
13452 is_whitespace,
13453 })
13454 .collect::<Vec<_>>()
13455 );
13456 }
13457}
13458
13459fn wrap_with_prefix(
13460 line_prefix: String,
13461 unwrapped_text: String,
13462 wrap_column: usize,
13463 tab_size: NonZeroU32,
13464) -> String {
13465 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13466 let mut wrapped_text = String::new();
13467 let mut current_line = line_prefix.clone();
13468
13469 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13470 let mut current_line_len = line_prefix_len;
13471 for WordBreakToken {
13472 token,
13473 grapheme_len,
13474 is_whitespace,
13475 } in tokenizer
13476 {
13477 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13478 wrapped_text.push_str(current_line.trim_end());
13479 wrapped_text.push('\n');
13480 current_line.truncate(line_prefix.len());
13481 current_line_len = line_prefix_len;
13482 if !is_whitespace {
13483 current_line.push_str(token);
13484 current_line_len += grapheme_len;
13485 }
13486 } else if !is_whitespace {
13487 current_line.push_str(token);
13488 current_line_len += grapheme_len;
13489 } else if current_line_len != line_prefix_len {
13490 current_line.push(' ');
13491 current_line_len += 1;
13492 }
13493 }
13494
13495 if !current_line.is_empty() {
13496 wrapped_text.push_str(¤t_line);
13497 }
13498 wrapped_text
13499}
13500
13501#[test]
13502fn test_wrap_with_prefix() {
13503 assert_eq!(
13504 wrap_with_prefix(
13505 "# ".to_string(),
13506 "abcdefg".to_string(),
13507 4,
13508 NonZeroU32::new(4).unwrap()
13509 ),
13510 "# abcdefg"
13511 );
13512 assert_eq!(
13513 wrap_with_prefix(
13514 "".to_string(),
13515 "\thello world".to_string(),
13516 8,
13517 NonZeroU32::new(4).unwrap()
13518 ),
13519 "hello\nworld"
13520 );
13521 assert_eq!(
13522 wrap_with_prefix(
13523 "// ".to_string(),
13524 "xx \nyy zz aa bb cc".to_string(),
13525 12,
13526 NonZeroU32::new(4).unwrap()
13527 ),
13528 "// xx yy zz\n// aa bb cc"
13529 );
13530 assert_eq!(
13531 wrap_with_prefix(
13532 String::new(),
13533 "这是什么 \n 钢笔".to_string(),
13534 3,
13535 NonZeroU32::new(4).unwrap()
13536 ),
13537 "这是什\n么 钢\n笔"
13538 );
13539}
13540
13541fn hunks_for_selections(
13542 snapshot: &EditorSnapshot,
13543 selections: &[Selection<Point>],
13544) -> Vec<MultiBufferDiffHunk> {
13545 hunks_for_ranges(
13546 selections.iter().map(|selection| selection.range()),
13547 snapshot,
13548 )
13549}
13550
13551pub fn hunks_for_ranges(
13552 ranges: impl Iterator<Item = Range<Point>>,
13553 snapshot: &EditorSnapshot,
13554) -> Vec<MultiBufferDiffHunk> {
13555 let mut hunks = Vec::new();
13556 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13557 HashMap::default();
13558 for query_range in ranges {
13559 let query_rows =
13560 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13561 for hunk in snapshot.diff_map.diff_hunks_in_range(
13562 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13563 &snapshot.buffer_snapshot,
13564 ) {
13565 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13566 // when the caret is just above or just below the deleted hunk.
13567 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13568 let related_to_selection = if allow_adjacent {
13569 hunk.row_range.overlaps(&query_rows)
13570 || hunk.row_range.start == query_rows.end
13571 || hunk.row_range.end == query_rows.start
13572 } else {
13573 hunk.row_range.overlaps(&query_rows)
13574 };
13575 if related_to_selection {
13576 if !processed_buffer_rows
13577 .entry(hunk.buffer_id)
13578 .or_default()
13579 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13580 {
13581 continue;
13582 }
13583 hunks.push(hunk);
13584 }
13585 }
13586 }
13587
13588 hunks
13589}
13590
13591pub trait CollaborationHub {
13592 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13593 fn user_participant_indices<'a>(
13594 &self,
13595 cx: &'a AppContext,
13596 ) -> &'a HashMap<u64, ParticipantIndex>;
13597 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13598}
13599
13600impl CollaborationHub for Model<Project> {
13601 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13602 self.read(cx).collaborators()
13603 }
13604
13605 fn user_participant_indices<'a>(
13606 &self,
13607 cx: &'a AppContext,
13608 ) -> &'a HashMap<u64, ParticipantIndex> {
13609 self.read(cx).user_store().read(cx).participant_indices()
13610 }
13611
13612 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13613 let this = self.read(cx);
13614 let user_ids = this.collaborators().values().map(|c| c.user_id);
13615 this.user_store().read_with(cx, |user_store, cx| {
13616 user_store.participant_names(user_ids, cx)
13617 })
13618 }
13619}
13620
13621pub trait SemanticsProvider {
13622 fn hover(
13623 &self,
13624 buffer: &Model<Buffer>,
13625 position: text::Anchor,
13626 cx: &mut AppContext,
13627 ) -> Option<Task<Vec<project::Hover>>>;
13628
13629 fn inlay_hints(
13630 &self,
13631 buffer_handle: Model<Buffer>,
13632 range: Range<text::Anchor>,
13633 cx: &mut AppContext,
13634 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13635
13636 fn resolve_inlay_hint(
13637 &self,
13638 hint: InlayHint,
13639 buffer_handle: Model<Buffer>,
13640 server_id: LanguageServerId,
13641 cx: &mut AppContext,
13642 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13643
13644 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13645
13646 fn document_highlights(
13647 &self,
13648 buffer: &Model<Buffer>,
13649 position: text::Anchor,
13650 cx: &mut AppContext,
13651 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13652
13653 fn definitions(
13654 &self,
13655 buffer: &Model<Buffer>,
13656 position: text::Anchor,
13657 kind: GotoDefinitionKind,
13658 cx: &mut AppContext,
13659 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13660
13661 fn range_for_rename(
13662 &self,
13663 buffer: &Model<Buffer>,
13664 position: text::Anchor,
13665 cx: &mut AppContext,
13666 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13667
13668 fn perform_rename(
13669 &self,
13670 buffer: &Model<Buffer>,
13671 position: text::Anchor,
13672 new_name: String,
13673 cx: &mut AppContext,
13674 ) -> Option<Task<Result<ProjectTransaction>>>;
13675}
13676
13677pub trait CompletionProvider {
13678 fn completions(
13679 &self,
13680 buffer: &Model<Buffer>,
13681 buffer_position: text::Anchor,
13682 trigger: CompletionContext,
13683 cx: &mut ViewContext<Editor>,
13684 ) -> Task<Result<Vec<Completion>>>;
13685
13686 fn resolve_completions(
13687 &self,
13688 buffer: Model<Buffer>,
13689 completion_indices: Vec<usize>,
13690 completions: Rc<RefCell<Box<[Completion]>>>,
13691 cx: &mut ViewContext<Editor>,
13692 ) -> Task<Result<bool>>;
13693
13694 fn apply_additional_edits_for_completion(
13695 &self,
13696 _buffer: Model<Buffer>,
13697 _completions: Rc<RefCell<Box<[Completion]>>>,
13698 _completion_index: usize,
13699 _push_to_history: bool,
13700 _cx: &mut ViewContext<Editor>,
13701 ) -> Task<Result<Option<language::Transaction>>> {
13702 Task::ready(Ok(None))
13703 }
13704
13705 fn is_completion_trigger(
13706 &self,
13707 buffer: &Model<Buffer>,
13708 position: language::Anchor,
13709 text: &str,
13710 trigger_in_words: bool,
13711 cx: &mut ViewContext<Editor>,
13712 ) -> bool;
13713
13714 fn sort_completions(&self) -> bool {
13715 true
13716 }
13717}
13718
13719pub trait CodeActionProvider {
13720 fn id(&self) -> Arc<str>;
13721
13722 fn code_actions(
13723 &self,
13724 buffer: &Model<Buffer>,
13725 range: Range<text::Anchor>,
13726 cx: &mut WindowContext,
13727 ) -> Task<Result<Vec<CodeAction>>>;
13728
13729 fn apply_code_action(
13730 &self,
13731 buffer_handle: Model<Buffer>,
13732 action: CodeAction,
13733 excerpt_id: ExcerptId,
13734 push_to_history: bool,
13735 cx: &mut WindowContext,
13736 ) -> Task<Result<ProjectTransaction>>;
13737}
13738
13739impl CodeActionProvider for Model<Project> {
13740 fn id(&self) -> Arc<str> {
13741 "project".into()
13742 }
13743
13744 fn code_actions(
13745 &self,
13746 buffer: &Model<Buffer>,
13747 range: Range<text::Anchor>,
13748 cx: &mut WindowContext,
13749 ) -> Task<Result<Vec<CodeAction>>> {
13750 self.update(cx, |project, cx| {
13751 project.code_actions(buffer, range, None, cx)
13752 })
13753 }
13754
13755 fn apply_code_action(
13756 &self,
13757 buffer_handle: Model<Buffer>,
13758 action: CodeAction,
13759 _excerpt_id: ExcerptId,
13760 push_to_history: bool,
13761 cx: &mut WindowContext,
13762 ) -> Task<Result<ProjectTransaction>> {
13763 self.update(cx, |project, cx| {
13764 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13765 })
13766 }
13767}
13768
13769fn snippet_completions(
13770 project: &Project,
13771 buffer: &Model<Buffer>,
13772 buffer_position: text::Anchor,
13773 cx: &mut AppContext,
13774) -> Task<Result<Vec<Completion>>> {
13775 let language = buffer.read(cx).language_at(buffer_position);
13776 let language_name = language.as_ref().map(|language| language.lsp_id());
13777 let snippet_store = project.snippets().read(cx);
13778 let snippets = snippet_store.snippets_for(language_name, cx);
13779
13780 if snippets.is_empty() {
13781 return Task::ready(Ok(vec![]));
13782 }
13783 let snapshot = buffer.read(cx).text_snapshot();
13784 let chars: String = snapshot
13785 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13786 .collect();
13787
13788 let scope = language.map(|language| language.default_scope());
13789 let executor = cx.background_executor().clone();
13790
13791 cx.background_executor().spawn(async move {
13792 let classifier = CharClassifier::new(scope).for_completion(true);
13793 let mut last_word = chars
13794 .chars()
13795 .take_while(|c| classifier.is_word(*c))
13796 .collect::<String>();
13797 last_word = last_word.chars().rev().collect();
13798
13799 if last_word.is_empty() {
13800 return Ok(vec![]);
13801 }
13802
13803 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13804 let to_lsp = |point: &text::Anchor| {
13805 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13806 point_to_lsp(end)
13807 };
13808 let lsp_end = to_lsp(&buffer_position);
13809
13810 let candidates = snippets
13811 .iter()
13812 .enumerate()
13813 .flat_map(|(ix, snippet)| {
13814 snippet
13815 .prefix
13816 .iter()
13817 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13818 })
13819 .collect::<Vec<StringMatchCandidate>>();
13820
13821 let mut matches = fuzzy::match_strings(
13822 &candidates,
13823 &last_word,
13824 last_word.chars().any(|c| c.is_uppercase()),
13825 100,
13826 &Default::default(),
13827 executor,
13828 )
13829 .await;
13830
13831 // Remove all candidates where the query's start does not match the start of any word in the candidate
13832 if let Some(query_start) = last_word.chars().next() {
13833 matches.retain(|string_match| {
13834 split_words(&string_match.string).any(|word| {
13835 // Check that the first codepoint of the word as lowercase matches the first
13836 // codepoint of the query as lowercase
13837 word.chars()
13838 .flat_map(|codepoint| codepoint.to_lowercase())
13839 .zip(query_start.to_lowercase())
13840 .all(|(word_cp, query_cp)| word_cp == query_cp)
13841 })
13842 });
13843 }
13844
13845 let matched_strings = matches
13846 .into_iter()
13847 .map(|m| m.string)
13848 .collect::<HashSet<_>>();
13849
13850 let result: Vec<Completion> = snippets
13851 .into_iter()
13852 .filter_map(|snippet| {
13853 let matching_prefix = snippet
13854 .prefix
13855 .iter()
13856 .find(|prefix| matched_strings.contains(*prefix))?;
13857 let start = as_offset - last_word.len();
13858 let start = snapshot.anchor_before(start);
13859 let range = start..buffer_position;
13860 let lsp_start = to_lsp(&start);
13861 let lsp_range = lsp::Range {
13862 start: lsp_start,
13863 end: lsp_end,
13864 };
13865 Some(Completion {
13866 old_range: range,
13867 new_text: snippet.body.clone(),
13868 resolved: false,
13869 label: CodeLabel {
13870 text: matching_prefix.clone(),
13871 runs: vec![],
13872 filter_range: 0..matching_prefix.len(),
13873 },
13874 server_id: LanguageServerId(usize::MAX),
13875 documentation: snippet.description.clone().map(Documentation::SingleLine),
13876 lsp_completion: lsp::CompletionItem {
13877 label: snippet.prefix.first().unwrap().clone(),
13878 kind: Some(CompletionItemKind::SNIPPET),
13879 label_details: snippet.description.as_ref().map(|description| {
13880 lsp::CompletionItemLabelDetails {
13881 detail: Some(description.clone()),
13882 description: None,
13883 }
13884 }),
13885 insert_text_format: Some(InsertTextFormat::SNIPPET),
13886 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13887 lsp::InsertReplaceEdit {
13888 new_text: snippet.body.clone(),
13889 insert: lsp_range,
13890 replace: lsp_range,
13891 },
13892 )),
13893 filter_text: Some(snippet.body.clone()),
13894 sort_text: Some(char::MAX.to_string()),
13895 ..Default::default()
13896 },
13897 confirm: None,
13898 })
13899 })
13900 .collect();
13901
13902 Ok(result)
13903 })
13904}
13905
13906impl CompletionProvider for Model<Project> {
13907 fn completions(
13908 &self,
13909 buffer: &Model<Buffer>,
13910 buffer_position: text::Anchor,
13911 options: CompletionContext,
13912 cx: &mut ViewContext<Editor>,
13913 ) -> Task<Result<Vec<Completion>>> {
13914 self.update(cx, |project, cx| {
13915 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13916 let project_completions = project.completions(buffer, buffer_position, options, cx);
13917 cx.background_executor().spawn(async move {
13918 let mut completions = project_completions.await?;
13919 let snippets_completions = snippets.await?;
13920 completions.extend(snippets_completions);
13921 Ok(completions)
13922 })
13923 })
13924 }
13925
13926 fn resolve_completions(
13927 &self,
13928 buffer: Model<Buffer>,
13929 completion_indices: Vec<usize>,
13930 completions: Rc<RefCell<Box<[Completion]>>>,
13931 cx: &mut ViewContext<Editor>,
13932 ) -> Task<Result<bool>> {
13933 self.update(cx, |project, cx| {
13934 project.lsp_store().update(cx, |lsp_store, cx| {
13935 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13936 })
13937 })
13938 }
13939
13940 fn apply_additional_edits_for_completion(
13941 &self,
13942 buffer: Model<Buffer>,
13943 completions: Rc<RefCell<Box<[Completion]>>>,
13944 completion_index: usize,
13945 push_to_history: bool,
13946 cx: &mut ViewContext<Editor>,
13947 ) -> Task<Result<Option<language::Transaction>>> {
13948 self.update(cx, |project, cx| {
13949 project.lsp_store().update(cx, |lsp_store, cx| {
13950 lsp_store.apply_additional_edits_for_completion(
13951 buffer,
13952 completions,
13953 completion_index,
13954 push_to_history,
13955 cx,
13956 )
13957 })
13958 })
13959 }
13960
13961 fn is_completion_trigger(
13962 &self,
13963 buffer: &Model<Buffer>,
13964 position: language::Anchor,
13965 text: &str,
13966 trigger_in_words: bool,
13967 cx: &mut ViewContext<Editor>,
13968 ) -> bool {
13969 let mut chars = text.chars();
13970 let char = if let Some(char) = chars.next() {
13971 char
13972 } else {
13973 return false;
13974 };
13975 if chars.next().is_some() {
13976 return false;
13977 }
13978
13979 let buffer = buffer.read(cx);
13980 let snapshot = buffer.snapshot();
13981 if !snapshot.settings_at(position, cx).show_completions_on_input {
13982 return false;
13983 }
13984 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13985 if trigger_in_words && classifier.is_word(char) {
13986 return true;
13987 }
13988
13989 buffer.completion_triggers().contains(text)
13990 }
13991}
13992
13993impl SemanticsProvider for Model<Project> {
13994 fn hover(
13995 &self,
13996 buffer: &Model<Buffer>,
13997 position: text::Anchor,
13998 cx: &mut AppContext,
13999 ) -> Option<Task<Vec<project::Hover>>> {
14000 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14001 }
14002
14003 fn document_highlights(
14004 &self,
14005 buffer: &Model<Buffer>,
14006 position: text::Anchor,
14007 cx: &mut AppContext,
14008 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14009 Some(self.update(cx, |project, cx| {
14010 project.document_highlights(buffer, position, cx)
14011 }))
14012 }
14013
14014 fn definitions(
14015 &self,
14016 buffer: &Model<Buffer>,
14017 position: text::Anchor,
14018 kind: GotoDefinitionKind,
14019 cx: &mut AppContext,
14020 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14021 Some(self.update(cx, |project, cx| match kind {
14022 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14023 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14024 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14025 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14026 }))
14027 }
14028
14029 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14030 // TODO: make this work for remote projects
14031 self.read(cx)
14032 .language_servers_for_local_buffer(buffer.read(cx), cx)
14033 .any(
14034 |(_, server)| match server.capabilities().inlay_hint_provider {
14035 Some(lsp::OneOf::Left(enabled)) => enabled,
14036 Some(lsp::OneOf::Right(_)) => true,
14037 None => false,
14038 },
14039 )
14040 }
14041
14042 fn inlay_hints(
14043 &self,
14044 buffer_handle: Model<Buffer>,
14045 range: Range<text::Anchor>,
14046 cx: &mut AppContext,
14047 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14048 Some(self.update(cx, |project, cx| {
14049 project.inlay_hints(buffer_handle, range, cx)
14050 }))
14051 }
14052
14053 fn resolve_inlay_hint(
14054 &self,
14055 hint: InlayHint,
14056 buffer_handle: Model<Buffer>,
14057 server_id: LanguageServerId,
14058 cx: &mut AppContext,
14059 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14060 Some(self.update(cx, |project, cx| {
14061 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14062 }))
14063 }
14064
14065 fn range_for_rename(
14066 &self,
14067 buffer: &Model<Buffer>,
14068 position: text::Anchor,
14069 cx: &mut AppContext,
14070 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14071 Some(self.update(cx, |project, cx| {
14072 let buffer = buffer.clone();
14073 let task = project.prepare_rename(buffer.clone(), position, cx);
14074 cx.spawn(|_, mut cx| async move {
14075 Ok(match task.await? {
14076 PrepareRenameResponse::Success(range) => Some(range),
14077 PrepareRenameResponse::InvalidPosition => None,
14078 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14079 // Fallback on using TreeSitter info to determine identifier range
14080 buffer.update(&mut cx, |buffer, _| {
14081 let snapshot = buffer.snapshot();
14082 let (range, kind) = snapshot.surrounding_word(position);
14083 if kind != Some(CharKind::Word) {
14084 return None;
14085 }
14086 Some(
14087 snapshot.anchor_before(range.start)
14088 ..snapshot.anchor_after(range.end),
14089 )
14090 })?
14091 }
14092 })
14093 })
14094 }))
14095 }
14096
14097 fn perform_rename(
14098 &self,
14099 buffer: &Model<Buffer>,
14100 position: text::Anchor,
14101 new_name: String,
14102 cx: &mut AppContext,
14103 ) -> Option<Task<Result<ProjectTransaction>>> {
14104 Some(self.update(cx, |project, cx| {
14105 project.perform_rename(buffer.clone(), position, new_name, cx)
14106 }))
14107 }
14108}
14109
14110fn inlay_hint_settings(
14111 location: Anchor,
14112 snapshot: &MultiBufferSnapshot,
14113 cx: &mut ViewContext<Editor>,
14114) -> InlayHintSettings {
14115 let file = snapshot.file_at(location);
14116 let language = snapshot.language_at(location).map(|l| l.name());
14117 language_settings(language, file, cx).inlay_hints
14118}
14119
14120fn consume_contiguous_rows(
14121 contiguous_row_selections: &mut Vec<Selection<Point>>,
14122 selection: &Selection<Point>,
14123 display_map: &DisplaySnapshot,
14124 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14125) -> (MultiBufferRow, MultiBufferRow) {
14126 contiguous_row_selections.push(selection.clone());
14127 let start_row = MultiBufferRow(selection.start.row);
14128 let mut end_row = ending_row(selection, display_map);
14129
14130 while let Some(next_selection) = selections.peek() {
14131 if next_selection.start.row <= end_row.0 {
14132 end_row = ending_row(next_selection, display_map);
14133 contiguous_row_selections.push(selections.next().unwrap().clone());
14134 } else {
14135 break;
14136 }
14137 }
14138 (start_row, end_row)
14139}
14140
14141fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14142 if next_selection.end.column > 0 || next_selection.is_empty() {
14143 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14144 } else {
14145 MultiBufferRow(next_selection.end.row)
14146 }
14147}
14148
14149impl EditorSnapshot {
14150 pub fn remote_selections_in_range<'a>(
14151 &'a self,
14152 range: &'a Range<Anchor>,
14153 collaboration_hub: &dyn CollaborationHub,
14154 cx: &'a AppContext,
14155 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14156 let participant_names = collaboration_hub.user_names(cx);
14157 let participant_indices = collaboration_hub.user_participant_indices(cx);
14158 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14159 let collaborators_by_replica_id = collaborators_by_peer_id
14160 .iter()
14161 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14162 .collect::<HashMap<_, _>>();
14163 self.buffer_snapshot
14164 .selections_in_range(range, false)
14165 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14166 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14167 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14168 let user_name = participant_names.get(&collaborator.user_id).cloned();
14169 Some(RemoteSelection {
14170 replica_id,
14171 selection,
14172 cursor_shape,
14173 line_mode,
14174 participant_index,
14175 peer_id: collaborator.peer_id,
14176 user_name,
14177 })
14178 })
14179 }
14180
14181 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14182 self.display_snapshot.buffer_snapshot.language_at(position)
14183 }
14184
14185 pub fn is_focused(&self) -> bool {
14186 self.is_focused
14187 }
14188
14189 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14190 self.placeholder_text.as_ref()
14191 }
14192
14193 pub fn scroll_position(&self) -> gpui::Point<f32> {
14194 self.scroll_anchor.scroll_position(&self.display_snapshot)
14195 }
14196
14197 fn gutter_dimensions(
14198 &self,
14199 font_id: FontId,
14200 font_size: Pixels,
14201 em_width: Pixels,
14202 em_advance: Pixels,
14203 max_line_number_width: Pixels,
14204 cx: &AppContext,
14205 ) -> GutterDimensions {
14206 if !self.show_gutter {
14207 return GutterDimensions::default();
14208 }
14209 let descent = cx.text_system().descent(font_id, font_size);
14210
14211 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14212 matches!(
14213 ProjectSettings::get_global(cx).git.git_gutter,
14214 Some(GitGutterSetting::TrackedFiles)
14215 )
14216 });
14217 let gutter_settings = EditorSettings::get_global(cx).gutter;
14218 let show_line_numbers = self
14219 .show_line_numbers
14220 .unwrap_or(gutter_settings.line_numbers);
14221 let line_gutter_width = if show_line_numbers {
14222 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14223 let min_width_for_number_on_gutter = em_advance * 4.0;
14224 max_line_number_width.max(min_width_for_number_on_gutter)
14225 } else {
14226 0.0.into()
14227 };
14228
14229 let show_code_actions = self
14230 .show_code_actions
14231 .unwrap_or(gutter_settings.code_actions);
14232
14233 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14234
14235 let git_blame_entries_width =
14236 self.git_blame_gutter_max_author_length
14237 .map(|max_author_length| {
14238 // Length of the author name, but also space for the commit hash,
14239 // the spacing and the timestamp.
14240 let max_char_count = max_author_length
14241 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14242 + 7 // length of commit sha
14243 + 14 // length of max relative timestamp ("60 minutes ago")
14244 + 4; // gaps and margins
14245
14246 em_advance * max_char_count
14247 });
14248
14249 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14250 left_padding += if show_code_actions || show_runnables {
14251 em_width * 3.0
14252 } else if show_git_gutter && show_line_numbers {
14253 em_width * 2.0
14254 } else if show_git_gutter || show_line_numbers {
14255 em_width
14256 } else {
14257 px(0.)
14258 };
14259
14260 let right_padding = if gutter_settings.folds && show_line_numbers {
14261 em_width * 4.0
14262 } else if gutter_settings.folds {
14263 em_width * 3.0
14264 } else if show_line_numbers {
14265 em_width
14266 } else {
14267 px(0.)
14268 };
14269
14270 GutterDimensions {
14271 left_padding,
14272 right_padding,
14273 width: line_gutter_width + left_padding + right_padding,
14274 margin: -descent,
14275 git_blame_entries_width,
14276 }
14277 }
14278
14279 pub fn render_crease_toggle(
14280 &self,
14281 buffer_row: MultiBufferRow,
14282 row_contains_cursor: bool,
14283 editor: View<Editor>,
14284 cx: &mut WindowContext,
14285 ) -> Option<AnyElement> {
14286 let folded = self.is_line_folded(buffer_row);
14287 let mut is_foldable = false;
14288
14289 if let Some(crease) = self
14290 .crease_snapshot
14291 .query_row(buffer_row, &self.buffer_snapshot)
14292 {
14293 is_foldable = true;
14294 match crease {
14295 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14296 if let Some(render_toggle) = render_toggle {
14297 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14298 if folded {
14299 editor.update(cx, |editor, cx| {
14300 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14301 });
14302 } else {
14303 editor.update(cx, |editor, cx| {
14304 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14305 });
14306 }
14307 });
14308 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14309 }
14310 }
14311 }
14312 }
14313
14314 is_foldable |= self.starts_indent(buffer_row);
14315
14316 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14317 Some(
14318 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14319 .toggle_state(folded)
14320 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14321 if folded {
14322 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14323 } else {
14324 this.fold_at(&FoldAt { buffer_row }, cx);
14325 }
14326 }))
14327 .into_any_element(),
14328 )
14329 } else {
14330 None
14331 }
14332 }
14333
14334 pub fn render_crease_trailer(
14335 &self,
14336 buffer_row: MultiBufferRow,
14337 cx: &mut WindowContext,
14338 ) -> Option<AnyElement> {
14339 let folded = self.is_line_folded(buffer_row);
14340 if let Crease::Inline { render_trailer, .. } = self
14341 .crease_snapshot
14342 .query_row(buffer_row, &self.buffer_snapshot)?
14343 {
14344 let render_trailer = render_trailer.as_ref()?;
14345 Some(render_trailer(buffer_row, folded, cx))
14346 } else {
14347 None
14348 }
14349 }
14350}
14351
14352impl Deref for EditorSnapshot {
14353 type Target = DisplaySnapshot;
14354
14355 fn deref(&self) -> &Self::Target {
14356 &self.display_snapshot
14357 }
14358}
14359
14360#[derive(Clone, Debug, PartialEq, Eq)]
14361pub enum EditorEvent {
14362 InputIgnored {
14363 text: Arc<str>,
14364 },
14365 InputHandled {
14366 utf16_range_to_replace: Option<Range<isize>>,
14367 text: Arc<str>,
14368 },
14369 ExcerptsAdded {
14370 buffer: Model<Buffer>,
14371 predecessor: ExcerptId,
14372 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14373 },
14374 ExcerptsRemoved {
14375 ids: Vec<ExcerptId>,
14376 },
14377 BufferFoldToggled {
14378 ids: Vec<ExcerptId>,
14379 folded: bool,
14380 },
14381 ExcerptsEdited {
14382 ids: Vec<ExcerptId>,
14383 },
14384 ExcerptsExpanded {
14385 ids: Vec<ExcerptId>,
14386 },
14387 BufferEdited,
14388 Edited {
14389 transaction_id: clock::Lamport,
14390 },
14391 Reparsed(BufferId),
14392 Focused,
14393 FocusedIn,
14394 Blurred,
14395 DirtyChanged,
14396 Saved,
14397 TitleChanged,
14398 DiffBaseChanged,
14399 SelectionsChanged {
14400 local: bool,
14401 },
14402 ScrollPositionChanged {
14403 local: bool,
14404 autoscroll: bool,
14405 },
14406 Closed,
14407 TransactionUndone {
14408 transaction_id: clock::Lamport,
14409 },
14410 TransactionBegun {
14411 transaction_id: clock::Lamport,
14412 },
14413 Reloaded,
14414 CursorShapeChanged,
14415}
14416
14417impl EventEmitter<EditorEvent> for Editor {}
14418
14419impl FocusableView for Editor {
14420 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14421 self.focus_handle.clone()
14422 }
14423}
14424
14425impl Render for Editor {
14426 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14427 let settings = ThemeSettings::get_global(cx);
14428
14429 let mut text_style = match self.mode {
14430 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14431 color: cx.theme().colors().editor_foreground,
14432 font_family: settings.ui_font.family.clone(),
14433 font_features: settings.ui_font.features.clone(),
14434 font_fallbacks: settings.ui_font.fallbacks.clone(),
14435 font_size: rems(0.875).into(),
14436 font_weight: settings.ui_font.weight,
14437 line_height: relative(settings.buffer_line_height.value()),
14438 ..Default::default()
14439 },
14440 EditorMode::Full => TextStyle {
14441 color: cx.theme().colors().editor_foreground,
14442 font_family: settings.buffer_font.family.clone(),
14443 font_features: settings.buffer_font.features.clone(),
14444 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14445 font_size: settings.buffer_font_size().into(),
14446 font_weight: settings.buffer_font.weight,
14447 line_height: relative(settings.buffer_line_height.value()),
14448 ..Default::default()
14449 },
14450 };
14451 if let Some(text_style_refinement) = &self.text_style_refinement {
14452 text_style.refine(text_style_refinement)
14453 }
14454
14455 let background = match self.mode {
14456 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14457 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14458 EditorMode::Full => cx.theme().colors().editor_background,
14459 };
14460
14461 EditorElement::new(
14462 cx.view(),
14463 EditorStyle {
14464 background,
14465 local_player: cx.theme().players().local(),
14466 text: text_style,
14467 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14468 syntax: cx.theme().syntax().clone(),
14469 status: cx.theme().status().clone(),
14470 inlay_hints_style: make_inlay_hints_style(cx),
14471 inline_completion_styles: make_suggestion_styles(cx),
14472 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14473 },
14474 )
14475 }
14476}
14477
14478impl ViewInputHandler for Editor {
14479 fn text_for_range(
14480 &mut self,
14481 range_utf16: Range<usize>,
14482 adjusted_range: &mut Option<Range<usize>>,
14483 cx: &mut ViewContext<Self>,
14484 ) -> Option<String> {
14485 let snapshot = self.buffer.read(cx).read(cx);
14486 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14487 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14488 if (start.0..end.0) != range_utf16 {
14489 adjusted_range.replace(start.0..end.0);
14490 }
14491 Some(snapshot.text_for_range(start..end).collect())
14492 }
14493
14494 fn selected_text_range(
14495 &mut self,
14496 ignore_disabled_input: bool,
14497 cx: &mut ViewContext<Self>,
14498 ) -> Option<UTF16Selection> {
14499 // Prevent the IME menu from appearing when holding down an alphabetic key
14500 // while input is disabled.
14501 if !ignore_disabled_input && !self.input_enabled {
14502 return None;
14503 }
14504
14505 let selection = self.selections.newest::<OffsetUtf16>(cx);
14506 let range = selection.range();
14507
14508 Some(UTF16Selection {
14509 range: range.start.0..range.end.0,
14510 reversed: selection.reversed,
14511 })
14512 }
14513
14514 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14515 let snapshot = self.buffer.read(cx).read(cx);
14516 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14517 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14518 }
14519
14520 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14521 self.clear_highlights::<InputComposition>(cx);
14522 self.ime_transaction.take();
14523 }
14524
14525 fn replace_text_in_range(
14526 &mut self,
14527 range_utf16: Option<Range<usize>>,
14528 text: &str,
14529 cx: &mut ViewContext<Self>,
14530 ) {
14531 if !self.input_enabled {
14532 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14533 return;
14534 }
14535
14536 self.transact(cx, |this, cx| {
14537 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14538 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14539 Some(this.selection_replacement_ranges(range_utf16, cx))
14540 } else {
14541 this.marked_text_ranges(cx)
14542 };
14543
14544 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14545 let newest_selection_id = this.selections.newest_anchor().id;
14546 this.selections
14547 .all::<OffsetUtf16>(cx)
14548 .iter()
14549 .zip(ranges_to_replace.iter())
14550 .find_map(|(selection, range)| {
14551 if selection.id == newest_selection_id {
14552 Some(
14553 (range.start.0 as isize - selection.head().0 as isize)
14554 ..(range.end.0 as isize - selection.head().0 as isize),
14555 )
14556 } else {
14557 None
14558 }
14559 })
14560 });
14561
14562 cx.emit(EditorEvent::InputHandled {
14563 utf16_range_to_replace: range_to_replace,
14564 text: text.into(),
14565 });
14566
14567 if let Some(new_selected_ranges) = new_selected_ranges {
14568 this.change_selections(None, cx, |selections| {
14569 selections.select_ranges(new_selected_ranges)
14570 });
14571 this.backspace(&Default::default(), cx);
14572 }
14573
14574 this.handle_input(text, cx);
14575 });
14576
14577 if let Some(transaction) = self.ime_transaction {
14578 self.buffer.update(cx, |buffer, cx| {
14579 buffer.group_until_transaction(transaction, cx);
14580 });
14581 }
14582
14583 self.unmark_text(cx);
14584 }
14585
14586 fn replace_and_mark_text_in_range(
14587 &mut self,
14588 range_utf16: Option<Range<usize>>,
14589 text: &str,
14590 new_selected_range_utf16: Option<Range<usize>>,
14591 cx: &mut ViewContext<Self>,
14592 ) {
14593 if !self.input_enabled {
14594 return;
14595 }
14596
14597 let transaction = self.transact(cx, |this, cx| {
14598 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14599 let snapshot = this.buffer.read(cx).read(cx);
14600 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14601 for marked_range in &mut marked_ranges {
14602 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14603 marked_range.start.0 += relative_range_utf16.start;
14604 marked_range.start =
14605 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14606 marked_range.end =
14607 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14608 }
14609 }
14610 Some(marked_ranges)
14611 } else if let Some(range_utf16) = range_utf16 {
14612 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14613 Some(this.selection_replacement_ranges(range_utf16, cx))
14614 } else {
14615 None
14616 };
14617
14618 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14619 let newest_selection_id = this.selections.newest_anchor().id;
14620 this.selections
14621 .all::<OffsetUtf16>(cx)
14622 .iter()
14623 .zip(ranges_to_replace.iter())
14624 .find_map(|(selection, range)| {
14625 if selection.id == newest_selection_id {
14626 Some(
14627 (range.start.0 as isize - selection.head().0 as isize)
14628 ..(range.end.0 as isize - selection.head().0 as isize),
14629 )
14630 } else {
14631 None
14632 }
14633 })
14634 });
14635
14636 cx.emit(EditorEvent::InputHandled {
14637 utf16_range_to_replace: range_to_replace,
14638 text: text.into(),
14639 });
14640
14641 if let Some(ranges) = ranges_to_replace {
14642 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14643 }
14644
14645 let marked_ranges = {
14646 let snapshot = this.buffer.read(cx).read(cx);
14647 this.selections
14648 .disjoint_anchors()
14649 .iter()
14650 .map(|selection| {
14651 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14652 })
14653 .collect::<Vec<_>>()
14654 };
14655
14656 if text.is_empty() {
14657 this.unmark_text(cx);
14658 } else {
14659 this.highlight_text::<InputComposition>(
14660 marked_ranges.clone(),
14661 HighlightStyle {
14662 underline: Some(UnderlineStyle {
14663 thickness: px(1.),
14664 color: None,
14665 wavy: false,
14666 }),
14667 ..Default::default()
14668 },
14669 cx,
14670 );
14671 }
14672
14673 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14674 let use_autoclose = this.use_autoclose;
14675 let use_auto_surround = this.use_auto_surround;
14676 this.set_use_autoclose(false);
14677 this.set_use_auto_surround(false);
14678 this.handle_input(text, cx);
14679 this.set_use_autoclose(use_autoclose);
14680 this.set_use_auto_surround(use_auto_surround);
14681
14682 if let Some(new_selected_range) = new_selected_range_utf16 {
14683 let snapshot = this.buffer.read(cx).read(cx);
14684 let new_selected_ranges = marked_ranges
14685 .into_iter()
14686 .map(|marked_range| {
14687 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14688 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14689 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14690 snapshot.clip_offset_utf16(new_start, Bias::Left)
14691 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14692 })
14693 .collect::<Vec<_>>();
14694
14695 drop(snapshot);
14696 this.change_selections(None, cx, |selections| {
14697 selections.select_ranges(new_selected_ranges)
14698 });
14699 }
14700 });
14701
14702 self.ime_transaction = self.ime_transaction.or(transaction);
14703 if let Some(transaction) = self.ime_transaction {
14704 self.buffer.update(cx, |buffer, cx| {
14705 buffer.group_until_transaction(transaction, cx);
14706 });
14707 }
14708
14709 if self.text_highlights::<InputComposition>(cx).is_none() {
14710 self.ime_transaction.take();
14711 }
14712 }
14713
14714 fn bounds_for_range(
14715 &mut self,
14716 range_utf16: Range<usize>,
14717 element_bounds: gpui::Bounds<Pixels>,
14718 cx: &mut ViewContext<Self>,
14719 ) -> Option<gpui::Bounds<Pixels>> {
14720 let text_layout_details = self.text_layout_details(cx);
14721 let gpui::Point {
14722 x: em_width,
14723 y: line_height,
14724 } = self.character_size(cx);
14725
14726 let snapshot = self.snapshot(cx);
14727 let scroll_position = snapshot.scroll_position();
14728 let scroll_left = scroll_position.x * em_width;
14729
14730 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14731 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14732 + self.gutter_dimensions.width
14733 + self.gutter_dimensions.margin;
14734 let y = line_height * (start.row().as_f32() - scroll_position.y);
14735
14736 Some(Bounds {
14737 origin: element_bounds.origin + point(x, y),
14738 size: size(em_width, line_height),
14739 })
14740 }
14741}
14742
14743trait SelectionExt {
14744 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14745 fn spanned_rows(
14746 &self,
14747 include_end_if_at_line_start: bool,
14748 map: &DisplaySnapshot,
14749 ) -> Range<MultiBufferRow>;
14750}
14751
14752impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14753 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14754 let start = self
14755 .start
14756 .to_point(&map.buffer_snapshot)
14757 .to_display_point(map);
14758 let end = self
14759 .end
14760 .to_point(&map.buffer_snapshot)
14761 .to_display_point(map);
14762 if self.reversed {
14763 end..start
14764 } else {
14765 start..end
14766 }
14767 }
14768
14769 fn spanned_rows(
14770 &self,
14771 include_end_if_at_line_start: bool,
14772 map: &DisplaySnapshot,
14773 ) -> Range<MultiBufferRow> {
14774 let start = self.start.to_point(&map.buffer_snapshot);
14775 let mut end = self.end.to_point(&map.buffer_snapshot);
14776 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14777 end.row -= 1;
14778 }
14779
14780 let buffer_start = map.prev_line_boundary(start).0;
14781 let buffer_end = map.next_line_boundary(end).0;
14782 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14783 }
14784}
14785
14786impl<T: InvalidationRegion> InvalidationStack<T> {
14787 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14788 where
14789 S: Clone + ToOffset,
14790 {
14791 while let Some(region) = self.last() {
14792 let all_selections_inside_invalidation_ranges =
14793 if selections.len() == region.ranges().len() {
14794 selections
14795 .iter()
14796 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14797 .all(|(selection, invalidation_range)| {
14798 let head = selection.head().to_offset(buffer);
14799 invalidation_range.start <= head && invalidation_range.end >= head
14800 })
14801 } else {
14802 false
14803 };
14804
14805 if all_selections_inside_invalidation_ranges {
14806 break;
14807 } else {
14808 self.pop();
14809 }
14810 }
14811 }
14812}
14813
14814impl<T> Default for InvalidationStack<T> {
14815 fn default() -> Self {
14816 Self(Default::default())
14817 }
14818}
14819
14820impl<T> Deref for InvalidationStack<T> {
14821 type Target = Vec<T>;
14822
14823 fn deref(&self) -> &Self::Target {
14824 &self.0
14825 }
14826}
14827
14828impl<T> DerefMut for InvalidationStack<T> {
14829 fn deref_mut(&mut self) -> &mut Self::Target {
14830 &mut self.0
14831 }
14832}
14833
14834impl InvalidationRegion for SnippetState {
14835 fn ranges(&self) -> &[Range<Anchor>] {
14836 &self.ranges[self.active_index]
14837 }
14838}
14839
14840pub fn diagnostic_block_renderer(
14841 diagnostic: Diagnostic,
14842 max_message_rows: Option<u8>,
14843 allow_closing: bool,
14844 _is_valid: bool,
14845) -> RenderBlock {
14846 let (text_without_backticks, code_ranges) =
14847 highlight_diagnostic_message(&diagnostic, max_message_rows);
14848
14849 Arc::new(move |cx: &mut BlockContext| {
14850 let group_id: SharedString = cx.block_id.to_string().into();
14851
14852 let mut text_style = cx.text_style().clone();
14853 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14854 let theme_settings = ThemeSettings::get_global(cx);
14855 text_style.font_family = theme_settings.buffer_font.family.clone();
14856 text_style.font_style = theme_settings.buffer_font.style;
14857 text_style.font_features = theme_settings.buffer_font.features.clone();
14858 text_style.font_weight = theme_settings.buffer_font.weight;
14859
14860 let multi_line_diagnostic = diagnostic.message.contains('\n');
14861
14862 let buttons = |diagnostic: &Diagnostic| {
14863 if multi_line_diagnostic {
14864 v_flex()
14865 } else {
14866 h_flex()
14867 }
14868 .when(allow_closing, |div| {
14869 div.children(diagnostic.is_primary.then(|| {
14870 IconButton::new("close-block", IconName::XCircle)
14871 .icon_color(Color::Muted)
14872 .size(ButtonSize::Compact)
14873 .style(ButtonStyle::Transparent)
14874 .visible_on_hover(group_id.clone())
14875 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14876 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14877 }))
14878 })
14879 .child(
14880 IconButton::new("copy-block", IconName::Copy)
14881 .icon_color(Color::Muted)
14882 .size(ButtonSize::Compact)
14883 .style(ButtonStyle::Transparent)
14884 .visible_on_hover(group_id.clone())
14885 .on_click({
14886 let message = diagnostic.message.clone();
14887 move |_click, cx| {
14888 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14889 }
14890 })
14891 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14892 )
14893 };
14894
14895 let icon_size = buttons(&diagnostic)
14896 .into_any_element()
14897 .layout_as_root(AvailableSpace::min_size(), cx);
14898
14899 h_flex()
14900 .id(cx.block_id)
14901 .group(group_id.clone())
14902 .relative()
14903 .size_full()
14904 .block_mouse_down()
14905 .pl(cx.gutter_dimensions.width)
14906 .w(cx.max_width - cx.gutter_dimensions.full_width())
14907 .child(
14908 div()
14909 .flex()
14910 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14911 .flex_shrink(),
14912 )
14913 .child(buttons(&diagnostic))
14914 .child(div().flex().flex_shrink_0().child(
14915 StyledText::new(text_without_backticks.clone()).with_highlights(
14916 &text_style,
14917 code_ranges.iter().map(|range| {
14918 (
14919 range.clone(),
14920 HighlightStyle {
14921 font_weight: Some(FontWeight::BOLD),
14922 ..Default::default()
14923 },
14924 )
14925 }),
14926 ),
14927 ))
14928 .into_any_element()
14929 })
14930}
14931
14932fn inline_completion_edit_text(
14933 editor_snapshot: &EditorSnapshot,
14934 edits: &Vec<(Range<Anchor>, String)>,
14935 include_deletions: bool,
14936 cx: &WindowContext,
14937) -> InlineCompletionText {
14938 let edit_start = edits
14939 .first()
14940 .unwrap()
14941 .0
14942 .start
14943 .to_display_point(editor_snapshot);
14944
14945 let mut text = String::new();
14946 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14947 let mut highlights = Vec::new();
14948 for (old_range, new_text) in edits {
14949 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14950 text.extend(
14951 editor_snapshot
14952 .buffer_snapshot
14953 .chunks(offset..old_offset_range.start, false)
14954 .map(|chunk| chunk.text),
14955 );
14956 offset = old_offset_range.end;
14957
14958 let start = text.len();
14959 let color = if include_deletions && new_text.is_empty() {
14960 text.extend(
14961 editor_snapshot
14962 .buffer_snapshot
14963 .chunks(old_offset_range.start..offset, false)
14964 .map(|chunk| chunk.text),
14965 );
14966 cx.theme().status().deleted_background
14967 } else {
14968 text.push_str(new_text);
14969 cx.theme().status().created_background
14970 };
14971 let end = text.len();
14972
14973 highlights.push((
14974 start..end,
14975 HighlightStyle {
14976 background_color: Some(color),
14977 ..Default::default()
14978 },
14979 ));
14980 }
14981
14982 let edit_end = edits
14983 .last()
14984 .unwrap()
14985 .0
14986 .end
14987 .to_display_point(editor_snapshot);
14988 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14989 .to_offset(editor_snapshot, Bias::Right);
14990 text.extend(
14991 editor_snapshot
14992 .buffer_snapshot
14993 .chunks(offset..end_of_line, false)
14994 .map(|chunk| chunk.text),
14995 );
14996
14997 InlineCompletionText::Edit {
14998 text: text.into(),
14999 highlights,
15000 }
15001}
15002
15003pub fn highlight_diagnostic_message(
15004 diagnostic: &Diagnostic,
15005 mut max_message_rows: Option<u8>,
15006) -> (SharedString, Vec<Range<usize>>) {
15007 let mut text_without_backticks = String::new();
15008 let mut code_ranges = Vec::new();
15009
15010 if let Some(source) = &diagnostic.source {
15011 text_without_backticks.push_str(source);
15012 code_ranges.push(0..source.len());
15013 text_without_backticks.push_str(": ");
15014 }
15015
15016 let mut prev_offset = 0;
15017 let mut in_code_block = false;
15018 let has_row_limit = max_message_rows.is_some();
15019 let mut newline_indices = diagnostic
15020 .message
15021 .match_indices('\n')
15022 .filter(|_| has_row_limit)
15023 .map(|(ix, _)| ix)
15024 .fuse()
15025 .peekable();
15026
15027 for (quote_ix, _) in diagnostic
15028 .message
15029 .match_indices('`')
15030 .chain([(diagnostic.message.len(), "")])
15031 {
15032 let mut first_newline_ix = None;
15033 let mut last_newline_ix = None;
15034 while let Some(newline_ix) = newline_indices.peek() {
15035 if *newline_ix < quote_ix {
15036 if first_newline_ix.is_none() {
15037 first_newline_ix = Some(*newline_ix);
15038 }
15039 last_newline_ix = Some(*newline_ix);
15040
15041 if let Some(rows_left) = &mut max_message_rows {
15042 if *rows_left == 0 {
15043 break;
15044 } else {
15045 *rows_left -= 1;
15046 }
15047 }
15048 let _ = newline_indices.next();
15049 } else {
15050 break;
15051 }
15052 }
15053 let prev_len = text_without_backticks.len();
15054 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15055 text_without_backticks.push_str(new_text);
15056 if in_code_block {
15057 code_ranges.push(prev_len..text_without_backticks.len());
15058 }
15059 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15060 in_code_block = !in_code_block;
15061 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15062 text_without_backticks.push_str("...");
15063 break;
15064 }
15065 }
15066
15067 (text_without_backticks.into(), code_ranges)
15068}
15069
15070fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15071 match severity {
15072 DiagnosticSeverity::ERROR => colors.error,
15073 DiagnosticSeverity::WARNING => colors.warning,
15074 DiagnosticSeverity::INFORMATION => colors.info,
15075 DiagnosticSeverity::HINT => colors.info,
15076 _ => colors.ignored,
15077 }
15078}
15079
15080pub fn styled_runs_for_code_label<'a>(
15081 label: &'a CodeLabel,
15082 syntax_theme: &'a theme::SyntaxTheme,
15083) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15084 let fade_out = HighlightStyle {
15085 fade_out: Some(0.35),
15086 ..Default::default()
15087 };
15088
15089 let mut prev_end = label.filter_range.end;
15090 label
15091 .runs
15092 .iter()
15093 .enumerate()
15094 .flat_map(move |(ix, (range, highlight_id))| {
15095 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15096 style
15097 } else {
15098 return Default::default();
15099 };
15100 let mut muted_style = style;
15101 muted_style.highlight(fade_out);
15102
15103 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15104 if range.start >= label.filter_range.end {
15105 if range.start > prev_end {
15106 runs.push((prev_end..range.start, fade_out));
15107 }
15108 runs.push((range.clone(), muted_style));
15109 } else if range.end <= label.filter_range.end {
15110 runs.push((range.clone(), style));
15111 } else {
15112 runs.push((range.start..label.filter_range.end, style));
15113 runs.push((label.filter_range.end..range.end, muted_style));
15114 }
15115 prev_end = cmp::max(prev_end, range.end);
15116
15117 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15118 runs.push((prev_end..label.text.len(), fade_out));
15119 }
15120
15121 runs
15122 })
15123}
15124
15125pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15126 let mut prev_index = 0;
15127 let mut prev_codepoint: Option<char> = None;
15128 text.char_indices()
15129 .chain([(text.len(), '\0')])
15130 .filter_map(move |(index, codepoint)| {
15131 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15132 let is_boundary = index == text.len()
15133 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15134 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15135 if is_boundary {
15136 let chunk = &text[prev_index..index];
15137 prev_index = index;
15138 Some(chunk)
15139 } else {
15140 None
15141 }
15142 })
15143}
15144
15145pub trait RangeToAnchorExt: Sized {
15146 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15147
15148 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15149 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15150 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15151 }
15152}
15153
15154impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15155 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15156 let start_offset = self.start.to_offset(snapshot);
15157 let end_offset = self.end.to_offset(snapshot);
15158 if start_offset == end_offset {
15159 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15160 } else {
15161 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15162 }
15163 }
15164}
15165
15166pub trait RowExt {
15167 fn as_f32(&self) -> f32;
15168
15169 fn next_row(&self) -> Self;
15170
15171 fn previous_row(&self) -> Self;
15172
15173 fn minus(&self, other: Self) -> u32;
15174}
15175
15176impl RowExt for DisplayRow {
15177 fn as_f32(&self) -> f32 {
15178 self.0 as f32
15179 }
15180
15181 fn next_row(&self) -> Self {
15182 Self(self.0 + 1)
15183 }
15184
15185 fn previous_row(&self) -> Self {
15186 Self(self.0.saturating_sub(1))
15187 }
15188
15189 fn minus(&self, other: Self) -> u32 {
15190 self.0 - other.0
15191 }
15192}
15193
15194impl RowExt for MultiBufferRow {
15195 fn as_f32(&self) -> f32 {
15196 self.0 as f32
15197 }
15198
15199 fn next_row(&self) -> Self {
15200 Self(self.0 + 1)
15201 }
15202
15203 fn previous_row(&self) -> Self {
15204 Self(self.0.saturating_sub(1))
15205 }
15206
15207 fn minus(&self, other: Self) -> u32 {
15208 self.0 - other.0
15209 }
15210}
15211
15212trait RowRangeExt {
15213 type Row;
15214
15215 fn len(&self) -> usize;
15216
15217 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15218}
15219
15220impl RowRangeExt for Range<MultiBufferRow> {
15221 type Row = MultiBufferRow;
15222
15223 fn len(&self) -> usize {
15224 (self.end.0 - self.start.0) as usize
15225 }
15226
15227 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15228 (self.start.0..self.end.0).map(MultiBufferRow)
15229 }
15230}
15231
15232impl RowRangeExt for Range<DisplayRow> {
15233 type Row = DisplayRow;
15234
15235 fn len(&self) -> usize {
15236 (self.end.0 - self.start.0) as usize
15237 }
15238
15239 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15240 (self.start.0..self.end.0).map(DisplayRow)
15241 }
15242}
15243
15244fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15245 if hunk.diff_base_byte_range.is_empty() {
15246 DiffHunkStatus::Added
15247 } else if hunk.row_range.is_empty() {
15248 DiffHunkStatus::Removed
15249 } else {
15250 DiffHunkStatus::Modified
15251 }
15252}
15253
15254/// If select range has more than one line, we
15255/// just point the cursor to range.start.
15256fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15257 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15258 range
15259 } else {
15260 range.start..range.start
15261 }
15262}
15263pub struct KillRing(ClipboardItem);
15264impl Global for KillRing {}
15265
15266const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);