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 toggle_fold_multiple_buffers: Task<()>,
710 _scroll_cursor_center_top_bottom_task: Task<()>,
711}
712
713#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
714enum NextScrollCursorCenterTopBottom {
715 #[default]
716 Center,
717 Top,
718 Bottom,
719}
720
721impl NextScrollCursorCenterTopBottom {
722 fn next(&self) -> Self {
723 match self {
724 Self::Center => Self::Top,
725 Self::Top => Self::Bottom,
726 Self::Bottom => Self::Center,
727 }
728 }
729}
730
731#[derive(Clone)]
732pub struct EditorSnapshot {
733 pub mode: EditorMode,
734 show_gutter: bool,
735 show_line_numbers: Option<bool>,
736 show_git_diff_gutter: Option<bool>,
737 show_code_actions: Option<bool>,
738 show_runnables: Option<bool>,
739 git_blame_gutter_max_author_length: Option<usize>,
740 pub display_snapshot: DisplaySnapshot,
741 pub placeholder_text: Option<Arc<str>>,
742 diff_map: DiffMapSnapshot,
743 is_focused: bool,
744 scroll_anchor: ScrollAnchor,
745 ongoing_scroll: OngoingScroll,
746 current_line_highlight: CurrentLineHighlight,
747 gutter_hovered: bool,
748}
749
750const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
751
752#[derive(Default, Debug, Clone, Copy)]
753pub struct GutterDimensions {
754 pub left_padding: Pixels,
755 pub right_padding: Pixels,
756 pub width: Pixels,
757 pub margin: Pixels,
758 pub git_blame_entries_width: Option<Pixels>,
759}
760
761impl GutterDimensions {
762 /// The full width of the space taken up by the gutter.
763 pub fn full_width(&self) -> Pixels {
764 self.margin + self.width
765 }
766
767 /// The width of the space reserved for the fold indicators,
768 /// use alongside 'justify_end' and `gutter_width` to
769 /// right align content with the line numbers
770 pub fn fold_area_width(&self) -> Pixels {
771 self.margin + self.right_padding
772 }
773}
774
775#[derive(Debug)]
776pub struct RemoteSelection {
777 pub replica_id: ReplicaId,
778 pub selection: Selection<Anchor>,
779 pub cursor_shape: CursorShape,
780 pub peer_id: PeerId,
781 pub line_mode: bool,
782 pub participant_index: Option<ParticipantIndex>,
783 pub user_name: Option<SharedString>,
784}
785
786#[derive(Clone, Debug)]
787struct SelectionHistoryEntry {
788 selections: Arc<[Selection<Anchor>]>,
789 select_next_state: Option<SelectNextState>,
790 select_prev_state: Option<SelectNextState>,
791 add_selections_state: Option<AddSelectionsState>,
792}
793
794enum SelectionHistoryMode {
795 Normal,
796 Undoing,
797 Redoing,
798}
799
800#[derive(Clone, PartialEq, Eq, Hash)]
801struct HoveredCursor {
802 replica_id: u16,
803 selection_id: usize,
804}
805
806impl Default for SelectionHistoryMode {
807 fn default() -> Self {
808 Self::Normal
809 }
810}
811
812#[derive(Default)]
813struct SelectionHistory {
814 #[allow(clippy::type_complexity)]
815 selections_by_transaction:
816 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
817 mode: SelectionHistoryMode,
818 undo_stack: VecDeque<SelectionHistoryEntry>,
819 redo_stack: VecDeque<SelectionHistoryEntry>,
820}
821
822impl SelectionHistory {
823 fn insert_transaction(
824 &mut self,
825 transaction_id: TransactionId,
826 selections: Arc<[Selection<Anchor>]>,
827 ) {
828 self.selections_by_transaction
829 .insert(transaction_id, (selections, None));
830 }
831
832 #[allow(clippy::type_complexity)]
833 fn transaction(
834 &self,
835 transaction_id: TransactionId,
836 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
837 self.selections_by_transaction.get(&transaction_id)
838 }
839
840 #[allow(clippy::type_complexity)]
841 fn transaction_mut(
842 &mut self,
843 transaction_id: TransactionId,
844 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
845 self.selections_by_transaction.get_mut(&transaction_id)
846 }
847
848 fn push(&mut self, entry: SelectionHistoryEntry) {
849 if !entry.selections.is_empty() {
850 match self.mode {
851 SelectionHistoryMode::Normal => {
852 self.push_undo(entry);
853 self.redo_stack.clear();
854 }
855 SelectionHistoryMode::Undoing => self.push_redo(entry),
856 SelectionHistoryMode::Redoing => self.push_undo(entry),
857 }
858 }
859 }
860
861 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
862 if self
863 .undo_stack
864 .back()
865 .map_or(true, |e| e.selections != entry.selections)
866 {
867 self.undo_stack.push_back(entry);
868 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
869 self.undo_stack.pop_front();
870 }
871 }
872 }
873
874 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
875 if self
876 .redo_stack
877 .back()
878 .map_or(true, |e| e.selections != entry.selections)
879 {
880 self.redo_stack.push_back(entry);
881 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
882 self.redo_stack.pop_front();
883 }
884 }
885 }
886}
887
888struct RowHighlight {
889 index: usize,
890 range: Range<Anchor>,
891 color: Hsla,
892 should_autoscroll: bool,
893}
894
895#[derive(Clone, Debug)]
896struct AddSelectionsState {
897 above: bool,
898 stack: Vec<usize>,
899}
900
901#[derive(Clone)]
902struct SelectNextState {
903 query: AhoCorasick,
904 wordwise: bool,
905 done: bool,
906}
907
908impl std::fmt::Debug for SelectNextState {
909 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
910 f.debug_struct(std::any::type_name::<Self>())
911 .field("wordwise", &self.wordwise)
912 .field("done", &self.done)
913 .finish()
914 }
915}
916
917#[derive(Debug)]
918struct AutocloseRegion {
919 selection_id: usize,
920 range: Range<Anchor>,
921 pair: BracketPair,
922}
923
924#[derive(Debug)]
925struct SnippetState {
926 ranges: Vec<Vec<Range<Anchor>>>,
927 active_index: usize,
928 choices: Vec<Option<Vec<String>>>,
929}
930
931#[doc(hidden)]
932pub struct RenameState {
933 pub range: Range<Anchor>,
934 pub old_name: Arc<str>,
935 pub editor: View<Editor>,
936 block_id: CustomBlockId,
937}
938
939struct InvalidationStack<T>(Vec<T>);
940
941struct RegisteredInlineCompletionProvider {
942 provider: Arc<dyn InlineCompletionProviderHandle>,
943 _subscription: Subscription,
944}
945
946#[derive(Debug)]
947struct ActiveDiagnosticGroup {
948 primary_range: Range<Anchor>,
949 primary_message: String,
950 group_id: usize,
951 blocks: HashMap<CustomBlockId, Diagnostic>,
952 is_valid: bool,
953}
954
955#[derive(Serialize, Deserialize, Clone, Debug)]
956pub struct ClipboardSelection {
957 pub len: usize,
958 pub is_entire_line: bool,
959 pub first_line_indent: u32,
960}
961
962#[derive(Debug)]
963pub(crate) struct NavigationData {
964 cursor_anchor: Anchor,
965 cursor_position: Point,
966 scroll_anchor: ScrollAnchor,
967 scroll_top_row: u32,
968}
969
970#[derive(Debug, Clone, Copy, PartialEq, Eq)]
971pub enum GotoDefinitionKind {
972 Symbol,
973 Declaration,
974 Type,
975 Implementation,
976}
977
978#[derive(Debug, Clone)]
979enum InlayHintRefreshReason {
980 Toggle(bool),
981 SettingsChange(InlayHintSettings),
982 NewLinesShown,
983 BufferEdited(HashSet<Arc<Language>>),
984 RefreshRequested,
985 ExcerptsRemoved(Vec<ExcerptId>),
986}
987
988impl InlayHintRefreshReason {
989 fn description(&self) -> &'static str {
990 match self {
991 Self::Toggle(_) => "toggle",
992 Self::SettingsChange(_) => "settings change",
993 Self::NewLinesShown => "new lines shown",
994 Self::BufferEdited(_) => "buffer edited",
995 Self::RefreshRequested => "refresh requested",
996 Self::ExcerptsRemoved(_) => "excerpts removed",
997 }
998 }
999}
1000
1001pub enum FormatTarget {
1002 Buffers,
1003 Ranges(Vec<Range<MultiBufferPoint>>),
1004}
1005
1006pub(crate) struct FocusedBlock {
1007 id: BlockId,
1008 focus_handle: WeakFocusHandle,
1009}
1010
1011#[derive(Clone)]
1012enum JumpData {
1013 MultiBufferRow {
1014 row: MultiBufferRow,
1015 line_offset_from_top: u32,
1016 },
1017 MultiBufferPoint {
1018 excerpt_id: ExcerptId,
1019 position: Point,
1020 anchor: text::Anchor,
1021 line_offset_from_top: u32,
1022 },
1023}
1024
1025impl Editor {
1026 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1027 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1028 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1029 Self::new(
1030 EditorMode::SingleLine { auto_width: false },
1031 buffer,
1032 None,
1033 false,
1034 cx,
1035 )
1036 }
1037
1038 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1039 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1040 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1041 Self::new(EditorMode::Full, buffer, None, false, cx)
1042 }
1043
1044 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1045 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1046 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1047 Self::new(
1048 EditorMode::SingleLine { auto_width: true },
1049 buffer,
1050 None,
1051 false,
1052 cx,
1053 )
1054 }
1055
1056 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1057 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1058 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1059 Self::new(
1060 EditorMode::AutoHeight { max_lines },
1061 buffer,
1062 None,
1063 false,
1064 cx,
1065 )
1066 }
1067
1068 pub fn for_buffer(
1069 buffer: Model<Buffer>,
1070 project: Option<Model<Project>>,
1071 cx: &mut ViewContext<Self>,
1072 ) -> Self {
1073 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(EditorMode::Full, buffer, project, false, cx)
1075 }
1076
1077 pub fn for_multibuffer(
1078 buffer: Model<MultiBuffer>,
1079 project: Option<Model<Project>>,
1080 show_excerpt_controls: bool,
1081 cx: &mut ViewContext<Self>,
1082 ) -> Self {
1083 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1084 }
1085
1086 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1087 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1088 let mut clone = Self::new(
1089 self.mode,
1090 self.buffer.clone(),
1091 self.project.clone(),
1092 show_excerpt_controls,
1093 cx,
1094 );
1095 self.display_map.update(cx, |display_map, cx| {
1096 let snapshot = display_map.snapshot(cx);
1097 clone.display_map.update(cx, |display_map, cx| {
1098 display_map.set_state(&snapshot, cx);
1099 });
1100 });
1101 clone.selections.clone_state(&self.selections);
1102 clone.scroll_manager.clone_state(&self.scroll_manager);
1103 clone.searchable = self.searchable;
1104 clone
1105 }
1106
1107 pub fn new(
1108 mode: EditorMode,
1109 buffer: Model<MultiBuffer>,
1110 project: Option<Model<Project>>,
1111 show_excerpt_controls: bool,
1112 cx: &mut ViewContext<Self>,
1113 ) -> Self {
1114 let style = cx.text_style();
1115 let font_size = style.font_size.to_pixels(cx.rem_size());
1116 let editor = cx.view().downgrade();
1117 let fold_placeholder = FoldPlaceholder {
1118 constrain_width: true,
1119 render: Arc::new(move |fold_id, fold_range, cx| {
1120 let editor = editor.clone();
1121 div()
1122 .id(fold_id)
1123 .bg(cx.theme().colors().ghost_element_background)
1124 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1125 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1126 .rounded_sm()
1127 .size_full()
1128 .cursor_pointer()
1129 .child("⋯")
1130 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1131 .on_click(move |_, cx| {
1132 editor
1133 .update(cx, |editor, cx| {
1134 editor.unfold_ranges(
1135 &[fold_range.start..fold_range.end],
1136 true,
1137 false,
1138 cx,
1139 );
1140 cx.stop_propagation();
1141 })
1142 .ok();
1143 })
1144 .into_any()
1145 }),
1146 merge_adjacent: true,
1147 ..Default::default()
1148 };
1149 let display_map = cx.new_model(|cx| {
1150 DisplayMap::new(
1151 buffer.clone(),
1152 style.font(),
1153 font_size,
1154 None,
1155 show_excerpt_controls,
1156 FILE_HEADER_HEIGHT,
1157 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1158 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1159 fold_placeholder,
1160 cx,
1161 )
1162 });
1163
1164 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1165
1166 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1167
1168 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1169 .then(|| language_settings::SoftWrap::None);
1170
1171 let mut project_subscriptions = Vec::new();
1172 if mode == EditorMode::Full {
1173 if let Some(project) = project.as_ref() {
1174 if buffer.read(cx).is_singleton() {
1175 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1176 cx.emit(EditorEvent::TitleChanged);
1177 }));
1178 }
1179 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1180 if let project::Event::RefreshInlayHints = event {
1181 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1182 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1183 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1184 let focus_handle = editor.focus_handle(cx);
1185 if focus_handle.is_focused(cx) {
1186 let snapshot = buffer.read(cx).snapshot();
1187 for (range, snippet) in snippet_edits {
1188 let editor_range =
1189 language::range_from_lsp(*range).to_offset(&snapshot);
1190 editor
1191 .insert_snippet(&[editor_range], snippet.clone(), cx)
1192 .ok();
1193 }
1194 }
1195 }
1196 }
1197 }));
1198 if let Some(task_inventory) = project
1199 .read(cx)
1200 .task_store()
1201 .read(cx)
1202 .task_inventory()
1203 .cloned()
1204 {
1205 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1206 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1207 }));
1208 }
1209 }
1210 }
1211
1212 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1213
1214 let inlay_hint_settings =
1215 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1216 let focus_handle = cx.focus_handle();
1217 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1218 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1219 .detach();
1220 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1221 .detach();
1222 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1223
1224 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1225 Some(false)
1226 } else {
1227 None
1228 };
1229
1230 let mut code_action_providers = Vec::new();
1231 if let Some(project) = project.clone() {
1232 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1233 code_action_providers.push(Rc::new(project) as Rc<_>);
1234 }
1235
1236 let mut this = Self {
1237 focus_handle,
1238 show_cursor_when_unfocused: false,
1239 last_focused_descendant: None,
1240 buffer: buffer.clone(),
1241 display_map: display_map.clone(),
1242 selections,
1243 scroll_manager: ScrollManager::new(cx),
1244 columnar_selection_tail: None,
1245 add_selections_state: None,
1246 select_next_state: None,
1247 select_prev_state: None,
1248 selection_history: Default::default(),
1249 autoclose_regions: Default::default(),
1250 snippet_stack: Default::default(),
1251 select_larger_syntax_node_stack: Vec::new(),
1252 ime_transaction: Default::default(),
1253 active_diagnostics: None,
1254 soft_wrap_mode_override,
1255 completion_provider: project.clone().map(|project| Box::new(project) as _),
1256 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1257 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1258 project,
1259 blink_manager: blink_manager.clone(),
1260 show_local_selections: true,
1261 show_scrollbars: true,
1262 mode,
1263 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1264 show_gutter: mode == EditorMode::Full,
1265 show_line_numbers: None,
1266 use_relative_line_numbers: None,
1267 show_git_diff_gutter: None,
1268 show_code_actions: None,
1269 show_runnables: None,
1270 show_wrap_guides: None,
1271 show_indent_guides,
1272 placeholder_text: None,
1273 highlight_order: 0,
1274 highlighted_rows: HashMap::default(),
1275 background_highlights: Default::default(),
1276 gutter_highlights: TreeMap::default(),
1277 scrollbar_marker_state: ScrollbarMarkerState::default(),
1278 active_indent_guides_state: ActiveIndentGuidesState::default(),
1279 nav_history: None,
1280 context_menu: RefCell::new(None),
1281 mouse_context_menu: None,
1282 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1283 completion_tasks: Default::default(),
1284 signature_help_state: SignatureHelpState::default(),
1285 auto_signature_help: None,
1286 find_all_references_task_sources: Vec::new(),
1287 next_completion_id: 0,
1288 next_inlay_id: 0,
1289 code_action_providers,
1290 available_code_actions: Default::default(),
1291 code_actions_task: Default::default(),
1292 document_highlights_task: Default::default(),
1293 linked_editing_range_task: Default::default(),
1294 pending_rename: Default::default(),
1295 searchable: true,
1296 cursor_shape: EditorSettings::get_global(cx)
1297 .cursor_shape
1298 .unwrap_or_default(),
1299 current_line_highlight: None,
1300 autoindent_mode: Some(AutoindentMode::EachLine),
1301 collapse_matches: false,
1302 workspace: None,
1303 input_enabled: true,
1304 use_modal_editing: mode == EditorMode::Full,
1305 read_only: false,
1306 use_autoclose: true,
1307 use_auto_surround: true,
1308 auto_replace_emoji_shortcode: false,
1309 leader_peer_id: None,
1310 remote_id: None,
1311 hover_state: Default::default(),
1312 hovered_link_state: Default::default(),
1313 inline_completion_provider: None,
1314 active_inline_completion: None,
1315 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1316 diff_map: DiffMap::default(),
1317 gutter_hovered: false,
1318 pixel_position_of_newest_cursor: None,
1319 last_bounds: None,
1320 expect_bounds_change: None,
1321 gutter_dimensions: GutterDimensions::default(),
1322 style: None,
1323 show_cursor_names: false,
1324 hovered_cursors: Default::default(),
1325 next_editor_action_id: EditorActionId::default(),
1326 editor_actions: Rc::default(),
1327 show_inline_completions_override: None,
1328 enable_inline_completions: true,
1329 custom_context_menu: None,
1330 show_git_blame_gutter: false,
1331 show_git_blame_inline: false,
1332 show_selection_menu: None,
1333 show_git_blame_inline_delay_task: None,
1334 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1335 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1336 .session
1337 .restore_unsaved_buffers,
1338 blame: None,
1339 blame_subscription: None,
1340 tasks: Default::default(),
1341 _subscriptions: vec![
1342 cx.observe(&buffer, Self::on_buffer_changed),
1343 cx.subscribe(&buffer, Self::on_buffer_event),
1344 cx.observe(&display_map, Self::on_display_map_changed),
1345 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1346 cx.observe_global::<SettingsStore>(Self::settings_changed),
1347 cx.observe_window_activation(|editor, cx| {
1348 let active = cx.is_window_active();
1349 editor.blink_manager.update(cx, |blink_manager, cx| {
1350 if active {
1351 blink_manager.enable(cx);
1352 } else {
1353 blink_manager.disable(cx);
1354 }
1355 });
1356 }),
1357 ],
1358 tasks_update_task: None,
1359 linked_edit_ranges: Default::default(),
1360 previous_search_ranges: None,
1361 breadcrumb_header: None,
1362 focused_block: None,
1363 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1364 addons: HashMap::default(),
1365 registered_buffers: HashMap::default(),
1366 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1367 toggle_fold_multiple_buffers: Task::ready(()),
1368 text_style_refinement: None,
1369 };
1370 this.tasks_update_task = Some(this.refresh_runnables(cx));
1371 this._subscriptions.extend(project_subscriptions);
1372
1373 this.end_selection(cx);
1374 this.scroll_manager.show_scrollbar(cx);
1375
1376 if mode == EditorMode::Full {
1377 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1378 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1379
1380 if this.git_blame_inline_enabled {
1381 this.git_blame_inline_enabled = true;
1382 this.start_git_blame_inline(false, cx);
1383 }
1384
1385 if let Some(buffer) = buffer.read(cx).as_singleton() {
1386 if let Some(project) = this.project.as_ref() {
1387 let lsp_store = project.read(cx).lsp_store();
1388 let handle = lsp_store.update(cx, |lsp_store, cx| {
1389 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1390 });
1391 this.registered_buffers
1392 .insert(buffer.read(cx).remote_id(), handle);
1393 }
1394 }
1395 }
1396
1397 this.report_editor_event("Editor Opened", None, cx);
1398 this
1399 }
1400
1401 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1402 self.mouse_context_menu
1403 .as_ref()
1404 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1405 }
1406
1407 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1408 let mut key_context = KeyContext::new_with_defaults();
1409 key_context.add("Editor");
1410 let mode = match self.mode {
1411 EditorMode::SingleLine { .. } => "single_line",
1412 EditorMode::AutoHeight { .. } => "auto_height",
1413 EditorMode::Full => "full",
1414 };
1415
1416 if EditorSettings::jupyter_enabled(cx) {
1417 key_context.add("jupyter");
1418 }
1419
1420 key_context.set("mode", mode);
1421 if self.pending_rename.is_some() {
1422 key_context.add("renaming");
1423 }
1424 match self.context_menu.borrow().as_ref() {
1425 Some(CodeContextMenu::Completions(_)) => {
1426 key_context.add("menu");
1427 key_context.add("showing_completions")
1428 }
1429 Some(CodeContextMenu::CodeActions(_)) => {
1430 key_context.add("menu");
1431 key_context.add("showing_code_actions")
1432 }
1433 None => {}
1434 }
1435
1436 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1437 if !self.focus_handle(cx).contains_focused(cx)
1438 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1439 {
1440 for addon in self.addons.values() {
1441 addon.extend_key_context(&mut key_context, cx)
1442 }
1443 }
1444
1445 if let Some(extension) = self
1446 .buffer
1447 .read(cx)
1448 .as_singleton()
1449 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1450 {
1451 key_context.set("extension", extension.to_string());
1452 }
1453
1454 if self.has_active_inline_completion() {
1455 key_context.add("copilot_suggestion");
1456 key_context.add("inline_completion");
1457 }
1458
1459 if !self
1460 .selections
1461 .disjoint
1462 .iter()
1463 .all(|selection| selection.start == selection.end)
1464 {
1465 key_context.add("selection");
1466 }
1467
1468 key_context
1469 }
1470
1471 pub fn new_file(
1472 workspace: &mut Workspace,
1473 _: &workspace::NewFile,
1474 cx: &mut ViewContext<Workspace>,
1475 ) {
1476 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1477 "Failed to create buffer",
1478 cx,
1479 |e, _| match e.error_code() {
1480 ErrorCode::RemoteUpgradeRequired => Some(format!(
1481 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1482 e.error_tag("required").unwrap_or("the latest version")
1483 )),
1484 _ => None,
1485 },
1486 );
1487 }
1488
1489 pub fn new_in_workspace(
1490 workspace: &mut Workspace,
1491 cx: &mut ViewContext<Workspace>,
1492 ) -> Task<Result<View<Editor>>> {
1493 let project = workspace.project().clone();
1494 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1495
1496 cx.spawn(|workspace, mut cx| async move {
1497 let buffer = create.await?;
1498 workspace.update(&mut cx, |workspace, cx| {
1499 let editor =
1500 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1501 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1502 editor
1503 })
1504 })
1505 }
1506
1507 fn new_file_vertical(
1508 workspace: &mut Workspace,
1509 _: &workspace::NewFileSplitVertical,
1510 cx: &mut ViewContext<Workspace>,
1511 ) {
1512 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1513 }
1514
1515 fn new_file_horizontal(
1516 workspace: &mut Workspace,
1517 _: &workspace::NewFileSplitHorizontal,
1518 cx: &mut ViewContext<Workspace>,
1519 ) {
1520 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1521 }
1522
1523 fn new_file_in_direction(
1524 workspace: &mut Workspace,
1525 direction: SplitDirection,
1526 cx: &mut ViewContext<Workspace>,
1527 ) {
1528 let project = workspace.project().clone();
1529 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1530
1531 cx.spawn(|workspace, mut cx| async move {
1532 let buffer = create.await?;
1533 workspace.update(&mut cx, move |workspace, cx| {
1534 workspace.split_item(
1535 direction,
1536 Box::new(
1537 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1538 ),
1539 cx,
1540 )
1541 })?;
1542 anyhow::Ok(())
1543 })
1544 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1545 ErrorCode::RemoteUpgradeRequired => Some(format!(
1546 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1547 e.error_tag("required").unwrap_or("the latest version")
1548 )),
1549 _ => None,
1550 });
1551 }
1552
1553 pub fn leader_peer_id(&self) -> Option<PeerId> {
1554 self.leader_peer_id
1555 }
1556
1557 pub fn buffer(&self) -> &Model<MultiBuffer> {
1558 &self.buffer
1559 }
1560
1561 pub fn workspace(&self) -> Option<View<Workspace>> {
1562 self.workspace.as_ref()?.0.upgrade()
1563 }
1564
1565 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1566 self.buffer().read(cx).title(cx)
1567 }
1568
1569 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1570 let git_blame_gutter_max_author_length = self
1571 .render_git_blame_gutter(cx)
1572 .then(|| {
1573 if let Some(blame) = self.blame.as_ref() {
1574 let max_author_length =
1575 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1576 Some(max_author_length)
1577 } else {
1578 None
1579 }
1580 })
1581 .flatten();
1582
1583 EditorSnapshot {
1584 mode: self.mode,
1585 show_gutter: self.show_gutter,
1586 show_line_numbers: self.show_line_numbers,
1587 show_git_diff_gutter: self.show_git_diff_gutter,
1588 show_code_actions: self.show_code_actions,
1589 show_runnables: self.show_runnables,
1590 git_blame_gutter_max_author_length,
1591 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1592 scroll_anchor: self.scroll_manager.anchor(),
1593 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1594 placeholder_text: self.placeholder_text.clone(),
1595 diff_map: self.diff_map.snapshot(),
1596 is_focused: self.focus_handle.is_focused(cx),
1597 current_line_highlight: self
1598 .current_line_highlight
1599 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1600 gutter_hovered: self.gutter_hovered,
1601 }
1602 }
1603
1604 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1605 self.buffer.read(cx).language_at(point, cx)
1606 }
1607
1608 pub fn file_at<T: ToOffset>(
1609 &self,
1610 point: T,
1611 cx: &AppContext,
1612 ) -> Option<Arc<dyn language::File>> {
1613 self.buffer.read(cx).read(cx).file_at(point).cloned()
1614 }
1615
1616 pub fn active_excerpt(
1617 &self,
1618 cx: &AppContext,
1619 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1620 self.buffer
1621 .read(cx)
1622 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1623 }
1624
1625 pub fn mode(&self) -> EditorMode {
1626 self.mode
1627 }
1628
1629 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1630 self.collaboration_hub.as_deref()
1631 }
1632
1633 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1634 self.collaboration_hub = Some(hub);
1635 }
1636
1637 pub fn set_custom_context_menu(
1638 &mut self,
1639 f: impl 'static
1640 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1641 ) {
1642 self.custom_context_menu = Some(Box::new(f))
1643 }
1644
1645 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1646 self.completion_provider = provider;
1647 }
1648
1649 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1650 self.semantics_provider.clone()
1651 }
1652
1653 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1654 self.semantics_provider = provider;
1655 }
1656
1657 pub fn set_inline_completion_provider<T>(
1658 &mut self,
1659 provider: Option<Model<T>>,
1660 cx: &mut ViewContext<Self>,
1661 ) where
1662 T: InlineCompletionProvider,
1663 {
1664 self.inline_completion_provider =
1665 provider.map(|provider| RegisteredInlineCompletionProvider {
1666 _subscription: cx.observe(&provider, |this, _, cx| {
1667 if this.focus_handle.is_focused(cx) {
1668 this.update_visible_inline_completion(cx);
1669 }
1670 }),
1671 provider: Arc::new(provider),
1672 });
1673 self.refresh_inline_completion(false, false, cx);
1674 }
1675
1676 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1677 self.placeholder_text.as_deref()
1678 }
1679
1680 pub fn set_placeholder_text(
1681 &mut self,
1682 placeholder_text: impl Into<Arc<str>>,
1683 cx: &mut ViewContext<Self>,
1684 ) {
1685 let placeholder_text = Some(placeholder_text.into());
1686 if self.placeholder_text != placeholder_text {
1687 self.placeholder_text = placeholder_text;
1688 cx.notify();
1689 }
1690 }
1691
1692 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1693 self.cursor_shape = cursor_shape;
1694
1695 // Disrupt blink for immediate user feedback that the cursor shape has changed
1696 self.blink_manager.update(cx, BlinkManager::show_cursor);
1697
1698 cx.notify();
1699 }
1700
1701 pub fn set_current_line_highlight(
1702 &mut self,
1703 current_line_highlight: Option<CurrentLineHighlight>,
1704 ) {
1705 self.current_line_highlight = current_line_highlight;
1706 }
1707
1708 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1709 self.collapse_matches = collapse_matches;
1710 }
1711
1712 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1713 let buffers = self.buffer.read(cx).all_buffers();
1714 let Some(lsp_store) = self.lsp_store(cx) else {
1715 return;
1716 };
1717 lsp_store.update(cx, |lsp_store, cx| {
1718 for buffer in buffers {
1719 self.registered_buffers
1720 .entry(buffer.read(cx).remote_id())
1721 .or_insert_with(|| {
1722 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1723 });
1724 }
1725 })
1726 }
1727
1728 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1729 if self.collapse_matches {
1730 return range.start..range.start;
1731 }
1732 range.clone()
1733 }
1734
1735 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1736 if self.display_map.read(cx).clip_at_line_ends != clip {
1737 self.display_map
1738 .update(cx, |map, _| map.clip_at_line_ends = clip);
1739 }
1740 }
1741
1742 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1743 self.input_enabled = input_enabled;
1744 }
1745
1746 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1747 self.enable_inline_completions = enabled;
1748 if !self.enable_inline_completions {
1749 self.take_active_inline_completion(cx);
1750 cx.notify();
1751 }
1752 }
1753
1754 pub fn set_autoindent(&mut self, autoindent: bool) {
1755 if autoindent {
1756 self.autoindent_mode = Some(AutoindentMode::EachLine);
1757 } else {
1758 self.autoindent_mode = None;
1759 }
1760 }
1761
1762 pub fn read_only(&self, cx: &AppContext) -> bool {
1763 self.read_only || self.buffer.read(cx).read_only()
1764 }
1765
1766 pub fn set_read_only(&mut self, read_only: bool) {
1767 self.read_only = read_only;
1768 }
1769
1770 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1771 self.use_autoclose = autoclose;
1772 }
1773
1774 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1775 self.use_auto_surround = auto_surround;
1776 }
1777
1778 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1779 self.auto_replace_emoji_shortcode = auto_replace;
1780 }
1781
1782 pub fn toggle_inline_completions(
1783 &mut self,
1784 _: &ToggleInlineCompletions,
1785 cx: &mut ViewContext<Self>,
1786 ) {
1787 if self.show_inline_completions_override.is_some() {
1788 self.set_show_inline_completions(None, cx);
1789 } else {
1790 let cursor = self.selections.newest_anchor().head();
1791 if let Some((buffer, cursor_buffer_position)) =
1792 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1793 {
1794 let show_inline_completions =
1795 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1796 self.set_show_inline_completions(Some(show_inline_completions), cx);
1797 }
1798 }
1799 }
1800
1801 pub fn set_show_inline_completions(
1802 &mut self,
1803 show_inline_completions: Option<bool>,
1804 cx: &mut ViewContext<Self>,
1805 ) {
1806 self.show_inline_completions_override = show_inline_completions;
1807 self.refresh_inline_completion(false, true, cx);
1808 }
1809
1810 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1811 let cursor = self.selections.newest_anchor().head();
1812 if let Some((buffer, buffer_position)) =
1813 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1814 {
1815 self.should_show_inline_completions(&buffer, buffer_position, cx)
1816 } else {
1817 false
1818 }
1819 }
1820
1821 fn should_show_inline_completions(
1822 &self,
1823 buffer: &Model<Buffer>,
1824 buffer_position: language::Anchor,
1825 cx: &AppContext,
1826 ) -> bool {
1827 if !self.snippet_stack.is_empty() {
1828 return false;
1829 }
1830
1831 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1832 return false;
1833 }
1834
1835 if let Some(provider) = self.inline_completion_provider() {
1836 if let Some(show_inline_completions) = self.show_inline_completions_override {
1837 show_inline_completions
1838 } else {
1839 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1840 }
1841 } else {
1842 false
1843 }
1844 }
1845
1846 fn inline_completions_disabled_in_scope(
1847 &self,
1848 buffer: &Model<Buffer>,
1849 buffer_position: language::Anchor,
1850 cx: &AppContext,
1851 ) -> bool {
1852 let snapshot = buffer.read(cx).snapshot();
1853 let settings = snapshot.settings_at(buffer_position, cx);
1854
1855 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1856 return false;
1857 };
1858
1859 scope.override_name().map_or(false, |scope_name| {
1860 settings
1861 .inline_completions_disabled_in
1862 .iter()
1863 .any(|s| s == scope_name)
1864 })
1865 }
1866
1867 pub fn set_use_modal_editing(&mut self, to: bool) {
1868 self.use_modal_editing = to;
1869 }
1870
1871 pub fn use_modal_editing(&self) -> bool {
1872 self.use_modal_editing
1873 }
1874
1875 fn selections_did_change(
1876 &mut self,
1877 local: bool,
1878 old_cursor_position: &Anchor,
1879 show_completions: bool,
1880 cx: &mut ViewContext<Self>,
1881 ) {
1882 cx.invalidate_character_coordinates();
1883
1884 // Copy selections to primary selection buffer
1885 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1886 if local {
1887 let selections = self.selections.all::<usize>(cx);
1888 let buffer_handle = self.buffer.read(cx).read(cx);
1889
1890 let mut text = String::new();
1891 for (index, selection) in selections.iter().enumerate() {
1892 let text_for_selection = buffer_handle
1893 .text_for_range(selection.start..selection.end)
1894 .collect::<String>();
1895
1896 text.push_str(&text_for_selection);
1897 if index != selections.len() - 1 {
1898 text.push('\n');
1899 }
1900 }
1901
1902 if !text.is_empty() {
1903 cx.write_to_primary(ClipboardItem::new_string(text));
1904 }
1905 }
1906
1907 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1908 self.buffer.update(cx, |buffer, cx| {
1909 buffer.set_active_selections(
1910 &self.selections.disjoint_anchors(),
1911 self.selections.line_mode,
1912 self.cursor_shape,
1913 cx,
1914 )
1915 });
1916 }
1917 let display_map = self
1918 .display_map
1919 .update(cx, |display_map, cx| display_map.snapshot(cx));
1920 let buffer = &display_map.buffer_snapshot;
1921 self.add_selections_state = None;
1922 self.select_next_state = None;
1923 self.select_prev_state = None;
1924 self.select_larger_syntax_node_stack.clear();
1925 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1926 self.snippet_stack
1927 .invalidate(&self.selections.disjoint_anchors(), buffer);
1928 self.take_rename(false, cx);
1929
1930 let new_cursor_position = self.selections.newest_anchor().head();
1931
1932 self.push_to_nav_history(
1933 *old_cursor_position,
1934 Some(new_cursor_position.to_point(buffer)),
1935 cx,
1936 );
1937
1938 if local {
1939 let new_cursor_position = self.selections.newest_anchor().head();
1940 let mut context_menu = self.context_menu.borrow_mut();
1941 let completion_menu = match context_menu.as_ref() {
1942 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1943 _ => {
1944 *context_menu = None;
1945 None
1946 }
1947 };
1948
1949 if let Some(completion_menu) = completion_menu {
1950 let cursor_position = new_cursor_position.to_offset(buffer);
1951 let (word_range, kind) =
1952 buffer.surrounding_word(completion_menu.initial_position, true);
1953 if kind == Some(CharKind::Word)
1954 && word_range.to_inclusive().contains(&cursor_position)
1955 {
1956 let mut completion_menu = completion_menu.clone();
1957 drop(context_menu);
1958
1959 let query = Self::completion_query(buffer, cursor_position);
1960 cx.spawn(move |this, mut cx| async move {
1961 completion_menu
1962 .filter(query.as_deref(), cx.background_executor().clone())
1963 .await;
1964
1965 this.update(&mut cx, |this, cx| {
1966 let mut context_menu = this.context_menu.borrow_mut();
1967 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1968 else {
1969 return;
1970 };
1971
1972 if menu.id > completion_menu.id {
1973 return;
1974 }
1975
1976 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1977 drop(context_menu);
1978 cx.notify();
1979 })
1980 })
1981 .detach();
1982
1983 if show_completions {
1984 self.show_completions(&ShowCompletions { trigger: None }, cx);
1985 }
1986 } else {
1987 drop(context_menu);
1988 self.hide_context_menu(cx);
1989 }
1990 } else {
1991 drop(context_menu);
1992 }
1993
1994 hide_hover(self, cx);
1995
1996 if old_cursor_position.to_display_point(&display_map).row()
1997 != new_cursor_position.to_display_point(&display_map).row()
1998 {
1999 self.available_code_actions.take();
2000 }
2001 self.refresh_code_actions(cx);
2002 self.refresh_document_highlights(cx);
2003 refresh_matching_bracket_highlights(self, cx);
2004 self.update_visible_inline_completion(cx);
2005 linked_editing_ranges::refresh_linked_ranges(self, cx);
2006 if self.git_blame_inline_enabled {
2007 self.start_inline_blame_timer(cx);
2008 }
2009 }
2010
2011 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2012 cx.emit(EditorEvent::SelectionsChanged { local });
2013
2014 if self.selections.disjoint_anchors().len() == 1 {
2015 cx.emit(SearchEvent::ActiveMatchChanged)
2016 }
2017 cx.notify();
2018 }
2019
2020 pub fn change_selections<R>(
2021 &mut self,
2022 autoscroll: Option<Autoscroll>,
2023 cx: &mut ViewContext<Self>,
2024 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2025 ) -> R {
2026 self.change_selections_inner(autoscroll, true, cx, change)
2027 }
2028
2029 pub fn change_selections_inner<R>(
2030 &mut self,
2031 autoscroll: Option<Autoscroll>,
2032 request_completions: bool,
2033 cx: &mut ViewContext<Self>,
2034 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2035 ) -> R {
2036 let old_cursor_position = self.selections.newest_anchor().head();
2037 self.push_to_selection_history();
2038
2039 let (changed, result) = self.selections.change_with(cx, change);
2040
2041 if changed {
2042 if let Some(autoscroll) = autoscroll {
2043 self.request_autoscroll(autoscroll, cx);
2044 }
2045 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2046
2047 if self.should_open_signature_help_automatically(
2048 &old_cursor_position,
2049 self.signature_help_state.backspace_pressed(),
2050 cx,
2051 ) {
2052 self.show_signature_help(&ShowSignatureHelp, cx);
2053 }
2054 self.signature_help_state.set_backspace_pressed(false);
2055 }
2056
2057 result
2058 }
2059
2060 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2061 where
2062 I: IntoIterator<Item = (Range<S>, T)>,
2063 S: ToOffset,
2064 T: Into<Arc<str>>,
2065 {
2066 if self.read_only(cx) {
2067 return;
2068 }
2069
2070 self.buffer
2071 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2072 }
2073
2074 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2075 where
2076 I: IntoIterator<Item = (Range<S>, T)>,
2077 S: ToOffset,
2078 T: Into<Arc<str>>,
2079 {
2080 if self.read_only(cx) {
2081 return;
2082 }
2083
2084 self.buffer.update(cx, |buffer, cx| {
2085 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2086 });
2087 }
2088
2089 pub fn edit_with_block_indent<I, S, T>(
2090 &mut self,
2091 edits: I,
2092 original_indent_columns: Vec<u32>,
2093 cx: &mut ViewContext<Self>,
2094 ) where
2095 I: IntoIterator<Item = (Range<S>, T)>,
2096 S: ToOffset,
2097 T: Into<Arc<str>>,
2098 {
2099 if self.read_only(cx) {
2100 return;
2101 }
2102
2103 self.buffer.update(cx, |buffer, cx| {
2104 buffer.edit(
2105 edits,
2106 Some(AutoindentMode::Block {
2107 original_indent_columns,
2108 }),
2109 cx,
2110 )
2111 });
2112 }
2113
2114 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2115 self.hide_context_menu(cx);
2116
2117 match phase {
2118 SelectPhase::Begin {
2119 position,
2120 add,
2121 click_count,
2122 } => self.begin_selection(position, add, click_count, cx),
2123 SelectPhase::BeginColumnar {
2124 position,
2125 goal_column,
2126 reset,
2127 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2128 SelectPhase::Extend {
2129 position,
2130 click_count,
2131 } => self.extend_selection(position, click_count, cx),
2132 SelectPhase::Update {
2133 position,
2134 goal_column,
2135 scroll_delta,
2136 } => self.update_selection(position, goal_column, scroll_delta, cx),
2137 SelectPhase::End => self.end_selection(cx),
2138 }
2139 }
2140
2141 fn extend_selection(
2142 &mut self,
2143 position: DisplayPoint,
2144 click_count: usize,
2145 cx: &mut ViewContext<Self>,
2146 ) {
2147 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2148 let tail = self.selections.newest::<usize>(cx).tail();
2149 self.begin_selection(position, false, click_count, cx);
2150
2151 let position = position.to_offset(&display_map, Bias::Left);
2152 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2153
2154 let mut pending_selection = self
2155 .selections
2156 .pending_anchor()
2157 .expect("extend_selection not called with pending selection");
2158 if position >= tail {
2159 pending_selection.start = tail_anchor;
2160 } else {
2161 pending_selection.end = tail_anchor;
2162 pending_selection.reversed = true;
2163 }
2164
2165 let mut pending_mode = self.selections.pending_mode().unwrap();
2166 match &mut pending_mode {
2167 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2168 _ => {}
2169 }
2170
2171 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2172 s.set_pending(pending_selection, pending_mode)
2173 });
2174 }
2175
2176 fn begin_selection(
2177 &mut self,
2178 position: DisplayPoint,
2179 add: bool,
2180 click_count: usize,
2181 cx: &mut ViewContext<Self>,
2182 ) {
2183 if !self.focus_handle.is_focused(cx) {
2184 self.last_focused_descendant = None;
2185 cx.focus(&self.focus_handle);
2186 }
2187
2188 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2189 let buffer = &display_map.buffer_snapshot;
2190 let newest_selection = self.selections.newest_anchor().clone();
2191 let position = display_map.clip_point(position, Bias::Left);
2192
2193 let start;
2194 let end;
2195 let mode;
2196 let mut auto_scroll;
2197 match click_count {
2198 1 => {
2199 start = buffer.anchor_before(position.to_point(&display_map));
2200 end = start;
2201 mode = SelectMode::Character;
2202 auto_scroll = true;
2203 }
2204 2 => {
2205 let range = movement::surrounding_word(&display_map, position);
2206 start = buffer.anchor_before(range.start.to_point(&display_map));
2207 end = buffer.anchor_before(range.end.to_point(&display_map));
2208 mode = SelectMode::Word(start..end);
2209 auto_scroll = true;
2210 }
2211 3 => {
2212 let position = display_map
2213 .clip_point(position, Bias::Left)
2214 .to_point(&display_map);
2215 let line_start = display_map.prev_line_boundary(position).0;
2216 let next_line_start = buffer.clip_point(
2217 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2218 Bias::Left,
2219 );
2220 start = buffer.anchor_before(line_start);
2221 end = buffer.anchor_before(next_line_start);
2222 mode = SelectMode::Line(start..end);
2223 auto_scroll = true;
2224 }
2225 _ => {
2226 start = buffer.anchor_before(0);
2227 end = buffer.anchor_before(buffer.len());
2228 mode = SelectMode::All;
2229 auto_scroll = false;
2230 }
2231 }
2232 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2233
2234 let point_to_delete: Option<usize> = {
2235 let selected_points: Vec<Selection<Point>> =
2236 self.selections.disjoint_in_range(start..end, cx);
2237
2238 if !add || click_count > 1 {
2239 None
2240 } else if !selected_points.is_empty() {
2241 Some(selected_points[0].id)
2242 } else {
2243 let clicked_point_already_selected =
2244 self.selections.disjoint.iter().find(|selection| {
2245 selection.start.to_point(buffer) == start.to_point(buffer)
2246 || selection.end.to_point(buffer) == end.to_point(buffer)
2247 });
2248
2249 clicked_point_already_selected.map(|selection| selection.id)
2250 }
2251 };
2252
2253 let selections_count = self.selections.count();
2254
2255 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2256 if let Some(point_to_delete) = point_to_delete {
2257 s.delete(point_to_delete);
2258
2259 if selections_count == 1 {
2260 s.set_pending_anchor_range(start..end, mode);
2261 }
2262 } else {
2263 if !add {
2264 s.clear_disjoint();
2265 } else if click_count > 1 {
2266 s.delete(newest_selection.id)
2267 }
2268
2269 s.set_pending_anchor_range(start..end, mode);
2270 }
2271 });
2272 }
2273
2274 fn begin_columnar_selection(
2275 &mut self,
2276 position: DisplayPoint,
2277 goal_column: u32,
2278 reset: bool,
2279 cx: &mut ViewContext<Self>,
2280 ) {
2281 if !self.focus_handle.is_focused(cx) {
2282 self.last_focused_descendant = None;
2283 cx.focus(&self.focus_handle);
2284 }
2285
2286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2287
2288 if reset {
2289 let pointer_position = display_map
2290 .buffer_snapshot
2291 .anchor_before(position.to_point(&display_map));
2292
2293 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2294 s.clear_disjoint();
2295 s.set_pending_anchor_range(
2296 pointer_position..pointer_position,
2297 SelectMode::Character,
2298 );
2299 });
2300 }
2301
2302 let tail = self.selections.newest::<Point>(cx).tail();
2303 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2304
2305 if !reset {
2306 self.select_columns(
2307 tail.to_display_point(&display_map),
2308 position,
2309 goal_column,
2310 &display_map,
2311 cx,
2312 );
2313 }
2314 }
2315
2316 fn update_selection(
2317 &mut self,
2318 position: DisplayPoint,
2319 goal_column: u32,
2320 scroll_delta: gpui::Point<f32>,
2321 cx: &mut ViewContext<Self>,
2322 ) {
2323 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2324
2325 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2326 let tail = tail.to_display_point(&display_map);
2327 self.select_columns(tail, position, goal_column, &display_map, cx);
2328 } else if let Some(mut pending) = self.selections.pending_anchor() {
2329 let buffer = self.buffer.read(cx).snapshot(cx);
2330 let head;
2331 let tail;
2332 let mode = self.selections.pending_mode().unwrap();
2333 match &mode {
2334 SelectMode::Character => {
2335 head = position.to_point(&display_map);
2336 tail = pending.tail().to_point(&buffer);
2337 }
2338 SelectMode::Word(original_range) => {
2339 let original_display_range = original_range.start.to_display_point(&display_map)
2340 ..original_range.end.to_display_point(&display_map);
2341 let original_buffer_range = original_display_range.start.to_point(&display_map)
2342 ..original_display_range.end.to_point(&display_map);
2343 if movement::is_inside_word(&display_map, position)
2344 || original_display_range.contains(&position)
2345 {
2346 let word_range = movement::surrounding_word(&display_map, position);
2347 if word_range.start < original_display_range.start {
2348 head = word_range.start.to_point(&display_map);
2349 } else {
2350 head = word_range.end.to_point(&display_map);
2351 }
2352 } else {
2353 head = position.to_point(&display_map);
2354 }
2355
2356 if head <= original_buffer_range.start {
2357 tail = original_buffer_range.end;
2358 } else {
2359 tail = original_buffer_range.start;
2360 }
2361 }
2362 SelectMode::Line(original_range) => {
2363 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2364
2365 let position = display_map
2366 .clip_point(position, Bias::Left)
2367 .to_point(&display_map);
2368 let line_start = display_map.prev_line_boundary(position).0;
2369 let next_line_start = buffer.clip_point(
2370 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2371 Bias::Left,
2372 );
2373
2374 if line_start < original_range.start {
2375 head = line_start
2376 } else {
2377 head = next_line_start
2378 }
2379
2380 if head <= original_range.start {
2381 tail = original_range.end;
2382 } else {
2383 tail = original_range.start;
2384 }
2385 }
2386 SelectMode::All => {
2387 return;
2388 }
2389 };
2390
2391 if head < tail {
2392 pending.start = buffer.anchor_before(head);
2393 pending.end = buffer.anchor_before(tail);
2394 pending.reversed = true;
2395 } else {
2396 pending.start = buffer.anchor_before(tail);
2397 pending.end = buffer.anchor_before(head);
2398 pending.reversed = false;
2399 }
2400
2401 self.change_selections(None, cx, |s| {
2402 s.set_pending(pending, mode);
2403 });
2404 } else {
2405 log::error!("update_selection dispatched with no pending selection");
2406 return;
2407 }
2408
2409 self.apply_scroll_delta(scroll_delta, cx);
2410 cx.notify();
2411 }
2412
2413 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2414 self.columnar_selection_tail.take();
2415 if self.selections.pending_anchor().is_some() {
2416 let selections = self.selections.all::<usize>(cx);
2417 self.change_selections(None, cx, |s| {
2418 s.select(selections);
2419 s.clear_pending();
2420 });
2421 }
2422 }
2423
2424 fn select_columns(
2425 &mut self,
2426 tail: DisplayPoint,
2427 head: DisplayPoint,
2428 goal_column: u32,
2429 display_map: &DisplaySnapshot,
2430 cx: &mut ViewContext<Self>,
2431 ) {
2432 let start_row = cmp::min(tail.row(), head.row());
2433 let end_row = cmp::max(tail.row(), head.row());
2434 let start_column = cmp::min(tail.column(), goal_column);
2435 let end_column = cmp::max(tail.column(), goal_column);
2436 let reversed = start_column < tail.column();
2437
2438 let selection_ranges = (start_row.0..=end_row.0)
2439 .map(DisplayRow)
2440 .filter_map(|row| {
2441 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2442 let start = display_map
2443 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2444 .to_point(display_map);
2445 let end = display_map
2446 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2447 .to_point(display_map);
2448 if reversed {
2449 Some(end..start)
2450 } else {
2451 Some(start..end)
2452 }
2453 } else {
2454 None
2455 }
2456 })
2457 .collect::<Vec<_>>();
2458
2459 self.change_selections(None, cx, |s| {
2460 s.select_ranges(selection_ranges);
2461 });
2462 cx.notify();
2463 }
2464
2465 pub fn has_pending_nonempty_selection(&self) -> bool {
2466 let pending_nonempty_selection = match self.selections.pending_anchor() {
2467 Some(Selection { start, end, .. }) => start != end,
2468 None => false,
2469 };
2470
2471 pending_nonempty_selection
2472 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2473 }
2474
2475 pub fn has_pending_selection(&self) -> bool {
2476 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2477 }
2478
2479 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2480 if self.clear_expanded_diff_hunks(cx) {
2481 cx.notify();
2482 return;
2483 }
2484 if self.dismiss_menus_and_popups(true, cx) {
2485 return;
2486 }
2487
2488 if self.mode == EditorMode::Full
2489 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2490 {
2491 return;
2492 }
2493
2494 cx.propagate();
2495 }
2496
2497 pub fn dismiss_menus_and_popups(
2498 &mut self,
2499 should_report_inline_completion_event: bool,
2500 cx: &mut ViewContext<Self>,
2501 ) -> bool {
2502 if self.take_rename(false, cx).is_some() {
2503 return true;
2504 }
2505
2506 if hide_hover(self, cx) {
2507 return true;
2508 }
2509
2510 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2511 return true;
2512 }
2513
2514 if self.hide_context_menu(cx).is_some() {
2515 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2516 self.update_visible_inline_completion(cx);
2517 }
2518 return true;
2519 }
2520
2521 if self.mouse_context_menu.take().is_some() {
2522 return true;
2523 }
2524
2525 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2526 return true;
2527 }
2528
2529 if self.snippet_stack.pop().is_some() {
2530 return true;
2531 }
2532
2533 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2534 self.dismiss_diagnostics(cx);
2535 return true;
2536 }
2537
2538 false
2539 }
2540
2541 fn linked_editing_ranges_for(
2542 &self,
2543 selection: Range<text::Anchor>,
2544 cx: &AppContext,
2545 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2546 if self.linked_edit_ranges.is_empty() {
2547 return None;
2548 }
2549 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2550 selection.end.buffer_id.and_then(|end_buffer_id| {
2551 if selection.start.buffer_id != Some(end_buffer_id) {
2552 return None;
2553 }
2554 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2555 let snapshot = buffer.read(cx).snapshot();
2556 self.linked_edit_ranges
2557 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2558 .map(|ranges| (ranges, snapshot, buffer))
2559 })?;
2560 use text::ToOffset as TO;
2561 // find offset from the start of current range to current cursor position
2562 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2563
2564 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2565 let start_difference = start_offset - start_byte_offset;
2566 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2567 let end_difference = end_offset - start_byte_offset;
2568 // Current range has associated linked ranges.
2569 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2570 for range in linked_ranges.iter() {
2571 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2572 let end_offset = start_offset + end_difference;
2573 let start_offset = start_offset + start_difference;
2574 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2575 continue;
2576 }
2577 if self.selections.disjoint_anchor_ranges().any(|s| {
2578 if s.start.buffer_id != selection.start.buffer_id
2579 || s.end.buffer_id != selection.end.buffer_id
2580 {
2581 return false;
2582 }
2583 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2584 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2585 }) {
2586 continue;
2587 }
2588 let start = buffer_snapshot.anchor_after(start_offset);
2589 let end = buffer_snapshot.anchor_after(end_offset);
2590 linked_edits
2591 .entry(buffer.clone())
2592 .or_default()
2593 .push(start..end);
2594 }
2595 Some(linked_edits)
2596 }
2597
2598 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2599 let text: Arc<str> = text.into();
2600
2601 if self.read_only(cx) {
2602 return;
2603 }
2604
2605 let selections = self.selections.all_adjusted(cx);
2606 let mut bracket_inserted = false;
2607 let mut edits = Vec::new();
2608 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2609 let mut new_selections = Vec::with_capacity(selections.len());
2610 let mut new_autoclose_regions = Vec::new();
2611 let snapshot = self.buffer.read(cx).read(cx);
2612
2613 for (selection, autoclose_region) in
2614 self.selections_with_autoclose_regions(selections, &snapshot)
2615 {
2616 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2617 // Determine if the inserted text matches the opening or closing
2618 // bracket of any of this language's bracket pairs.
2619 let mut bracket_pair = None;
2620 let mut is_bracket_pair_start = false;
2621 let mut is_bracket_pair_end = false;
2622 if !text.is_empty() {
2623 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2624 // and they are removing the character that triggered IME popup.
2625 for (pair, enabled) in scope.brackets() {
2626 if !pair.close && !pair.surround {
2627 continue;
2628 }
2629
2630 if enabled && pair.start.ends_with(text.as_ref()) {
2631 let prefix_len = pair.start.len() - text.len();
2632 let preceding_text_matches_prefix = prefix_len == 0
2633 || (selection.start.column >= (prefix_len as u32)
2634 && snapshot.contains_str_at(
2635 Point::new(
2636 selection.start.row,
2637 selection.start.column - (prefix_len as u32),
2638 ),
2639 &pair.start[..prefix_len],
2640 ));
2641 if preceding_text_matches_prefix {
2642 bracket_pair = Some(pair.clone());
2643 is_bracket_pair_start = true;
2644 break;
2645 }
2646 }
2647 if pair.end.as_str() == text.as_ref() {
2648 bracket_pair = Some(pair.clone());
2649 is_bracket_pair_end = true;
2650 break;
2651 }
2652 }
2653 }
2654
2655 if let Some(bracket_pair) = bracket_pair {
2656 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2657 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2658 let auto_surround =
2659 self.use_auto_surround && snapshot_settings.use_auto_surround;
2660 if selection.is_empty() {
2661 if is_bracket_pair_start {
2662 // If the inserted text is a suffix of an opening bracket and the
2663 // selection is preceded by the rest of the opening bracket, then
2664 // insert the closing bracket.
2665 let following_text_allows_autoclose = snapshot
2666 .chars_at(selection.start)
2667 .next()
2668 .map_or(true, |c| scope.should_autoclose_before(c));
2669
2670 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2671 && bracket_pair.start.len() == 1
2672 {
2673 let target = bracket_pair.start.chars().next().unwrap();
2674 let current_line_count = snapshot
2675 .reversed_chars_at(selection.start)
2676 .take_while(|&c| c != '\n')
2677 .filter(|&c| c == target)
2678 .count();
2679 current_line_count % 2 == 1
2680 } else {
2681 false
2682 };
2683
2684 if autoclose
2685 && bracket_pair.close
2686 && following_text_allows_autoclose
2687 && !is_closing_quote
2688 {
2689 let anchor = snapshot.anchor_before(selection.end);
2690 new_selections.push((selection.map(|_| anchor), text.len()));
2691 new_autoclose_regions.push((
2692 anchor,
2693 text.len(),
2694 selection.id,
2695 bracket_pair.clone(),
2696 ));
2697 edits.push((
2698 selection.range(),
2699 format!("{}{}", text, bracket_pair.end).into(),
2700 ));
2701 bracket_inserted = true;
2702 continue;
2703 }
2704 }
2705
2706 if let Some(region) = autoclose_region {
2707 // If the selection is followed by an auto-inserted closing bracket,
2708 // then don't insert that closing bracket again; just move the selection
2709 // past the closing bracket.
2710 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2711 && text.as_ref() == region.pair.end.as_str();
2712 if should_skip {
2713 let anchor = snapshot.anchor_after(selection.end);
2714 new_selections
2715 .push((selection.map(|_| anchor), region.pair.end.len()));
2716 continue;
2717 }
2718 }
2719
2720 let always_treat_brackets_as_autoclosed = snapshot
2721 .settings_at(selection.start, cx)
2722 .always_treat_brackets_as_autoclosed;
2723 if always_treat_brackets_as_autoclosed
2724 && is_bracket_pair_end
2725 && snapshot.contains_str_at(selection.end, text.as_ref())
2726 {
2727 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2728 // and the inserted text is a closing bracket and the selection is followed
2729 // by the closing bracket then move the selection past the closing bracket.
2730 let anchor = snapshot.anchor_after(selection.end);
2731 new_selections.push((selection.map(|_| anchor), text.len()));
2732 continue;
2733 }
2734 }
2735 // If an opening bracket is 1 character long and is typed while
2736 // text is selected, then surround that text with the bracket pair.
2737 else if auto_surround
2738 && bracket_pair.surround
2739 && is_bracket_pair_start
2740 && bracket_pair.start.chars().count() == 1
2741 {
2742 edits.push((selection.start..selection.start, text.clone()));
2743 edits.push((
2744 selection.end..selection.end,
2745 bracket_pair.end.as_str().into(),
2746 ));
2747 bracket_inserted = true;
2748 new_selections.push((
2749 Selection {
2750 id: selection.id,
2751 start: snapshot.anchor_after(selection.start),
2752 end: snapshot.anchor_before(selection.end),
2753 reversed: selection.reversed,
2754 goal: selection.goal,
2755 },
2756 0,
2757 ));
2758 continue;
2759 }
2760 }
2761 }
2762
2763 if self.auto_replace_emoji_shortcode
2764 && selection.is_empty()
2765 && text.as_ref().ends_with(':')
2766 {
2767 if let Some(possible_emoji_short_code) =
2768 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2769 {
2770 if !possible_emoji_short_code.is_empty() {
2771 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2772 let emoji_shortcode_start = Point::new(
2773 selection.start.row,
2774 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2775 );
2776
2777 // Remove shortcode from buffer
2778 edits.push((
2779 emoji_shortcode_start..selection.start,
2780 "".to_string().into(),
2781 ));
2782 new_selections.push((
2783 Selection {
2784 id: selection.id,
2785 start: snapshot.anchor_after(emoji_shortcode_start),
2786 end: snapshot.anchor_before(selection.start),
2787 reversed: selection.reversed,
2788 goal: selection.goal,
2789 },
2790 0,
2791 ));
2792
2793 // Insert emoji
2794 let selection_start_anchor = snapshot.anchor_after(selection.start);
2795 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2796 edits.push((selection.start..selection.end, emoji.to_string().into()));
2797
2798 continue;
2799 }
2800 }
2801 }
2802 }
2803
2804 // If not handling any auto-close operation, then just replace the selected
2805 // text with the given input and move the selection to the end of the
2806 // newly inserted text.
2807 let anchor = snapshot.anchor_after(selection.end);
2808 if !self.linked_edit_ranges.is_empty() {
2809 let start_anchor = snapshot.anchor_before(selection.start);
2810
2811 let is_word_char = text.chars().next().map_or(true, |char| {
2812 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2813 classifier.is_word(char)
2814 });
2815
2816 if is_word_char {
2817 if let Some(ranges) = self
2818 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2819 {
2820 for (buffer, edits) in ranges {
2821 linked_edits
2822 .entry(buffer.clone())
2823 .or_default()
2824 .extend(edits.into_iter().map(|range| (range, text.clone())));
2825 }
2826 }
2827 }
2828 }
2829
2830 new_selections.push((selection.map(|_| anchor), 0));
2831 edits.push((selection.start..selection.end, text.clone()));
2832 }
2833
2834 drop(snapshot);
2835
2836 self.transact(cx, |this, cx| {
2837 this.buffer.update(cx, |buffer, cx| {
2838 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2839 });
2840 for (buffer, edits) in linked_edits {
2841 buffer.update(cx, |buffer, cx| {
2842 let snapshot = buffer.snapshot();
2843 let edits = edits
2844 .into_iter()
2845 .map(|(range, text)| {
2846 use text::ToPoint as TP;
2847 let end_point = TP::to_point(&range.end, &snapshot);
2848 let start_point = TP::to_point(&range.start, &snapshot);
2849 (start_point..end_point, text)
2850 })
2851 .sorted_by_key(|(range, _)| range.start)
2852 .collect::<Vec<_>>();
2853 buffer.edit(edits, None, cx);
2854 })
2855 }
2856 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2857 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2858 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2859 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2860 .zip(new_selection_deltas)
2861 .map(|(selection, delta)| Selection {
2862 id: selection.id,
2863 start: selection.start + delta,
2864 end: selection.end + delta,
2865 reversed: selection.reversed,
2866 goal: SelectionGoal::None,
2867 })
2868 .collect::<Vec<_>>();
2869
2870 let mut i = 0;
2871 for (position, delta, selection_id, pair) in new_autoclose_regions {
2872 let position = position.to_offset(&map.buffer_snapshot) + delta;
2873 let start = map.buffer_snapshot.anchor_before(position);
2874 let end = map.buffer_snapshot.anchor_after(position);
2875 while let Some(existing_state) = this.autoclose_regions.get(i) {
2876 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2877 Ordering::Less => i += 1,
2878 Ordering::Greater => break,
2879 Ordering::Equal => {
2880 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2881 Ordering::Less => i += 1,
2882 Ordering::Equal => break,
2883 Ordering::Greater => break,
2884 }
2885 }
2886 }
2887 }
2888 this.autoclose_regions.insert(
2889 i,
2890 AutocloseRegion {
2891 selection_id,
2892 range: start..end,
2893 pair,
2894 },
2895 );
2896 }
2897
2898 let had_active_inline_completion = this.has_active_inline_completion();
2899 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2900 s.select(new_selections)
2901 });
2902
2903 if !bracket_inserted {
2904 if let Some(on_type_format_task) =
2905 this.trigger_on_type_formatting(text.to_string(), cx)
2906 {
2907 on_type_format_task.detach_and_log_err(cx);
2908 }
2909 }
2910
2911 let editor_settings = EditorSettings::get_global(cx);
2912 if bracket_inserted
2913 && (editor_settings.auto_signature_help
2914 || editor_settings.show_signature_help_after_edits)
2915 {
2916 this.show_signature_help(&ShowSignatureHelp, cx);
2917 }
2918
2919 let trigger_in_words =
2920 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2921 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2922 linked_editing_ranges::refresh_linked_ranges(this, cx);
2923 this.refresh_inline_completion(true, false, cx);
2924 });
2925 }
2926
2927 fn find_possible_emoji_shortcode_at_position(
2928 snapshot: &MultiBufferSnapshot,
2929 position: Point,
2930 ) -> Option<String> {
2931 let mut chars = Vec::new();
2932 let mut found_colon = false;
2933 for char in snapshot.reversed_chars_at(position).take(100) {
2934 // Found a possible emoji shortcode in the middle of the buffer
2935 if found_colon {
2936 if char.is_whitespace() {
2937 chars.reverse();
2938 return Some(chars.iter().collect());
2939 }
2940 // If the previous character is not a whitespace, we are in the middle of a word
2941 // and we only want to complete the shortcode if the word is made up of other emojis
2942 let mut containing_word = String::new();
2943 for ch in snapshot
2944 .reversed_chars_at(position)
2945 .skip(chars.len() + 1)
2946 .take(100)
2947 {
2948 if ch.is_whitespace() {
2949 break;
2950 }
2951 containing_word.push(ch);
2952 }
2953 let containing_word = containing_word.chars().rev().collect::<String>();
2954 if util::word_consists_of_emojis(containing_word.as_str()) {
2955 chars.reverse();
2956 return Some(chars.iter().collect());
2957 }
2958 }
2959
2960 if char.is_whitespace() || !char.is_ascii() {
2961 return None;
2962 }
2963 if char == ':' {
2964 found_colon = true;
2965 } else {
2966 chars.push(char);
2967 }
2968 }
2969 // Found a possible emoji shortcode at the beginning of the buffer
2970 chars.reverse();
2971 Some(chars.iter().collect())
2972 }
2973
2974 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2975 self.transact(cx, |this, cx| {
2976 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2977 let selections = this.selections.all::<usize>(cx);
2978 let multi_buffer = this.buffer.read(cx);
2979 let buffer = multi_buffer.snapshot(cx);
2980 selections
2981 .iter()
2982 .map(|selection| {
2983 let start_point = selection.start.to_point(&buffer);
2984 let mut indent =
2985 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2986 indent.len = cmp::min(indent.len, start_point.column);
2987 let start = selection.start;
2988 let end = selection.end;
2989 let selection_is_empty = start == end;
2990 let language_scope = buffer.language_scope_at(start);
2991 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2992 &language_scope
2993 {
2994 let leading_whitespace_len = buffer
2995 .reversed_chars_at(start)
2996 .take_while(|c| c.is_whitespace() && *c != '\n')
2997 .map(|c| c.len_utf8())
2998 .sum::<usize>();
2999
3000 let trailing_whitespace_len = buffer
3001 .chars_at(end)
3002 .take_while(|c| c.is_whitespace() && *c != '\n')
3003 .map(|c| c.len_utf8())
3004 .sum::<usize>();
3005
3006 let insert_extra_newline =
3007 language.brackets().any(|(pair, enabled)| {
3008 let pair_start = pair.start.trim_end();
3009 let pair_end = pair.end.trim_start();
3010
3011 enabled
3012 && pair.newline
3013 && buffer.contains_str_at(
3014 end + trailing_whitespace_len,
3015 pair_end,
3016 )
3017 && buffer.contains_str_at(
3018 (start - leading_whitespace_len)
3019 .saturating_sub(pair_start.len()),
3020 pair_start,
3021 )
3022 });
3023
3024 // Comment extension on newline is allowed only for cursor selections
3025 let comment_delimiter = maybe!({
3026 if !selection_is_empty {
3027 return None;
3028 }
3029
3030 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3031 return None;
3032 }
3033
3034 let delimiters = language.line_comment_prefixes();
3035 let max_len_of_delimiter =
3036 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3037 let (snapshot, range) =
3038 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3039
3040 let mut index_of_first_non_whitespace = 0;
3041 let comment_candidate = snapshot
3042 .chars_for_range(range)
3043 .skip_while(|c| {
3044 let should_skip = c.is_whitespace();
3045 if should_skip {
3046 index_of_first_non_whitespace += 1;
3047 }
3048 should_skip
3049 })
3050 .take(max_len_of_delimiter)
3051 .collect::<String>();
3052 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3053 comment_candidate.starts_with(comment_prefix.as_ref())
3054 })?;
3055 let cursor_is_placed_after_comment_marker =
3056 index_of_first_non_whitespace + comment_prefix.len()
3057 <= start_point.column as usize;
3058 if cursor_is_placed_after_comment_marker {
3059 Some(comment_prefix.clone())
3060 } else {
3061 None
3062 }
3063 });
3064 (comment_delimiter, insert_extra_newline)
3065 } else {
3066 (None, false)
3067 };
3068
3069 let capacity_for_delimiter = comment_delimiter
3070 .as_deref()
3071 .map(str::len)
3072 .unwrap_or_default();
3073 let mut new_text =
3074 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3075 new_text.push('\n');
3076 new_text.extend(indent.chars());
3077 if let Some(delimiter) = &comment_delimiter {
3078 new_text.push_str(delimiter);
3079 }
3080 if insert_extra_newline {
3081 new_text = new_text.repeat(2);
3082 }
3083
3084 let anchor = buffer.anchor_after(end);
3085 let new_selection = selection.map(|_| anchor);
3086 (
3087 (start..end, new_text),
3088 (insert_extra_newline, new_selection),
3089 )
3090 })
3091 .unzip()
3092 };
3093
3094 this.edit_with_autoindent(edits, cx);
3095 let buffer = this.buffer.read(cx).snapshot(cx);
3096 let new_selections = selection_fixup_info
3097 .into_iter()
3098 .map(|(extra_newline_inserted, new_selection)| {
3099 let mut cursor = new_selection.end.to_point(&buffer);
3100 if extra_newline_inserted {
3101 cursor.row -= 1;
3102 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3103 }
3104 new_selection.map(|_| cursor)
3105 })
3106 .collect();
3107
3108 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3109 this.refresh_inline_completion(true, false, cx);
3110 });
3111 }
3112
3113 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3114 let buffer = self.buffer.read(cx);
3115 let snapshot = buffer.snapshot(cx);
3116
3117 let mut edits = Vec::new();
3118 let mut rows = Vec::new();
3119
3120 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3121 let cursor = selection.head();
3122 let row = cursor.row;
3123
3124 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3125
3126 let newline = "\n".to_string();
3127 edits.push((start_of_line..start_of_line, newline));
3128
3129 rows.push(row + rows_inserted as u32);
3130 }
3131
3132 self.transact(cx, |editor, cx| {
3133 editor.edit(edits, cx);
3134
3135 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3136 let mut index = 0;
3137 s.move_cursors_with(|map, _, _| {
3138 let row = rows[index];
3139 index += 1;
3140
3141 let point = Point::new(row, 0);
3142 let boundary = map.next_line_boundary(point).1;
3143 let clipped = map.clip_point(boundary, Bias::Left);
3144
3145 (clipped, SelectionGoal::None)
3146 });
3147 });
3148
3149 let mut indent_edits = Vec::new();
3150 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3151 for row in rows {
3152 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3153 for (row, indent) in indents {
3154 if indent.len == 0 {
3155 continue;
3156 }
3157
3158 let text = match indent.kind {
3159 IndentKind::Space => " ".repeat(indent.len as usize),
3160 IndentKind::Tab => "\t".repeat(indent.len as usize),
3161 };
3162 let point = Point::new(row.0, 0);
3163 indent_edits.push((point..point, text));
3164 }
3165 }
3166 editor.edit(indent_edits, cx);
3167 });
3168 }
3169
3170 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3171 let buffer = self.buffer.read(cx);
3172 let snapshot = buffer.snapshot(cx);
3173
3174 let mut edits = Vec::new();
3175 let mut rows = Vec::new();
3176 let mut rows_inserted = 0;
3177
3178 for selection in self.selections.all_adjusted(cx) {
3179 let cursor = selection.head();
3180 let row = cursor.row;
3181
3182 let point = Point::new(row + 1, 0);
3183 let start_of_line = snapshot.clip_point(point, Bias::Left);
3184
3185 let newline = "\n".to_string();
3186 edits.push((start_of_line..start_of_line, newline));
3187
3188 rows_inserted += 1;
3189 rows.push(row + rows_inserted);
3190 }
3191
3192 self.transact(cx, |editor, cx| {
3193 editor.edit(edits, cx);
3194
3195 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3196 let mut index = 0;
3197 s.move_cursors_with(|map, _, _| {
3198 let row = rows[index];
3199 index += 1;
3200
3201 let point = Point::new(row, 0);
3202 let boundary = map.next_line_boundary(point).1;
3203 let clipped = map.clip_point(boundary, Bias::Left);
3204
3205 (clipped, SelectionGoal::None)
3206 });
3207 });
3208
3209 let mut indent_edits = Vec::new();
3210 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3211 for row in rows {
3212 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3213 for (row, indent) in indents {
3214 if indent.len == 0 {
3215 continue;
3216 }
3217
3218 let text = match indent.kind {
3219 IndentKind::Space => " ".repeat(indent.len as usize),
3220 IndentKind::Tab => "\t".repeat(indent.len as usize),
3221 };
3222 let point = Point::new(row.0, 0);
3223 indent_edits.push((point..point, text));
3224 }
3225 }
3226 editor.edit(indent_edits, cx);
3227 });
3228 }
3229
3230 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3231 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3232 original_indent_columns: Vec::new(),
3233 });
3234 self.insert_with_autoindent_mode(text, autoindent, cx);
3235 }
3236
3237 fn insert_with_autoindent_mode(
3238 &mut self,
3239 text: &str,
3240 autoindent_mode: Option<AutoindentMode>,
3241 cx: &mut ViewContext<Self>,
3242 ) {
3243 if self.read_only(cx) {
3244 return;
3245 }
3246
3247 let text: Arc<str> = text.into();
3248 self.transact(cx, |this, cx| {
3249 let old_selections = this.selections.all_adjusted(cx);
3250 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3251 let anchors = {
3252 let snapshot = buffer.read(cx);
3253 old_selections
3254 .iter()
3255 .map(|s| {
3256 let anchor = snapshot.anchor_after(s.head());
3257 s.map(|_| anchor)
3258 })
3259 .collect::<Vec<_>>()
3260 };
3261 buffer.edit(
3262 old_selections
3263 .iter()
3264 .map(|s| (s.start..s.end, text.clone())),
3265 autoindent_mode,
3266 cx,
3267 );
3268 anchors
3269 });
3270
3271 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3272 s.select_anchors(selection_anchors);
3273 })
3274 });
3275 }
3276
3277 fn trigger_completion_on_input(
3278 &mut self,
3279 text: &str,
3280 trigger_in_words: bool,
3281 cx: &mut ViewContext<Self>,
3282 ) {
3283 if self.is_completion_trigger(text, trigger_in_words, cx) {
3284 self.show_completions(
3285 &ShowCompletions {
3286 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3287 },
3288 cx,
3289 );
3290 } else {
3291 self.hide_context_menu(cx);
3292 }
3293 }
3294
3295 fn is_completion_trigger(
3296 &self,
3297 text: &str,
3298 trigger_in_words: bool,
3299 cx: &mut ViewContext<Self>,
3300 ) -> bool {
3301 let position = self.selections.newest_anchor().head();
3302 let multibuffer = self.buffer.read(cx);
3303 let Some(buffer) = position
3304 .buffer_id
3305 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3306 else {
3307 return false;
3308 };
3309
3310 if let Some(completion_provider) = &self.completion_provider {
3311 completion_provider.is_completion_trigger(
3312 &buffer,
3313 position.text_anchor,
3314 text,
3315 trigger_in_words,
3316 cx,
3317 )
3318 } else {
3319 false
3320 }
3321 }
3322
3323 /// If any empty selections is touching the start of its innermost containing autoclose
3324 /// region, expand it to select the brackets.
3325 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3326 let selections = self.selections.all::<usize>(cx);
3327 let buffer = self.buffer.read(cx).read(cx);
3328 let new_selections = self
3329 .selections_with_autoclose_regions(selections, &buffer)
3330 .map(|(mut selection, region)| {
3331 if !selection.is_empty() {
3332 return selection;
3333 }
3334
3335 if let Some(region) = region {
3336 let mut range = region.range.to_offset(&buffer);
3337 if selection.start == range.start && range.start >= region.pair.start.len() {
3338 range.start -= region.pair.start.len();
3339 if buffer.contains_str_at(range.start, ®ion.pair.start)
3340 && buffer.contains_str_at(range.end, ®ion.pair.end)
3341 {
3342 range.end += region.pair.end.len();
3343 selection.start = range.start;
3344 selection.end = range.end;
3345
3346 return selection;
3347 }
3348 }
3349 }
3350
3351 let always_treat_brackets_as_autoclosed = buffer
3352 .settings_at(selection.start, cx)
3353 .always_treat_brackets_as_autoclosed;
3354
3355 if !always_treat_brackets_as_autoclosed {
3356 return selection;
3357 }
3358
3359 if let Some(scope) = buffer.language_scope_at(selection.start) {
3360 for (pair, enabled) in scope.brackets() {
3361 if !enabled || !pair.close {
3362 continue;
3363 }
3364
3365 if buffer.contains_str_at(selection.start, &pair.end) {
3366 let pair_start_len = pair.start.len();
3367 if buffer.contains_str_at(
3368 selection.start.saturating_sub(pair_start_len),
3369 &pair.start,
3370 ) {
3371 selection.start -= pair_start_len;
3372 selection.end += pair.end.len();
3373
3374 return selection;
3375 }
3376 }
3377 }
3378 }
3379
3380 selection
3381 })
3382 .collect();
3383
3384 drop(buffer);
3385 self.change_selections(None, cx, |selections| selections.select(new_selections));
3386 }
3387
3388 /// Iterate the given selections, and for each one, find the smallest surrounding
3389 /// autoclose region. This uses the ordering of the selections and the autoclose
3390 /// regions to avoid repeated comparisons.
3391 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3392 &'a self,
3393 selections: impl IntoIterator<Item = Selection<D>>,
3394 buffer: &'a MultiBufferSnapshot,
3395 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3396 let mut i = 0;
3397 let mut regions = self.autoclose_regions.as_slice();
3398 selections.into_iter().map(move |selection| {
3399 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3400
3401 let mut enclosing = None;
3402 while let Some(pair_state) = regions.get(i) {
3403 if pair_state.range.end.to_offset(buffer) < range.start {
3404 regions = ®ions[i + 1..];
3405 i = 0;
3406 } else if pair_state.range.start.to_offset(buffer) > range.end {
3407 break;
3408 } else {
3409 if pair_state.selection_id == selection.id {
3410 enclosing = Some(pair_state);
3411 }
3412 i += 1;
3413 }
3414 }
3415
3416 (selection, enclosing)
3417 })
3418 }
3419
3420 /// Remove any autoclose regions that no longer contain their selection.
3421 fn invalidate_autoclose_regions(
3422 &mut self,
3423 mut selections: &[Selection<Anchor>],
3424 buffer: &MultiBufferSnapshot,
3425 ) {
3426 self.autoclose_regions.retain(|state| {
3427 let mut i = 0;
3428 while let Some(selection) = selections.get(i) {
3429 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3430 selections = &selections[1..];
3431 continue;
3432 }
3433 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3434 break;
3435 }
3436 if selection.id == state.selection_id {
3437 return true;
3438 } else {
3439 i += 1;
3440 }
3441 }
3442 false
3443 });
3444 }
3445
3446 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3447 let offset = position.to_offset(buffer);
3448 let (word_range, kind) = buffer.surrounding_word(offset, true);
3449 if offset > word_range.start && kind == Some(CharKind::Word) {
3450 Some(
3451 buffer
3452 .text_for_range(word_range.start..offset)
3453 .collect::<String>(),
3454 )
3455 } else {
3456 None
3457 }
3458 }
3459
3460 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3461 self.refresh_inlay_hints(
3462 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3463 cx,
3464 );
3465 }
3466
3467 pub fn inlay_hints_enabled(&self) -> bool {
3468 self.inlay_hint_cache.enabled
3469 }
3470
3471 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3472 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3473 return;
3474 }
3475
3476 let reason_description = reason.description();
3477 let ignore_debounce = matches!(
3478 reason,
3479 InlayHintRefreshReason::SettingsChange(_)
3480 | InlayHintRefreshReason::Toggle(_)
3481 | InlayHintRefreshReason::ExcerptsRemoved(_)
3482 );
3483 let (invalidate_cache, required_languages) = match reason {
3484 InlayHintRefreshReason::Toggle(enabled) => {
3485 self.inlay_hint_cache.enabled = enabled;
3486 if enabled {
3487 (InvalidationStrategy::RefreshRequested, None)
3488 } else {
3489 self.inlay_hint_cache.clear();
3490 self.splice_inlays(
3491 self.visible_inlay_hints(cx)
3492 .iter()
3493 .map(|inlay| inlay.id)
3494 .collect(),
3495 Vec::new(),
3496 cx,
3497 );
3498 return;
3499 }
3500 }
3501 InlayHintRefreshReason::SettingsChange(new_settings) => {
3502 match self.inlay_hint_cache.update_settings(
3503 &self.buffer,
3504 new_settings,
3505 self.visible_inlay_hints(cx),
3506 cx,
3507 ) {
3508 ControlFlow::Break(Some(InlaySplice {
3509 to_remove,
3510 to_insert,
3511 })) => {
3512 self.splice_inlays(to_remove, to_insert, cx);
3513 return;
3514 }
3515 ControlFlow::Break(None) => return,
3516 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3517 }
3518 }
3519 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3520 if let Some(InlaySplice {
3521 to_remove,
3522 to_insert,
3523 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3524 {
3525 self.splice_inlays(to_remove, to_insert, cx);
3526 }
3527 return;
3528 }
3529 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3530 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3531 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3532 }
3533 InlayHintRefreshReason::RefreshRequested => {
3534 (InvalidationStrategy::RefreshRequested, None)
3535 }
3536 };
3537
3538 if let Some(InlaySplice {
3539 to_remove,
3540 to_insert,
3541 }) = self.inlay_hint_cache.spawn_hint_refresh(
3542 reason_description,
3543 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3544 invalidate_cache,
3545 ignore_debounce,
3546 cx,
3547 ) {
3548 self.splice_inlays(to_remove, to_insert, cx);
3549 }
3550 }
3551
3552 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3553 self.display_map
3554 .read(cx)
3555 .current_inlays()
3556 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3557 .cloned()
3558 .collect()
3559 }
3560
3561 pub fn excerpts_for_inlay_hints_query(
3562 &self,
3563 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3564 cx: &mut ViewContext<Editor>,
3565 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3566 let Some(project) = self.project.as_ref() else {
3567 return HashMap::default();
3568 };
3569 let project = project.read(cx);
3570 let multi_buffer = self.buffer().read(cx);
3571 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3572 let multi_buffer_visible_start = self
3573 .scroll_manager
3574 .anchor()
3575 .anchor
3576 .to_point(&multi_buffer_snapshot);
3577 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3578 multi_buffer_visible_start
3579 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3580 Bias::Left,
3581 );
3582 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3583 multi_buffer_snapshot
3584 .range_to_buffer_ranges(multi_buffer_visible_range)
3585 .into_iter()
3586 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3587 .filter_map(|(excerpt, excerpt_visible_range)| {
3588 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3589 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3590 let worktree_entry = buffer_worktree
3591 .read(cx)
3592 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3593 if worktree_entry.is_ignored {
3594 return None;
3595 }
3596
3597 let language = excerpt.buffer().language()?;
3598 if let Some(restrict_to_languages) = restrict_to_languages {
3599 if !restrict_to_languages.contains(language) {
3600 return None;
3601 }
3602 }
3603 Some((
3604 excerpt.id(),
3605 (
3606 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3607 excerpt.buffer().version().clone(),
3608 excerpt_visible_range,
3609 ),
3610 ))
3611 })
3612 .collect()
3613 }
3614
3615 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3616 TextLayoutDetails {
3617 text_system: cx.text_system().clone(),
3618 editor_style: self.style.clone().unwrap(),
3619 rem_size: cx.rem_size(),
3620 scroll_anchor: self.scroll_manager.anchor(),
3621 visible_rows: self.visible_line_count(),
3622 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3623 }
3624 }
3625
3626 pub fn splice_inlays(
3627 &self,
3628 to_remove: Vec<InlayId>,
3629 to_insert: Vec<Inlay>,
3630 cx: &mut ViewContext<Self>,
3631 ) {
3632 self.display_map.update(cx, |display_map, cx| {
3633 display_map.splice_inlays(to_remove, to_insert, cx)
3634 });
3635 cx.notify();
3636 }
3637
3638 fn trigger_on_type_formatting(
3639 &self,
3640 input: String,
3641 cx: &mut ViewContext<Self>,
3642 ) -> Option<Task<Result<()>>> {
3643 if input.len() != 1 {
3644 return None;
3645 }
3646
3647 let project = self.project.as_ref()?;
3648 let position = self.selections.newest_anchor().head();
3649 let (buffer, buffer_position) = self
3650 .buffer
3651 .read(cx)
3652 .text_anchor_for_position(position, cx)?;
3653
3654 let settings = language_settings::language_settings(
3655 buffer
3656 .read(cx)
3657 .language_at(buffer_position)
3658 .map(|l| l.name()),
3659 buffer.read(cx).file(),
3660 cx,
3661 );
3662 if !settings.use_on_type_format {
3663 return None;
3664 }
3665
3666 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3667 // hence we do LSP request & edit on host side only — add formats to host's history.
3668 let push_to_lsp_host_history = true;
3669 // If this is not the host, append its history with new edits.
3670 let push_to_client_history = project.read(cx).is_via_collab();
3671
3672 let on_type_formatting = project.update(cx, |project, cx| {
3673 project.on_type_format(
3674 buffer.clone(),
3675 buffer_position,
3676 input,
3677 push_to_lsp_host_history,
3678 cx,
3679 )
3680 });
3681 Some(cx.spawn(|editor, mut cx| async move {
3682 if let Some(transaction) = on_type_formatting.await? {
3683 if push_to_client_history {
3684 buffer
3685 .update(&mut cx, |buffer, _| {
3686 buffer.push_transaction(transaction, Instant::now());
3687 })
3688 .ok();
3689 }
3690 editor.update(&mut cx, |editor, cx| {
3691 editor.refresh_document_highlights(cx);
3692 })?;
3693 }
3694 Ok(())
3695 }))
3696 }
3697
3698 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3699 if self.pending_rename.is_some() {
3700 return;
3701 }
3702
3703 let Some(provider) = self.completion_provider.as_ref() else {
3704 return;
3705 };
3706
3707 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3708 return;
3709 }
3710
3711 let position = self.selections.newest_anchor().head();
3712 let (buffer, buffer_position) =
3713 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3714 output
3715 } else {
3716 return;
3717 };
3718 let show_completion_documentation = buffer
3719 .read(cx)
3720 .snapshot()
3721 .settings_at(buffer_position, cx)
3722 .show_completion_documentation;
3723
3724 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3725
3726 let trigger_kind = match &options.trigger {
3727 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3728 CompletionTriggerKind::TRIGGER_CHARACTER
3729 }
3730 _ => CompletionTriggerKind::INVOKED,
3731 };
3732 let completion_context = CompletionContext {
3733 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3734 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3735 Some(String::from(trigger))
3736 } else {
3737 None
3738 }
3739 }),
3740 trigger_kind,
3741 };
3742 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3743 let sort_completions = provider.sort_completions();
3744
3745 let id = post_inc(&mut self.next_completion_id);
3746 let task = cx.spawn(|editor, mut cx| {
3747 async move {
3748 editor.update(&mut cx, |this, _| {
3749 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3750 })?;
3751 let completions = completions.await.log_err();
3752 let menu = if let Some(completions) = completions {
3753 let mut menu = CompletionsMenu::new(
3754 id,
3755 sort_completions,
3756 show_completion_documentation,
3757 position,
3758 buffer.clone(),
3759 completions.into(),
3760 );
3761
3762 menu.filter(query.as_deref(), cx.background_executor().clone())
3763 .await;
3764
3765 menu.visible().then_some(menu)
3766 } else {
3767 None
3768 };
3769
3770 editor.update(&mut cx, |editor, cx| {
3771 match editor.context_menu.borrow().as_ref() {
3772 None => {}
3773 Some(CodeContextMenu::Completions(prev_menu)) => {
3774 if prev_menu.id > id {
3775 return;
3776 }
3777 }
3778 _ => return,
3779 }
3780
3781 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3782 let mut menu = menu.unwrap();
3783 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3784
3785 if editor.show_inline_completions_in_menu(cx) {
3786 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3787 menu.show_inline_completion_hint(hint);
3788 }
3789 } else {
3790 editor.discard_inline_completion(false, cx);
3791 }
3792
3793 *editor.context_menu.borrow_mut() =
3794 Some(CodeContextMenu::Completions(menu));
3795
3796 cx.notify();
3797 } else if editor.completion_tasks.len() <= 1 {
3798 // If there are no more completion tasks and the last menu was
3799 // empty, we should hide it.
3800 let was_hidden = editor.hide_context_menu(cx).is_none();
3801 // If it was already hidden and we don't show inline
3802 // completions in the menu, we should also show the
3803 // inline-completion when available.
3804 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3805 editor.update_visible_inline_completion(cx);
3806 }
3807 }
3808 })?;
3809
3810 Ok::<_, anyhow::Error>(())
3811 }
3812 .log_err()
3813 });
3814
3815 self.completion_tasks.push((id, task));
3816 }
3817
3818 pub fn confirm_completion(
3819 &mut self,
3820 action: &ConfirmCompletion,
3821 cx: &mut ViewContext<Self>,
3822 ) -> Option<Task<Result<()>>> {
3823 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3824 }
3825
3826 pub fn compose_completion(
3827 &mut self,
3828 action: &ComposeCompletion,
3829 cx: &mut ViewContext<Self>,
3830 ) -> Option<Task<Result<()>>> {
3831 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3832 }
3833
3834 fn toggle_zed_predict_tos(&mut self, cx: &mut ViewContext<Self>) {
3835 let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
3836 return;
3837 };
3838
3839 ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), cx);
3840 }
3841
3842 fn do_completion(
3843 &mut self,
3844 item_ix: Option<usize>,
3845 intent: CompletionIntent,
3846 cx: &mut ViewContext<Editor>,
3847 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3848 use language::ToOffset as _;
3849
3850 {
3851 let context_menu = self.context_menu.borrow();
3852 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3853 let entries = menu.entries.borrow();
3854 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3855 match entry {
3856 Some(CompletionEntry::InlineCompletionHint(
3857 InlineCompletionMenuHint::Loading,
3858 )) => return Some(Task::ready(Ok(()))),
3859 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3860 drop(entries);
3861 drop(context_menu);
3862 self.context_menu_next(&Default::default(), cx);
3863 return Some(Task::ready(Ok(())));
3864 }
3865 Some(CompletionEntry::InlineCompletionHint(
3866 InlineCompletionMenuHint::PendingTermsAcceptance,
3867 )) => {
3868 drop(entries);
3869 drop(context_menu);
3870 self.toggle_zed_predict_tos(cx);
3871 return Some(Task::ready(Ok(())));
3872 }
3873 _ => {}
3874 }
3875 }
3876 }
3877
3878 let completions_menu =
3879 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3880 menu
3881 } else {
3882 return None;
3883 };
3884
3885 let entries = completions_menu.entries.borrow();
3886 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3887 let mat = match mat {
3888 CompletionEntry::InlineCompletionHint(_) => {
3889 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3890 cx.stop_propagation();
3891 return Some(Task::ready(Ok(())));
3892 }
3893 CompletionEntry::Match(mat) => {
3894 if self.show_inline_completions_in_menu(cx) {
3895 self.discard_inline_completion(true, cx);
3896 }
3897 mat
3898 }
3899 };
3900 let candidate_id = mat.candidate_id;
3901 drop(entries);
3902
3903 let buffer_handle = completions_menu.buffer;
3904 let completion = completions_menu
3905 .completions
3906 .borrow()
3907 .get(candidate_id)?
3908 .clone();
3909 cx.stop_propagation();
3910
3911 let snippet;
3912 let text;
3913
3914 if completion.is_snippet() {
3915 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3916 text = snippet.as_ref().unwrap().text.clone();
3917 } else {
3918 snippet = None;
3919 text = completion.new_text.clone();
3920 };
3921 let selections = self.selections.all::<usize>(cx);
3922 let buffer = buffer_handle.read(cx);
3923 let old_range = completion.old_range.to_offset(buffer);
3924 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3925
3926 let newest_selection = self.selections.newest_anchor();
3927 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3928 return None;
3929 }
3930
3931 let lookbehind = newest_selection
3932 .start
3933 .text_anchor
3934 .to_offset(buffer)
3935 .saturating_sub(old_range.start);
3936 let lookahead = old_range
3937 .end
3938 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3939 let mut common_prefix_len = old_text
3940 .bytes()
3941 .zip(text.bytes())
3942 .take_while(|(a, b)| a == b)
3943 .count();
3944
3945 let snapshot = self.buffer.read(cx).snapshot(cx);
3946 let mut range_to_replace: Option<Range<isize>> = None;
3947 let mut ranges = Vec::new();
3948 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3949 for selection in &selections {
3950 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3951 let start = selection.start.saturating_sub(lookbehind);
3952 let end = selection.end + lookahead;
3953 if selection.id == newest_selection.id {
3954 range_to_replace = Some(
3955 ((start + common_prefix_len) as isize - selection.start as isize)
3956 ..(end as isize - selection.start as isize),
3957 );
3958 }
3959 ranges.push(start + common_prefix_len..end);
3960 } else {
3961 common_prefix_len = 0;
3962 ranges.clear();
3963 ranges.extend(selections.iter().map(|s| {
3964 if s.id == newest_selection.id {
3965 range_to_replace = Some(
3966 old_range.start.to_offset_utf16(&snapshot).0 as isize
3967 - selection.start as isize
3968 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3969 - selection.start as isize,
3970 );
3971 old_range.clone()
3972 } else {
3973 s.start..s.end
3974 }
3975 }));
3976 break;
3977 }
3978 if !self.linked_edit_ranges.is_empty() {
3979 let start_anchor = snapshot.anchor_before(selection.head());
3980 let end_anchor = snapshot.anchor_after(selection.tail());
3981 if let Some(ranges) = self
3982 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3983 {
3984 for (buffer, edits) in ranges {
3985 linked_edits.entry(buffer.clone()).or_default().extend(
3986 edits
3987 .into_iter()
3988 .map(|range| (range, text[common_prefix_len..].to_owned())),
3989 );
3990 }
3991 }
3992 }
3993 }
3994 let text = &text[common_prefix_len..];
3995
3996 cx.emit(EditorEvent::InputHandled {
3997 utf16_range_to_replace: range_to_replace,
3998 text: text.into(),
3999 });
4000
4001 self.transact(cx, |this, cx| {
4002 if let Some(mut snippet) = snippet {
4003 snippet.text = text.to_string();
4004 for tabstop in snippet
4005 .tabstops
4006 .iter_mut()
4007 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4008 {
4009 tabstop.start -= common_prefix_len as isize;
4010 tabstop.end -= common_prefix_len as isize;
4011 }
4012
4013 this.insert_snippet(&ranges, snippet, cx).log_err();
4014 } else {
4015 this.buffer.update(cx, |buffer, cx| {
4016 buffer.edit(
4017 ranges.iter().map(|range| (range.clone(), text)),
4018 this.autoindent_mode.clone(),
4019 cx,
4020 );
4021 });
4022 }
4023 for (buffer, edits) in linked_edits {
4024 buffer.update(cx, |buffer, cx| {
4025 let snapshot = buffer.snapshot();
4026 let edits = edits
4027 .into_iter()
4028 .map(|(range, text)| {
4029 use text::ToPoint as TP;
4030 let end_point = TP::to_point(&range.end, &snapshot);
4031 let start_point = TP::to_point(&range.start, &snapshot);
4032 (start_point..end_point, text)
4033 })
4034 .sorted_by_key(|(range, _)| range.start)
4035 .collect::<Vec<_>>();
4036 buffer.edit(edits, None, cx);
4037 })
4038 }
4039
4040 this.refresh_inline_completion(true, false, cx);
4041 });
4042
4043 let show_new_completions_on_confirm = completion
4044 .confirm
4045 .as_ref()
4046 .map_or(false, |confirm| confirm(intent, cx));
4047 if show_new_completions_on_confirm {
4048 self.show_completions(&ShowCompletions { trigger: None }, cx);
4049 }
4050
4051 let provider = self.completion_provider.as_ref()?;
4052 drop(completion);
4053 let apply_edits = provider.apply_additional_edits_for_completion(
4054 buffer_handle,
4055 completions_menu.completions.clone(),
4056 candidate_id,
4057 true,
4058 cx,
4059 );
4060
4061 let editor_settings = EditorSettings::get_global(cx);
4062 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4063 // After the code completion is finished, users often want to know what signatures are needed.
4064 // so we should automatically call signature_help
4065 self.show_signature_help(&ShowSignatureHelp, cx);
4066 }
4067
4068 Some(cx.foreground_executor().spawn(async move {
4069 apply_edits.await?;
4070 Ok(())
4071 }))
4072 }
4073
4074 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4075 let mut context_menu = self.context_menu.borrow_mut();
4076 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4077 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4078 // Toggle if we're selecting the same one
4079 *context_menu = None;
4080 cx.notify();
4081 return;
4082 } else {
4083 // Otherwise, clear it and start a new one
4084 *context_menu = None;
4085 cx.notify();
4086 }
4087 }
4088 drop(context_menu);
4089 let snapshot = self.snapshot(cx);
4090 let deployed_from_indicator = action.deployed_from_indicator;
4091 let mut task = self.code_actions_task.take();
4092 let action = action.clone();
4093 cx.spawn(|editor, mut cx| async move {
4094 while let Some(prev_task) = task {
4095 prev_task.await.log_err();
4096 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4097 }
4098
4099 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4100 if editor.focus_handle.is_focused(cx) {
4101 let multibuffer_point = action
4102 .deployed_from_indicator
4103 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4104 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4105 let (buffer, buffer_row) = snapshot
4106 .buffer_snapshot
4107 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4108 .and_then(|(buffer_snapshot, range)| {
4109 editor
4110 .buffer
4111 .read(cx)
4112 .buffer(buffer_snapshot.remote_id())
4113 .map(|buffer| (buffer, range.start.row))
4114 })?;
4115 let (_, code_actions) = editor
4116 .available_code_actions
4117 .clone()
4118 .and_then(|(location, code_actions)| {
4119 let snapshot = location.buffer.read(cx).snapshot();
4120 let point_range = location.range.to_point(&snapshot);
4121 let point_range = point_range.start.row..=point_range.end.row;
4122 if point_range.contains(&buffer_row) {
4123 Some((location, code_actions))
4124 } else {
4125 None
4126 }
4127 })
4128 .unzip();
4129 let buffer_id = buffer.read(cx).remote_id();
4130 let tasks = editor
4131 .tasks
4132 .get(&(buffer_id, buffer_row))
4133 .map(|t| Arc::new(t.to_owned()));
4134 if tasks.is_none() && code_actions.is_none() {
4135 return None;
4136 }
4137
4138 editor.completion_tasks.clear();
4139 editor.discard_inline_completion(false, cx);
4140 let task_context =
4141 tasks
4142 .as_ref()
4143 .zip(editor.project.clone())
4144 .map(|(tasks, project)| {
4145 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4146 });
4147
4148 Some(cx.spawn(|editor, mut cx| async move {
4149 let task_context = match task_context {
4150 Some(task_context) => task_context.await,
4151 None => None,
4152 };
4153 let resolved_tasks =
4154 tasks.zip(task_context).map(|(tasks, task_context)| {
4155 Rc::new(ResolvedTasks {
4156 templates: tasks.resolve(&task_context).collect(),
4157 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4158 multibuffer_point.row,
4159 tasks.column,
4160 )),
4161 })
4162 });
4163 let spawn_straight_away = resolved_tasks
4164 .as_ref()
4165 .map_or(false, |tasks| tasks.templates.len() == 1)
4166 && code_actions
4167 .as_ref()
4168 .map_or(true, |actions| actions.is_empty());
4169 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4170 *editor.context_menu.borrow_mut() =
4171 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4172 buffer,
4173 actions: CodeActionContents {
4174 tasks: resolved_tasks,
4175 actions: code_actions,
4176 },
4177 selected_item: Default::default(),
4178 scroll_handle: UniformListScrollHandle::default(),
4179 deployed_from_indicator,
4180 }));
4181 if spawn_straight_away {
4182 if let Some(task) = editor.confirm_code_action(
4183 &ConfirmCodeAction { item_ix: Some(0) },
4184 cx,
4185 ) {
4186 cx.notify();
4187 return task;
4188 }
4189 }
4190 cx.notify();
4191 Task::ready(Ok(()))
4192 }) {
4193 task.await
4194 } else {
4195 Ok(())
4196 }
4197 }))
4198 } else {
4199 Some(Task::ready(Ok(())))
4200 }
4201 })?;
4202 if let Some(task) = spawned_test_task {
4203 task.await?;
4204 }
4205
4206 Ok::<_, anyhow::Error>(())
4207 })
4208 .detach_and_log_err(cx);
4209 }
4210
4211 pub fn confirm_code_action(
4212 &mut self,
4213 action: &ConfirmCodeAction,
4214 cx: &mut ViewContext<Self>,
4215 ) -> Option<Task<Result<()>>> {
4216 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4217 menu
4218 } else {
4219 return None;
4220 };
4221 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4222 let action = actions_menu.actions.get(action_ix)?;
4223 let title = action.label();
4224 let buffer = actions_menu.buffer;
4225 let workspace = self.workspace()?;
4226
4227 match action {
4228 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4229 workspace.update(cx, |workspace, cx| {
4230 workspace::tasks::schedule_resolved_task(
4231 workspace,
4232 task_source_kind,
4233 resolved_task,
4234 false,
4235 cx,
4236 );
4237
4238 Some(Task::ready(Ok(())))
4239 })
4240 }
4241 CodeActionsItem::CodeAction {
4242 excerpt_id,
4243 action,
4244 provider,
4245 } => {
4246 let apply_code_action =
4247 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4248 let workspace = workspace.downgrade();
4249 Some(cx.spawn(|editor, cx| async move {
4250 let project_transaction = apply_code_action.await?;
4251 Self::open_project_transaction(
4252 &editor,
4253 workspace,
4254 project_transaction,
4255 title,
4256 cx,
4257 )
4258 .await
4259 }))
4260 }
4261 }
4262 }
4263
4264 pub async fn open_project_transaction(
4265 this: &WeakView<Editor>,
4266 workspace: WeakView<Workspace>,
4267 transaction: ProjectTransaction,
4268 title: String,
4269 mut cx: AsyncWindowContext,
4270 ) -> Result<()> {
4271 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4272 cx.update(|cx| {
4273 entries.sort_unstable_by_key(|(buffer, _)| {
4274 buffer.read(cx).file().map(|f| f.path().clone())
4275 });
4276 })?;
4277
4278 // If the project transaction's edits are all contained within this editor, then
4279 // avoid opening a new editor to display them.
4280
4281 if let Some((buffer, transaction)) = entries.first() {
4282 if entries.len() == 1 {
4283 let excerpt = this.update(&mut cx, |editor, cx| {
4284 editor
4285 .buffer()
4286 .read(cx)
4287 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4288 })?;
4289 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4290 if excerpted_buffer == *buffer {
4291 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4292 let excerpt_range = excerpt_range.to_offset(buffer);
4293 buffer
4294 .edited_ranges_for_transaction::<usize>(transaction)
4295 .all(|range| {
4296 excerpt_range.start <= range.start
4297 && excerpt_range.end >= range.end
4298 })
4299 })?;
4300
4301 if all_edits_within_excerpt {
4302 return Ok(());
4303 }
4304 }
4305 }
4306 }
4307 } else {
4308 return Ok(());
4309 }
4310
4311 let mut ranges_to_highlight = Vec::new();
4312 let excerpt_buffer = cx.new_model(|cx| {
4313 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4314 for (buffer_handle, transaction) in &entries {
4315 let buffer = buffer_handle.read(cx);
4316 ranges_to_highlight.extend(
4317 multibuffer.push_excerpts_with_context_lines(
4318 buffer_handle.clone(),
4319 buffer
4320 .edited_ranges_for_transaction::<usize>(transaction)
4321 .collect(),
4322 DEFAULT_MULTIBUFFER_CONTEXT,
4323 cx,
4324 ),
4325 );
4326 }
4327 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4328 multibuffer
4329 })?;
4330
4331 workspace.update(&mut cx, |workspace, cx| {
4332 let project = workspace.project().clone();
4333 let editor =
4334 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4335 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4336 editor.update(cx, |editor, cx| {
4337 editor.highlight_background::<Self>(
4338 &ranges_to_highlight,
4339 |theme| theme.editor_highlighted_line_background,
4340 cx,
4341 );
4342 });
4343 })?;
4344
4345 Ok(())
4346 }
4347
4348 pub fn clear_code_action_providers(&mut self) {
4349 self.code_action_providers.clear();
4350 self.available_code_actions.take();
4351 }
4352
4353 pub fn add_code_action_provider(
4354 &mut self,
4355 provider: Rc<dyn CodeActionProvider>,
4356 cx: &mut ViewContext<Self>,
4357 ) {
4358 if self
4359 .code_action_providers
4360 .iter()
4361 .any(|existing_provider| existing_provider.id() == provider.id())
4362 {
4363 return;
4364 }
4365
4366 self.code_action_providers.push(provider);
4367 self.refresh_code_actions(cx);
4368 }
4369
4370 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4371 self.code_action_providers
4372 .retain(|provider| provider.id() != id);
4373 self.refresh_code_actions(cx);
4374 }
4375
4376 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4377 let buffer = self.buffer.read(cx);
4378 let newest_selection = self.selections.newest_anchor().clone();
4379 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4380 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4381 if start_buffer != end_buffer {
4382 return None;
4383 }
4384
4385 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4386 cx.background_executor()
4387 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4388 .await;
4389
4390 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4391 let providers = this.code_action_providers.clone();
4392 let tasks = this
4393 .code_action_providers
4394 .iter()
4395 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4396 .collect::<Vec<_>>();
4397 (providers, tasks)
4398 })?;
4399
4400 let mut actions = Vec::new();
4401 for (provider, provider_actions) in
4402 providers.into_iter().zip(future::join_all(tasks).await)
4403 {
4404 if let Some(provider_actions) = provider_actions.log_err() {
4405 actions.extend(provider_actions.into_iter().map(|action| {
4406 AvailableCodeAction {
4407 excerpt_id: newest_selection.start.excerpt_id,
4408 action,
4409 provider: provider.clone(),
4410 }
4411 }));
4412 }
4413 }
4414
4415 this.update(&mut cx, |this, cx| {
4416 this.available_code_actions = if actions.is_empty() {
4417 None
4418 } else {
4419 Some((
4420 Location {
4421 buffer: start_buffer,
4422 range: start..end,
4423 },
4424 actions.into(),
4425 ))
4426 };
4427 cx.notify();
4428 })
4429 }));
4430 None
4431 }
4432
4433 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4434 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4435 self.show_git_blame_inline = false;
4436
4437 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4438 cx.background_executor().timer(delay).await;
4439
4440 this.update(&mut cx, |this, cx| {
4441 this.show_git_blame_inline = true;
4442 cx.notify();
4443 })
4444 .log_err();
4445 }));
4446 }
4447 }
4448
4449 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4450 if self.pending_rename.is_some() {
4451 return None;
4452 }
4453
4454 let provider = self.semantics_provider.clone()?;
4455 let buffer = self.buffer.read(cx);
4456 let newest_selection = self.selections.newest_anchor().clone();
4457 let cursor_position = newest_selection.head();
4458 let (cursor_buffer, cursor_buffer_position) =
4459 buffer.text_anchor_for_position(cursor_position, cx)?;
4460 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4461 if cursor_buffer != tail_buffer {
4462 return None;
4463 }
4464 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4465 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4466 cx.background_executor()
4467 .timer(Duration::from_millis(debounce))
4468 .await;
4469
4470 let highlights = if let Some(highlights) = cx
4471 .update(|cx| {
4472 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4473 })
4474 .ok()
4475 .flatten()
4476 {
4477 highlights.await.log_err()
4478 } else {
4479 None
4480 };
4481
4482 if let Some(highlights) = highlights {
4483 this.update(&mut cx, |this, cx| {
4484 if this.pending_rename.is_some() {
4485 return;
4486 }
4487
4488 let buffer_id = cursor_position.buffer_id;
4489 let buffer = this.buffer.read(cx);
4490 if !buffer
4491 .text_anchor_for_position(cursor_position, cx)
4492 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4493 {
4494 return;
4495 }
4496
4497 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4498 let mut write_ranges = Vec::new();
4499 let mut read_ranges = Vec::new();
4500 for highlight in highlights {
4501 for (excerpt_id, excerpt_range) in
4502 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4503 {
4504 let start = highlight
4505 .range
4506 .start
4507 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4508 let end = highlight
4509 .range
4510 .end
4511 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4512 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4513 continue;
4514 }
4515
4516 let range = Anchor {
4517 buffer_id,
4518 excerpt_id,
4519 text_anchor: start,
4520 }..Anchor {
4521 buffer_id,
4522 excerpt_id,
4523 text_anchor: end,
4524 };
4525 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4526 write_ranges.push(range);
4527 } else {
4528 read_ranges.push(range);
4529 }
4530 }
4531 }
4532
4533 this.highlight_background::<DocumentHighlightRead>(
4534 &read_ranges,
4535 |theme| theme.editor_document_highlight_read_background,
4536 cx,
4537 );
4538 this.highlight_background::<DocumentHighlightWrite>(
4539 &write_ranges,
4540 |theme| theme.editor_document_highlight_write_background,
4541 cx,
4542 );
4543 cx.notify();
4544 })
4545 .log_err();
4546 }
4547 }));
4548 None
4549 }
4550
4551 pub fn refresh_inline_completion(
4552 &mut self,
4553 debounce: bool,
4554 user_requested: bool,
4555 cx: &mut ViewContext<Self>,
4556 ) -> Option<()> {
4557 let provider = self.inline_completion_provider()?;
4558 let cursor = self.selections.newest_anchor().head();
4559 let (buffer, cursor_buffer_position) =
4560 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4561
4562 if !user_requested
4563 && (!self.enable_inline_completions
4564 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4565 || !self.is_focused(cx)
4566 || buffer.read(cx).is_empty())
4567 {
4568 self.discard_inline_completion(false, cx);
4569 return None;
4570 }
4571
4572 self.update_visible_inline_completion(cx);
4573 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4574 Some(())
4575 }
4576
4577 fn cycle_inline_completion(
4578 &mut self,
4579 direction: Direction,
4580 cx: &mut ViewContext<Self>,
4581 ) -> Option<()> {
4582 let provider = self.inline_completion_provider()?;
4583 let cursor = self.selections.newest_anchor().head();
4584 let (buffer, cursor_buffer_position) =
4585 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4586 if !self.enable_inline_completions
4587 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4588 {
4589 return None;
4590 }
4591
4592 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4593 self.update_visible_inline_completion(cx);
4594
4595 Some(())
4596 }
4597
4598 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4599 if !self.has_active_inline_completion() {
4600 self.refresh_inline_completion(false, true, cx);
4601 return;
4602 }
4603
4604 self.update_visible_inline_completion(cx);
4605 }
4606
4607 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4608 self.show_cursor_names(cx);
4609 }
4610
4611 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4612 self.show_cursor_names = true;
4613 cx.notify();
4614 cx.spawn(|this, mut cx| async move {
4615 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4616 this.update(&mut cx, |this, cx| {
4617 this.show_cursor_names = false;
4618 cx.notify()
4619 })
4620 .ok()
4621 })
4622 .detach();
4623 }
4624
4625 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4626 if self.has_active_inline_completion() {
4627 self.cycle_inline_completion(Direction::Next, cx);
4628 } else {
4629 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4630 if is_copilot_disabled {
4631 cx.propagate();
4632 }
4633 }
4634 }
4635
4636 pub fn previous_inline_completion(
4637 &mut self,
4638 _: &PreviousInlineCompletion,
4639 cx: &mut ViewContext<Self>,
4640 ) {
4641 if self.has_active_inline_completion() {
4642 self.cycle_inline_completion(Direction::Prev, cx);
4643 } else {
4644 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4645 if is_copilot_disabled {
4646 cx.propagate();
4647 }
4648 }
4649 }
4650
4651 pub fn accept_inline_completion(
4652 &mut self,
4653 _: &AcceptInlineCompletion,
4654 cx: &mut ViewContext<Self>,
4655 ) {
4656 let buffer = self.buffer.read(cx);
4657 let snapshot = buffer.snapshot(cx);
4658 let selection = self.selections.newest_adjusted(cx);
4659 let cursor = selection.head();
4660 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4661 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4662 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4663 {
4664 if cursor.column < suggested_indent.len
4665 && cursor.column <= current_indent.len
4666 && current_indent.len <= suggested_indent.len
4667 {
4668 self.tab(&Default::default(), cx);
4669 return;
4670 }
4671 }
4672
4673 if self.show_inline_completions_in_menu(cx) {
4674 self.hide_context_menu(cx);
4675 }
4676
4677 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4678 return;
4679 };
4680
4681 self.report_inline_completion_event(true, cx);
4682
4683 match &active_inline_completion.completion {
4684 InlineCompletion::Move(position) => {
4685 let position = *position;
4686 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4687 selections.select_anchor_ranges([position..position]);
4688 });
4689 }
4690 InlineCompletion::Edit(edits) => {
4691 if let Some(provider) = self.inline_completion_provider() {
4692 provider.accept(cx);
4693 }
4694
4695 let snapshot = self.buffer.read(cx).snapshot(cx);
4696 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4697
4698 self.buffer.update(cx, |buffer, cx| {
4699 buffer.edit(edits.iter().cloned(), None, cx)
4700 });
4701
4702 self.change_selections(None, cx, |s| {
4703 s.select_anchor_ranges([last_edit_end..last_edit_end])
4704 });
4705
4706 self.update_visible_inline_completion(cx);
4707 if self.active_inline_completion.is_none() {
4708 self.refresh_inline_completion(true, true, cx);
4709 }
4710
4711 cx.notify();
4712 }
4713 }
4714 }
4715
4716 pub fn accept_partial_inline_completion(
4717 &mut self,
4718 _: &AcceptPartialInlineCompletion,
4719 cx: &mut ViewContext<Self>,
4720 ) {
4721 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4722 return;
4723 };
4724 if self.selections.count() != 1 {
4725 return;
4726 }
4727
4728 self.report_inline_completion_event(true, cx);
4729
4730 match &active_inline_completion.completion {
4731 InlineCompletion::Move(position) => {
4732 let position = *position;
4733 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4734 selections.select_anchor_ranges([position..position]);
4735 });
4736 }
4737 InlineCompletion::Edit(edits) => {
4738 // Find an insertion that starts at the cursor position.
4739 let snapshot = self.buffer.read(cx).snapshot(cx);
4740 let cursor_offset = self.selections.newest::<usize>(cx).head();
4741 let insertion = edits.iter().find_map(|(range, text)| {
4742 let range = range.to_offset(&snapshot);
4743 if range.is_empty() && range.start == cursor_offset {
4744 Some(text)
4745 } else {
4746 None
4747 }
4748 });
4749
4750 if let Some(text) = insertion {
4751 let mut partial_completion = text
4752 .chars()
4753 .by_ref()
4754 .take_while(|c| c.is_alphabetic())
4755 .collect::<String>();
4756 if partial_completion.is_empty() {
4757 partial_completion = text
4758 .chars()
4759 .by_ref()
4760 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4761 .collect::<String>();
4762 }
4763
4764 cx.emit(EditorEvent::InputHandled {
4765 utf16_range_to_replace: None,
4766 text: partial_completion.clone().into(),
4767 });
4768
4769 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4770
4771 self.refresh_inline_completion(true, true, cx);
4772 cx.notify();
4773 } else {
4774 self.accept_inline_completion(&Default::default(), cx);
4775 }
4776 }
4777 }
4778 }
4779
4780 fn discard_inline_completion(
4781 &mut self,
4782 should_report_inline_completion_event: bool,
4783 cx: &mut ViewContext<Self>,
4784 ) -> bool {
4785 if should_report_inline_completion_event {
4786 self.report_inline_completion_event(false, cx);
4787 }
4788
4789 if let Some(provider) = self.inline_completion_provider() {
4790 provider.discard(cx);
4791 }
4792
4793 self.take_active_inline_completion(cx).is_some()
4794 }
4795
4796 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4797 let Some(provider) = self.inline_completion_provider() else {
4798 return;
4799 };
4800
4801 let Some((_, buffer, _)) = self
4802 .buffer
4803 .read(cx)
4804 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4805 else {
4806 return;
4807 };
4808
4809 let extension = buffer
4810 .read(cx)
4811 .file()
4812 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4813
4814 let event_type = match accepted {
4815 true => "Inline Completion Accepted",
4816 false => "Inline Completion Discarded",
4817 };
4818 telemetry::event!(
4819 event_type,
4820 provider = provider.name(),
4821 suggestion_accepted = accepted,
4822 file_extension = extension,
4823 );
4824 }
4825
4826 pub fn has_active_inline_completion(&self) -> bool {
4827 self.active_inline_completion.is_some()
4828 }
4829
4830 fn take_active_inline_completion(
4831 &mut self,
4832 cx: &mut ViewContext<Self>,
4833 ) -> Option<InlineCompletion> {
4834 let active_inline_completion = self.active_inline_completion.take()?;
4835 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4836 self.clear_highlights::<InlineCompletionHighlight>(cx);
4837 Some(active_inline_completion.completion)
4838 }
4839
4840 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4841 let selection = self.selections.newest_anchor();
4842 let cursor = selection.head();
4843 let multibuffer = self.buffer.read(cx).snapshot(cx);
4844 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4845 let excerpt_id = cursor.excerpt_id;
4846
4847 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4848 && (self.context_menu.borrow().is_some()
4849 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4850 if completions_menu_has_precedence
4851 || !offset_selection.is_empty()
4852 || !self.enable_inline_completions
4853 || self
4854 .active_inline_completion
4855 .as_ref()
4856 .map_or(false, |completion| {
4857 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4858 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4859 !invalidation_range.contains(&offset_selection.head())
4860 })
4861 {
4862 self.discard_inline_completion(false, cx);
4863 return None;
4864 }
4865
4866 self.take_active_inline_completion(cx);
4867 let provider = self.inline_completion_provider()?;
4868
4869 let (buffer, cursor_buffer_position) =
4870 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4871
4872 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4873 let edits = completion
4874 .edits
4875 .into_iter()
4876 .flat_map(|(range, new_text)| {
4877 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4878 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4879 Some((start..end, new_text))
4880 })
4881 .collect::<Vec<_>>();
4882 if edits.is_empty() {
4883 return None;
4884 }
4885
4886 let first_edit_start = edits.first().unwrap().0.start;
4887 let edit_start_row = first_edit_start
4888 .to_point(&multibuffer)
4889 .row
4890 .saturating_sub(2);
4891
4892 let last_edit_end = edits.last().unwrap().0.end;
4893 let edit_end_row = cmp::min(
4894 multibuffer.max_point().row,
4895 last_edit_end.to_point(&multibuffer).row + 2,
4896 );
4897
4898 let cursor_row = cursor.to_point(&multibuffer).row;
4899
4900 let mut inlay_ids = Vec::new();
4901 let invalidation_row_range;
4902 let completion;
4903 if cursor_row < edit_start_row {
4904 invalidation_row_range = cursor_row..edit_end_row;
4905 completion = InlineCompletion::Move(first_edit_start);
4906 } else if cursor_row > edit_end_row {
4907 invalidation_row_range = edit_start_row..cursor_row;
4908 completion = InlineCompletion::Move(first_edit_start);
4909 } else {
4910 if edits
4911 .iter()
4912 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4913 {
4914 let mut inlays = Vec::new();
4915 for (range, new_text) in &edits {
4916 let inlay = Inlay::inline_completion(
4917 post_inc(&mut self.next_inlay_id),
4918 range.start,
4919 new_text.as_str(),
4920 );
4921 inlay_ids.push(inlay.id);
4922 inlays.push(inlay);
4923 }
4924
4925 self.splice_inlays(vec![], inlays, cx);
4926 } else {
4927 let background_color = cx.theme().status().deleted_background;
4928 self.highlight_text::<InlineCompletionHighlight>(
4929 edits.iter().map(|(range, _)| range.clone()).collect(),
4930 HighlightStyle {
4931 background_color: Some(background_color),
4932 ..Default::default()
4933 },
4934 cx,
4935 );
4936 }
4937
4938 invalidation_row_range = edit_start_row..edit_end_row;
4939 completion = InlineCompletion::Edit(edits);
4940 };
4941
4942 let invalidation_range = multibuffer
4943 .anchor_before(Point::new(invalidation_row_range.start, 0))
4944 ..multibuffer.anchor_after(Point::new(
4945 invalidation_row_range.end,
4946 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4947 ));
4948
4949 self.active_inline_completion = Some(InlineCompletionState {
4950 inlay_ids,
4951 completion,
4952 invalidation_range,
4953 });
4954
4955 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4956 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4957 match self.context_menu.borrow_mut().as_mut() {
4958 Some(CodeContextMenu::Completions(menu)) => {
4959 menu.show_inline_completion_hint(hint);
4960 }
4961 _ => {}
4962 }
4963 }
4964 }
4965
4966 cx.notify();
4967
4968 Some(())
4969 }
4970
4971 fn inline_completion_menu_hint(
4972 &mut self,
4973 cx: &mut ViewContext<Self>,
4974 ) -> Option<InlineCompletionMenuHint> {
4975 let provider = self.inline_completion_provider()?;
4976 if self.has_active_inline_completion() {
4977 let editor_snapshot = self.snapshot(cx);
4978
4979 let text = match &self.active_inline_completion.as_ref()?.completion {
4980 InlineCompletion::Edit(edits) => {
4981 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4982 }
4983 InlineCompletion::Move(target) => {
4984 let target_point =
4985 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4986 let target_line = target_point.row + 1;
4987 InlineCompletionText::Move(
4988 format!("Jump to edit in line {}", target_line).into(),
4989 )
4990 }
4991 };
4992
4993 Some(InlineCompletionMenuHint::Loaded { text })
4994 } else if provider.is_refreshing(cx) {
4995 Some(InlineCompletionMenuHint::Loading)
4996 } else if provider.needs_terms_acceptance(cx) {
4997 Some(InlineCompletionMenuHint::PendingTermsAcceptance)
4998 } else {
4999 Some(InlineCompletionMenuHint::None)
5000 }
5001 }
5002
5003 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5004 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5005 }
5006
5007 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
5008 EditorSettings::get_global(cx).show_inline_completions_in_menu
5009 && self
5010 .inline_completion_provider()
5011 .map_or(false, |provider| provider.show_completions_in_menu())
5012 }
5013
5014 fn render_code_actions_indicator(
5015 &self,
5016 _style: &EditorStyle,
5017 row: DisplayRow,
5018 is_active: bool,
5019 cx: &mut ViewContext<Self>,
5020 ) -> Option<IconButton> {
5021 if self.available_code_actions.is_some() {
5022 Some(
5023 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5024 .shape(ui::IconButtonShape::Square)
5025 .icon_size(IconSize::XSmall)
5026 .icon_color(Color::Muted)
5027 .toggle_state(is_active)
5028 .tooltip({
5029 let focus_handle = self.focus_handle.clone();
5030 move |cx| {
5031 Tooltip::for_action_in(
5032 "Toggle Code Actions",
5033 &ToggleCodeActions {
5034 deployed_from_indicator: None,
5035 },
5036 &focus_handle,
5037 cx,
5038 )
5039 }
5040 })
5041 .on_click(cx.listener(move |editor, _e, cx| {
5042 editor.focus(cx);
5043 editor.toggle_code_actions(
5044 &ToggleCodeActions {
5045 deployed_from_indicator: Some(row),
5046 },
5047 cx,
5048 );
5049 })),
5050 )
5051 } else {
5052 None
5053 }
5054 }
5055
5056 fn clear_tasks(&mut self) {
5057 self.tasks.clear()
5058 }
5059
5060 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5061 if self.tasks.insert(key, value).is_some() {
5062 // This case should hopefully be rare, but just in case...
5063 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5064 }
5065 }
5066
5067 fn build_tasks_context(
5068 project: &Model<Project>,
5069 buffer: &Model<Buffer>,
5070 buffer_row: u32,
5071 tasks: &Arc<RunnableTasks>,
5072 cx: &mut ViewContext<Self>,
5073 ) -> Task<Option<task::TaskContext>> {
5074 let position = Point::new(buffer_row, tasks.column);
5075 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5076 let location = Location {
5077 buffer: buffer.clone(),
5078 range: range_start..range_start,
5079 };
5080 // Fill in the environmental variables from the tree-sitter captures
5081 let mut captured_task_variables = TaskVariables::default();
5082 for (capture_name, value) in tasks.extra_variables.clone() {
5083 captured_task_variables.insert(
5084 task::VariableName::Custom(capture_name.into()),
5085 value.clone(),
5086 );
5087 }
5088 project.update(cx, |project, cx| {
5089 project.task_store().update(cx, |task_store, cx| {
5090 task_store.task_context_for_location(captured_task_variables, location, cx)
5091 })
5092 })
5093 }
5094
5095 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5096 let Some((workspace, _)) = self.workspace.clone() else {
5097 return;
5098 };
5099 let Some(project) = self.project.clone() else {
5100 return;
5101 };
5102
5103 // Try to find a closest, enclosing node using tree-sitter that has a
5104 // task
5105 let Some((buffer, buffer_row, tasks)) = self
5106 .find_enclosing_node_task(cx)
5107 // Or find the task that's closest in row-distance.
5108 .or_else(|| self.find_closest_task(cx))
5109 else {
5110 return;
5111 };
5112
5113 let reveal_strategy = action.reveal;
5114 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5115 cx.spawn(|_, mut cx| async move {
5116 let context = task_context.await?;
5117 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5118
5119 let resolved = resolved_task.resolved.as_mut()?;
5120 resolved.reveal = reveal_strategy;
5121
5122 workspace
5123 .update(&mut cx, |workspace, cx| {
5124 workspace::tasks::schedule_resolved_task(
5125 workspace,
5126 task_source_kind,
5127 resolved_task,
5128 false,
5129 cx,
5130 );
5131 })
5132 .ok()
5133 })
5134 .detach();
5135 }
5136
5137 fn find_closest_task(
5138 &mut self,
5139 cx: &mut ViewContext<Self>,
5140 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5141 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5142
5143 let ((buffer_id, row), tasks) = self
5144 .tasks
5145 .iter()
5146 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5147
5148 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5149 let tasks = Arc::new(tasks.to_owned());
5150 Some((buffer, *row, tasks))
5151 }
5152
5153 fn find_enclosing_node_task(
5154 &mut self,
5155 cx: &mut ViewContext<Self>,
5156 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5157 let snapshot = self.buffer.read(cx).snapshot(cx);
5158 let offset = self.selections.newest::<usize>(cx).head();
5159 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5160 let buffer_id = excerpt.buffer().remote_id();
5161
5162 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5163 let mut cursor = layer.node().walk();
5164
5165 while cursor.goto_first_child_for_byte(offset).is_some() {
5166 if cursor.node().end_byte() == offset {
5167 cursor.goto_next_sibling();
5168 }
5169 }
5170
5171 // Ascend to the smallest ancestor that contains the range and has a task.
5172 loop {
5173 let node = cursor.node();
5174 let node_range = node.byte_range();
5175 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5176
5177 // Check if this node contains our offset
5178 if node_range.start <= offset && node_range.end >= offset {
5179 // If it contains offset, check for task
5180 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5181 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5182 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5183 }
5184 }
5185
5186 if !cursor.goto_parent() {
5187 break;
5188 }
5189 }
5190 None
5191 }
5192
5193 fn render_run_indicator(
5194 &self,
5195 _style: &EditorStyle,
5196 is_active: bool,
5197 row: DisplayRow,
5198 cx: &mut ViewContext<Self>,
5199 ) -> IconButton {
5200 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5201 .shape(ui::IconButtonShape::Square)
5202 .icon_size(IconSize::XSmall)
5203 .icon_color(Color::Muted)
5204 .toggle_state(is_active)
5205 .on_click(cx.listener(move |editor, _e, cx| {
5206 editor.focus(cx);
5207 editor.toggle_code_actions(
5208 &ToggleCodeActions {
5209 deployed_from_indicator: Some(row),
5210 },
5211 cx,
5212 );
5213 }))
5214 }
5215
5216 #[cfg(any(feature = "test-support", test))]
5217 pub fn context_menu_visible(&self) -> bool {
5218 self.context_menu
5219 .borrow()
5220 .as_ref()
5221 .map_or(false, |menu| menu.visible())
5222 }
5223
5224 #[cfg(feature = "test-support")]
5225 pub fn context_menu_contains_inline_completion(&self) -> bool {
5226 self.context_menu
5227 .borrow()
5228 .as_ref()
5229 .map_or(false, |menu| match menu {
5230 CodeContextMenu::Completions(menu) => {
5231 menu.entries.borrow().first().map_or(false, |entry| {
5232 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5233 })
5234 }
5235 CodeContextMenu::CodeActions(_) => false,
5236 })
5237 }
5238
5239 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5240 self.context_menu
5241 .borrow()
5242 .as_ref()
5243 .map(|menu| menu.origin(cursor_position))
5244 }
5245
5246 fn render_context_menu(
5247 &self,
5248 style: &EditorStyle,
5249 max_height_in_lines: u32,
5250 cx: &mut ViewContext<Editor>,
5251 ) -> Option<AnyElement> {
5252 self.context_menu.borrow().as_ref().and_then(|menu| {
5253 if menu.visible() {
5254 Some(menu.render(style, max_height_in_lines, cx))
5255 } else {
5256 None
5257 }
5258 })
5259 }
5260
5261 fn render_context_menu_aside(
5262 &self,
5263 style: &EditorStyle,
5264 max_size: Size<Pixels>,
5265 cx: &mut ViewContext<Editor>,
5266 ) -> Option<AnyElement> {
5267 self.context_menu.borrow().as_ref().and_then(|menu| {
5268 if menu.visible() {
5269 menu.render_aside(
5270 style,
5271 max_size,
5272 self.workspace.as_ref().map(|(w, _)| w.clone()),
5273 cx,
5274 )
5275 } else {
5276 None
5277 }
5278 })
5279 }
5280
5281 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5282 cx.notify();
5283 self.completion_tasks.clear();
5284 let context_menu = self.context_menu.borrow_mut().take();
5285 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5286 self.update_visible_inline_completion(cx);
5287 }
5288 context_menu
5289 }
5290
5291 fn show_snippet_choices(
5292 &mut self,
5293 choices: &Vec<String>,
5294 selection: Range<Anchor>,
5295 cx: &mut ViewContext<Self>,
5296 ) {
5297 if selection.start.buffer_id.is_none() {
5298 return;
5299 }
5300 let buffer_id = selection.start.buffer_id.unwrap();
5301 let buffer = self.buffer().read(cx).buffer(buffer_id);
5302 let id = post_inc(&mut self.next_completion_id);
5303
5304 if let Some(buffer) = buffer {
5305 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5306 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5307 ));
5308 }
5309 }
5310
5311 pub fn insert_snippet(
5312 &mut self,
5313 insertion_ranges: &[Range<usize>],
5314 snippet: Snippet,
5315 cx: &mut ViewContext<Self>,
5316 ) -> Result<()> {
5317 struct Tabstop<T> {
5318 is_end_tabstop: bool,
5319 ranges: Vec<Range<T>>,
5320 choices: Option<Vec<String>>,
5321 }
5322
5323 let tabstops = self.buffer.update(cx, |buffer, cx| {
5324 let snippet_text: Arc<str> = snippet.text.clone().into();
5325 buffer.edit(
5326 insertion_ranges
5327 .iter()
5328 .cloned()
5329 .map(|range| (range, snippet_text.clone())),
5330 Some(AutoindentMode::EachLine),
5331 cx,
5332 );
5333
5334 let snapshot = &*buffer.read(cx);
5335 let snippet = &snippet;
5336 snippet
5337 .tabstops
5338 .iter()
5339 .map(|tabstop| {
5340 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5341 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5342 });
5343 let mut tabstop_ranges = tabstop
5344 .ranges
5345 .iter()
5346 .flat_map(|tabstop_range| {
5347 let mut delta = 0_isize;
5348 insertion_ranges.iter().map(move |insertion_range| {
5349 let insertion_start = insertion_range.start as isize + delta;
5350 delta +=
5351 snippet.text.len() as isize - insertion_range.len() as isize;
5352
5353 let start = ((insertion_start + tabstop_range.start) as usize)
5354 .min(snapshot.len());
5355 let end = ((insertion_start + tabstop_range.end) as usize)
5356 .min(snapshot.len());
5357 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5358 })
5359 })
5360 .collect::<Vec<_>>();
5361 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5362
5363 Tabstop {
5364 is_end_tabstop,
5365 ranges: tabstop_ranges,
5366 choices: tabstop.choices.clone(),
5367 }
5368 })
5369 .collect::<Vec<_>>()
5370 });
5371 if let Some(tabstop) = tabstops.first() {
5372 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5373 s.select_ranges(tabstop.ranges.iter().cloned());
5374 });
5375
5376 if let Some(choices) = &tabstop.choices {
5377 if let Some(selection) = tabstop.ranges.first() {
5378 self.show_snippet_choices(choices, selection.clone(), cx)
5379 }
5380 }
5381
5382 // If we're already at the last tabstop and it's at the end of the snippet,
5383 // we're done, we don't need to keep the state around.
5384 if !tabstop.is_end_tabstop {
5385 let choices = tabstops
5386 .iter()
5387 .map(|tabstop| tabstop.choices.clone())
5388 .collect();
5389
5390 let ranges = tabstops
5391 .into_iter()
5392 .map(|tabstop| tabstop.ranges)
5393 .collect::<Vec<_>>();
5394
5395 self.snippet_stack.push(SnippetState {
5396 active_index: 0,
5397 ranges,
5398 choices,
5399 });
5400 }
5401
5402 // Check whether the just-entered snippet ends with an auto-closable bracket.
5403 if self.autoclose_regions.is_empty() {
5404 let snapshot = self.buffer.read(cx).snapshot(cx);
5405 for selection in &mut self.selections.all::<Point>(cx) {
5406 let selection_head = selection.head();
5407 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5408 continue;
5409 };
5410
5411 let mut bracket_pair = None;
5412 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5413 let prev_chars = snapshot
5414 .reversed_chars_at(selection_head)
5415 .collect::<String>();
5416 for (pair, enabled) in scope.brackets() {
5417 if enabled
5418 && pair.close
5419 && prev_chars.starts_with(pair.start.as_str())
5420 && next_chars.starts_with(pair.end.as_str())
5421 {
5422 bracket_pair = Some(pair.clone());
5423 break;
5424 }
5425 }
5426 if let Some(pair) = bracket_pair {
5427 let start = snapshot.anchor_after(selection_head);
5428 let end = snapshot.anchor_after(selection_head);
5429 self.autoclose_regions.push(AutocloseRegion {
5430 selection_id: selection.id,
5431 range: start..end,
5432 pair,
5433 });
5434 }
5435 }
5436 }
5437 }
5438 Ok(())
5439 }
5440
5441 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5442 self.move_to_snippet_tabstop(Bias::Right, cx)
5443 }
5444
5445 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5446 self.move_to_snippet_tabstop(Bias::Left, cx)
5447 }
5448
5449 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5450 if let Some(mut snippet) = self.snippet_stack.pop() {
5451 match bias {
5452 Bias::Left => {
5453 if snippet.active_index > 0 {
5454 snippet.active_index -= 1;
5455 } else {
5456 self.snippet_stack.push(snippet);
5457 return false;
5458 }
5459 }
5460 Bias::Right => {
5461 if snippet.active_index + 1 < snippet.ranges.len() {
5462 snippet.active_index += 1;
5463 } else {
5464 self.snippet_stack.push(snippet);
5465 return false;
5466 }
5467 }
5468 }
5469 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5471 s.select_anchor_ranges(current_ranges.iter().cloned())
5472 });
5473
5474 if let Some(choices) = &snippet.choices[snippet.active_index] {
5475 if let Some(selection) = current_ranges.first() {
5476 self.show_snippet_choices(&choices, selection.clone(), cx);
5477 }
5478 }
5479
5480 // If snippet state is not at the last tabstop, push it back on the stack
5481 if snippet.active_index + 1 < snippet.ranges.len() {
5482 self.snippet_stack.push(snippet);
5483 }
5484 return true;
5485 }
5486 }
5487
5488 false
5489 }
5490
5491 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5492 self.transact(cx, |this, cx| {
5493 this.select_all(&SelectAll, cx);
5494 this.insert("", cx);
5495 });
5496 }
5497
5498 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5499 self.transact(cx, |this, cx| {
5500 this.select_autoclose_pair(cx);
5501 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5502 if !this.linked_edit_ranges.is_empty() {
5503 let selections = this.selections.all::<MultiBufferPoint>(cx);
5504 let snapshot = this.buffer.read(cx).snapshot(cx);
5505
5506 for selection in selections.iter() {
5507 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5508 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5509 if selection_start.buffer_id != selection_end.buffer_id {
5510 continue;
5511 }
5512 if let Some(ranges) =
5513 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5514 {
5515 for (buffer, entries) in ranges {
5516 linked_ranges.entry(buffer).or_default().extend(entries);
5517 }
5518 }
5519 }
5520 }
5521
5522 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5523 if !this.selections.line_mode {
5524 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5525 for selection in &mut selections {
5526 if selection.is_empty() {
5527 let old_head = selection.head();
5528 let mut new_head =
5529 movement::left(&display_map, old_head.to_display_point(&display_map))
5530 .to_point(&display_map);
5531 if let Some((buffer, line_buffer_range)) = display_map
5532 .buffer_snapshot
5533 .buffer_line_for_row(MultiBufferRow(old_head.row))
5534 {
5535 let indent_size =
5536 buffer.indent_size_for_line(line_buffer_range.start.row);
5537 let indent_len = match indent_size.kind {
5538 IndentKind::Space => {
5539 buffer.settings_at(line_buffer_range.start, cx).tab_size
5540 }
5541 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5542 };
5543 if old_head.column <= indent_size.len && old_head.column > 0 {
5544 let indent_len = indent_len.get();
5545 new_head = cmp::min(
5546 new_head,
5547 MultiBufferPoint::new(
5548 old_head.row,
5549 ((old_head.column - 1) / indent_len) * indent_len,
5550 ),
5551 );
5552 }
5553 }
5554
5555 selection.set_head(new_head, SelectionGoal::None);
5556 }
5557 }
5558 }
5559
5560 this.signature_help_state.set_backspace_pressed(true);
5561 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5562 this.insert("", cx);
5563 let empty_str: Arc<str> = Arc::from("");
5564 for (buffer, edits) in linked_ranges {
5565 let snapshot = buffer.read(cx).snapshot();
5566 use text::ToPoint as TP;
5567
5568 let edits = edits
5569 .into_iter()
5570 .map(|range| {
5571 let end_point = TP::to_point(&range.end, &snapshot);
5572 let mut start_point = TP::to_point(&range.start, &snapshot);
5573
5574 if end_point == start_point {
5575 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5576 .saturating_sub(1);
5577 start_point =
5578 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5579 };
5580
5581 (start_point..end_point, empty_str.clone())
5582 })
5583 .sorted_by_key(|(range, _)| range.start)
5584 .collect::<Vec<_>>();
5585 buffer.update(cx, |this, cx| {
5586 this.edit(edits, None, cx);
5587 })
5588 }
5589 this.refresh_inline_completion(true, false, cx);
5590 linked_editing_ranges::refresh_linked_ranges(this, cx);
5591 });
5592 }
5593
5594 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5595 self.transact(cx, |this, cx| {
5596 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5597 let line_mode = s.line_mode;
5598 s.move_with(|map, selection| {
5599 if selection.is_empty() && !line_mode {
5600 let cursor = movement::right(map, selection.head());
5601 selection.end = cursor;
5602 selection.reversed = true;
5603 selection.goal = SelectionGoal::None;
5604 }
5605 })
5606 });
5607 this.insert("", cx);
5608 this.refresh_inline_completion(true, false, cx);
5609 });
5610 }
5611
5612 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5613 if self.move_to_prev_snippet_tabstop(cx) {
5614 return;
5615 }
5616
5617 self.outdent(&Outdent, cx);
5618 }
5619
5620 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5621 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5622 return;
5623 }
5624
5625 let mut selections = self.selections.all_adjusted(cx);
5626 let buffer = self.buffer.read(cx);
5627 let snapshot = buffer.snapshot(cx);
5628 let rows_iter = selections.iter().map(|s| s.head().row);
5629 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5630
5631 let mut edits = Vec::new();
5632 let mut prev_edited_row = 0;
5633 let mut row_delta = 0;
5634 for selection in &mut selections {
5635 if selection.start.row != prev_edited_row {
5636 row_delta = 0;
5637 }
5638 prev_edited_row = selection.end.row;
5639
5640 // If the selection is non-empty, then increase the indentation of the selected lines.
5641 if !selection.is_empty() {
5642 row_delta =
5643 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5644 continue;
5645 }
5646
5647 // If the selection is empty and the cursor is in the leading whitespace before the
5648 // suggested indentation, then auto-indent the line.
5649 let cursor = selection.head();
5650 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5651 if let Some(suggested_indent) =
5652 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5653 {
5654 if cursor.column < suggested_indent.len
5655 && cursor.column <= current_indent.len
5656 && current_indent.len <= suggested_indent.len
5657 {
5658 selection.start = Point::new(cursor.row, suggested_indent.len);
5659 selection.end = selection.start;
5660 if row_delta == 0 {
5661 edits.extend(Buffer::edit_for_indent_size_adjustment(
5662 cursor.row,
5663 current_indent,
5664 suggested_indent,
5665 ));
5666 row_delta = suggested_indent.len - current_indent.len;
5667 }
5668 continue;
5669 }
5670 }
5671
5672 // Otherwise, insert a hard or soft tab.
5673 let settings = buffer.settings_at(cursor, cx);
5674 let tab_size = if settings.hard_tabs {
5675 IndentSize::tab()
5676 } else {
5677 let tab_size = settings.tab_size.get();
5678 let char_column = snapshot
5679 .text_for_range(Point::new(cursor.row, 0)..cursor)
5680 .flat_map(str::chars)
5681 .count()
5682 + row_delta as usize;
5683 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5684 IndentSize::spaces(chars_to_next_tab_stop)
5685 };
5686 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5687 selection.end = selection.start;
5688 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5689 row_delta += tab_size.len;
5690 }
5691
5692 self.transact(cx, |this, cx| {
5693 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5694 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5695 this.refresh_inline_completion(true, false, cx);
5696 });
5697 }
5698
5699 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5700 if self.read_only(cx) {
5701 return;
5702 }
5703 let mut selections = self.selections.all::<Point>(cx);
5704 let mut prev_edited_row = 0;
5705 let mut row_delta = 0;
5706 let mut edits = Vec::new();
5707 let buffer = self.buffer.read(cx);
5708 let snapshot = buffer.snapshot(cx);
5709 for selection in &mut selections {
5710 if selection.start.row != prev_edited_row {
5711 row_delta = 0;
5712 }
5713 prev_edited_row = selection.end.row;
5714
5715 row_delta =
5716 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5717 }
5718
5719 self.transact(cx, |this, cx| {
5720 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5721 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5722 });
5723 }
5724
5725 fn indent_selection(
5726 buffer: &MultiBuffer,
5727 snapshot: &MultiBufferSnapshot,
5728 selection: &mut Selection<Point>,
5729 edits: &mut Vec<(Range<Point>, String)>,
5730 delta_for_start_row: u32,
5731 cx: &AppContext,
5732 ) -> u32 {
5733 let settings = buffer.settings_at(selection.start, cx);
5734 let tab_size = settings.tab_size.get();
5735 let indent_kind = if settings.hard_tabs {
5736 IndentKind::Tab
5737 } else {
5738 IndentKind::Space
5739 };
5740 let mut start_row = selection.start.row;
5741 let mut end_row = selection.end.row + 1;
5742
5743 // If a selection ends at the beginning of a line, don't indent
5744 // that last line.
5745 if selection.end.column == 0 && selection.end.row > selection.start.row {
5746 end_row -= 1;
5747 }
5748
5749 // Avoid re-indenting a row that has already been indented by a
5750 // previous selection, but still update this selection's column
5751 // to reflect that indentation.
5752 if delta_for_start_row > 0 {
5753 start_row += 1;
5754 selection.start.column += delta_for_start_row;
5755 if selection.end.row == selection.start.row {
5756 selection.end.column += delta_for_start_row;
5757 }
5758 }
5759
5760 let mut delta_for_end_row = 0;
5761 let has_multiple_rows = start_row + 1 != end_row;
5762 for row in start_row..end_row {
5763 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5764 let indent_delta = match (current_indent.kind, indent_kind) {
5765 (IndentKind::Space, IndentKind::Space) => {
5766 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5767 IndentSize::spaces(columns_to_next_tab_stop)
5768 }
5769 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5770 (_, IndentKind::Tab) => IndentSize::tab(),
5771 };
5772
5773 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5774 0
5775 } else {
5776 selection.start.column
5777 };
5778 let row_start = Point::new(row, start);
5779 edits.push((
5780 row_start..row_start,
5781 indent_delta.chars().collect::<String>(),
5782 ));
5783
5784 // Update this selection's endpoints to reflect the indentation.
5785 if row == selection.start.row {
5786 selection.start.column += indent_delta.len;
5787 }
5788 if row == selection.end.row {
5789 selection.end.column += indent_delta.len;
5790 delta_for_end_row = indent_delta.len;
5791 }
5792 }
5793
5794 if selection.start.row == selection.end.row {
5795 delta_for_start_row + delta_for_end_row
5796 } else {
5797 delta_for_end_row
5798 }
5799 }
5800
5801 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5802 if self.read_only(cx) {
5803 return;
5804 }
5805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5806 let selections = self.selections.all::<Point>(cx);
5807 let mut deletion_ranges = Vec::new();
5808 let mut last_outdent = None;
5809 {
5810 let buffer = self.buffer.read(cx);
5811 let snapshot = buffer.snapshot(cx);
5812 for selection in &selections {
5813 let settings = buffer.settings_at(selection.start, cx);
5814 let tab_size = settings.tab_size.get();
5815 let mut rows = selection.spanned_rows(false, &display_map);
5816
5817 // Avoid re-outdenting a row that has already been outdented by a
5818 // previous selection.
5819 if let Some(last_row) = last_outdent {
5820 if last_row == rows.start {
5821 rows.start = rows.start.next_row();
5822 }
5823 }
5824 let has_multiple_rows = rows.len() > 1;
5825 for row in rows.iter_rows() {
5826 let indent_size = snapshot.indent_size_for_line(row);
5827 if indent_size.len > 0 {
5828 let deletion_len = match indent_size.kind {
5829 IndentKind::Space => {
5830 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5831 if columns_to_prev_tab_stop == 0 {
5832 tab_size
5833 } else {
5834 columns_to_prev_tab_stop
5835 }
5836 }
5837 IndentKind::Tab => 1,
5838 };
5839 let start = if has_multiple_rows
5840 || deletion_len > selection.start.column
5841 || indent_size.len < selection.start.column
5842 {
5843 0
5844 } else {
5845 selection.start.column - deletion_len
5846 };
5847 deletion_ranges.push(
5848 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5849 );
5850 last_outdent = Some(row);
5851 }
5852 }
5853 }
5854 }
5855
5856 self.transact(cx, |this, cx| {
5857 this.buffer.update(cx, |buffer, cx| {
5858 let empty_str: Arc<str> = Arc::default();
5859 buffer.edit(
5860 deletion_ranges
5861 .into_iter()
5862 .map(|range| (range, empty_str.clone())),
5863 None,
5864 cx,
5865 );
5866 });
5867 let selections = this.selections.all::<usize>(cx);
5868 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5869 });
5870 }
5871
5872 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5873 if self.read_only(cx) {
5874 return;
5875 }
5876 let selections = self
5877 .selections
5878 .all::<usize>(cx)
5879 .into_iter()
5880 .map(|s| s.range());
5881
5882 self.transact(cx, |this, cx| {
5883 this.buffer.update(cx, |buffer, cx| {
5884 buffer.autoindent_ranges(selections, cx);
5885 });
5886 let selections = this.selections.all::<usize>(cx);
5887 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5888 });
5889 }
5890
5891 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5892 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5893 let selections = self.selections.all::<Point>(cx);
5894
5895 let mut new_cursors = Vec::new();
5896 let mut edit_ranges = Vec::new();
5897 let mut selections = selections.iter().peekable();
5898 while let Some(selection) = selections.next() {
5899 let mut rows = selection.spanned_rows(false, &display_map);
5900 let goal_display_column = selection.head().to_display_point(&display_map).column();
5901
5902 // Accumulate contiguous regions of rows that we want to delete.
5903 while let Some(next_selection) = selections.peek() {
5904 let next_rows = next_selection.spanned_rows(false, &display_map);
5905 if next_rows.start <= rows.end {
5906 rows.end = next_rows.end;
5907 selections.next().unwrap();
5908 } else {
5909 break;
5910 }
5911 }
5912
5913 let buffer = &display_map.buffer_snapshot;
5914 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5915 let edit_end;
5916 let cursor_buffer_row;
5917 if buffer.max_point().row >= rows.end.0 {
5918 // If there's a line after the range, delete the \n from the end of the row range
5919 // and position the cursor on the next line.
5920 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5921 cursor_buffer_row = rows.end;
5922 } else {
5923 // If there isn't a line after the range, delete the \n from the line before the
5924 // start of the row range and position the cursor there.
5925 edit_start = edit_start.saturating_sub(1);
5926 edit_end = buffer.len();
5927 cursor_buffer_row = rows.start.previous_row();
5928 }
5929
5930 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5931 *cursor.column_mut() =
5932 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5933
5934 new_cursors.push((
5935 selection.id,
5936 buffer.anchor_after(cursor.to_point(&display_map)),
5937 ));
5938 edit_ranges.push(edit_start..edit_end);
5939 }
5940
5941 self.transact(cx, |this, cx| {
5942 let buffer = this.buffer.update(cx, |buffer, cx| {
5943 let empty_str: Arc<str> = Arc::default();
5944 buffer.edit(
5945 edit_ranges
5946 .into_iter()
5947 .map(|range| (range, empty_str.clone())),
5948 None,
5949 cx,
5950 );
5951 buffer.snapshot(cx)
5952 });
5953 let new_selections = new_cursors
5954 .into_iter()
5955 .map(|(id, cursor)| {
5956 let cursor = cursor.to_point(&buffer);
5957 Selection {
5958 id,
5959 start: cursor,
5960 end: cursor,
5961 reversed: false,
5962 goal: SelectionGoal::None,
5963 }
5964 })
5965 .collect();
5966
5967 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5968 s.select(new_selections);
5969 });
5970 });
5971 }
5972
5973 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5974 if self.read_only(cx) {
5975 return;
5976 }
5977 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5978 for selection in self.selections.all::<Point>(cx) {
5979 let start = MultiBufferRow(selection.start.row);
5980 // Treat single line selections as if they include the next line. Otherwise this action
5981 // would do nothing for single line selections individual cursors.
5982 let end = if selection.start.row == selection.end.row {
5983 MultiBufferRow(selection.start.row + 1)
5984 } else {
5985 MultiBufferRow(selection.end.row)
5986 };
5987
5988 if let Some(last_row_range) = row_ranges.last_mut() {
5989 if start <= last_row_range.end {
5990 last_row_range.end = end;
5991 continue;
5992 }
5993 }
5994 row_ranges.push(start..end);
5995 }
5996
5997 let snapshot = self.buffer.read(cx).snapshot(cx);
5998 let mut cursor_positions = Vec::new();
5999 for row_range in &row_ranges {
6000 let anchor = snapshot.anchor_before(Point::new(
6001 row_range.end.previous_row().0,
6002 snapshot.line_len(row_range.end.previous_row()),
6003 ));
6004 cursor_positions.push(anchor..anchor);
6005 }
6006
6007 self.transact(cx, |this, cx| {
6008 for row_range in row_ranges.into_iter().rev() {
6009 for row in row_range.iter_rows().rev() {
6010 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6011 let next_line_row = row.next_row();
6012 let indent = snapshot.indent_size_for_line(next_line_row);
6013 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6014
6015 let replace =
6016 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6017 " "
6018 } else {
6019 ""
6020 };
6021
6022 this.buffer.update(cx, |buffer, cx| {
6023 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6024 });
6025 }
6026 }
6027
6028 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6029 s.select_anchor_ranges(cursor_positions)
6030 });
6031 });
6032 }
6033
6034 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6035 self.join_lines_impl(true, cx);
6036 }
6037
6038 pub fn sort_lines_case_sensitive(
6039 &mut self,
6040 _: &SortLinesCaseSensitive,
6041 cx: &mut ViewContext<Self>,
6042 ) {
6043 self.manipulate_lines(cx, |lines| lines.sort())
6044 }
6045
6046 pub fn sort_lines_case_insensitive(
6047 &mut self,
6048 _: &SortLinesCaseInsensitive,
6049 cx: &mut ViewContext<Self>,
6050 ) {
6051 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6052 }
6053
6054 pub fn unique_lines_case_insensitive(
6055 &mut self,
6056 _: &UniqueLinesCaseInsensitive,
6057 cx: &mut ViewContext<Self>,
6058 ) {
6059 self.manipulate_lines(cx, |lines| {
6060 let mut seen = HashSet::default();
6061 lines.retain(|line| seen.insert(line.to_lowercase()));
6062 })
6063 }
6064
6065 pub fn unique_lines_case_sensitive(
6066 &mut self,
6067 _: &UniqueLinesCaseSensitive,
6068 cx: &mut ViewContext<Self>,
6069 ) {
6070 self.manipulate_lines(cx, |lines| {
6071 let mut seen = HashSet::default();
6072 lines.retain(|line| seen.insert(*line));
6073 })
6074 }
6075
6076 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6077 let mut revert_changes = HashMap::default();
6078 let snapshot = self.snapshot(cx);
6079 for hunk in hunks_for_ranges(
6080 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6081 &snapshot,
6082 ) {
6083 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6084 }
6085 if !revert_changes.is_empty() {
6086 self.transact(cx, |editor, cx| {
6087 editor.revert(revert_changes, cx);
6088 });
6089 }
6090 }
6091
6092 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6093 let Some(project) = self.project.clone() else {
6094 return;
6095 };
6096 self.reload(project, cx).detach_and_notify_err(cx);
6097 }
6098
6099 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6100 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6101 if !revert_changes.is_empty() {
6102 self.transact(cx, |editor, cx| {
6103 editor.revert(revert_changes, cx);
6104 });
6105 }
6106 }
6107
6108 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6109 let snapshot = self.buffer.read(cx).read(cx);
6110 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6111 drop(snapshot);
6112 let mut revert_changes = HashMap::default();
6113 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6114 if !revert_changes.is_empty() {
6115 self.revert(revert_changes, cx)
6116 }
6117 }
6118 }
6119
6120 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6121 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6122 let project_path = buffer.read(cx).project_path(cx)?;
6123 let project = self.project.as_ref()?.read(cx);
6124 let entry = project.entry_for_path(&project_path, cx)?;
6125 let parent = match &entry.canonical_path {
6126 Some(canonical_path) => canonical_path.to_path_buf(),
6127 None => project.absolute_path(&project_path, cx)?,
6128 }
6129 .parent()?
6130 .to_path_buf();
6131 Some(parent)
6132 }) {
6133 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6134 }
6135 }
6136
6137 fn gather_revert_changes(
6138 &mut self,
6139 selections: &[Selection<Point>],
6140 cx: &mut ViewContext<Editor>,
6141 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6142 let mut revert_changes = HashMap::default();
6143 let snapshot = self.snapshot(cx);
6144 for hunk in hunks_for_selections(&snapshot, selections) {
6145 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6146 }
6147 revert_changes
6148 }
6149
6150 pub fn prepare_revert_change(
6151 &mut self,
6152 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6153 hunk: &MultiBufferDiffHunk,
6154 cx: &AppContext,
6155 ) -> Option<()> {
6156 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6157 let buffer = buffer.read(cx);
6158 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6159 let original_text = change_set
6160 .read(cx)
6161 .base_text
6162 .as_ref()?
6163 .read(cx)
6164 .as_rope()
6165 .slice(hunk.diff_base_byte_range.clone());
6166 let buffer_snapshot = buffer.snapshot();
6167 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6168 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6169 probe
6170 .0
6171 .start
6172 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6173 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6174 }) {
6175 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6176 Some(())
6177 } else {
6178 None
6179 }
6180 }
6181
6182 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6183 self.manipulate_lines(cx, |lines| lines.reverse())
6184 }
6185
6186 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6187 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6188 }
6189
6190 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6191 where
6192 Fn: FnMut(&mut Vec<&str>),
6193 {
6194 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6195 let buffer = self.buffer.read(cx).snapshot(cx);
6196
6197 let mut edits = Vec::new();
6198
6199 let selections = self.selections.all::<Point>(cx);
6200 let mut selections = selections.iter().peekable();
6201 let mut contiguous_row_selections = Vec::new();
6202 let mut new_selections = Vec::new();
6203 let mut added_lines = 0;
6204 let mut removed_lines = 0;
6205
6206 while let Some(selection) = selections.next() {
6207 let (start_row, end_row) = consume_contiguous_rows(
6208 &mut contiguous_row_selections,
6209 selection,
6210 &display_map,
6211 &mut selections,
6212 );
6213
6214 let start_point = Point::new(start_row.0, 0);
6215 let end_point = Point::new(
6216 end_row.previous_row().0,
6217 buffer.line_len(end_row.previous_row()),
6218 );
6219 let text = buffer
6220 .text_for_range(start_point..end_point)
6221 .collect::<String>();
6222
6223 let mut lines = text.split('\n').collect_vec();
6224
6225 let lines_before = lines.len();
6226 callback(&mut lines);
6227 let lines_after = lines.len();
6228
6229 edits.push((start_point..end_point, lines.join("\n")));
6230
6231 // Selections must change based on added and removed line count
6232 let start_row =
6233 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6234 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6235 new_selections.push(Selection {
6236 id: selection.id,
6237 start: start_row,
6238 end: end_row,
6239 goal: SelectionGoal::None,
6240 reversed: selection.reversed,
6241 });
6242
6243 if lines_after > lines_before {
6244 added_lines += lines_after - lines_before;
6245 } else if lines_before > lines_after {
6246 removed_lines += lines_before - lines_after;
6247 }
6248 }
6249
6250 self.transact(cx, |this, cx| {
6251 let buffer = this.buffer.update(cx, |buffer, cx| {
6252 buffer.edit(edits, None, cx);
6253 buffer.snapshot(cx)
6254 });
6255
6256 // Recalculate offsets on newly edited buffer
6257 let new_selections = new_selections
6258 .iter()
6259 .map(|s| {
6260 let start_point = Point::new(s.start.0, 0);
6261 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6262 Selection {
6263 id: s.id,
6264 start: buffer.point_to_offset(start_point),
6265 end: buffer.point_to_offset(end_point),
6266 goal: s.goal,
6267 reversed: s.reversed,
6268 }
6269 })
6270 .collect();
6271
6272 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6273 s.select(new_selections);
6274 });
6275
6276 this.request_autoscroll(Autoscroll::fit(), cx);
6277 });
6278 }
6279
6280 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6281 self.manipulate_text(cx, |text| text.to_uppercase())
6282 }
6283
6284 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6285 self.manipulate_text(cx, |text| text.to_lowercase())
6286 }
6287
6288 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6289 self.manipulate_text(cx, |text| {
6290 text.split('\n')
6291 .map(|line| line.to_case(Case::Title))
6292 .join("\n")
6293 })
6294 }
6295
6296 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6297 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6298 }
6299
6300 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6301 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6302 }
6303
6304 pub fn convert_to_upper_camel_case(
6305 &mut self,
6306 _: &ConvertToUpperCamelCase,
6307 cx: &mut ViewContext<Self>,
6308 ) {
6309 self.manipulate_text(cx, |text| {
6310 text.split('\n')
6311 .map(|line| line.to_case(Case::UpperCamel))
6312 .join("\n")
6313 })
6314 }
6315
6316 pub fn convert_to_lower_camel_case(
6317 &mut self,
6318 _: &ConvertToLowerCamelCase,
6319 cx: &mut ViewContext<Self>,
6320 ) {
6321 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6322 }
6323
6324 pub fn convert_to_opposite_case(
6325 &mut self,
6326 _: &ConvertToOppositeCase,
6327 cx: &mut ViewContext<Self>,
6328 ) {
6329 self.manipulate_text(cx, |text| {
6330 text.chars()
6331 .fold(String::with_capacity(text.len()), |mut t, c| {
6332 if c.is_uppercase() {
6333 t.extend(c.to_lowercase());
6334 } else {
6335 t.extend(c.to_uppercase());
6336 }
6337 t
6338 })
6339 })
6340 }
6341
6342 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6343 where
6344 Fn: FnMut(&str) -> String,
6345 {
6346 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6347 let buffer = self.buffer.read(cx).snapshot(cx);
6348
6349 let mut new_selections = Vec::new();
6350 let mut edits = Vec::new();
6351 let mut selection_adjustment = 0i32;
6352
6353 for selection in self.selections.all::<usize>(cx) {
6354 let selection_is_empty = selection.is_empty();
6355
6356 let (start, end) = if selection_is_empty {
6357 let word_range = movement::surrounding_word(
6358 &display_map,
6359 selection.start.to_display_point(&display_map),
6360 );
6361 let start = word_range.start.to_offset(&display_map, Bias::Left);
6362 let end = word_range.end.to_offset(&display_map, Bias::Left);
6363 (start, end)
6364 } else {
6365 (selection.start, selection.end)
6366 };
6367
6368 let text = buffer.text_for_range(start..end).collect::<String>();
6369 let old_length = text.len() as i32;
6370 let text = callback(&text);
6371
6372 new_selections.push(Selection {
6373 start: (start as i32 - selection_adjustment) as usize,
6374 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6375 goal: SelectionGoal::None,
6376 ..selection
6377 });
6378
6379 selection_adjustment += old_length - text.len() as i32;
6380
6381 edits.push((start..end, text));
6382 }
6383
6384 self.transact(cx, |this, cx| {
6385 this.buffer.update(cx, |buffer, cx| {
6386 buffer.edit(edits, None, cx);
6387 });
6388
6389 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6390 s.select(new_selections);
6391 });
6392
6393 this.request_autoscroll(Autoscroll::fit(), cx);
6394 });
6395 }
6396
6397 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6399 let buffer = &display_map.buffer_snapshot;
6400 let selections = self.selections.all::<Point>(cx);
6401
6402 let mut edits = Vec::new();
6403 let mut selections_iter = selections.iter().peekable();
6404 while let Some(selection) = selections_iter.next() {
6405 let mut rows = selection.spanned_rows(false, &display_map);
6406 // duplicate line-wise
6407 if whole_lines || selection.start == selection.end {
6408 // Avoid duplicating the same lines twice.
6409 while let Some(next_selection) = selections_iter.peek() {
6410 let next_rows = next_selection.spanned_rows(false, &display_map);
6411 if next_rows.start < rows.end {
6412 rows.end = next_rows.end;
6413 selections_iter.next().unwrap();
6414 } else {
6415 break;
6416 }
6417 }
6418
6419 // Copy the text from the selected row region and splice it either at the start
6420 // or end of the region.
6421 let start = Point::new(rows.start.0, 0);
6422 let end = Point::new(
6423 rows.end.previous_row().0,
6424 buffer.line_len(rows.end.previous_row()),
6425 );
6426 let text = buffer
6427 .text_for_range(start..end)
6428 .chain(Some("\n"))
6429 .collect::<String>();
6430 let insert_location = if upwards {
6431 Point::new(rows.end.0, 0)
6432 } else {
6433 start
6434 };
6435 edits.push((insert_location..insert_location, text));
6436 } else {
6437 // duplicate character-wise
6438 let start = selection.start;
6439 let end = selection.end;
6440 let text = buffer.text_for_range(start..end).collect::<String>();
6441 edits.push((selection.end..selection.end, text));
6442 }
6443 }
6444
6445 self.transact(cx, |this, cx| {
6446 this.buffer.update(cx, |buffer, cx| {
6447 buffer.edit(edits, None, cx);
6448 });
6449
6450 this.request_autoscroll(Autoscroll::fit(), cx);
6451 });
6452 }
6453
6454 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6455 self.duplicate(true, true, cx);
6456 }
6457
6458 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6459 self.duplicate(false, true, cx);
6460 }
6461
6462 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6463 self.duplicate(false, false, cx);
6464 }
6465
6466 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6468 let buffer = self.buffer.read(cx).snapshot(cx);
6469
6470 let mut edits = Vec::new();
6471 let mut unfold_ranges = Vec::new();
6472 let mut refold_creases = Vec::new();
6473
6474 let selections = self.selections.all::<Point>(cx);
6475 let mut selections = selections.iter().peekable();
6476 let mut contiguous_row_selections = Vec::new();
6477 let mut new_selections = Vec::new();
6478
6479 while let Some(selection) = selections.next() {
6480 // Find all the selections that span a contiguous row range
6481 let (start_row, end_row) = consume_contiguous_rows(
6482 &mut contiguous_row_selections,
6483 selection,
6484 &display_map,
6485 &mut selections,
6486 );
6487
6488 // Move the text spanned by the row range to be before the line preceding the row range
6489 if start_row.0 > 0 {
6490 let range_to_move = Point::new(
6491 start_row.previous_row().0,
6492 buffer.line_len(start_row.previous_row()),
6493 )
6494 ..Point::new(
6495 end_row.previous_row().0,
6496 buffer.line_len(end_row.previous_row()),
6497 );
6498 let insertion_point = display_map
6499 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6500 .0;
6501
6502 // Don't move lines across excerpts
6503 if buffer
6504 .excerpt_boundaries_in_range((
6505 Bound::Excluded(insertion_point),
6506 Bound::Included(range_to_move.end),
6507 ))
6508 .next()
6509 .is_none()
6510 {
6511 let text = buffer
6512 .text_for_range(range_to_move.clone())
6513 .flat_map(|s| s.chars())
6514 .skip(1)
6515 .chain(['\n'])
6516 .collect::<String>();
6517
6518 edits.push((
6519 buffer.anchor_after(range_to_move.start)
6520 ..buffer.anchor_before(range_to_move.end),
6521 String::new(),
6522 ));
6523 let insertion_anchor = buffer.anchor_after(insertion_point);
6524 edits.push((insertion_anchor..insertion_anchor, text));
6525
6526 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6527
6528 // Move selections up
6529 new_selections.extend(contiguous_row_selections.drain(..).map(
6530 |mut selection| {
6531 selection.start.row -= row_delta;
6532 selection.end.row -= row_delta;
6533 selection
6534 },
6535 ));
6536
6537 // Move folds up
6538 unfold_ranges.push(range_to_move.clone());
6539 for fold in display_map.folds_in_range(
6540 buffer.anchor_before(range_to_move.start)
6541 ..buffer.anchor_after(range_to_move.end),
6542 ) {
6543 let mut start = fold.range.start.to_point(&buffer);
6544 let mut end = fold.range.end.to_point(&buffer);
6545 start.row -= row_delta;
6546 end.row -= row_delta;
6547 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6548 }
6549 }
6550 }
6551
6552 // If we didn't move line(s), preserve the existing selections
6553 new_selections.append(&mut contiguous_row_selections);
6554 }
6555
6556 self.transact(cx, |this, cx| {
6557 this.unfold_ranges(&unfold_ranges, true, true, cx);
6558 this.buffer.update(cx, |buffer, cx| {
6559 for (range, text) in edits {
6560 buffer.edit([(range, text)], None, cx);
6561 }
6562 });
6563 this.fold_creases(refold_creases, true, cx);
6564 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6565 s.select(new_selections);
6566 })
6567 });
6568 }
6569
6570 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6571 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6572 let buffer = self.buffer.read(cx).snapshot(cx);
6573
6574 let mut edits = Vec::new();
6575 let mut unfold_ranges = Vec::new();
6576 let mut refold_creases = Vec::new();
6577
6578 let selections = self.selections.all::<Point>(cx);
6579 let mut selections = selections.iter().peekable();
6580 let mut contiguous_row_selections = Vec::new();
6581 let mut new_selections = Vec::new();
6582
6583 while let Some(selection) = selections.next() {
6584 // Find all the selections that span a contiguous row range
6585 let (start_row, end_row) = consume_contiguous_rows(
6586 &mut contiguous_row_selections,
6587 selection,
6588 &display_map,
6589 &mut selections,
6590 );
6591
6592 // Move the text spanned by the row range to be after the last line of the row range
6593 if end_row.0 <= buffer.max_point().row {
6594 let range_to_move =
6595 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6596 let insertion_point = display_map
6597 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6598 .0;
6599
6600 // Don't move lines across excerpt boundaries
6601 if buffer
6602 .excerpt_boundaries_in_range((
6603 Bound::Excluded(range_to_move.start),
6604 Bound::Included(insertion_point),
6605 ))
6606 .next()
6607 .is_none()
6608 {
6609 let mut text = String::from("\n");
6610 text.extend(buffer.text_for_range(range_to_move.clone()));
6611 text.pop(); // Drop trailing newline
6612 edits.push((
6613 buffer.anchor_after(range_to_move.start)
6614 ..buffer.anchor_before(range_to_move.end),
6615 String::new(),
6616 ));
6617 let insertion_anchor = buffer.anchor_after(insertion_point);
6618 edits.push((insertion_anchor..insertion_anchor, text));
6619
6620 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6621
6622 // Move selections down
6623 new_selections.extend(contiguous_row_selections.drain(..).map(
6624 |mut selection| {
6625 selection.start.row += row_delta;
6626 selection.end.row += row_delta;
6627 selection
6628 },
6629 ));
6630
6631 // Move folds down
6632 unfold_ranges.push(range_to_move.clone());
6633 for fold in display_map.folds_in_range(
6634 buffer.anchor_before(range_to_move.start)
6635 ..buffer.anchor_after(range_to_move.end),
6636 ) {
6637 let mut start = fold.range.start.to_point(&buffer);
6638 let mut end = fold.range.end.to_point(&buffer);
6639 start.row += row_delta;
6640 end.row += row_delta;
6641 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6642 }
6643 }
6644 }
6645
6646 // If we didn't move line(s), preserve the existing selections
6647 new_selections.append(&mut contiguous_row_selections);
6648 }
6649
6650 self.transact(cx, |this, cx| {
6651 this.unfold_ranges(&unfold_ranges, true, true, cx);
6652 this.buffer.update(cx, |buffer, cx| {
6653 for (range, text) in edits {
6654 buffer.edit([(range, text)], None, cx);
6655 }
6656 });
6657 this.fold_creases(refold_creases, true, cx);
6658 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6659 });
6660 }
6661
6662 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6663 let text_layout_details = &self.text_layout_details(cx);
6664 self.transact(cx, |this, cx| {
6665 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6666 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6667 let line_mode = s.line_mode;
6668 s.move_with(|display_map, selection| {
6669 if !selection.is_empty() || line_mode {
6670 return;
6671 }
6672
6673 let mut head = selection.head();
6674 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6675 if head.column() == display_map.line_len(head.row()) {
6676 transpose_offset = display_map
6677 .buffer_snapshot
6678 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6679 }
6680
6681 if transpose_offset == 0 {
6682 return;
6683 }
6684
6685 *head.column_mut() += 1;
6686 head = display_map.clip_point(head, Bias::Right);
6687 let goal = SelectionGoal::HorizontalPosition(
6688 display_map
6689 .x_for_display_point(head, text_layout_details)
6690 .into(),
6691 );
6692 selection.collapse_to(head, goal);
6693
6694 let transpose_start = display_map
6695 .buffer_snapshot
6696 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6697 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6698 let transpose_end = display_map
6699 .buffer_snapshot
6700 .clip_offset(transpose_offset + 1, Bias::Right);
6701 if let Some(ch) =
6702 display_map.buffer_snapshot.chars_at(transpose_start).next()
6703 {
6704 edits.push((transpose_start..transpose_offset, String::new()));
6705 edits.push((transpose_end..transpose_end, ch.to_string()));
6706 }
6707 }
6708 });
6709 edits
6710 });
6711 this.buffer
6712 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6713 let selections = this.selections.all::<usize>(cx);
6714 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6715 s.select(selections);
6716 });
6717 });
6718 }
6719
6720 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6721 self.rewrap_impl(IsVimMode::No, cx)
6722 }
6723
6724 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6725 let buffer = self.buffer.read(cx).snapshot(cx);
6726 let selections = self.selections.all::<Point>(cx);
6727 let mut selections = selections.iter().peekable();
6728
6729 let mut edits = Vec::new();
6730 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6731
6732 while let Some(selection) = selections.next() {
6733 let mut start_row = selection.start.row;
6734 let mut end_row = selection.end.row;
6735
6736 // Skip selections that overlap with a range that has already been rewrapped.
6737 let selection_range = start_row..end_row;
6738 if rewrapped_row_ranges
6739 .iter()
6740 .any(|range| range.overlaps(&selection_range))
6741 {
6742 continue;
6743 }
6744
6745 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6746
6747 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6748 match language_scope.language_name().0.as_ref() {
6749 "Markdown" | "Plain Text" => {
6750 should_rewrap = true;
6751 }
6752 _ => {}
6753 }
6754 }
6755
6756 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6757
6758 // Since not all lines in the selection may be at the same indent
6759 // level, choose the indent size that is the most common between all
6760 // of the lines.
6761 //
6762 // If there is a tie, we use the deepest indent.
6763 let (indent_size, indent_end) = {
6764 let mut indent_size_occurrences = HashMap::default();
6765 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6766
6767 for row in start_row..=end_row {
6768 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6769 rows_by_indent_size.entry(indent).or_default().push(row);
6770 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6771 }
6772
6773 let indent_size = indent_size_occurrences
6774 .into_iter()
6775 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6776 .map(|(indent, _)| indent)
6777 .unwrap_or_default();
6778 let row = rows_by_indent_size[&indent_size][0];
6779 let indent_end = Point::new(row, indent_size.len);
6780
6781 (indent_size, indent_end)
6782 };
6783
6784 let mut line_prefix = indent_size.chars().collect::<String>();
6785
6786 if let Some(comment_prefix) =
6787 buffer
6788 .language_scope_at(selection.head())
6789 .and_then(|language| {
6790 language
6791 .line_comment_prefixes()
6792 .iter()
6793 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6794 .cloned()
6795 })
6796 {
6797 line_prefix.push_str(&comment_prefix);
6798 should_rewrap = true;
6799 }
6800
6801 if !should_rewrap {
6802 continue;
6803 }
6804
6805 if selection.is_empty() {
6806 'expand_upwards: while start_row > 0 {
6807 let prev_row = start_row - 1;
6808 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6809 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6810 {
6811 start_row = prev_row;
6812 } else {
6813 break 'expand_upwards;
6814 }
6815 }
6816
6817 'expand_downwards: while end_row < buffer.max_point().row {
6818 let next_row = end_row + 1;
6819 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6820 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6821 {
6822 end_row = next_row;
6823 } else {
6824 break 'expand_downwards;
6825 }
6826 }
6827 }
6828
6829 let start = Point::new(start_row, 0);
6830 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6831 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6832 let Some(lines_without_prefixes) = selection_text
6833 .lines()
6834 .map(|line| {
6835 line.strip_prefix(&line_prefix)
6836 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6837 .ok_or_else(|| {
6838 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6839 })
6840 })
6841 .collect::<Result<Vec<_>, _>>()
6842 .log_err()
6843 else {
6844 continue;
6845 };
6846
6847 let wrap_column = buffer
6848 .settings_at(Point::new(start_row, 0), cx)
6849 .preferred_line_length as usize;
6850 let wrapped_text = wrap_with_prefix(
6851 line_prefix,
6852 lines_without_prefixes.join(" "),
6853 wrap_column,
6854 tab_size,
6855 );
6856
6857 // TODO: should always use char-based diff while still supporting cursor behavior that
6858 // matches vim.
6859 let diff = match is_vim_mode {
6860 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6861 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6862 };
6863 let mut offset = start.to_offset(&buffer);
6864 let mut moved_since_edit = true;
6865
6866 for change in diff.iter_all_changes() {
6867 let value = change.value();
6868 match change.tag() {
6869 ChangeTag::Equal => {
6870 offset += value.len();
6871 moved_since_edit = true;
6872 }
6873 ChangeTag::Delete => {
6874 let start = buffer.anchor_after(offset);
6875 let end = buffer.anchor_before(offset + value.len());
6876
6877 if moved_since_edit {
6878 edits.push((start..end, String::new()));
6879 } else {
6880 edits.last_mut().unwrap().0.end = end;
6881 }
6882
6883 offset += value.len();
6884 moved_since_edit = false;
6885 }
6886 ChangeTag::Insert => {
6887 if moved_since_edit {
6888 let anchor = buffer.anchor_after(offset);
6889 edits.push((anchor..anchor, value.to_string()));
6890 } else {
6891 edits.last_mut().unwrap().1.push_str(value);
6892 }
6893
6894 moved_since_edit = false;
6895 }
6896 }
6897 }
6898
6899 rewrapped_row_ranges.push(start_row..=end_row);
6900 }
6901
6902 self.buffer
6903 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6904 }
6905
6906 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6907 let mut text = String::new();
6908 let buffer = self.buffer.read(cx).snapshot(cx);
6909 let mut selections = self.selections.all::<Point>(cx);
6910 let mut clipboard_selections = Vec::with_capacity(selections.len());
6911 {
6912 let max_point = buffer.max_point();
6913 let mut is_first = true;
6914 for selection in &mut selections {
6915 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6916 if is_entire_line {
6917 selection.start = Point::new(selection.start.row, 0);
6918 if !selection.is_empty() && selection.end.column == 0 {
6919 selection.end = cmp::min(max_point, selection.end);
6920 } else {
6921 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6922 }
6923 selection.goal = SelectionGoal::None;
6924 }
6925 if is_first {
6926 is_first = false;
6927 } else {
6928 text += "\n";
6929 }
6930 let mut len = 0;
6931 for chunk in buffer.text_for_range(selection.start..selection.end) {
6932 text.push_str(chunk);
6933 len += chunk.len();
6934 }
6935 clipboard_selections.push(ClipboardSelection {
6936 len,
6937 is_entire_line,
6938 first_line_indent: buffer
6939 .indent_size_for_line(MultiBufferRow(selection.start.row))
6940 .len,
6941 });
6942 }
6943 }
6944
6945 self.transact(cx, |this, cx| {
6946 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6947 s.select(selections);
6948 });
6949 this.insert("", cx);
6950 });
6951 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6952 }
6953
6954 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6955 let item = self.cut_common(cx);
6956 cx.write_to_clipboard(item);
6957 }
6958
6959 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6960 self.change_selections(None, cx, |s| {
6961 s.move_with(|snapshot, sel| {
6962 if sel.is_empty() {
6963 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6964 }
6965 });
6966 });
6967 let item = self.cut_common(cx);
6968 cx.set_global(KillRing(item))
6969 }
6970
6971 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6972 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6973 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6974 (kill_ring.text().to_string(), kill_ring.metadata_json())
6975 } else {
6976 return;
6977 }
6978 } else {
6979 return;
6980 };
6981 self.do_paste(&text, metadata, false, cx);
6982 }
6983
6984 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6985 let selections = self.selections.all::<Point>(cx);
6986 let buffer = self.buffer.read(cx).read(cx);
6987 let mut text = String::new();
6988
6989 let mut clipboard_selections = Vec::with_capacity(selections.len());
6990 {
6991 let max_point = buffer.max_point();
6992 let mut is_first = true;
6993 for selection in selections.iter() {
6994 let mut start = selection.start;
6995 let mut end = selection.end;
6996 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6997 if is_entire_line {
6998 start = Point::new(start.row, 0);
6999 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7000 }
7001 if is_first {
7002 is_first = false;
7003 } else {
7004 text += "\n";
7005 }
7006 let mut len = 0;
7007 for chunk in buffer.text_for_range(start..end) {
7008 text.push_str(chunk);
7009 len += chunk.len();
7010 }
7011 clipboard_selections.push(ClipboardSelection {
7012 len,
7013 is_entire_line,
7014 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7015 });
7016 }
7017 }
7018
7019 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7020 text,
7021 clipboard_selections,
7022 ));
7023 }
7024
7025 pub fn do_paste(
7026 &mut self,
7027 text: &String,
7028 clipboard_selections: Option<Vec<ClipboardSelection>>,
7029 handle_entire_lines: bool,
7030 cx: &mut ViewContext<Self>,
7031 ) {
7032 if self.read_only(cx) {
7033 return;
7034 }
7035
7036 let clipboard_text = Cow::Borrowed(text);
7037
7038 self.transact(cx, |this, cx| {
7039 if let Some(mut clipboard_selections) = clipboard_selections {
7040 let old_selections = this.selections.all::<usize>(cx);
7041 let all_selections_were_entire_line =
7042 clipboard_selections.iter().all(|s| s.is_entire_line);
7043 let first_selection_indent_column =
7044 clipboard_selections.first().map(|s| s.first_line_indent);
7045 if clipboard_selections.len() != old_selections.len() {
7046 clipboard_selections.drain(..);
7047 }
7048 let cursor_offset = this.selections.last::<usize>(cx).head();
7049 let mut auto_indent_on_paste = true;
7050
7051 this.buffer.update(cx, |buffer, cx| {
7052 let snapshot = buffer.read(cx);
7053 auto_indent_on_paste =
7054 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7055
7056 let mut start_offset = 0;
7057 let mut edits = Vec::new();
7058 let mut original_indent_columns = Vec::new();
7059 for (ix, selection) in old_selections.iter().enumerate() {
7060 let to_insert;
7061 let entire_line;
7062 let original_indent_column;
7063 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7064 let end_offset = start_offset + clipboard_selection.len;
7065 to_insert = &clipboard_text[start_offset..end_offset];
7066 entire_line = clipboard_selection.is_entire_line;
7067 start_offset = end_offset + 1;
7068 original_indent_column = Some(clipboard_selection.first_line_indent);
7069 } else {
7070 to_insert = clipboard_text.as_str();
7071 entire_line = all_selections_were_entire_line;
7072 original_indent_column = first_selection_indent_column
7073 }
7074
7075 // If the corresponding selection was empty when this slice of the
7076 // clipboard text was written, then the entire line containing the
7077 // selection was copied. If this selection is also currently empty,
7078 // then paste the line before the current line of the buffer.
7079 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7080 let column = selection.start.to_point(&snapshot).column as usize;
7081 let line_start = selection.start - column;
7082 line_start..line_start
7083 } else {
7084 selection.range()
7085 };
7086
7087 edits.push((range, to_insert));
7088 original_indent_columns.extend(original_indent_column);
7089 }
7090 drop(snapshot);
7091
7092 buffer.edit(
7093 edits,
7094 if auto_indent_on_paste {
7095 Some(AutoindentMode::Block {
7096 original_indent_columns,
7097 })
7098 } else {
7099 None
7100 },
7101 cx,
7102 );
7103 });
7104
7105 let selections = this.selections.all::<usize>(cx);
7106 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7107 } else {
7108 this.insert(&clipboard_text, cx);
7109 }
7110 });
7111 }
7112
7113 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7114 if let Some(item) = cx.read_from_clipboard() {
7115 let entries = item.entries();
7116
7117 match entries.first() {
7118 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7119 // of all the pasted entries.
7120 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7121 .do_paste(
7122 clipboard_string.text(),
7123 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7124 true,
7125 cx,
7126 ),
7127 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7128 }
7129 }
7130 }
7131
7132 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7133 if self.read_only(cx) {
7134 return;
7135 }
7136
7137 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7138 if let Some((selections, _)) =
7139 self.selection_history.transaction(transaction_id).cloned()
7140 {
7141 self.change_selections(None, cx, |s| {
7142 s.select_anchors(selections.to_vec());
7143 });
7144 }
7145 self.request_autoscroll(Autoscroll::fit(), cx);
7146 self.unmark_text(cx);
7147 self.refresh_inline_completion(true, false, cx);
7148 cx.emit(EditorEvent::Edited { transaction_id });
7149 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7150 }
7151 }
7152
7153 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7154 if self.read_only(cx) {
7155 return;
7156 }
7157
7158 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7159 if let Some((_, Some(selections))) =
7160 self.selection_history.transaction(transaction_id).cloned()
7161 {
7162 self.change_selections(None, cx, |s| {
7163 s.select_anchors(selections.to_vec());
7164 });
7165 }
7166 self.request_autoscroll(Autoscroll::fit(), cx);
7167 self.unmark_text(cx);
7168 self.refresh_inline_completion(true, false, cx);
7169 cx.emit(EditorEvent::Edited { transaction_id });
7170 }
7171 }
7172
7173 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7174 self.buffer
7175 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7176 }
7177
7178 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7179 self.buffer
7180 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7181 }
7182
7183 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7184 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7185 let line_mode = s.line_mode;
7186 s.move_with(|map, selection| {
7187 let cursor = if selection.is_empty() && !line_mode {
7188 movement::left(map, selection.start)
7189 } else {
7190 selection.start
7191 };
7192 selection.collapse_to(cursor, SelectionGoal::None);
7193 });
7194 })
7195 }
7196
7197 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7198 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7199 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7200 })
7201 }
7202
7203 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7205 let line_mode = s.line_mode;
7206 s.move_with(|map, selection| {
7207 let cursor = if selection.is_empty() && !line_mode {
7208 movement::right(map, selection.end)
7209 } else {
7210 selection.end
7211 };
7212 selection.collapse_to(cursor, SelectionGoal::None)
7213 });
7214 })
7215 }
7216
7217 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7219 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7220 })
7221 }
7222
7223 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7224 if self.take_rename(true, cx).is_some() {
7225 return;
7226 }
7227
7228 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7229 cx.propagate();
7230 return;
7231 }
7232
7233 let text_layout_details = &self.text_layout_details(cx);
7234 let selection_count = self.selections.count();
7235 let first_selection = self.selections.first_anchor();
7236
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 let line_mode = s.line_mode;
7239 s.move_with(|map, selection| {
7240 if !selection.is_empty() && !line_mode {
7241 selection.goal = SelectionGoal::None;
7242 }
7243 let (cursor, goal) = movement::up(
7244 map,
7245 selection.start,
7246 selection.goal,
7247 false,
7248 text_layout_details,
7249 );
7250 selection.collapse_to(cursor, goal);
7251 });
7252 });
7253
7254 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7255 {
7256 cx.propagate();
7257 }
7258 }
7259
7260 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7261 if self.take_rename(true, cx).is_some() {
7262 return;
7263 }
7264
7265 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7266 cx.propagate();
7267 return;
7268 }
7269
7270 let text_layout_details = &self.text_layout_details(cx);
7271
7272 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7273 let line_mode = s.line_mode;
7274 s.move_with(|map, selection| {
7275 if !selection.is_empty() && !line_mode {
7276 selection.goal = SelectionGoal::None;
7277 }
7278 let (cursor, goal) = movement::up_by_rows(
7279 map,
7280 selection.start,
7281 action.lines,
7282 selection.goal,
7283 false,
7284 text_layout_details,
7285 );
7286 selection.collapse_to(cursor, goal);
7287 });
7288 })
7289 }
7290
7291 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7292 if self.take_rename(true, cx).is_some() {
7293 return;
7294 }
7295
7296 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7297 cx.propagate();
7298 return;
7299 }
7300
7301 let text_layout_details = &self.text_layout_details(cx);
7302
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 let line_mode = s.line_mode;
7305 s.move_with(|map, selection| {
7306 if !selection.is_empty() && !line_mode {
7307 selection.goal = SelectionGoal::None;
7308 }
7309 let (cursor, goal) = movement::down_by_rows(
7310 map,
7311 selection.start,
7312 action.lines,
7313 selection.goal,
7314 false,
7315 text_layout_details,
7316 );
7317 selection.collapse_to(cursor, goal);
7318 });
7319 })
7320 }
7321
7322 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7323 let text_layout_details = &self.text_layout_details(cx);
7324 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7325 s.move_heads_with(|map, head, goal| {
7326 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7327 })
7328 })
7329 }
7330
7331 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7332 let text_layout_details = &self.text_layout_details(cx);
7333 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7334 s.move_heads_with(|map, head, goal| {
7335 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7336 })
7337 })
7338 }
7339
7340 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7341 let Some(row_count) = self.visible_row_count() else {
7342 return;
7343 };
7344
7345 let text_layout_details = &self.text_layout_details(cx);
7346
7347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7348 s.move_heads_with(|map, head, goal| {
7349 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7350 })
7351 })
7352 }
7353
7354 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7355 if self.take_rename(true, cx).is_some() {
7356 return;
7357 }
7358
7359 if self
7360 .context_menu
7361 .borrow_mut()
7362 .as_mut()
7363 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7364 .unwrap_or(false)
7365 {
7366 return;
7367 }
7368
7369 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7370 cx.propagate();
7371 return;
7372 }
7373
7374 let Some(row_count) = self.visible_row_count() else {
7375 return;
7376 };
7377
7378 let autoscroll = if action.center_cursor {
7379 Autoscroll::center()
7380 } else {
7381 Autoscroll::fit()
7382 };
7383
7384 let text_layout_details = &self.text_layout_details(cx);
7385
7386 self.change_selections(Some(autoscroll), cx, |s| {
7387 let line_mode = s.line_mode;
7388 s.move_with(|map, selection| {
7389 if !selection.is_empty() && !line_mode {
7390 selection.goal = SelectionGoal::None;
7391 }
7392 let (cursor, goal) = movement::up_by_rows(
7393 map,
7394 selection.end,
7395 row_count,
7396 selection.goal,
7397 false,
7398 text_layout_details,
7399 );
7400 selection.collapse_to(cursor, goal);
7401 });
7402 });
7403 }
7404
7405 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7406 let text_layout_details = &self.text_layout_details(cx);
7407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7408 s.move_heads_with(|map, head, goal| {
7409 movement::up(map, head, goal, false, text_layout_details)
7410 })
7411 })
7412 }
7413
7414 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7415 self.take_rename(true, cx);
7416
7417 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7418 cx.propagate();
7419 return;
7420 }
7421
7422 let text_layout_details = &self.text_layout_details(cx);
7423 let selection_count = self.selections.count();
7424 let first_selection = self.selections.first_anchor();
7425
7426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7427 let line_mode = s.line_mode;
7428 s.move_with(|map, selection| {
7429 if !selection.is_empty() && !line_mode {
7430 selection.goal = SelectionGoal::None;
7431 }
7432 let (cursor, goal) = movement::down(
7433 map,
7434 selection.end,
7435 selection.goal,
7436 false,
7437 text_layout_details,
7438 );
7439 selection.collapse_to(cursor, goal);
7440 });
7441 });
7442
7443 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7444 {
7445 cx.propagate();
7446 }
7447 }
7448
7449 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7450 let Some(row_count) = self.visible_row_count() else {
7451 return;
7452 };
7453
7454 let text_layout_details = &self.text_layout_details(cx);
7455
7456 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7457 s.move_heads_with(|map, head, goal| {
7458 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7459 })
7460 })
7461 }
7462
7463 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7464 if self.take_rename(true, cx).is_some() {
7465 return;
7466 }
7467
7468 if self
7469 .context_menu
7470 .borrow_mut()
7471 .as_mut()
7472 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7473 .unwrap_or(false)
7474 {
7475 return;
7476 }
7477
7478 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7479 cx.propagate();
7480 return;
7481 }
7482
7483 let Some(row_count) = self.visible_row_count() else {
7484 return;
7485 };
7486
7487 let autoscroll = if action.center_cursor {
7488 Autoscroll::center()
7489 } else {
7490 Autoscroll::fit()
7491 };
7492
7493 let text_layout_details = &self.text_layout_details(cx);
7494 self.change_selections(Some(autoscroll), cx, |s| {
7495 let line_mode = s.line_mode;
7496 s.move_with(|map, selection| {
7497 if !selection.is_empty() && !line_mode {
7498 selection.goal = SelectionGoal::None;
7499 }
7500 let (cursor, goal) = movement::down_by_rows(
7501 map,
7502 selection.end,
7503 row_count,
7504 selection.goal,
7505 false,
7506 text_layout_details,
7507 );
7508 selection.collapse_to(cursor, goal);
7509 });
7510 });
7511 }
7512
7513 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7514 let text_layout_details = &self.text_layout_details(cx);
7515 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7516 s.move_heads_with(|map, head, goal| {
7517 movement::down(map, head, goal, false, text_layout_details)
7518 })
7519 });
7520 }
7521
7522 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7523 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7524 context_menu.select_first(self.completion_provider.as_deref(), cx);
7525 }
7526 }
7527
7528 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7529 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7530 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7531 }
7532 }
7533
7534 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7535 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7536 context_menu.select_next(self.completion_provider.as_deref(), cx);
7537 }
7538 }
7539
7540 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7541 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7542 context_menu.select_last(self.completion_provider.as_deref(), cx);
7543 }
7544 }
7545
7546 pub fn move_to_previous_word_start(
7547 &mut self,
7548 _: &MoveToPreviousWordStart,
7549 cx: &mut ViewContext<Self>,
7550 ) {
7551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 s.move_cursors_with(|map, head, _| {
7553 (
7554 movement::previous_word_start(map, head),
7555 SelectionGoal::None,
7556 )
7557 });
7558 })
7559 }
7560
7561 pub fn move_to_previous_subword_start(
7562 &mut self,
7563 _: &MoveToPreviousSubwordStart,
7564 cx: &mut ViewContext<Self>,
7565 ) {
7566 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7567 s.move_cursors_with(|map, head, _| {
7568 (
7569 movement::previous_subword_start(map, head),
7570 SelectionGoal::None,
7571 )
7572 });
7573 })
7574 }
7575
7576 pub fn select_to_previous_word_start(
7577 &mut self,
7578 _: &SelectToPreviousWordStart,
7579 cx: &mut ViewContext<Self>,
7580 ) {
7581 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7582 s.move_heads_with(|map, head, _| {
7583 (
7584 movement::previous_word_start(map, head),
7585 SelectionGoal::None,
7586 )
7587 });
7588 })
7589 }
7590
7591 pub fn select_to_previous_subword_start(
7592 &mut self,
7593 _: &SelectToPreviousSubwordStart,
7594 cx: &mut ViewContext<Self>,
7595 ) {
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.move_heads_with(|map, head, _| {
7598 (
7599 movement::previous_subword_start(map, head),
7600 SelectionGoal::None,
7601 )
7602 });
7603 })
7604 }
7605
7606 pub fn delete_to_previous_word_start(
7607 &mut self,
7608 action: &DeleteToPreviousWordStart,
7609 cx: &mut ViewContext<Self>,
7610 ) {
7611 self.transact(cx, |this, cx| {
7612 this.select_autoclose_pair(cx);
7613 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 let line_mode = s.line_mode;
7615 s.move_with(|map, selection| {
7616 if selection.is_empty() && !line_mode {
7617 let cursor = if action.ignore_newlines {
7618 movement::previous_word_start(map, selection.head())
7619 } else {
7620 movement::previous_word_start_or_newline(map, selection.head())
7621 };
7622 selection.set_head(cursor, SelectionGoal::None);
7623 }
7624 });
7625 });
7626 this.insert("", cx);
7627 });
7628 }
7629
7630 pub fn delete_to_previous_subword_start(
7631 &mut self,
7632 _: &DeleteToPreviousSubwordStart,
7633 cx: &mut ViewContext<Self>,
7634 ) {
7635 self.transact(cx, |this, cx| {
7636 this.select_autoclose_pair(cx);
7637 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 let line_mode = s.line_mode;
7639 s.move_with(|map, selection| {
7640 if selection.is_empty() && !line_mode {
7641 let cursor = movement::previous_subword_start(map, selection.head());
7642 selection.set_head(cursor, SelectionGoal::None);
7643 }
7644 });
7645 });
7646 this.insert("", cx);
7647 });
7648 }
7649
7650 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7651 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7652 s.move_cursors_with(|map, head, _| {
7653 (movement::next_word_end(map, head), SelectionGoal::None)
7654 });
7655 })
7656 }
7657
7658 pub fn move_to_next_subword_end(
7659 &mut self,
7660 _: &MoveToNextSubwordEnd,
7661 cx: &mut ViewContext<Self>,
7662 ) {
7663 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7664 s.move_cursors_with(|map, head, _| {
7665 (movement::next_subword_end(map, head), SelectionGoal::None)
7666 });
7667 })
7668 }
7669
7670 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7671 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 s.move_heads_with(|map, head, _| {
7673 (movement::next_word_end(map, head), SelectionGoal::None)
7674 });
7675 })
7676 }
7677
7678 pub fn select_to_next_subword_end(
7679 &mut self,
7680 _: &SelectToNextSubwordEnd,
7681 cx: &mut ViewContext<Self>,
7682 ) {
7683 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7684 s.move_heads_with(|map, head, _| {
7685 (movement::next_subword_end(map, head), SelectionGoal::None)
7686 });
7687 })
7688 }
7689
7690 pub fn delete_to_next_word_end(
7691 &mut self,
7692 action: &DeleteToNextWordEnd,
7693 cx: &mut ViewContext<Self>,
7694 ) {
7695 self.transact(cx, |this, cx| {
7696 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7697 let line_mode = s.line_mode;
7698 s.move_with(|map, selection| {
7699 if selection.is_empty() && !line_mode {
7700 let cursor = if action.ignore_newlines {
7701 movement::next_word_end(map, selection.head())
7702 } else {
7703 movement::next_word_end_or_newline(map, selection.head())
7704 };
7705 selection.set_head(cursor, SelectionGoal::None);
7706 }
7707 });
7708 });
7709 this.insert("", cx);
7710 });
7711 }
7712
7713 pub fn delete_to_next_subword_end(
7714 &mut self,
7715 _: &DeleteToNextSubwordEnd,
7716 cx: &mut ViewContext<Self>,
7717 ) {
7718 self.transact(cx, |this, cx| {
7719 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7720 s.move_with(|map, selection| {
7721 if selection.is_empty() {
7722 let cursor = movement::next_subword_end(map, selection.head());
7723 selection.set_head(cursor, SelectionGoal::None);
7724 }
7725 });
7726 });
7727 this.insert("", cx);
7728 });
7729 }
7730
7731 pub fn move_to_beginning_of_line(
7732 &mut self,
7733 action: &MoveToBeginningOfLine,
7734 cx: &mut ViewContext<Self>,
7735 ) {
7736 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7737 s.move_cursors_with(|map, head, _| {
7738 (
7739 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7740 SelectionGoal::None,
7741 )
7742 });
7743 })
7744 }
7745
7746 pub fn select_to_beginning_of_line(
7747 &mut self,
7748 action: &SelectToBeginningOfLine,
7749 cx: &mut ViewContext<Self>,
7750 ) {
7751 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7752 s.move_heads_with(|map, head, _| {
7753 (
7754 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7755 SelectionGoal::None,
7756 )
7757 });
7758 });
7759 }
7760
7761 pub fn delete_to_beginning_of_line(
7762 &mut self,
7763 _: &DeleteToBeginningOfLine,
7764 cx: &mut ViewContext<Self>,
7765 ) {
7766 self.transact(cx, |this, cx| {
7767 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7768 s.move_with(|_, selection| {
7769 selection.reversed = true;
7770 });
7771 });
7772
7773 this.select_to_beginning_of_line(
7774 &SelectToBeginningOfLine {
7775 stop_at_soft_wraps: false,
7776 },
7777 cx,
7778 );
7779 this.backspace(&Backspace, cx);
7780 });
7781 }
7782
7783 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7784 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7785 s.move_cursors_with(|map, head, _| {
7786 (
7787 movement::line_end(map, head, action.stop_at_soft_wraps),
7788 SelectionGoal::None,
7789 )
7790 });
7791 })
7792 }
7793
7794 pub fn select_to_end_of_line(
7795 &mut self,
7796 action: &SelectToEndOfLine,
7797 cx: &mut ViewContext<Self>,
7798 ) {
7799 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7800 s.move_heads_with(|map, head, _| {
7801 (
7802 movement::line_end(map, head, action.stop_at_soft_wraps),
7803 SelectionGoal::None,
7804 )
7805 });
7806 })
7807 }
7808
7809 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7810 self.transact(cx, |this, cx| {
7811 this.select_to_end_of_line(
7812 &SelectToEndOfLine {
7813 stop_at_soft_wraps: false,
7814 },
7815 cx,
7816 );
7817 this.delete(&Delete, cx);
7818 });
7819 }
7820
7821 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7822 self.transact(cx, |this, cx| {
7823 this.select_to_end_of_line(
7824 &SelectToEndOfLine {
7825 stop_at_soft_wraps: false,
7826 },
7827 cx,
7828 );
7829 this.cut(&Cut, cx);
7830 });
7831 }
7832
7833 pub fn move_to_start_of_paragraph(
7834 &mut self,
7835 _: &MoveToStartOfParagraph,
7836 cx: &mut ViewContext<Self>,
7837 ) {
7838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7839 cx.propagate();
7840 return;
7841 }
7842
7843 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7844 s.move_with(|map, selection| {
7845 selection.collapse_to(
7846 movement::start_of_paragraph(map, selection.head(), 1),
7847 SelectionGoal::None,
7848 )
7849 });
7850 })
7851 }
7852
7853 pub fn move_to_end_of_paragraph(
7854 &mut self,
7855 _: &MoveToEndOfParagraph,
7856 cx: &mut ViewContext<Self>,
7857 ) {
7858 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7859 cx.propagate();
7860 return;
7861 }
7862
7863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7864 s.move_with(|map, selection| {
7865 selection.collapse_to(
7866 movement::end_of_paragraph(map, selection.head(), 1),
7867 SelectionGoal::None,
7868 )
7869 });
7870 })
7871 }
7872
7873 pub fn select_to_start_of_paragraph(
7874 &mut self,
7875 _: &SelectToStartOfParagraph,
7876 cx: &mut ViewContext<Self>,
7877 ) {
7878 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7879 cx.propagate();
7880 return;
7881 }
7882
7883 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7884 s.move_heads_with(|map, head, _| {
7885 (
7886 movement::start_of_paragraph(map, head, 1),
7887 SelectionGoal::None,
7888 )
7889 });
7890 })
7891 }
7892
7893 pub fn select_to_end_of_paragraph(
7894 &mut self,
7895 _: &SelectToEndOfParagraph,
7896 cx: &mut ViewContext<Self>,
7897 ) {
7898 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7899 cx.propagate();
7900 return;
7901 }
7902
7903 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7904 s.move_heads_with(|map, head, _| {
7905 (
7906 movement::end_of_paragraph(map, head, 1),
7907 SelectionGoal::None,
7908 )
7909 });
7910 })
7911 }
7912
7913 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7914 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7915 cx.propagate();
7916 return;
7917 }
7918
7919 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7920 s.select_ranges(vec![0..0]);
7921 });
7922 }
7923
7924 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7925 let mut selection = self.selections.last::<Point>(cx);
7926 selection.set_head(Point::zero(), SelectionGoal::None);
7927
7928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7929 s.select(vec![selection]);
7930 });
7931 }
7932
7933 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7934 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7935 cx.propagate();
7936 return;
7937 }
7938
7939 let cursor = self.buffer.read(cx).read(cx).len();
7940 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7941 s.select_ranges(vec![cursor..cursor])
7942 });
7943 }
7944
7945 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7946 self.nav_history = nav_history;
7947 }
7948
7949 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7950 self.nav_history.as_ref()
7951 }
7952
7953 fn push_to_nav_history(
7954 &mut self,
7955 cursor_anchor: Anchor,
7956 new_position: Option<Point>,
7957 cx: &mut ViewContext<Self>,
7958 ) {
7959 if let Some(nav_history) = self.nav_history.as_mut() {
7960 let buffer = self.buffer.read(cx).read(cx);
7961 let cursor_position = cursor_anchor.to_point(&buffer);
7962 let scroll_state = self.scroll_manager.anchor();
7963 let scroll_top_row = scroll_state.top_row(&buffer);
7964 drop(buffer);
7965
7966 if let Some(new_position) = new_position {
7967 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7968 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7969 return;
7970 }
7971 }
7972
7973 nav_history.push(
7974 Some(NavigationData {
7975 cursor_anchor,
7976 cursor_position,
7977 scroll_anchor: scroll_state,
7978 scroll_top_row,
7979 }),
7980 cx,
7981 );
7982 }
7983 }
7984
7985 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7986 let buffer = self.buffer.read(cx).snapshot(cx);
7987 let mut selection = self.selections.first::<usize>(cx);
7988 selection.set_head(buffer.len(), SelectionGoal::None);
7989 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7990 s.select(vec![selection]);
7991 });
7992 }
7993
7994 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7995 let end = self.buffer.read(cx).read(cx).len();
7996 self.change_selections(None, cx, |s| {
7997 s.select_ranges(vec![0..end]);
7998 });
7999 }
8000
8001 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8003 let mut selections = self.selections.all::<Point>(cx);
8004 let max_point = display_map.buffer_snapshot.max_point();
8005 for selection in &mut selections {
8006 let rows = selection.spanned_rows(true, &display_map);
8007 selection.start = Point::new(rows.start.0, 0);
8008 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8009 selection.reversed = false;
8010 }
8011 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8012 s.select(selections);
8013 });
8014 }
8015
8016 pub fn split_selection_into_lines(
8017 &mut self,
8018 _: &SplitSelectionIntoLines,
8019 cx: &mut ViewContext<Self>,
8020 ) {
8021 let mut to_unfold = Vec::new();
8022 let mut new_selection_ranges = Vec::new();
8023 {
8024 let selections = self.selections.all::<Point>(cx);
8025 let buffer = self.buffer.read(cx).read(cx);
8026 for selection in selections {
8027 for row in selection.start.row..selection.end.row {
8028 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8029 new_selection_ranges.push(cursor..cursor);
8030 }
8031 new_selection_ranges.push(selection.end..selection.end);
8032 to_unfold.push(selection.start..selection.end);
8033 }
8034 }
8035 self.unfold_ranges(&to_unfold, true, true, cx);
8036 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8037 s.select_ranges(new_selection_ranges);
8038 });
8039 }
8040
8041 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8042 self.add_selection(true, cx);
8043 }
8044
8045 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8046 self.add_selection(false, cx);
8047 }
8048
8049 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8051 let mut selections = self.selections.all::<Point>(cx);
8052 let text_layout_details = self.text_layout_details(cx);
8053 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8054 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8055 let range = oldest_selection.display_range(&display_map).sorted();
8056
8057 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8058 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8059 let positions = start_x.min(end_x)..start_x.max(end_x);
8060
8061 selections.clear();
8062 let mut stack = Vec::new();
8063 for row in range.start.row().0..=range.end.row().0 {
8064 if let Some(selection) = self.selections.build_columnar_selection(
8065 &display_map,
8066 DisplayRow(row),
8067 &positions,
8068 oldest_selection.reversed,
8069 &text_layout_details,
8070 ) {
8071 stack.push(selection.id);
8072 selections.push(selection);
8073 }
8074 }
8075
8076 if above {
8077 stack.reverse();
8078 }
8079
8080 AddSelectionsState { above, stack }
8081 });
8082
8083 let last_added_selection = *state.stack.last().unwrap();
8084 let mut new_selections = Vec::new();
8085 if above == state.above {
8086 let end_row = if above {
8087 DisplayRow(0)
8088 } else {
8089 display_map.max_point().row()
8090 };
8091
8092 'outer: for selection in selections {
8093 if selection.id == last_added_selection {
8094 let range = selection.display_range(&display_map).sorted();
8095 debug_assert_eq!(range.start.row(), range.end.row());
8096 let mut row = range.start.row();
8097 let positions =
8098 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8099 px(start)..px(end)
8100 } else {
8101 let start_x =
8102 display_map.x_for_display_point(range.start, &text_layout_details);
8103 let end_x =
8104 display_map.x_for_display_point(range.end, &text_layout_details);
8105 start_x.min(end_x)..start_x.max(end_x)
8106 };
8107
8108 while row != end_row {
8109 if above {
8110 row.0 -= 1;
8111 } else {
8112 row.0 += 1;
8113 }
8114
8115 if let Some(new_selection) = self.selections.build_columnar_selection(
8116 &display_map,
8117 row,
8118 &positions,
8119 selection.reversed,
8120 &text_layout_details,
8121 ) {
8122 state.stack.push(new_selection.id);
8123 if above {
8124 new_selections.push(new_selection);
8125 new_selections.push(selection);
8126 } else {
8127 new_selections.push(selection);
8128 new_selections.push(new_selection);
8129 }
8130
8131 continue 'outer;
8132 }
8133 }
8134 }
8135
8136 new_selections.push(selection);
8137 }
8138 } else {
8139 new_selections = selections;
8140 new_selections.retain(|s| s.id != last_added_selection);
8141 state.stack.pop();
8142 }
8143
8144 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8145 s.select(new_selections);
8146 });
8147 if state.stack.len() > 1 {
8148 self.add_selections_state = Some(state);
8149 }
8150 }
8151
8152 pub fn select_next_match_internal(
8153 &mut self,
8154 display_map: &DisplaySnapshot,
8155 replace_newest: bool,
8156 autoscroll: Option<Autoscroll>,
8157 cx: &mut ViewContext<Self>,
8158 ) -> Result<()> {
8159 fn select_next_match_ranges(
8160 this: &mut Editor,
8161 range: Range<usize>,
8162 replace_newest: bool,
8163 auto_scroll: Option<Autoscroll>,
8164 cx: &mut ViewContext<Editor>,
8165 ) {
8166 this.unfold_ranges(&[range.clone()], false, true, cx);
8167 this.change_selections(auto_scroll, cx, |s| {
8168 if replace_newest {
8169 s.delete(s.newest_anchor().id);
8170 }
8171 s.insert_range(range.clone());
8172 });
8173 }
8174
8175 let buffer = &display_map.buffer_snapshot;
8176 let mut selections = self.selections.all::<usize>(cx);
8177 if let Some(mut select_next_state) = self.select_next_state.take() {
8178 let query = &select_next_state.query;
8179 if !select_next_state.done {
8180 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8181 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8182 let mut next_selected_range = None;
8183
8184 let bytes_after_last_selection =
8185 buffer.bytes_in_range(last_selection.end..buffer.len());
8186 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8187 let query_matches = query
8188 .stream_find_iter(bytes_after_last_selection)
8189 .map(|result| (last_selection.end, result))
8190 .chain(
8191 query
8192 .stream_find_iter(bytes_before_first_selection)
8193 .map(|result| (0, result)),
8194 );
8195
8196 for (start_offset, query_match) in query_matches {
8197 let query_match = query_match.unwrap(); // can only fail due to I/O
8198 let offset_range =
8199 start_offset + query_match.start()..start_offset + query_match.end();
8200 let display_range = offset_range.start.to_display_point(display_map)
8201 ..offset_range.end.to_display_point(display_map);
8202
8203 if !select_next_state.wordwise
8204 || (!movement::is_inside_word(display_map, display_range.start)
8205 && !movement::is_inside_word(display_map, display_range.end))
8206 {
8207 // TODO: This is n^2, because we might check all the selections
8208 if !selections
8209 .iter()
8210 .any(|selection| selection.range().overlaps(&offset_range))
8211 {
8212 next_selected_range = Some(offset_range);
8213 break;
8214 }
8215 }
8216 }
8217
8218 if let Some(next_selected_range) = next_selected_range {
8219 select_next_match_ranges(
8220 self,
8221 next_selected_range,
8222 replace_newest,
8223 autoscroll,
8224 cx,
8225 );
8226 } else {
8227 select_next_state.done = true;
8228 }
8229 }
8230
8231 self.select_next_state = Some(select_next_state);
8232 } else {
8233 let mut only_carets = true;
8234 let mut same_text_selected = true;
8235 let mut selected_text = None;
8236
8237 let mut selections_iter = selections.iter().peekable();
8238 while let Some(selection) = selections_iter.next() {
8239 if selection.start != selection.end {
8240 only_carets = false;
8241 }
8242
8243 if same_text_selected {
8244 if selected_text.is_none() {
8245 selected_text =
8246 Some(buffer.text_for_range(selection.range()).collect::<String>());
8247 }
8248
8249 if let Some(next_selection) = selections_iter.peek() {
8250 if next_selection.range().len() == selection.range().len() {
8251 let next_selected_text = buffer
8252 .text_for_range(next_selection.range())
8253 .collect::<String>();
8254 if Some(next_selected_text) != selected_text {
8255 same_text_selected = false;
8256 selected_text = None;
8257 }
8258 } else {
8259 same_text_selected = false;
8260 selected_text = None;
8261 }
8262 }
8263 }
8264 }
8265
8266 if only_carets {
8267 for selection in &mut selections {
8268 let word_range = movement::surrounding_word(
8269 display_map,
8270 selection.start.to_display_point(display_map),
8271 );
8272 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8273 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8274 selection.goal = SelectionGoal::None;
8275 selection.reversed = false;
8276 select_next_match_ranges(
8277 self,
8278 selection.start..selection.end,
8279 replace_newest,
8280 autoscroll,
8281 cx,
8282 );
8283 }
8284
8285 if selections.len() == 1 {
8286 let selection = selections
8287 .last()
8288 .expect("ensured that there's only one selection");
8289 let query = buffer
8290 .text_for_range(selection.start..selection.end)
8291 .collect::<String>();
8292 let is_empty = query.is_empty();
8293 let select_state = SelectNextState {
8294 query: AhoCorasick::new(&[query])?,
8295 wordwise: true,
8296 done: is_empty,
8297 };
8298 self.select_next_state = Some(select_state);
8299 } else {
8300 self.select_next_state = None;
8301 }
8302 } else if let Some(selected_text) = selected_text {
8303 self.select_next_state = Some(SelectNextState {
8304 query: AhoCorasick::new(&[selected_text])?,
8305 wordwise: false,
8306 done: false,
8307 });
8308 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8309 }
8310 }
8311 Ok(())
8312 }
8313
8314 pub fn select_all_matches(
8315 &mut self,
8316 _action: &SelectAllMatches,
8317 cx: &mut ViewContext<Self>,
8318 ) -> Result<()> {
8319 self.push_to_selection_history();
8320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8321
8322 self.select_next_match_internal(&display_map, false, None, cx)?;
8323 let Some(select_next_state) = self.select_next_state.as_mut() else {
8324 return Ok(());
8325 };
8326 if select_next_state.done {
8327 return Ok(());
8328 }
8329
8330 let mut new_selections = self.selections.all::<usize>(cx);
8331
8332 let buffer = &display_map.buffer_snapshot;
8333 let query_matches = select_next_state
8334 .query
8335 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8336
8337 for query_match in query_matches {
8338 let query_match = query_match.unwrap(); // can only fail due to I/O
8339 let offset_range = query_match.start()..query_match.end();
8340 let display_range = offset_range.start.to_display_point(&display_map)
8341 ..offset_range.end.to_display_point(&display_map);
8342
8343 if !select_next_state.wordwise
8344 || (!movement::is_inside_word(&display_map, display_range.start)
8345 && !movement::is_inside_word(&display_map, display_range.end))
8346 {
8347 self.selections.change_with(cx, |selections| {
8348 new_selections.push(Selection {
8349 id: selections.new_selection_id(),
8350 start: offset_range.start,
8351 end: offset_range.end,
8352 reversed: false,
8353 goal: SelectionGoal::None,
8354 });
8355 });
8356 }
8357 }
8358
8359 new_selections.sort_by_key(|selection| selection.start);
8360 let mut ix = 0;
8361 while ix + 1 < new_selections.len() {
8362 let current_selection = &new_selections[ix];
8363 let next_selection = &new_selections[ix + 1];
8364 if current_selection.range().overlaps(&next_selection.range()) {
8365 if current_selection.id < next_selection.id {
8366 new_selections.remove(ix + 1);
8367 } else {
8368 new_selections.remove(ix);
8369 }
8370 } else {
8371 ix += 1;
8372 }
8373 }
8374
8375 select_next_state.done = true;
8376 self.unfold_ranges(
8377 &new_selections
8378 .iter()
8379 .map(|selection| selection.range())
8380 .collect::<Vec<_>>(),
8381 false,
8382 false,
8383 cx,
8384 );
8385 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8386 selections.select(new_selections)
8387 });
8388
8389 Ok(())
8390 }
8391
8392 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8393 self.push_to_selection_history();
8394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8395 self.select_next_match_internal(
8396 &display_map,
8397 action.replace_newest,
8398 Some(Autoscroll::newest()),
8399 cx,
8400 )?;
8401 Ok(())
8402 }
8403
8404 pub fn select_previous(
8405 &mut self,
8406 action: &SelectPrevious,
8407 cx: &mut ViewContext<Self>,
8408 ) -> Result<()> {
8409 self.push_to_selection_history();
8410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8411 let buffer = &display_map.buffer_snapshot;
8412 let mut selections = self.selections.all::<usize>(cx);
8413 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8414 let query = &select_prev_state.query;
8415 if !select_prev_state.done {
8416 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8417 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8418 let mut next_selected_range = None;
8419 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8420 let bytes_before_last_selection =
8421 buffer.reversed_bytes_in_range(0..last_selection.start);
8422 let bytes_after_first_selection =
8423 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8424 let query_matches = query
8425 .stream_find_iter(bytes_before_last_selection)
8426 .map(|result| (last_selection.start, result))
8427 .chain(
8428 query
8429 .stream_find_iter(bytes_after_first_selection)
8430 .map(|result| (buffer.len(), result)),
8431 );
8432 for (end_offset, query_match) in query_matches {
8433 let query_match = query_match.unwrap(); // can only fail due to I/O
8434 let offset_range =
8435 end_offset - query_match.end()..end_offset - query_match.start();
8436 let display_range = offset_range.start.to_display_point(&display_map)
8437 ..offset_range.end.to_display_point(&display_map);
8438
8439 if !select_prev_state.wordwise
8440 || (!movement::is_inside_word(&display_map, display_range.start)
8441 && !movement::is_inside_word(&display_map, display_range.end))
8442 {
8443 next_selected_range = Some(offset_range);
8444 break;
8445 }
8446 }
8447
8448 if let Some(next_selected_range) = next_selected_range {
8449 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8450 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8451 if action.replace_newest {
8452 s.delete(s.newest_anchor().id);
8453 }
8454 s.insert_range(next_selected_range);
8455 });
8456 } else {
8457 select_prev_state.done = true;
8458 }
8459 }
8460
8461 self.select_prev_state = Some(select_prev_state);
8462 } else {
8463 let mut only_carets = true;
8464 let mut same_text_selected = true;
8465 let mut selected_text = None;
8466
8467 let mut selections_iter = selections.iter().peekable();
8468 while let Some(selection) = selections_iter.next() {
8469 if selection.start != selection.end {
8470 only_carets = false;
8471 }
8472
8473 if same_text_selected {
8474 if selected_text.is_none() {
8475 selected_text =
8476 Some(buffer.text_for_range(selection.range()).collect::<String>());
8477 }
8478
8479 if let Some(next_selection) = selections_iter.peek() {
8480 if next_selection.range().len() == selection.range().len() {
8481 let next_selected_text = buffer
8482 .text_for_range(next_selection.range())
8483 .collect::<String>();
8484 if Some(next_selected_text) != selected_text {
8485 same_text_selected = false;
8486 selected_text = None;
8487 }
8488 } else {
8489 same_text_selected = false;
8490 selected_text = None;
8491 }
8492 }
8493 }
8494 }
8495
8496 if only_carets {
8497 for selection in &mut selections {
8498 let word_range = movement::surrounding_word(
8499 &display_map,
8500 selection.start.to_display_point(&display_map),
8501 );
8502 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8503 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8504 selection.goal = SelectionGoal::None;
8505 selection.reversed = false;
8506 }
8507 if selections.len() == 1 {
8508 let selection = selections
8509 .last()
8510 .expect("ensured that there's only one selection");
8511 let query = buffer
8512 .text_for_range(selection.start..selection.end)
8513 .collect::<String>();
8514 let is_empty = query.is_empty();
8515 let select_state = SelectNextState {
8516 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8517 wordwise: true,
8518 done: is_empty,
8519 };
8520 self.select_prev_state = Some(select_state);
8521 } else {
8522 self.select_prev_state = None;
8523 }
8524
8525 self.unfold_ranges(
8526 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8527 false,
8528 true,
8529 cx,
8530 );
8531 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8532 s.select(selections);
8533 });
8534 } else if let Some(selected_text) = selected_text {
8535 self.select_prev_state = Some(SelectNextState {
8536 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8537 wordwise: false,
8538 done: false,
8539 });
8540 self.select_previous(action, cx)?;
8541 }
8542 }
8543 Ok(())
8544 }
8545
8546 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8547 if self.read_only(cx) {
8548 return;
8549 }
8550 let text_layout_details = &self.text_layout_details(cx);
8551 self.transact(cx, |this, cx| {
8552 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8553 let mut edits = Vec::new();
8554 let mut selection_edit_ranges = Vec::new();
8555 let mut last_toggled_row = None;
8556 let snapshot = this.buffer.read(cx).read(cx);
8557 let empty_str: Arc<str> = Arc::default();
8558 let mut suffixes_inserted = Vec::new();
8559 let ignore_indent = action.ignore_indent;
8560
8561 fn comment_prefix_range(
8562 snapshot: &MultiBufferSnapshot,
8563 row: MultiBufferRow,
8564 comment_prefix: &str,
8565 comment_prefix_whitespace: &str,
8566 ignore_indent: bool,
8567 ) -> Range<Point> {
8568 let indent_size = if ignore_indent {
8569 0
8570 } else {
8571 snapshot.indent_size_for_line(row).len
8572 };
8573
8574 let start = Point::new(row.0, indent_size);
8575
8576 let mut line_bytes = snapshot
8577 .bytes_in_range(start..snapshot.max_point())
8578 .flatten()
8579 .copied();
8580
8581 // If this line currently begins with the line comment prefix, then record
8582 // the range containing the prefix.
8583 if line_bytes
8584 .by_ref()
8585 .take(comment_prefix.len())
8586 .eq(comment_prefix.bytes())
8587 {
8588 // Include any whitespace that matches the comment prefix.
8589 let matching_whitespace_len = line_bytes
8590 .zip(comment_prefix_whitespace.bytes())
8591 .take_while(|(a, b)| a == b)
8592 .count() as u32;
8593 let end = Point::new(
8594 start.row,
8595 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8596 );
8597 start..end
8598 } else {
8599 start..start
8600 }
8601 }
8602
8603 fn comment_suffix_range(
8604 snapshot: &MultiBufferSnapshot,
8605 row: MultiBufferRow,
8606 comment_suffix: &str,
8607 comment_suffix_has_leading_space: bool,
8608 ) -> Range<Point> {
8609 let end = Point::new(row.0, snapshot.line_len(row));
8610 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8611
8612 let mut line_end_bytes = snapshot
8613 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8614 .flatten()
8615 .copied();
8616
8617 let leading_space_len = if suffix_start_column > 0
8618 && line_end_bytes.next() == Some(b' ')
8619 && comment_suffix_has_leading_space
8620 {
8621 1
8622 } else {
8623 0
8624 };
8625
8626 // If this line currently begins with the line comment prefix, then record
8627 // the range containing the prefix.
8628 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8629 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8630 start..end
8631 } else {
8632 end..end
8633 }
8634 }
8635
8636 // TODO: Handle selections that cross excerpts
8637 for selection in &mut selections {
8638 let start_column = snapshot
8639 .indent_size_for_line(MultiBufferRow(selection.start.row))
8640 .len;
8641 let language = if let Some(language) =
8642 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8643 {
8644 language
8645 } else {
8646 continue;
8647 };
8648
8649 selection_edit_ranges.clear();
8650
8651 // If multiple selections contain a given row, avoid processing that
8652 // row more than once.
8653 let mut start_row = MultiBufferRow(selection.start.row);
8654 if last_toggled_row == Some(start_row) {
8655 start_row = start_row.next_row();
8656 }
8657 let end_row =
8658 if selection.end.row > selection.start.row && selection.end.column == 0 {
8659 MultiBufferRow(selection.end.row - 1)
8660 } else {
8661 MultiBufferRow(selection.end.row)
8662 };
8663 last_toggled_row = Some(end_row);
8664
8665 if start_row > end_row {
8666 continue;
8667 }
8668
8669 // If the language has line comments, toggle those.
8670 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8671
8672 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8673 if ignore_indent {
8674 full_comment_prefixes = full_comment_prefixes
8675 .into_iter()
8676 .map(|s| Arc::from(s.trim_end()))
8677 .collect();
8678 }
8679
8680 if !full_comment_prefixes.is_empty() {
8681 let first_prefix = full_comment_prefixes
8682 .first()
8683 .expect("prefixes is non-empty");
8684 let prefix_trimmed_lengths = full_comment_prefixes
8685 .iter()
8686 .map(|p| p.trim_end_matches(' ').len())
8687 .collect::<SmallVec<[usize; 4]>>();
8688
8689 let mut all_selection_lines_are_comments = true;
8690
8691 for row in start_row.0..=end_row.0 {
8692 let row = MultiBufferRow(row);
8693 if start_row < end_row && snapshot.is_line_blank(row) {
8694 continue;
8695 }
8696
8697 let prefix_range = full_comment_prefixes
8698 .iter()
8699 .zip(prefix_trimmed_lengths.iter().copied())
8700 .map(|(prefix, trimmed_prefix_len)| {
8701 comment_prefix_range(
8702 snapshot.deref(),
8703 row,
8704 &prefix[..trimmed_prefix_len],
8705 &prefix[trimmed_prefix_len..],
8706 ignore_indent,
8707 )
8708 })
8709 .max_by_key(|range| range.end.column - range.start.column)
8710 .expect("prefixes is non-empty");
8711
8712 if prefix_range.is_empty() {
8713 all_selection_lines_are_comments = false;
8714 }
8715
8716 selection_edit_ranges.push(prefix_range);
8717 }
8718
8719 if all_selection_lines_are_comments {
8720 edits.extend(
8721 selection_edit_ranges
8722 .iter()
8723 .cloned()
8724 .map(|range| (range, empty_str.clone())),
8725 );
8726 } else {
8727 let min_column = selection_edit_ranges
8728 .iter()
8729 .map(|range| range.start.column)
8730 .min()
8731 .unwrap_or(0);
8732 edits.extend(selection_edit_ranges.iter().map(|range| {
8733 let position = Point::new(range.start.row, min_column);
8734 (position..position, first_prefix.clone())
8735 }));
8736 }
8737 } else if let Some((full_comment_prefix, comment_suffix)) =
8738 language.block_comment_delimiters()
8739 {
8740 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8741 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8742 let prefix_range = comment_prefix_range(
8743 snapshot.deref(),
8744 start_row,
8745 comment_prefix,
8746 comment_prefix_whitespace,
8747 ignore_indent,
8748 );
8749 let suffix_range = comment_suffix_range(
8750 snapshot.deref(),
8751 end_row,
8752 comment_suffix.trim_start_matches(' '),
8753 comment_suffix.starts_with(' '),
8754 );
8755
8756 if prefix_range.is_empty() || suffix_range.is_empty() {
8757 edits.push((
8758 prefix_range.start..prefix_range.start,
8759 full_comment_prefix.clone(),
8760 ));
8761 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8762 suffixes_inserted.push((end_row, comment_suffix.len()));
8763 } else {
8764 edits.push((prefix_range, empty_str.clone()));
8765 edits.push((suffix_range, empty_str.clone()));
8766 }
8767 } else {
8768 continue;
8769 }
8770 }
8771
8772 drop(snapshot);
8773 this.buffer.update(cx, |buffer, cx| {
8774 buffer.edit(edits, None, cx);
8775 });
8776
8777 // Adjust selections so that they end before any comment suffixes that
8778 // were inserted.
8779 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8780 let mut selections = this.selections.all::<Point>(cx);
8781 let snapshot = this.buffer.read(cx).read(cx);
8782 for selection in &mut selections {
8783 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8784 match row.cmp(&MultiBufferRow(selection.end.row)) {
8785 Ordering::Less => {
8786 suffixes_inserted.next();
8787 continue;
8788 }
8789 Ordering::Greater => break,
8790 Ordering::Equal => {
8791 if selection.end.column == snapshot.line_len(row) {
8792 if selection.is_empty() {
8793 selection.start.column -= suffix_len as u32;
8794 }
8795 selection.end.column -= suffix_len as u32;
8796 }
8797 break;
8798 }
8799 }
8800 }
8801 }
8802
8803 drop(snapshot);
8804 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8805
8806 let selections = this.selections.all::<Point>(cx);
8807 let selections_on_single_row = selections.windows(2).all(|selections| {
8808 selections[0].start.row == selections[1].start.row
8809 && selections[0].end.row == selections[1].end.row
8810 && selections[0].start.row == selections[0].end.row
8811 });
8812 let selections_selecting = selections
8813 .iter()
8814 .any(|selection| selection.start != selection.end);
8815 let advance_downwards = action.advance_downwards
8816 && selections_on_single_row
8817 && !selections_selecting
8818 && !matches!(this.mode, EditorMode::SingleLine { .. });
8819
8820 if advance_downwards {
8821 let snapshot = this.buffer.read(cx).snapshot(cx);
8822
8823 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8824 s.move_cursors_with(|display_snapshot, display_point, _| {
8825 let mut point = display_point.to_point(display_snapshot);
8826 point.row += 1;
8827 point = snapshot.clip_point(point, Bias::Left);
8828 let display_point = point.to_display_point(display_snapshot);
8829 let goal = SelectionGoal::HorizontalPosition(
8830 display_snapshot
8831 .x_for_display_point(display_point, text_layout_details)
8832 .into(),
8833 );
8834 (display_point, goal)
8835 })
8836 });
8837 }
8838 });
8839 }
8840
8841 pub fn select_enclosing_symbol(
8842 &mut self,
8843 _: &SelectEnclosingSymbol,
8844 cx: &mut ViewContext<Self>,
8845 ) {
8846 let buffer = self.buffer.read(cx).snapshot(cx);
8847 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8848
8849 fn update_selection(
8850 selection: &Selection<usize>,
8851 buffer_snap: &MultiBufferSnapshot,
8852 ) -> Option<Selection<usize>> {
8853 let cursor = selection.head();
8854 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8855 for symbol in symbols.iter().rev() {
8856 let start = symbol.range.start.to_offset(buffer_snap);
8857 let end = symbol.range.end.to_offset(buffer_snap);
8858 let new_range = start..end;
8859 if start < selection.start || end > selection.end {
8860 return Some(Selection {
8861 id: selection.id,
8862 start: new_range.start,
8863 end: new_range.end,
8864 goal: SelectionGoal::None,
8865 reversed: selection.reversed,
8866 });
8867 }
8868 }
8869 None
8870 }
8871
8872 let mut selected_larger_symbol = false;
8873 let new_selections = old_selections
8874 .iter()
8875 .map(|selection| match update_selection(selection, &buffer) {
8876 Some(new_selection) => {
8877 if new_selection.range() != selection.range() {
8878 selected_larger_symbol = true;
8879 }
8880 new_selection
8881 }
8882 None => selection.clone(),
8883 })
8884 .collect::<Vec<_>>();
8885
8886 if selected_larger_symbol {
8887 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8888 s.select(new_selections);
8889 });
8890 }
8891 }
8892
8893 pub fn select_larger_syntax_node(
8894 &mut self,
8895 _: &SelectLargerSyntaxNode,
8896 cx: &mut ViewContext<Self>,
8897 ) {
8898 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8899 let buffer = self.buffer.read(cx).snapshot(cx);
8900 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8901
8902 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8903 let mut selected_larger_node = false;
8904 let new_selections = old_selections
8905 .iter()
8906 .map(|selection| {
8907 let old_range = selection.start..selection.end;
8908 let mut new_range = old_range.clone();
8909 let mut new_node = None;
8910 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8911 {
8912 new_node = Some(node);
8913 new_range = containing_range;
8914 if !display_map.intersects_fold(new_range.start)
8915 && !display_map.intersects_fold(new_range.end)
8916 {
8917 break;
8918 }
8919 }
8920
8921 if let Some(node) = new_node {
8922 // Log the ancestor, to support using this action as a way to explore TreeSitter
8923 // nodes. Parent and grandparent are also logged because this operation will not
8924 // visit nodes that have the same range as their parent.
8925 log::info!("Node: {node:?}");
8926 let parent = node.parent();
8927 log::info!("Parent: {parent:?}");
8928 let grandparent = parent.and_then(|x| x.parent());
8929 log::info!("Grandparent: {grandparent:?}");
8930 }
8931
8932 selected_larger_node |= new_range != old_range;
8933 Selection {
8934 id: selection.id,
8935 start: new_range.start,
8936 end: new_range.end,
8937 goal: SelectionGoal::None,
8938 reversed: selection.reversed,
8939 }
8940 })
8941 .collect::<Vec<_>>();
8942
8943 if selected_larger_node {
8944 stack.push(old_selections);
8945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8946 s.select(new_selections);
8947 });
8948 }
8949 self.select_larger_syntax_node_stack = stack;
8950 }
8951
8952 pub fn select_smaller_syntax_node(
8953 &mut self,
8954 _: &SelectSmallerSyntaxNode,
8955 cx: &mut ViewContext<Self>,
8956 ) {
8957 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8958 if let Some(selections) = stack.pop() {
8959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8960 s.select(selections.to_vec());
8961 });
8962 }
8963 self.select_larger_syntax_node_stack = stack;
8964 }
8965
8966 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8967 if !EditorSettings::get_global(cx).gutter.runnables {
8968 self.clear_tasks();
8969 return Task::ready(());
8970 }
8971 let project = self.project.as_ref().map(Model::downgrade);
8972 cx.spawn(|this, mut cx| async move {
8973 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8974 let Some(project) = project.and_then(|p| p.upgrade()) else {
8975 return;
8976 };
8977 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8978 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8979 }) else {
8980 return;
8981 };
8982
8983 let hide_runnables = project
8984 .update(&mut cx, |project, cx| {
8985 // Do not display any test indicators in non-dev server remote projects.
8986 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8987 })
8988 .unwrap_or(true);
8989 if hide_runnables {
8990 return;
8991 }
8992 let new_rows =
8993 cx.background_executor()
8994 .spawn({
8995 let snapshot = display_snapshot.clone();
8996 async move {
8997 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8998 }
8999 })
9000 .await;
9001 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9002
9003 this.update(&mut cx, |this, _| {
9004 this.clear_tasks();
9005 for (key, value) in rows {
9006 this.insert_tasks(key, value);
9007 }
9008 })
9009 .ok();
9010 })
9011 }
9012 fn fetch_runnable_ranges(
9013 snapshot: &DisplaySnapshot,
9014 range: Range<Anchor>,
9015 ) -> Vec<language::RunnableRange> {
9016 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9017 }
9018
9019 fn runnable_rows(
9020 project: Model<Project>,
9021 snapshot: DisplaySnapshot,
9022 runnable_ranges: Vec<RunnableRange>,
9023 mut cx: AsyncWindowContext,
9024 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9025 runnable_ranges
9026 .into_iter()
9027 .filter_map(|mut runnable| {
9028 let tasks = cx
9029 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9030 .ok()?;
9031 if tasks.is_empty() {
9032 return None;
9033 }
9034
9035 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9036
9037 let row = snapshot
9038 .buffer_snapshot
9039 .buffer_line_for_row(MultiBufferRow(point.row))?
9040 .1
9041 .start
9042 .row;
9043
9044 let context_range =
9045 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9046 Some((
9047 (runnable.buffer_id, row),
9048 RunnableTasks {
9049 templates: tasks,
9050 offset: MultiBufferOffset(runnable.run_range.start),
9051 context_range,
9052 column: point.column,
9053 extra_variables: runnable.extra_captures,
9054 },
9055 ))
9056 })
9057 .collect()
9058 }
9059
9060 fn templates_with_tags(
9061 project: &Model<Project>,
9062 runnable: &mut Runnable,
9063 cx: &WindowContext,
9064 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9065 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9066 let (worktree_id, file) = project
9067 .buffer_for_id(runnable.buffer, cx)
9068 .and_then(|buffer| buffer.read(cx).file())
9069 .map(|file| (file.worktree_id(cx), file.clone()))
9070 .unzip();
9071
9072 (
9073 project.task_store().read(cx).task_inventory().cloned(),
9074 worktree_id,
9075 file,
9076 )
9077 });
9078
9079 let tags = mem::take(&mut runnable.tags);
9080 let mut tags: Vec<_> = tags
9081 .into_iter()
9082 .flat_map(|tag| {
9083 let tag = tag.0.clone();
9084 inventory
9085 .as_ref()
9086 .into_iter()
9087 .flat_map(|inventory| {
9088 inventory.read(cx).list_tasks(
9089 file.clone(),
9090 Some(runnable.language.clone()),
9091 worktree_id,
9092 cx,
9093 )
9094 })
9095 .filter(move |(_, template)| {
9096 template.tags.iter().any(|source_tag| source_tag == &tag)
9097 })
9098 })
9099 .sorted_by_key(|(kind, _)| kind.to_owned())
9100 .collect();
9101 if let Some((leading_tag_source, _)) = tags.first() {
9102 // Strongest source wins; if we have worktree tag binding, prefer that to
9103 // global and language bindings;
9104 // if we have a global binding, prefer that to language binding.
9105 let first_mismatch = tags
9106 .iter()
9107 .position(|(tag_source, _)| tag_source != leading_tag_source);
9108 if let Some(index) = first_mismatch {
9109 tags.truncate(index);
9110 }
9111 }
9112
9113 tags
9114 }
9115
9116 pub fn move_to_enclosing_bracket(
9117 &mut self,
9118 _: &MoveToEnclosingBracket,
9119 cx: &mut ViewContext<Self>,
9120 ) {
9121 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9122 s.move_offsets_with(|snapshot, selection| {
9123 let Some(enclosing_bracket_ranges) =
9124 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9125 else {
9126 return;
9127 };
9128
9129 let mut best_length = usize::MAX;
9130 let mut best_inside = false;
9131 let mut best_in_bracket_range = false;
9132 let mut best_destination = None;
9133 for (open, close) in enclosing_bracket_ranges {
9134 let close = close.to_inclusive();
9135 let length = close.end() - open.start;
9136 let inside = selection.start >= open.end && selection.end <= *close.start();
9137 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9138 || close.contains(&selection.head());
9139
9140 // If best is next to a bracket and current isn't, skip
9141 if !in_bracket_range && best_in_bracket_range {
9142 continue;
9143 }
9144
9145 // Prefer smaller lengths unless best is inside and current isn't
9146 if length > best_length && (best_inside || !inside) {
9147 continue;
9148 }
9149
9150 best_length = length;
9151 best_inside = inside;
9152 best_in_bracket_range = in_bracket_range;
9153 best_destination = Some(
9154 if close.contains(&selection.start) && close.contains(&selection.end) {
9155 if inside {
9156 open.end
9157 } else {
9158 open.start
9159 }
9160 } else if inside {
9161 *close.start()
9162 } else {
9163 *close.end()
9164 },
9165 );
9166 }
9167
9168 if let Some(destination) = best_destination {
9169 selection.collapse_to(destination, SelectionGoal::None);
9170 }
9171 })
9172 });
9173 }
9174
9175 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9176 self.end_selection(cx);
9177 self.selection_history.mode = SelectionHistoryMode::Undoing;
9178 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9179 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9180 self.select_next_state = entry.select_next_state;
9181 self.select_prev_state = entry.select_prev_state;
9182 self.add_selections_state = entry.add_selections_state;
9183 self.request_autoscroll(Autoscroll::newest(), cx);
9184 }
9185 self.selection_history.mode = SelectionHistoryMode::Normal;
9186 }
9187
9188 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9189 self.end_selection(cx);
9190 self.selection_history.mode = SelectionHistoryMode::Redoing;
9191 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9192 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9193 self.select_next_state = entry.select_next_state;
9194 self.select_prev_state = entry.select_prev_state;
9195 self.add_selections_state = entry.add_selections_state;
9196 self.request_autoscroll(Autoscroll::newest(), cx);
9197 }
9198 self.selection_history.mode = SelectionHistoryMode::Normal;
9199 }
9200
9201 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9202 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9203 }
9204
9205 pub fn expand_excerpts_down(
9206 &mut self,
9207 action: &ExpandExcerptsDown,
9208 cx: &mut ViewContext<Self>,
9209 ) {
9210 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9211 }
9212
9213 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9214 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9215 }
9216
9217 pub fn expand_excerpts_for_direction(
9218 &mut self,
9219 lines: u32,
9220 direction: ExpandExcerptDirection,
9221 cx: &mut ViewContext<Self>,
9222 ) {
9223 let selections = self.selections.disjoint_anchors();
9224
9225 let lines = if lines == 0 {
9226 EditorSettings::get_global(cx).expand_excerpt_lines
9227 } else {
9228 lines
9229 };
9230
9231 self.buffer.update(cx, |buffer, cx| {
9232 let snapshot = buffer.snapshot(cx);
9233 let mut excerpt_ids = selections
9234 .iter()
9235 .flat_map(|selection| {
9236 snapshot
9237 .excerpts_for_range(selection.range())
9238 .map(|excerpt| excerpt.id())
9239 })
9240 .collect::<Vec<_>>();
9241 excerpt_ids.sort();
9242 excerpt_ids.dedup();
9243 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9244 })
9245 }
9246
9247 pub fn expand_excerpt(
9248 &mut self,
9249 excerpt: ExcerptId,
9250 direction: ExpandExcerptDirection,
9251 cx: &mut ViewContext<Self>,
9252 ) {
9253 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9254 self.buffer.update(cx, |buffer, cx| {
9255 buffer.expand_excerpts([excerpt], lines, direction, cx)
9256 })
9257 }
9258
9259 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9260 self.go_to_diagnostic_impl(Direction::Next, cx)
9261 }
9262
9263 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9264 self.go_to_diagnostic_impl(Direction::Prev, cx)
9265 }
9266
9267 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9268 let buffer = self.buffer.read(cx).snapshot(cx);
9269 let selection = self.selections.newest::<usize>(cx);
9270
9271 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9272 if direction == Direction::Next {
9273 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9274 self.activate_diagnostics(popover.group_id(), cx);
9275 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9276 let primary_range_start = active_diagnostics.primary_range.start;
9277 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9278 let mut new_selection = s.newest_anchor().clone();
9279 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9280 s.select_anchors(vec![new_selection.clone()]);
9281 });
9282 self.refresh_inline_completion(false, true, cx);
9283 }
9284 return;
9285 }
9286 }
9287
9288 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9289 active_diagnostics
9290 .primary_range
9291 .to_offset(&buffer)
9292 .to_inclusive()
9293 });
9294 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9295 if active_primary_range.contains(&selection.head()) {
9296 *active_primary_range.start()
9297 } else {
9298 selection.head()
9299 }
9300 } else {
9301 selection.head()
9302 };
9303 let snapshot = self.snapshot(cx);
9304 loop {
9305 let diagnostics = if direction == Direction::Prev {
9306 buffer.diagnostics_in_range(0..search_start, true)
9307 } else {
9308 buffer.diagnostics_in_range(search_start..buffer.len(), false)
9309 }
9310 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9311 let search_start_anchor = buffer.anchor_after(search_start);
9312 let group = diagnostics
9313 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9314 // be sorted in a stable way
9315 // skip until we are at current active diagnostic, if it exists
9316 .skip_while(|entry| {
9317 let is_in_range = match direction {
9318 Direction::Prev => {
9319 entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
9320 }
9321 Direction::Next => {
9322 entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
9323 }
9324 };
9325 is_in_range
9326 && self
9327 .active_diagnostics
9328 .as_ref()
9329 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9330 })
9331 .find_map(|entry| {
9332 if entry.diagnostic.is_primary
9333 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9334 && !(entry.range.start == entry.range.end)
9335 // if we match with the active diagnostic, skip it
9336 && Some(entry.diagnostic.group_id)
9337 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9338 {
9339 Some((entry.range, entry.diagnostic.group_id))
9340 } else {
9341 None
9342 }
9343 });
9344
9345 if let Some((primary_range, group_id)) = group {
9346 self.activate_diagnostics(group_id, cx);
9347 let primary_range = primary_range.to_offset(&buffer);
9348 if self.active_diagnostics.is_some() {
9349 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9350 s.select(vec![Selection {
9351 id: selection.id,
9352 start: primary_range.start,
9353 end: primary_range.start,
9354 reversed: false,
9355 goal: SelectionGoal::None,
9356 }]);
9357 });
9358 self.refresh_inline_completion(false, true, cx);
9359 }
9360 break;
9361 } else {
9362 // Cycle around to the start of the buffer, potentially moving back to the start of
9363 // the currently active diagnostic.
9364 active_primary_range.take();
9365 if direction == Direction::Prev {
9366 if search_start == buffer.len() {
9367 break;
9368 } else {
9369 search_start = buffer.len();
9370 }
9371 } else if search_start == 0 {
9372 break;
9373 } else {
9374 search_start = 0;
9375 }
9376 }
9377 }
9378 }
9379
9380 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9381 let snapshot = self.snapshot(cx);
9382 let selection = self.selections.newest::<Point>(cx);
9383 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9384 }
9385
9386 fn go_to_hunk_after_position(
9387 &mut self,
9388 snapshot: &EditorSnapshot,
9389 position: Point,
9390 cx: &mut ViewContext<Editor>,
9391 ) -> Option<MultiBufferDiffHunk> {
9392 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9393 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9394 snapshot,
9395 position,
9396 ix > 0,
9397 snapshot.diff_map.diff_hunks_in_range(
9398 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9399 &snapshot.buffer_snapshot,
9400 ),
9401 cx,
9402 ) {
9403 return Some(hunk);
9404 }
9405 }
9406 None
9407 }
9408
9409 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9410 let snapshot = self.snapshot(cx);
9411 let selection = self.selections.newest::<Point>(cx);
9412 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9413 }
9414
9415 fn go_to_hunk_before_position(
9416 &mut self,
9417 snapshot: &EditorSnapshot,
9418 position: Point,
9419 cx: &mut ViewContext<Editor>,
9420 ) -> Option<MultiBufferDiffHunk> {
9421 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9422 .into_iter()
9423 .enumerate()
9424 {
9425 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9426 snapshot,
9427 position,
9428 ix > 0,
9429 snapshot
9430 .diff_map
9431 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9432 cx,
9433 ) {
9434 return Some(hunk);
9435 }
9436 }
9437 None
9438 }
9439
9440 fn go_to_next_hunk_in_direction(
9441 &mut self,
9442 snapshot: &DisplaySnapshot,
9443 initial_point: Point,
9444 is_wrapped: bool,
9445 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9446 cx: &mut ViewContext<Editor>,
9447 ) -> Option<MultiBufferDiffHunk> {
9448 let display_point = initial_point.to_display_point(snapshot);
9449 let mut hunks = hunks
9450 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9451 .filter(|(display_hunk, _)| {
9452 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9453 })
9454 .dedup();
9455
9456 if let Some((display_hunk, hunk)) = hunks.next() {
9457 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9458 let row = display_hunk.start_display_row();
9459 let point = DisplayPoint::new(row, 0);
9460 s.select_display_ranges([point..point]);
9461 });
9462
9463 Some(hunk)
9464 } else {
9465 None
9466 }
9467 }
9468
9469 pub fn go_to_definition(
9470 &mut self,
9471 _: &GoToDefinition,
9472 cx: &mut ViewContext<Self>,
9473 ) -> Task<Result<Navigated>> {
9474 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9475 cx.spawn(|editor, mut cx| async move {
9476 if definition.await? == Navigated::Yes {
9477 return Ok(Navigated::Yes);
9478 }
9479 match editor.update(&mut cx, |editor, cx| {
9480 editor.find_all_references(&FindAllReferences, cx)
9481 })? {
9482 Some(references) => references.await,
9483 None => Ok(Navigated::No),
9484 }
9485 })
9486 }
9487
9488 pub fn go_to_declaration(
9489 &mut self,
9490 _: &GoToDeclaration,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9494 }
9495
9496 pub fn go_to_declaration_split(
9497 &mut self,
9498 _: &GoToDeclaration,
9499 cx: &mut ViewContext<Self>,
9500 ) -> Task<Result<Navigated>> {
9501 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9502 }
9503
9504 pub fn go_to_implementation(
9505 &mut self,
9506 _: &GoToImplementation,
9507 cx: &mut ViewContext<Self>,
9508 ) -> Task<Result<Navigated>> {
9509 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9510 }
9511
9512 pub fn go_to_implementation_split(
9513 &mut self,
9514 _: &GoToImplementationSplit,
9515 cx: &mut ViewContext<Self>,
9516 ) -> Task<Result<Navigated>> {
9517 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9518 }
9519
9520 pub fn go_to_type_definition(
9521 &mut self,
9522 _: &GoToTypeDefinition,
9523 cx: &mut ViewContext<Self>,
9524 ) -> Task<Result<Navigated>> {
9525 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9526 }
9527
9528 pub fn go_to_definition_split(
9529 &mut self,
9530 _: &GoToDefinitionSplit,
9531 cx: &mut ViewContext<Self>,
9532 ) -> Task<Result<Navigated>> {
9533 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9534 }
9535
9536 pub fn go_to_type_definition_split(
9537 &mut self,
9538 _: &GoToTypeDefinitionSplit,
9539 cx: &mut ViewContext<Self>,
9540 ) -> Task<Result<Navigated>> {
9541 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9542 }
9543
9544 fn go_to_definition_of_kind(
9545 &mut self,
9546 kind: GotoDefinitionKind,
9547 split: bool,
9548 cx: &mut ViewContext<Self>,
9549 ) -> Task<Result<Navigated>> {
9550 let Some(provider) = self.semantics_provider.clone() else {
9551 return Task::ready(Ok(Navigated::No));
9552 };
9553 let head = self.selections.newest::<usize>(cx).head();
9554 let buffer = self.buffer.read(cx);
9555 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9556 text_anchor
9557 } else {
9558 return Task::ready(Ok(Navigated::No));
9559 };
9560
9561 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9562 return Task::ready(Ok(Navigated::No));
9563 };
9564
9565 cx.spawn(|editor, mut cx| async move {
9566 let definitions = definitions.await?;
9567 let navigated = editor
9568 .update(&mut cx, |editor, cx| {
9569 editor.navigate_to_hover_links(
9570 Some(kind),
9571 definitions
9572 .into_iter()
9573 .filter(|location| {
9574 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9575 })
9576 .map(HoverLink::Text)
9577 .collect::<Vec<_>>(),
9578 split,
9579 cx,
9580 )
9581 })?
9582 .await?;
9583 anyhow::Ok(navigated)
9584 })
9585 }
9586
9587 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9588 let selection = self.selections.newest_anchor();
9589 let head = selection.head();
9590 let tail = selection.tail();
9591
9592 let Some((buffer, start_position)) =
9593 self.buffer.read(cx).text_anchor_for_position(head, cx)
9594 else {
9595 return;
9596 };
9597
9598 let end_position = if head != tail {
9599 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9600 return;
9601 };
9602 Some(pos)
9603 } else {
9604 None
9605 };
9606
9607 let url_finder = cx.spawn(|editor, mut cx| async move {
9608 let url = if let Some(end_pos) = end_position {
9609 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9610 } else {
9611 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9612 };
9613
9614 if let Some(url) = url {
9615 editor.update(&mut cx, |_, cx| {
9616 cx.open_url(&url);
9617 })
9618 } else {
9619 Ok(())
9620 }
9621 });
9622
9623 url_finder.detach();
9624 }
9625
9626 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9627 let Some(workspace) = self.workspace() else {
9628 return;
9629 };
9630
9631 let position = self.selections.newest_anchor().head();
9632
9633 let Some((buffer, buffer_position)) =
9634 self.buffer.read(cx).text_anchor_for_position(position, cx)
9635 else {
9636 return;
9637 };
9638
9639 let project = self.project.clone();
9640
9641 cx.spawn(|_, mut cx| async move {
9642 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9643
9644 if let Some((_, path)) = result {
9645 workspace
9646 .update(&mut cx, |workspace, cx| {
9647 workspace.open_resolved_path(path, cx)
9648 })?
9649 .await?;
9650 }
9651 anyhow::Ok(())
9652 })
9653 .detach();
9654 }
9655
9656 pub(crate) fn navigate_to_hover_links(
9657 &mut self,
9658 kind: Option<GotoDefinitionKind>,
9659 mut definitions: Vec<HoverLink>,
9660 split: bool,
9661 cx: &mut ViewContext<Editor>,
9662 ) -> Task<Result<Navigated>> {
9663 // If there is one definition, just open it directly
9664 if definitions.len() == 1 {
9665 let definition = definitions.pop().unwrap();
9666
9667 enum TargetTaskResult {
9668 Location(Option<Location>),
9669 AlreadyNavigated,
9670 }
9671
9672 let target_task = match definition {
9673 HoverLink::Text(link) => {
9674 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9675 }
9676 HoverLink::InlayHint(lsp_location, server_id) => {
9677 let computation = self.compute_target_location(lsp_location, server_id, cx);
9678 cx.background_executor().spawn(async move {
9679 let location = computation.await?;
9680 Ok(TargetTaskResult::Location(location))
9681 })
9682 }
9683 HoverLink::Url(url) => {
9684 cx.open_url(&url);
9685 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9686 }
9687 HoverLink::File(path) => {
9688 if let Some(workspace) = self.workspace() {
9689 cx.spawn(|_, mut cx| async move {
9690 workspace
9691 .update(&mut cx, |workspace, cx| {
9692 workspace.open_resolved_path(path, cx)
9693 })?
9694 .await
9695 .map(|_| TargetTaskResult::AlreadyNavigated)
9696 })
9697 } else {
9698 Task::ready(Ok(TargetTaskResult::Location(None)))
9699 }
9700 }
9701 };
9702 cx.spawn(|editor, mut cx| async move {
9703 let target = match target_task.await.context("target resolution task")? {
9704 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9705 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9706 TargetTaskResult::Location(Some(target)) => target,
9707 };
9708
9709 editor.update(&mut cx, |editor, cx| {
9710 let Some(workspace) = editor.workspace() else {
9711 return Navigated::No;
9712 };
9713 let pane = workspace.read(cx).active_pane().clone();
9714
9715 let range = target.range.to_offset(target.buffer.read(cx));
9716 let range = editor.range_for_match(&range);
9717
9718 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9719 let buffer = target.buffer.read(cx);
9720 let range = check_multiline_range(buffer, range);
9721 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9722 s.select_ranges([range]);
9723 });
9724 } else {
9725 cx.window_context().defer(move |cx| {
9726 let target_editor: View<Self> =
9727 workspace.update(cx, |workspace, cx| {
9728 let pane = if split {
9729 workspace.adjacent_pane(cx)
9730 } else {
9731 workspace.active_pane().clone()
9732 };
9733
9734 workspace.open_project_item(
9735 pane,
9736 target.buffer.clone(),
9737 true,
9738 true,
9739 cx,
9740 )
9741 });
9742 target_editor.update(cx, |target_editor, cx| {
9743 // When selecting a definition in a different buffer, disable the nav history
9744 // to avoid creating a history entry at the previous cursor location.
9745 pane.update(cx, |pane, _| pane.disable_history());
9746 let buffer = target.buffer.read(cx);
9747 let range = check_multiline_range(buffer, range);
9748 target_editor.change_selections(
9749 Some(Autoscroll::focused()),
9750 cx,
9751 |s| {
9752 s.select_ranges([range]);
9753 },
9754 );
9755 pane.update(cx, |pane, _| pane.enable_history());
9756 });
9757 });
9758 }
9759 Navigated::Yes
9760 })
9761 })
9762 } else if !definitions.is_empty() {
9763 cx.spawn(|editor, mut cx| async move {
9764 let (title, location_tasks, workspace) = editor
9765 .update(&mut cx, |editor, cx| {
9766 let tab_kind = match kind {
9767 Some(GotoDefinitionKind::Implementation) => "Implementations",
9768 _ => "Definitions",
9769 };
9770 let title = definitions
9771 .iter()
9772 .find_map(|definition| match definition {
9773 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9774 let buffer = origin.buffer.read(cx);
9775 format!(
9776 "{} for {}",
9777 tab_kind,
9778 buffer
9779 .text_for_range(origin.range.clone())
9780 .collect::<String>()
9781 )
9782 }),
9783 HoverLink::InlayHint(_, _) => None,
9784 HoverLink::Url(_) => None,
9785 HoverLink::File(_) => None,
9786 })
9787 .unwrap_or(tab_kind.to_string());
9788 let location_tasks = definitions
9789 .into_iter()
9790 .map(|definition| match definition {
9791 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9792 HoverLink::InlayHint(lsp_location, server_id) => {
9793 editor.compute_target_location(lsp_location, server_id, cx)
9794 }
9795 HoverLink::Url(_) => Task::ready(Ok(None)),
9796 HoverLink::File(_) => Task::ready(Ok(None)),
9797 })
9798 .collect::<Vec<_>>();
9799 (title, location_tasks, editor.workspace().clone())
9800 })
9801 .context("location tasks preparation")?;
9802
9803 let locations = future::join_all(location_tasks)
9804 .await
9805 .into_iter()
9806 .filter_map(|location| location.transpose())
9807 .collect::<Result<_>>()
9808 .context("location tasks")?;
9809
9810 let Some(workspace) = workspace else {
9811 return Ok(Navigated::No);
9812 };
9813 let opened = workspace
9814 .update(&mut cx, |workspace, cx| {
9815 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9816 })
9817 .ok();
9818
9819 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9820 })
9821 } else {
9822 Task::ready(Ok(Navigated::No))
9823 }
9824 }
9825
9826 fn compute_target_location(
9827 &self,
9828 lsp_location: lsp::Location,
9829 server_id: LanguageServerId,
9830 cx: &mut ViewContext<Self>,
9831 ) -> Task<anyhow::Result<Option<Location>>> {
9832 let Some(project) = self.project.clone() else {
9833 return Task::ready(Ok(None));
9834 };
9835
9836 cx.spawn(move |editor, mut cx| async move {
9837 let location_task = editor.update(&mut cx, |_, cx| {
9838 project.update(cx, |project, cx| {
9839 let language_server_name = project
9840 .language_server_statuses(cx)
9841 .find(|(id, _)| server_id == *id)
9842 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9843 language_server_name.map(|language_server_name| {
9844 project.open_local_buffer_via_lsp(
9845 lsp_location.uri.clone(),
9846 server_id,
9847 language_server_name,
9848 cx,
9849 )
9850 })
9851 })
9852 })?;
9853 let location = match location_task {
9854 Some(task) => Some({
9855 let target_buffer_handle = task.await.context("open local buffer")?;
9856 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9857 let target_start = target_buffer
9858 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9859 let target_end = target_buffer
9860 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9861 target_buffer.anchor_after(target_start)
9862 ..target_buffer.anchor_before(target_end)
9863 })?;
9864 Location {
9865 buffer: target_buffer_handle,
9866 range,
9867 }
9868 }),
9869 None => None,
9870 };
9871 Ok(location)
9872 })
9873 }
9874
9875 pub fn find_all_references(
9876 &mut self,
9877 _: &FindAllReferences,
9878 cx: &mut ViewContext<Self>,
9879 ) -> Option<Task<Result<Navigated>>> {
9880 let selection = self.selections.newest::<usize>(cx);
9881 let multi_buffer = self.buffer.read(cx);
9882 let head = selection.head();
9883
9884 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9885 let head_anchor = multi_buffer_snapshot.anchor_at(
9886 head,
9887 if head < selection.tail() {
9888 Bias::Right
9889 } else {
9890 Bias::Left
9891 },
9892 );
9893
9894 match self
9895 .find_all_references_task_sources
9896 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9897 {
9898 Ok(_) => {
9899 log::info!(
9900 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9901 );
9902 return None;
9903 }
9904 Err(i) => {
9905 self.find_all_references_task_sources.insert(i, head_anchor);
9906 }
9907 }
9908
9909 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9910 let workspace = self.workspace()?;
9911 let project = workspace.read(cx).project().clone();
9912 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9913 Some(cx.spawn(|editor, mut cx| async move {
9914 let _cleanup = defer({
9915 let mut cx = cx.clone();
9916 move || {
9917 let _ = editor.update(&mut cx, |editor, _| {
9918 if let Ok(i) =
9919 editor
9920 .find_all_references_task_sources
9921 .binary_search_by(|anchor| {
9922 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9923 })
9924 {
9925 editor.find_all_references_task_sources.remove(i);
9926 }
9927 });
9928 }
9929 });
9930
9931 let locations = references.await?;
9932 if locations.is_empty() {
9933 return anyhow::Ok(Navigated::No);
9934 }
9935
9936 workspace.update(&mut cx, |workspace, cx| {
9937 let title = locations
9938 .first()
9939 .as_ref()
9940 .map(|location| {
9941 let buffer = location.buffer.read(cx);
9942 format!(
9943 "References to `{}`",
9944 buffer
9945 .text_for_range(location.range.clone())
9946 .collect::<String>()
9947 )
9948 })
9949 .unwrap();
9950 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9951 Navigated::Yes
9952 })
9953 }))
9954 }
9955
9956 /// Opens a multibuffer with the given project locations in it
9957 pub fn open_locations_in_multibuffer(
9958 workspace: &mut Workspace,
9959 mut locations: Vec<Location>,
9960 title: String,
9961 split: bool,
9962 cx: &mut ViewContext<Workspace>,
9963 ) {
9964 // If there are multiple definitions, open them in a multibuffer
9965 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9966 let mut locations = locations.into_iter().peekable();
9967 let mut ranges_to_highlight = Vec::new();
9968 let capability = workspace.project().read(cx).capability();
9969
9970 let excerpt_buffer = cx.new_model(|cx| {
9971 let mut multibuffer = MultiBuffer::new(capability);
9972 while let Some(location) = locations.next() {
9973 let buffer = location.buffer.read(cx);
9974 let mut ranges_for_buffer = Vec::new();
9975 let range = location.range.to_offset(buffer);
9976 ranges_for_buffer.push(range.clone());
9977
9978 while let Some(next_location) = locations.peek() {
9979 if next_location.buffer == location.buffer {
9980 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9981 locations.next();
9982 } else {
9983 break;
9984 }
9985 }
9986
9987 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9988 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9989 location.buffer.clone(),
9990 ranges_for_buffer,
9991 DEFAULT_MULTIBUFFER_CONTEXT,
9992 cx,
9993 ))
9994 }
9995
9996 multibuffer.with_title(title)
9997 });
9998
9999 let editor = cx.new_view(|cx| {
10000 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10001 });
10002 editor.update(cx, |editor, cx| {
10003 if let Some(first_range) = ranges_to_highlight.first() {
10004 editor.change_selections(None, cx, |selections| {
10005 selections.clear_disjoint();
10006 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10007 });
10008 }
10009 editor.highlight_background::<Self>(
10010 &ranges_to_highlight,
10011 |theme| theme.editor_highlighted_line_background,
10012 cx,
10013 );
10014 editor.register_buffers_with_language_servers(cx);
10015 });
10016
10017 let item = Box::new(editor);
10018 let item_id = item.item_id();
10019
10020 if split {
10021 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10022 } else {
10023 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10024 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10025 pane.close_current_preview_item(cx)
10026 } else {
10027 None
10028 }
10029 });
10030 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10031 }
10032 workspace.active_pane().update(cx, |pane, cx| {
10033 pane.set_preview_item_id(Some(item_id), cx);
10034 });
10035 }
10036
10037 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10038 use language::ToOffset as _;
10039
10040 let provider = self.semantics_provider.clone()?;
10041 let selection = self.selections.newest_anchor().clone();
10042 let (cursor_buffer, cursor_buffer_position) = self
10043 .buffer
10044 .read(cx)
10045 .text_anchor_for_position(selection.head(), cx)?;
10046 let (tail_buffer, cursor_buffer_position_end) = self
10047 .buffer
10048 .read(cx)
10049 .text_anchor_for_position(selection.tail(), cx)?;
10050 if tail_buffer != cursor_buffer {
10051 return None;
10052 }
10053
10054 let snapshot = cursor_buffer.read(cx).snapshot();
10055 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10056 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10057 let prepare_rename = provider
10058 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10059 .unwrap_or_else(|| Task::ready(Ok(None)));
10060 drop(snapshot);
10061
10062 Some(cx.spawn(|this, mut cx| async move {
10063 let rename_range = if let Some(range) = prepare_rename.await? {
10064 Some(range)
10065 } else {
10066 this.update(&mut cx, |this, cx| {
10067 let buffer = this.buffer.read(cx).snapshot(cx);
10068 let mut buffer_highlights = this
10069 .document_highlights_for_position(selection.head(), &buffer)
10070 .filter(|highlight| {
10071 highlight.start.excerpt_id == selection.head().excerpt_id
10072 && highlight.end.excerpt_id == selection.head().excerpt_id
10073 });
10074 buffer_highlights
10075 .next()
10076 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10077 })?
10078 };
10079 if let Some(rename_range) = rename_range {
10080 this.update(&mut cx, |this, cx| {
10081 let snapshot = cursor_buffer.read(cx).snapshot();
10082 let rename_buffer_range = rename_range.to_offset(&snapshot);
10083 let cursor_offset_in_rename_range =
10084 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10085 let cursor_offset_in_rename_range_end =
10086 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10087
10088 this.take_rename(false, cx);
10089 let buffer = this.buffer.read(cx).read(cx);
10090 let cursor_offset = selection.head().to_offset(&buffer);
10091 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10092 let rename_end = rename_start + rename_buffer_range.len();
10093 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10094 let mut old_highlight_id = None;
10095 let old_name: Arc<str> = buffer
10096 .chunks(rename_start..rename_end, true)
10097 .map(|chunk| {
10098 if old_highlight_id.is_none() {
10099 old_highlight_id = chunk.syntax_highlight_id;
10100 }
10101 chunk.text
10102 })
10103 .collect::<String>()
10104 .into();
10105
10106 drop(buffer);
10107
10108 // Position the selection in the rename editor so that it matches the current selection.
10109 this.show_local_selections = false;
10110 let rename_editor = cx.new_view(|cx| {
10111 let mut editor = Editor::single_line(cx);
10112 editor.buffer.update(cx, |buffer, cx| {
10113 buffer.edit([(0..0, old_name.clone())], None, cx)
10114 });
10115 let rename_selection_range = match cursor_offset_in_rename_range
10116 .cmp(&cursor_offset_in_rename_range_end)
10117 {
10118 Ordering::Equal => {
10119 editor.select_all(&SelectAll, cx);
10120 return editor;
10121 }
10122 Ordering::Less => {
10123 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10124 }
10125 Ordering::Greater => {
10126 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10127 }
10128 };
10129 if rename_selection_range.end > old_name.len() {
10130 editor.select_all(&SelectAll, cx);
10131 } else {
10132 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10133 s.select_ranges([rename_selection_range]);
10134 });
10135 }
10136 editor
10137 });
10138 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10139 if e == &EditorEvent::Focused {
10140 cx.emit(EditorEvent::FocusedIn)
10141 }
10142 })
10143 .detach();
10144
10145 let write_highlights =
10146 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10147 let read_highlights =
10148 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10149 let ranges = write_highlights
10150 .iter()
10151 .flat_map(|(_, ranges)| ranges.iter())
10152 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10153 .cloned()
10154 .collect();
10155
10156 this.highlight_text::<Rename>(
10157 ranges,
10158 HighlightStyle {
10159 fade_out: Some(0.6),
10160 ..Default::default()
10161 },
10162 cx,
10163 );
10164 let rename_focus_handle = rename_editor.focus_handle(cx);
10165 cx.focus(&rename_focus_handle);
10166 let block_id = this.insert_blocks(
10167 [BlockProperties {
10168 style: BlockStyle::Flex,
10169 placement: BlockPlacement::Below(range.start),
10170 height: 1,
10171 render: Arc::new({
10172 let rename_editor = rename_editor.clone();
10173 move |cx: &mut BlockContext| {
10174 let mut text_style = cx.editor_style.text.clone();
10175 if let Some(highlight_style) = old_highlight_id
10176 .and_then(|h| h.style(&cx.editor_style.syntax))
10177 {
10178 text_style = text_style.highlight(highlight_style);
10179 }
10180 div()
10181 .block_mouse_down()
10182 .pl(cx.anchor_x)
10183 .child(EditorElement::new(
10184 &rename_editor,
10185 EditorStyle {
10186 background: cx.theme().system().transparent,
10187 local_player: cx.editor_style.local_player,
10188 text: text_style,
10189 scrollbar_width: cx.editor_style.scrollbar_width,
10190 syntax: cx.editor_style.syntax.clone(),
10191 status: cx.editor_style.status.clone(),
10192 inlay_hints_style: HighlightStyle {
10193 font_weight: Some(FontWeight::BOLD),
10194 ..make_inlay_hints_style(cx)
10195 },
10196 inline_completion_styles: make_suggestion_styles(
10197 cx,
10198 ),
10199 ..EditorStyle::default()
10200 },
10201 ))
10202 .into_any_element()
10203 }
10204 }),
10205 priority: 0,
10206 }],
10207 Some(Autoscroll::fit()),
10208 cx,
10209 )[0];
10210 this.pending_rename = Some(RenameState {
10211 range,
10212 old_name,
10213 editor: rename_editor,
10214 block_id,
10215 });
10216 })?;
10217 }
10218
10219 Ok(())
10220 }))
10221 }
10222
10223 pub fn confirm_rename(
10224 &mut self,
10225 _: &ConfirmRename,
10226 cx: &mut ViewContext<Self>,
10227 ) -> Option<Task<Result<()>>> {
10228 let rename = self.take_rename(false, cx)?;
10229 let workspace = self.workspace()?.downgrade();
10230 let (buffer, start) = self
10231 .buffer
10232 .read(cx)
10233 .text_anchor_for_position(rename.range.start, cx)?;
10234 let (end_buffer, _) = self
10235 .buffer
10236 .read(cx)
10237 .text_anchor_for_position(rename.range.end, cx)?;
10238 if buffer != end_buffer {
10239 return None;
10240 }
10241
10242 let old_name = rename.old_name;
10243 let new_name = rename.editor.read(cx).text(cx);
10244
10245 let rename = self.semantics_provider.as_ref()?.perform_rename(
10246 &buffer,
10247 start,
10248 new_name.clone(),
10249 cx,
10250 )?;
10251
10252 Some(cx.spawn(|editor, mut cx| async move {
10253 let project_transaction = rename.await?;
10254 Self::open_project_transaction(
10255 &editor,
10256 workspace,
10257 project_transaction,
10258 format!("Rename: {} → {}", old_name, new_name),
10259 cx.clone(),
10260 )
10261 .await?;
10262
10263 editor.update(&mut cx, |editor, cx| {
10264 editor.refresh_document_highlights(cx);
10265 })?;
10266 Ok(())
10267 }))
10268 }
10269
10270 fn take_rename(
10271 &mut self,
10272 moving_cursor: bool,
10273 cx: &mut ViewContext<Self>,
10274 ) -> Option<RenameState> {
10275 let rename = self.pending_rename.take()?;
10276 if rename.editor.focus_handle(cx).is_focused(cx) {
10277 cx.focus(&self.focus_handle);
10278 }
10279
10280 self.remove_blocks(
10281 [rename.block_id].into_iter().collect(),
10282 Some(Autoscroll::fit()),
10283 cx,
10284 );
10285 self.clear_highlights::<Rename>(cx);
10286 self.show_local_selections = true;
10287
10288 if moving_cursor {
10289 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10290 editor.selections.newest::<usize>(cx).head()
10291 });
10292
10293 // Update the selection to match the position of the selection inside
10294 // the rename editor.
10295 let snapshot = self.buffer.read(cx).read(cx);
10296 let rename_range = rename.range.to_offset(&snapshot);
10297 let cursor_in_editor = snapshot
10298 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10299 .min(rename_range.end);
10300 drop(snapshot);
10301
10302 self.change_selections(None, cx, |s| {
10303 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10304 });
10305 } else {
10306 self.refresh_document_highlights(cx);
10307 }
10308
10309 Some(rename)
10310 }
10311
10312 pub fn pending_rename(&self) -> Option<&RenameState> {
10313 self.pending_rename.as_ref()
10314 }
10315
10316 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10317 let project = match &self.project {
10318 Some(project) => project.clone(),
10319 None => return None,
10320 };
10321
10322 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10323 }
10324
10325 fn format_selections(
10326 &mut self,
10327 _: &FormatSelections,
10328 cx: &mut ViewContext<Self>,
10329 ) -> Option<Task<Result<()>>> {
10330 let project = match &self.project {
10331 Some(project) => project.clone(),
10332 None => return None,
10333 };
10334
10335 let ranges = self
10336 .selections
10337 .all_adjusted(cx)
10338 .into_iter()
10339 .map(|selection| selection.range())
10340 .collect_vec();
10341
10342 Some(self.perform_format(
10343 project,
10344 FormatTrigger::Manual,
10345 FormatTarget::Ranges(ranges),
10346 cx,
10347 ))
10348 }
10349
10350 fn perform_format(
10351 &mut self,
10352 project: Model<Project>,
10353 trigger: FormatTrigger,
10354 target: FormatTarget,
10355 cx: &mut ViewContext<Self>,
10356 ) -> Task<Result<()>> {
10357 let buffer = self.buffer.clone();
10358 let (buffers, target) = match target {
10359 FormatTarget::Buffers => {
10360 let mut buffers = buffer.read(cx).all_buffers();
10361 if trigger == FormatTrigger::Save {
10362 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10363 }
10364 (buffers, LspFormatTarget::Buffers)
10365 }
10366 FormatTarget::Ranges(selection_ranges) => {
10367 let multi_buffer = buffer.read(cx);
10368 let snapshot = multi_buffer.read(cx);
10369 let mut buffers = HashSet::default();
10370 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10371 BTreeMap::new();
10372 for selection_range in selection_ranges {
10373 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10374 {
10375 let buffer_id = excerpt.buffer_id();
10376 let start = excerpt.buffer().anchor_before(buffer_range.start);
10377 let end = excerpt.buffer().anchor_after(buffer_range.end);
10378 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10379 buffer_id_to_ranges
10380 .entry(buffer_id)
10381 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10382 .or_insert_with(|| vec![start..end]);
10383 }
10384 }
10385 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10386 }
10387 };
10388
10389 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10390 let format = project.update(cx, |project, cx| {
10391 project.format(buffers, target, true, trigger, cx)
10392 });
10393
10394 cx.spawn(|_, mut cx| async move {
10395 let transaction = futures::select_biased! {
10396 () = timeout => {
10397 log::warn!("timed out waiting for formatting");
10398 None
10399 }
10400 transaction = format.log_err().fuse() => transaction,
10401 };
10402
10403 buffer
10404 .update(&mut cx, |buffer, cx| {
10405 if let Some(transaction) = transaction {
10406 if !buffer.is_singleton() {
10407 buffer.push_transaction(&transaction.0, cx);
10408 }
10409 }
10410
10411 cx.notify();
10412 })
10413 .ok();
10414
10415 Ok(())
10416 })
10417 }
10418
10419 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10420 if let Some(project) = self.project.clone() {
10421 self.buffer.update(cx, |multi_buffer, cx| {
10422 project.update(cx, |project, cx| {
10423 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10424 });
10425 })
10426 }
10427 }
10428
10429 fn cancel_language_server_work(
10430 &mut self,
10431 _: &actions::CancelLanguageServerWork,
10432 cx: &mut ViewContext<Self>,
10433 ) {
10434 if let Some(project) = self.project.clone() {
10435 self.buffer.update(cx, |multi_buffer, cx| {
10436 project.update(cx, |project, cx| {
10437 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10438 });
10439 })
10440 }
10441 }
10442
10443 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10444 cx.show_character_palette();
10445 }
10446
10447 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10448 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10449 let buffer = self.buffer.read(cx).snapshot(cx);
10450 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10451 let is_valid = buffer
10452 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10453 .any(|entry| {
10454 let range = entry.range.to_offset(&buffer);
10455 entry.diagnostic.is_primary
10456 && !range.is_empty()
10457 && range.start == primary_range_start
10458 && entry.diagnostic.message == active_diagnostics.primary_message
10459 });
10460
10461 if is_valid != active_diagnostics.is_valid {
10462 active_diagnostics.is_valid = is_valid;
10463 let mut new_styles = HashMap::default();
10464 for (block_id, diagnostic) in &active_diagnostics.blocks {
10465 new_styles.insert(
10466 *block_id,
10467 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10468 );
10469 }
10470 self.display_map.update(cx, |display_map, _cx| {
10471 display_map.replace_blocks(new_styles)
10472 });
10473 }
10474 }
10475 }
10476
10477 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10478 self.dismiss_diagnostics(cx);
10479 let snapshot = self.snapshot(cx);
10480 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10481 let buffer = self.buffer.read(cx).snapshot(cx);
10482
10483 let mut primary_range = None;
10484 let mut primary_message = None;
10485 let mut group_end = Point::zero();
10486 let diagnostic_group = buffer
10487 .diagnostic_group(group_id)
10488 .filter_map(|entry| {
10489 let start = entry.range.start.to_point(&buffer);
10490 let end = entry.range.end.to_point(&buffer);
10491 if snapshot.is_line_folded(MultiBufferRow(start.row))
10492 && (start.row == end.row
10493 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10494 {
10495 return None;
10496 }
10497 if end > group_end {
10498 group_end = end;
10499 }
10500 if entry.diagnostic.is_primary {
10501 primary_range = Some(entry.range.clone());
10502 primary_message = Some(entry.diagnostic.message.clone());
10503 }
10504 Some(entry)
10505 })
10506 .collect::<Vec<_>>();
10507 let primary_range = primary_range?;
10508 let primary_message = primary_message?;
10509
10510 let blocks = display_map
10511 .insert_blocks(
10512 diagnostic_group.iter().map(|entry| {
10513 let diagnostic = entry.diagnostic.clone();
10514 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10515 BlockProperties {
10516 style: BlockStyle::Fixed,
10517 placement: BlockPlacement::Below(
10518 buffer.anchor_after(entry.range.start),
10519 ),
10520 height: message_height,
10521 render: diagnostic_block_renderer(diagnostic, None, true, true),
10522 priority: 0,
10523 }
10524 }),
10525 cx,
10526 )
10527 .into_iter()
10528 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10529 .collect();
10530
10531 Some(ActiveDiagnosticGroup {
10532 primary_range,
10533 primary_message,
10534 group_id,
10535 blocks,
10536 is_valid: true,
10537 })
10538 });
10539 }
10540
10541 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10542 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10543 self.display_map.update(cx, |display_map, cx| {
10544 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10545 });
10546 cx.notify();
10547 }
10548 }
10549
10550 pub fn set_selections_from_remote(
10551 &mut self,
10552 selections: Vec<Selection<Anchor>>,
10553 pending_selection: Option<Selection<Anchor>>,
10554 cx: &mut ViewContext<Self>,
10555 ) {
10556 let old_cursor_position = self.selections.newest_anchor().head();
10557 self.selections.change_with(cx, |s| {
10558 s.select_anchors(selections);
10559 if let Some(pending_selection) = pending_selection {
10560 s.set_pending(pending_selection, SelectMode::Character);
10561 } else {
10562 s.clear_pending();
10563 }
10564 });
10565 self.selections_did_change(false, &old_cursor_position, true, cx);
10566 }
10567
10568 fn push_to_selection_history(&mut self) {
10569 self.selection_history.push(SelectionHistoryEntry {
10570 selections: self.selections.disjoint_anchors(),
10571 select_next_state: self.select_next_state.clone(),
10572 select_prev_state: self.select_prev_state.clone(),
10573 add_selections_state: self.add_selections_state.clone(),
10574 });
10575 }
10576
10577 pub fn transact(
10578 &mut self,
10579 cx: &mut ViewContext<Self>,
10580 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10581 ) -> Option<TransactionId> {
10582 self.start_transaction_at(Instant::now(), cx);
10583 update(self, cx);
10584 self.end_transaction_at(Instant::now(), cx)
10585 }
10586
10587 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10588 self.end_selection(cx);
10589 if let Some(tx_id) = self
10590 .buffer
10591 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10592 {
10593 self.selection_history
10594 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10595 cx.emit(EditorEvent::TransactionBegun {
10596 transaction_id: tx_id,
10597 })
10598 }
10599 }
10600
10601 pub fn end_transaction_at(
10602 &mut self,
10603 now: Instant,
10604 cx: &mut ViewContext<Self>,
10605 ) -> Option<TransactionId> {
10606 if let Some(transaction_id) = self
10607 .buffer
10608 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10609 {
10610 if let Some((_, end_selections)) =
10611 self.selection_history.transaction_mut(transaction_id)
10612 {
10613 *end_selections = Some(self.selections.disjoint_anchors());
10614 } else {
10615 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10616 }
10617
10618 cx.emit(EditorEvent::Edited { transaction_id });
10619 Some(transaction_id)
10620 } else {
10621 None
10622 }
10623 }
10624
10625 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10626 if self.is_singleton(cx) {
10627 let selection = self.selections.newest::<Point>(cx);
10628
10629 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10630 let range = if selection.is_empty() {
10631 let point = selection.head().to_display_point(&display_map);
10632 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10633 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10634 .to_point(&display_map);
10635 start..end
10636 } else {
10637 selection.range()
10638 };
10639 if display_map.folds_in_range(range).next().is_some() {
10640 self.unfold_lines(&Default::default(), cx)
10641 } else {
10642 self.fold(&Default::default(), cx)
10643 }
10644 } else {
10645 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10646 let mut toggled_buffers = HashSet::default();
10647 for (_, buffer_snapshot, _) in
10648 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10649 {
10650 let buffer_id = buffer_snapshot.remote_id();
10651 if toggled_buffers.insert(buffer_id) {
10652 if self.buffer_folded(buffer_id, cx) {
10653 self.unfold_buffer(buffer_id, cx);
10654 } else {
10655 self.fold_buffer(buffer_id, cx);
10656 }
10657 }
10658 }
10659 }
10660 }
10661
10662 pub fn toggle_fold_recursive(
10663 &mut self,
10664 _: &actions::ToggleFoldRecursive,
10665 cx: &mut ViewContext<Self>,
10666 ) {
10667 let selection = self.selections.newest::<Point>(cx);
10668
10669 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10670 let range = if selection.is_empty() {
10671 let point = selection.head().to_display_point(&display_map);
10672 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10673 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10674 .to_point(&display_map);
10675 start..end
10676 } else {
10677 selection.range()
10678 };
10679 if display_map.folds_in_range(range).next().is_some() {
10680 self.unfold_recursive(&Default::default(), cx)
10681 } else {
10682 self.fold_recursive(&Default::default(), cx)
10683 }
10684 }
10685
10686 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10687 if self.is_singleton(cx) {
10688 let mut to_fold = Vec::new();
10689 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10690 let selections = self.selections.all_adjusted(cx);
10691
10692 for selection in selections {
10693 let range = selection.range().sorted();
10694 let buffer_start_row = range.start.row;
10695
10696 if range.start.row != range.end.row {
10697 let mut found = false;
10698 let mut row = range.start.row;
10699 while row <= range.end.row {
10700 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10701 {
10702 found = true;
10703 row = crease.range().end.row + 1;
10704 to_fold.push(crease);
10705 } else {
10706 row += 1
10707 }
10708 }
10709 if found {
10710 continue;
10711 }
10712 }
10713
10714 for row in (0..=range.start.row).rev() {
10715 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10716 if crease.range().end.row >= buffer_start_row {
10717 to_fold.push(crease);
10718 if row <= range.start.row {
10719 break;
10720 }
10721 }
10722 }
10723 }
10724 }
10725
10726 self.fold_creases(to_fold, true, cx);
10727 } else {
10728 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10729 let mut folded_buffers = HashSet::default();
10730 for (_, buffer_snapshot, _) in
10731 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10732 {
10733 let buffer_id = buffer_snapshot.remote_id();
10734 if folded_buffers.insert(buffer_id) {
10735 self.fold_buffer(buffer_id, cx);
10736 }
10737 }
10738 }
10739 }
10740
10741 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10742 if !self.buffer.read(cx).is_singleton() {
10743 return;
10744 }
10745
10746 let fold_at_level = fold_at.level;
10747 let snapshot = self.buffer.read(cx).snapshot(cx);
10748 let mut to_fold = Vec::new();
10749 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10750
10751 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10752 while start_row < end_row {
10753 match self
10754 .snapshot(cx)
10755 .crease_for_buffer_row(MultiBufferRow(start_row))
10756 {
10757 Some(crease) => {
10758 let nested_start_row = crease.range().start.row + 1;
10759 let nested_end_row = crease.range().end.row;
10760
10761 if current_level < fold_at_level {
10762 stack.push((nested_start_row, nested_end_row, current_level + 1));
10763 } else if current_level == fold_at_level {
10764 to_fold.push(crease);
10765 }
10766
10767 start_row = nested_end_row + 1;
10768 }
10769 None => start_row += 1,
10770 }
10771 }
10772 }
10773
10774 self.fold_creases(to_fold, true, cx);
10775 }
10776
10777 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10778 if self.buffer.read(cx).is_singleton() {
10779 let mut fold_ranges = Vec::new();
10780 let snapshot = self.buffer.read(cx).snapshot(cx);
10781
10782 for row in 0..snapshot.max_row().0 {
10783 if let Some(foldable_range) =
10784 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10785 {
10786 fold_ranges.push(foldable_range);
10787 }
10788 }
10789
10790 self.fold_creases(fold_ranges, true, cx);
10791 } else {
10792 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10793 editor
10794 .update(&mut cx, |editor, cx| {
10795 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10796 editor.fold_buffer(buffer_id, cx);
10797 }
10798 })
10799 .ok();
10800 });
10801 }
10802 }
10803
10804 pub fn fold_function_bodies(
10805 &mut self,
10806 _: &actions::FoldFunctionBodies,
10807 cx: &mut ViewContext<Self>,
10808 ) {
10809 let snapshot = self.buffer.read(cx).snapshot(cx);
10810 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10811 return;
10812 };
10813 let creases = buffer
10814 .function_body_fold_ranges(0..buffer.len())
10815 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10816 .collect();
10817
10818 self.fold_creases(creases, true, cx);
10819 }
10820
10821 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10822 let mut to_fold = Vec::new();
10823 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10824 let selections = self.selections.all_adjusted(cx);
10825
10826 for selection in selections {
10827 let range = selection.range().sorted();
10828 let buffer_start_row = range.start.row;
10829
10830 if range.start.row != range.end.row {
10831 let mut found = false;
10832 for row in range.start.row..=range.end.row {
10833 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10834 found = true;
10835 to_fold.push(crease);
10836 }
10837 }
10838 if found {
10839 continue;
10840 }
10841 }
10842
10843 for row in (0..=range.start.row).rev() {
10844 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10845 if crease.range().end.row >= buffer_start_row {
10846 to_fold.push(crease);
10847 } else {
10848 break;
10849 }
10850 }
10851 }
10852 }
10853
10854 self.fold_creases(to_fold, true, cx);
10855 }
10856
10857 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10858 let buffer_row = fold_at.buffer_row;
10859 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10860
10861 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10862 let autoscroll = self
10863 .selections
10864 .all::<Point>(cx)
10865 .iter()
10866 .any(|selection| crease.range().overlaps(&selection.range()));
10867
10868 self.fold_creases(vec![crease], autoscroll, cx);
10869 }
10870 }
10871
10872 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10873 if self.is_singleton(cx) {
10874 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10875 let buffer = &display_map.buffer_snapshot;
10876 let selections = self.selections.all::<Point>(cx);
10877 let ranges = selections
10878 .iter()
10879 .map(|s| {
10880 let range = s.display_range(&display_map).sorted();
10881 let mut start = range.start.to_point(&display_map);
10882 let mut end = range.end.to_point(&display_map);
10883 start.column = 0;
10884 end.column = buffer.line_len(MultiBufferRow(end.row));
10885 start..end
10886 })
10887 .collect::<Vec<_>>();
10888
10889 self.unfold_ranges(&ranges, true, true, cx);
10890 } else {
10891 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10892 let mut unfolded_buffers = HashSet::default();
10893 for (_, buffer_snapshot, _) in
10894 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10895 {
10896 let buffer_id = buffer_snapshot.remote_id();
10897 if unfolded_buffers.insert(buffer_id) {
10898 self.unfold_buffer(buffer_id, cx);
10899 }
10900 }
10901 }
10902 }
10903
10904 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10906 let selections = self.selections.all::<Point>(cx);
10907 let ranges = selections
10908 .iter()
10909 .map(|s| {
10910 let mut range = s.display_range(&display_map).sorted();
10911 *range.start.column_mut() = 0;
10912 *range.end.column_mut() = display_map.line_len(range.end.row());
10913 let start = range.start.to_point(&display_map);
10914 let end = range.end.to_point(&display_map);
10915 start..end
10916 })
10917 .collect::<Vec<_>>();
10918
10919 self.unfold_ranges(&ranges, true, true, cx);
10920 }
10921
10922 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10923 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10924
10925 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10926 ..Point::new(
10927 unfold_at.buffer_row.0,
10928 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10929 );
10930
10931 let autoscroll = self
10932 .selections
10933 .all::<Point>(cx)
10934 .iter()
10935 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10936
10937 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10938 }
10939
10940 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10941 if self.buffer.read(cx).is_singleton() {
10942 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10943 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10944 } else {
10945 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10946 editor
10947 .update(&mut cx, |editor, cx| {
10948 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10949 editor.unfold_buffer(buffer_id, cx);
10950 }
10951 })
10952 .ok();
10953 });
10954 }
10955 }
10956
10957 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10958 let selections = self.selections.all::<Point>(cx);
10959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10960 let line_mode = self.selections.line_mode;
10961 let ranges = selections
10962 .into_iter()
10963 .map(|s| {
10964 if line_mode {
10965 let start = Point::new(s.start.row, 0);
10966 let end = Point::new(
10967 s.end.row,
10968 display_map
10969 .buffer_snapshot
10970 .line_len(MultiBufferRow(s.end.row)),
10971 );
10972 Crease::simple(start..end, display_map.fold_placeholder.clone())
10973 } else {
10974 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10975 }
10976 })
10977 .collect::<Vec<_>>();
10978 self.fold_creases(ranges, true, cx);
10979 }
10980
10981 pub fn fold_ranges<T: ToOffset + Clone>(
10982 &mut self,
10983 ranges: Vec<Range<T>>,
10984 auto_scroll: bool,
10985 cx: &mut ViewContext<Self>,
10986 ) {
10987 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10988 let ranges = ranges
10989 .into_iter()
10990 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10991 .collect::<Vec<_>>();
10992 self.fold_creases(ranges, auto_scroll, cx);
10993 }
10994
10995 pub fn fold_creases<T: ToOffset + Clone>(
10996 &mut self,
10997 creases: Vec<Crease<T>>,
10998 auto_scroll: bool,
10999 cx: &mut ViewContext<Self>,
11000 ) {
11001 if creases.is_empty() {
11002 return;
11003 }
11004
11005 let mut buffers_affected = HashSet::default();
11006 let multi_buffer = self.buffer().read(cx);
11007 for crease in &creases {
11008 if let Some((_, buffer, _)) =
11009 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11010 {
11011 buffers_affected.insert(buffer.read(cx).remote_id());
11012 };
11013 }
11014
11015 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11016
11017 if auto_scroll {
11018 self.request_autoscroll(Autoscroll::fit(), cx);
11019 }
11020
11021 for buffer_id in buffers_affected {
11022 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11023 }
11024
11025 cx.notify();
11026
11027 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11028 // Clear diagnostics block when folding a range that contains it.
11029 let snapshot = self.snapshot(cx);
11030 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11031 drop(snapshot);
11032 self.active_diagnostics = Some(active_diagnostics);
11033 self.dismiss_diagnostics(cx);
11034 } else {
11035 self.active_diagnostics = Some(active_diagnostics);
11036 }
11037 }
11038
11039 self.scrollbar_marker_state.dirty = true;
11040 }
11041
11042 /// Removes any folds whose ranges intersect any of the given ranges.
11043 pub fn unfold_ranges<T: ToOffset + Clone>(
11044 &mut self,
11045 ranges: &[Range<T>],
11046 inclusive: bool,
11047 auto_scroll: bool,
11048 cx: &mut ViewContext<Self>,
11049 ) {
11050 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11051 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11052 });
11053 }
11054
11055 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11056 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11057 return;
11058 }
11059 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11060 return;
11061 };
11062 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11063 self.display_map
11064 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11065 cx.emit(EditorEvent::BufferFoldToggled {
11066 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11067 folded: true,
11068 });
11069 cx.notify();
11070 }
11071
11072 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11073 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11074 return;
11075 }
11076 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11077 return;
11078 };
11079 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11080 self.display_map.update(cx, |display_map, cx| {
11081 display_map.unfold_buffer(buffer_id, cx);
11082 });
11083 cx.emit(EditorEvent::BufferFoldToggled {
11084 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11085 folded: false,
11086 });
11087 cx.notify();
11088 }
11089
11090 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11091 self.display_map.read(cx).buffer_folded(buffer)
11092 }
11093
11094 /// Removes any folds with the given ranges.
11095 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11096 &mut self,
11097 ranges: &[Range<T>],
11098 type_id: TypeId,
11099 auto_scroll: bool,
11100 cx: &mut ViewContext<Self>,
11101 ) {
11102 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11103 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11104 });
11105 }
11106
11107 fn remove_folds_with<T: ToOffset + Clone>(
11108 &mut self,
11109 ranges: &[Range<T>],
11110 auto_scroll: bool,
11111 cx: &mut ViewContext<Self>,
11112 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11113 ) {
11114 if ranges.is_empty() {
11115 return;
11116 }
11117
11118 let mut buffers_affected = HashSet::default();
11119 let multi_buffer = self.buffer().read(cx);
11120 for range in ranges {
11121 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11122 buffers_affected.insert(buffer.read(cx).remote_id());
11123 };
11124 }
11125
11126 self.display_map.update(cx, update);
11127
11128 if auto_scroll {
11129 self.request_autoscroll(Autoscroll::fit(), cx);
11130 }
11131
11132 for buffer_id in buffers_affected {
11133 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11134 }
11135
11136 cx.notify();
11137 self.scrollbar_marker_state.dirty = true;
11138 self.active_indent_guides_state.dirty = true;
11139 }
11140
11141 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11142 self.display_map.read(cx).fold_placeholder.clone()
11143 }
11144
11145 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11146 if hovered != self.gutter_hovered {
11147 self.gutter_hovered = hovered;
11148 cx.notify();
11149 }
11150 }
11151
11152 pub fn insert_blocks(
11153 &mut self,
11154 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11155 autoscroll: Option<Autoscroll>,
11156 cx: &mut ViewContext<Self>,
11157 ) -> Vec<CustomBlockId> {
11158 let blocks = self
11159 .display_map
11160 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11161 if let Some(autoscroll) = autoscroll {
11162 self.request_autoscroll(autoscroll, cx);
11163 }
11164 cx.notify();
11165 blocks
11166 }
11167
11168 pub fn resize_blocks(
11169 &mut self,
11170 heights: HashMap<CustomBlockId, u32>,
11171 autoscroll: Option<Autoscroll>,
11172 cx: &mut ViewContext<Self>,
11173 ) {
11174 self.display_map
11175 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11176 if let Some(autoscroll) = autoscroll {
11177 self.request_autoscroll(autoscroll, cx);
11178 }
11179 cx.notify();
11180 }
11181
11182 pub fn replace_blocks(
11183 &mut self,
11184 renderers: HashMap<CustomBlockId, RenderBlock>,
11185 autoscroll: Option<Autoscroll>,
11186 cx: &mut ViewContext<Self>,
11187 ) {
11188 self.display_map
11189 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11190 if let Some(autoscroll) = autoscroll {
11191 self.request_autoscroll(autoscroll, cx);
11192 }
11193 cx.notify();
11194 }
11195
11196 pub fn remove_blocks(
11197 &mut self,
11198 block_ids: HashSet<CustomBlockId>,
11199 autoscroll: Option<Autoscroll>,
11200 cx: &mut ViewContext<Self>,
11201 ) {
11202 self.display_map.update(cx, |display_map, cx| {
11203 display_map.remove_blocks(block_ids, cx)
11204 });
11205 if let Some(autoscroll) = autoscroll {
11206 self.request_autoscroll(autoscroll, cx);
11207 }
11208 cx.notify();
11209 }
11210
11211 pub fn row_for_block(
11212 &self,
11213 block_id: CustomBlockId,
11214 cx: &mut ViewContext<Self>,
11215 ) -> Option<DisplayRow> {
11216 self.display_map
11217 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11218 }
11219
11220 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11221 self.focused_block = Some(focused_block);
11222 }
11223
11224 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11225 self.focused_block.take()
11226 }
11227
11228 pub fn insert_creases(
11229 &mut self,
11230 creases: impl IntoIterator<Item = Crease<Anchor>>,
11231 cx: &mut ViewContext<Self>,
11232 ) -> Vec<CreaseId> {
11233 self.display_map
11234 .update(cx, |map, cx| map.insert_creases(creases, cx))
11235 }
11236
11237 pub fn remove_creases(
11238 &mut self,
11239 ids: impl IntoIterator<Item = CreaseId>,
11240 cx: &mut ViewContext<Self>,
11241 ) {
11242 self.display_map
11243 .update(cx, |map, cx| map.remove_creases(ids, cx));
11244 }
11245
11246 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11247 self.display_map
11248 .update(cx, |map, cx| map.snapshot(cx))
11249 .longest_row()
11250 }
11251
11252 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11253 self.display_map
11254 .update(cx, |map, cx| map.snapshot(cx))
11255 .max_point()
11256 }
11257
11258 pub fn text(&self, cx: &AppContext) -> String {
11259 self.buffer.read(cx).read(cx).text()
11260 }
11261
11262 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11263 let text = self.text(cx);
11264 let text = text.trim();
11265
11266 if text.is_empty() {
11267 return None;
11268 }
11269
11270 Some(text.to_string())
11271 }
11272
11273 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11274 self.transact(cx, |this, cx| {
11275 this.buffer
11276 .read(cx)
11277 .as_singleton()
11278 .expect("you can only call set_text on editors for singleton buffers")
11279 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11280 });
11281 }
11282
11283 pub fn display_text(&self, cx: &mut AppContext) -> String {
11284 self.display_map
11285 .update(cx, |map, cx| map.snapshot(cx))
11286 .text()
11287 }
11288
11289 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11290 let mut wrap_guides = smallvec::smallvec![];
11291
11292 if self.show_wrap_guides == Some(false) {
11293 return wrap_guides;
11294 }
11295
11296 let settings = self.buffer.read(cx).settings_at(0, cx);
11297 if settings.show_wrap_guides {
11298 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11299 wrap_guides.push((soft_wrap as usize, true));
11300 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11301 wrap_guides.push((soft_wrap as usize, true));
11302 }
11303 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11304 }
11305
11306 wrap_guides
11307 }
11308
11309 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11310 let settings = self.buffer.read(cx).settings_at(0, cx);
11311 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11312 match mode {
11313 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11314 SoftWrap::None
11315 }
11316 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11317 language_settings::SoftWrap::PreferredLineLength => {
11318 SoftWrap::Column(settings.preferred_line_length)
11319 }
11320 language_settings::SoftWrap::Bounded => {
11321 SoftWrap::Bounded(settings.preferred_line_length)
11322 }
11323 }
11324 }
11325
11326 pub fn set_soft_wrap_mode(
11327 &mut self,
11328 mode: language_settings::SoftWrap,
11329 cx: &mut ViewContext<Self>,
11330 ) {
11331 self.soft_wrap_mode_override = Some(mode);
11332 cx.notify();
11333 }
11334
11335 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11336 self.text_style_refinement = Some(style);
11337 }
11338
11339 /// called by the Element so we know what style we were most recently rendered with.
11340 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11341 let rem_size = cx.rem_size();
11342 self.display_map.update(cx, |map, cx| {
11343 map.set_font(
11344 style.text.font(),
11345 style.text.font_size.to_pixels(rem_size),
11346 cx,
11347 )
11348 });
11349 self.style = Some(style);
11350 }
11351
11352 pub fn style(&self) -> Option<&EditorStyle> {
11353 self.style.as_ref()
11354 }
11355
11356 // Called by the element. This method is not designed to be called outside of the editor
11357 // element's layout code because it does not notify when rewrapping is computed synchronously.
11358 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11359 self.display_map
11360 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11361 }
11362
11363 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11364 if self.soft_wrap_mode_override.is_some() {
11365 self.soft_wrap_mode_override.take();
11366 } else {
11367 let soft_wrap = match self.soft_wrap_mode(cx) {
11368 SoftWrap::GitDiff => return,
11369 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11370 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11371 language_settings::SoftWrap::None
11372 }
11373 };
11374 self.soft_wrap_mode_override = Some(soft_wrap);
11375 }
11376 cx.notify();
11377 }
11378
11379 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11380 let Some(workspace) = self.workspace() else {
11381 return;
11382 };
11383 let fs = workspace.read(cx).app_state().fs.clone();
11384 let current_show = TabBarSettings::get_global(cx).show;
11385 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11386 setting.show = Some(!current_show);
11387 });
11388 }
11389
11390 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11391 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11392 self.buffer
11393 .read(cx)
11394 .settings_at(0, cx)
11395 .indent_guides
11396 .enabled
11397 });
11398 self.show_indent_guides = Some(!currently_enabled);
11399 cx.notify();
11400 }
11401
11402 fn should_show_indent_guides(&self) -> Option<bool> {
11403 self.show_indent_guides
11404 }
11405
11406 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11407 let mut editor_settings = EditorSettings::get_global(cx).clone();
11408 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11409 EditorSettings::override_global(editor_settings, cx);
11410 }
11411
11412 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11413 self.use_relative_line_numbers
11414 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11415 }
11416
11417 pub fn toggle_relative_line_numbers(
11418 &mut self,
11419 _: &ToggleRelativeLineNumbers,
11420 cx: &mut ViewContext<Self>,
11421 ) {
11422 let is_relative = self.should_use_relative_line_numbers(cx);
11423 self.set_relative_line_number(Some(!is_relative), cx)
11424 }
11425
11426 pub fn set_relative_line_number(
11427 &mut self,
11428 is_relative: Option<bool>,
11429 cx: &mut ViewContext<Self>,
11430 ) {
11431 self.use_relative_line_numbers = is_relative;
11432 cx.notify();
11433 }
11434
11435 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11436 self.show_gutter = show_gutter;
11437 cx.notify();
11438 }
11439
11440 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11441 self.show_scrollbars = show_scrollbars;
11442 cx.notify();
11443 }
11444
11445 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11446 self.show_line_numbers = Some(show_line_numbers);
11447 cx.notify();
11448 }
11449
11450 pub fn set_show_git_diff_gutter(
11451 &mut self,
11452 show_git_diff_gutter: bool,
11453 cx: &mut ViewContext<Self>,
11454 ) {
11455 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11456 cx.notify();
11457 }
11458
11459 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11460 self.show_code_actions = Some(show_code_actions);
11461 cx.notify();
11462 }
11463
11464 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11465 self.show_runnables = Some(show_runnables);
11466 cx.notify();
11467 }
11468
11469 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11470 if self.display_map.read(cx).masked != masked {
11471 self.display_map.update(cx, |map, _| map.masked = masked);
11472 }
11473 cx.notify()
11474 }
11475
11476 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11477 self.show_wrap_guides = Some(show_wrap_guides);
11478 cx.notify();
11479 }
11480
11481 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11482 self.show_indent_guides = Some(show_indent_guides);
11483 cx.notify();
11484 }
11485
11486 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11487 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11488 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11489 if let Some(dir) = file.abs_path(cx).parent() {
11490 return Some(dir.to_owned());
11491 }
11492 }
11493
11494 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11495 return Some(project_path.path.to_path_buf());
11496 }
11497 }
11498
11499 None
11500 }
11501
11502 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11503 self.active_excerpt(cx)?
11504 .1
11505 .read(cx)
11506 .file()
11507 .and_then(|f| f.as_local())
11508 }
11509
11510 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11511 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11512 let project_path = buffer.read(cx).project_path(cx)?;
11513 let project = self.project.as_ref()?.read(cx);
11514 project.absolute_path(&project_path, cx)
11515 })
11516 }
11517
11518 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11519 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11520 let project_path = buffer.read(cx).project_path(cx)?;
11521 let project = self.project.as_ref()?.read(cx);
11522 let entry = project.entry_for_path(&project_path, cx)?;
11523 let path = entry.path.to_path_buf();
11524 Some(path)
11525 })
11526 }
11527
11528 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11529 if let Some(target) = self.target_file(cx) {
11530 cx.reveal_path(&target.abs_path(cx));
11531 }
11532 }
11533
11534 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11535 if let Some(path) = self.target_file_abs_path(cx) {
11536 if let Some(path) = path.to_str() {
11537 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11538 }
11539 }
11540 }
11541
11542 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11543 if let Some(path) = self.target_file_path(cx) {
11544 if let Some(path) = path.to_str() {
11545 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11546 }
11547 }
11548 }
11549
11550 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11551 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11552
11553 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11554 self.start_git_blame(true, cx);
11555 }
11556
11557 cx.notify();
11558 }
11559
11560 pub fn toggle_git_blame_inline(
11561 &mut self,
11562 _: &ToggleGitBlameInline,
11563 cx: &mut ViewContext<Self>,
11564 ) {
11565 self.toggle_git_blame_inline_internal(true, cx);
11566 cx.notify();
11567 }
11568
11569 pub fn git_blame_inline_enabled(&self) -> bool {
11570 self.git_blame_inline_enabled
11571 }
11572
11573 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11574 self.show_selection_menu = self
11575 .show_selection_menu
11576 .map(|show_selections_menu| !show_selections_menu)
11577 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11578
11579 cx.notify();
11580 }
11581
11582 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11583 self.show_selection_menu
11584 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11585 }
11586
11587 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11588 if let Some(project) = self.project.as_ref() {
11589 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11590 return;
11591 };
11592
11593 if buffer.read(cx).file().is_none() {
11594 return;
11595 }
11596
11597 let focused = self.focus_handle(cx).contains_focused(cx);
11598
11599 let project = project.clone();
11600 let blame =
11601 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11602 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11603 self.blame = Some(blame);
11604 }
11605 }
11606
11607 fn toggle_git_blame_inline_internal(
11608 &mut self,
11609 user_triggered: bool,
11610 cx: &mut ViewContext<Self>,
11611 ) {
11612 if self.git_blame_inline_enabled {
11613 self.git_blame_inline_enabled = false;
11614 self.show_git_blame_inline = false;
11615 self.show_git_blame_inline_delay_task.take();
11616 } else {
11617 self.git_blame_inline_enabled = true;
11618 self.start_git_blame_inline(user_triggered, cx);
11619 }
11620
11621 cx.notify();
11622 }
11623
11624 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11625 self.start_git_blame(user_triggered, cx);
11626
11627 if ProjectSettings::get_global(cx)
11628 .git
11629 .inline_blame_delay()
11630 .is_some()
11631 {
11632 self.start_inline_blame_timer(cx);
11633 } else {
11634 self.show_git_blame_inline = true
11635 }
11636 }
11637
11638 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11639 self.blame.as_ref()
11640 }
11641
11642 pub fn show_git_blame_gutter(&self) -> bool {
11643 self.show_git_blame_gutter
11644 }
11645
11646 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11647 self.show_git_blame_gutter && self.has_blame_entries(cx)
11648 }
11649
11650 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11651 self.show_git_blame_inline
11652 && self.focus_handle.is_focused(cx)
11653 && !self.newest_selection_head_on_empty_line(cx)
11654 && self.has_blame_entries(cx)
11655 }
11656
11657 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11658 self.blame()
11659 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11660 }
11661
11662 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11663 let cursor_anchor = self.selections.newest_anchor().head();
11664
11665 let snapshot = self.buffer.read(cx).snapshot(cx);
11666 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11667
11668 snapshot.line_len(buffer_row) == 0
11669 }
11670
11671 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11672 let buffer_and_selection = maybe!({
11673 let selection = self.selections.newest::<Point>(cx);
11674 let selection_range = selection.range();
11675
11676 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11677 (buffer, selection_range.start.row..selection_range.end.row)
11678 } else {
11679 let multi_buffer = self.buffer().read(cx);
11680 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11681 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11682
11683 let (excerpt, range) = if selection.reversed {
11684 buffer_ranges.first()
11685 } else {
11686 buffer_ranges.last()
11687 }?;
11688
11689 let snapshot = excerpt.buffer();
11690 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11691 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11692 (
11693 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11694 selection,
11695 )
11696 };
11697
11698 Some((buffer, selection))
11699 });
11700
11701 let Some((buffer, selection)) = buffer_and_selection else {
11702 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11703 };
11704
11705 let Some(project) = self.project.as_ref() else {
11706 return Task::ready(Err(anyhow!("editor does not have project")));
11707 };
11708
11709 project.update(cx, |project, cx| {
11710 project.get_permalink_to_line(&buffer, selection, cx)
11711 })
11712 }
11713
11714 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11715 let permalink_task = self.get_permalink_to_line(cx);
11716 let workspace = self.workspace();
11717
11718 cx.spawn(|_, mut cx| async move {
11719 match permalink_task.await {
11720 Ok(permalink) => {
11721 cx.update(|cx| {
11722 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11723 })
11724 .ok();
11725 }
11726 Err(err) => {
11727 let message = format!("Failed to copy permalink: {err}");
11728
11729 Err::<(), anyhow::Error>(err).log_err();
11730
11731 if let Some(workspace) = workspace {
11732 workspace
11733 .update(&mut cx, |workspace, cx| {
11734 struct CopyPermalinkToLine;
11735
11736 workspace.show_toast(
11737 Toast::new(
11738 NotificationId::unique::<CopyPermalinkToLine>(),
11739 message,
11740 ),
11741 cx,
11742 )
11743 })
11744 .ok();
11745 }
11746 }
11747 }
11748 })
11749 .detach();
11750 }
11751
11752 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11753 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11754 if let Some(file) = self.target_file(cx) {
11755 if let Some(path) = file.path().to_str() {
11756 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11757 }
11758 }
11759 }
11760
11761 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11762 let permalink_task = self.get_permalink_to_line(cx);
11763 let workspace = self.workspace();
11764
11765 cx.spawn(|_, mut cx| async move {
11766 match permalink_task.await {
11767 Ok(permalink) => {
11768 cx.update(|cx| {
11769 cx.open_url(permalink.as_ref());
11770 })
11771 .ok();
11772 }
11773 Err(err) => {
11774 let message = format!("Failed to open permalink: {err}");
11775
11776 Err::<(), anyhow::Error>(err).log_err();
11777
11778 if let Some(workspace) = workspace {
11779 workspace
11780 .update(&mut cx, |workspace, cx| {
11781 struct OpenPermalinkToLine;
11782
11783 workspace.show_toast(
11784 Toast::new(
11785 NotificationId::unique::<OpenPermalinkToLine>(),
11786 message,
11787 ),
11788 cx,
11789 )
11790 })
11791 .ok();
11792 }
11793 }
11794 }
11795 })
11796 .detach();
11797 }
11798
11799 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11800 self.insert_uuid(UuidVersion::V4, cx);
11801 }
11802
11803 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11804 self.insert_uuid(UuidVersion::V7, cx);
11805 }
11806
11807 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11808 self.transact(cx, |this, cx| {
11809 let edits = this
11810 .selections
11811 .all::<Point>(cx)
11812 .into_iter()
11813 .map(|selection| {
11814 let uuid = match version {
11815 UuidVersion::V4 => uuid::Uuid::new_v4(),
11816 UuidVersion::V7 => uuid::Uuid::now_v7(),
11817 };
11818
11819 (selection.range(), uuid.to_string())
11820 });
11821 this.edit(edits, cx);
11822 this.refresh_inline_completion(true, false, cx);
11823 });
11824 }
11825
11826 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11827 /// last highlight added will be used.
11828 ///
11829 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11830 pub fn highlight_rows<T: 'static>(
11831 &mut self,
11832 range: Range<Anchor>,
11833 color: Hsla,
11834 should_autoscroll: bool,
11835 cx: &mut ViewContext<Self>,
11836 ) {
11837 let snapshot = self.buffer().read(cx).snapshot(cx);
11838 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11839 let ix = row_highlights.binary_search_by(|highlight| {
11840 Ordering::Equal
11841 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11842 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11843 });
11844
11845 if let Err(mut ix) = ix {
11846 let index = post_inc(&mut self.highlight_order);
11847
11848 // If this range intersects with the preceding highlight, then merge it with
11849 // the preceding highlight. Otherwise insert a new highlight.
11850 let mut merged = false;
11851 if ix > 0 {
11852 let prev_highlight = &mut row_highlights[ix - 1];
11853 if prev_highlight
11854 .range
11855 .end
11856 .cmp(&range.start, &snapshot)
11857 .is_ge()
11858 {
11859 ix -= 1;
11860 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11861 prev_highlight.range.end = range.end;
11862 }
11863 merged = true;
11864 prev_highlight.index = index;
11865 prev_highlight.color = color;
11866 prev_highlight.should_autoscroll = should_autoscroll;
11867 }
11868 }
11869
11870 if !merged {
11871 row_highlights.insert(
11872 ix,
11873 RowHighlight {
11874 range: range.clone(),
11875 index,
11876 color,
11877 should_autoscroll,
11878 },
11879 );
11880 }
11881
11882 // If any of the following highlights intersect with this one, merge them.
11883 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11884 let highlight = &row_highlights[ix];
11885 if next_highlight
11886 .range
11887 .start
11888 .cmp(&highlight.range.end, &snapshot)
11889 .is_le()
11890 {
11891 if next_highlight
11892 .range
11893 .end
11894 .cmp(&highlight.range.end, &snapshot)
11895 .is_gt()
11896 {
11897 row_highlights[ix].range.end = next_highlight.range.end;
11898 }
11899 row_highlights.remove(ix + 1);
11900 } else {
11901 break;
11902 }
11903 }
11904 }
11905 }
11906
11907 /// Remove any highlighted row ranges of the given type that intersect the
11908 /// given ranges.
11909 pub fn remove_highlighted_rows<T: 'static>(
11910 &mut self,
11911 ranges_to_remove: Vec<Range<Anchor>>,
11912 cx: &mut ViewContext<Self>,
11913 ) {
11914 let snapshot = self.buffer().read(cx).snapshot(cx);
11915 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11916 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11917 row_highlights.retain(|highlight| {
11918 while let Some(range_to_remove) = ranges_to_remove.peek() {
11919 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11920 Ordering::Less | Ordering::Equal => {
11921 ranges_to_remove.next();
11922 }
11923 Ordering::Greater => {
11924 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11925 Ordering::Less | Ordering::Equal => {
11926 return false;
11927 }
11928 Ordering::Greater => break,
11929 }
11930 }
11931 }
11932 }
11933
11934 true
11935 })
11936 }
11937
11938 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11939 pub fn clear_row_highlights<T: 'static>(&mut self) {
11940 self.highlighted_rows.remove(&TypeId::of::<T>());
11941 }
11942
11943 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11944 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11945 self.highlighted_rows
11946 .get(&TypeId::of::<T>())
11947 .map_or(&[] as &[_], |vec| vec.as_slice())
11948 .iter()
11949 .map(|highlight| (highlight.range.clone(), highlight.color))
11950 }
11951
11952 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11953 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11954 /// Allows to ignore certain kinds of highlights.
11955 pub fn highlighted_display_rows(
11956 &mut self,
11957 cx: &mut WindowContext,
11958 ) -> BTreeMap<DisplayRow, Hsla> {
11959 let snapshot = self.snapshot(cx);
11960 let mut used_highlight_orders = HashMap::default();
11961 self.highlighted_rows
11962 .iter()
11963 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11964 .fold(
11965 BTreeMap::<DisplayRow, Hsla>::new(),
11966 |mut unique_rows, highlight| {
11967 let start = highlight.range.start.to_display_point(&snapshot);
11968 let end = highlight.range.end.to_display_point(&snapshot);
11969 let start_row = start.row().0;
11970 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11971 && end.column() == 0
11972 {
11973 end.row().0.saturating_sub(1)
11974 } else {
11975 end.row().0
11976 };
11977 for row in start_row..=end_row {
11978 let used_index =
11979 used_highlight_orders.entry(row).or_insert(highlight.index);
11980 if highlight.index >= *used_index {
11981 *used_index = highlight.index;
11982 unique_rows.insert(DisplayRow(row), highlight.color);
11983 }
11984 }
11985 unique_rows
11986 },
11987 )
11988 }
11989
11990 pub fn highlighted_display_row_for_autoscroll(
11991 &self,
11992 snapshot: &DisplaySnapshot,
11993 ) -> Option<DisplayRow> {
11994 self.highlighted_rows
11995 .values()
11996 .flat_map(|highlighted_rows| highlighted_rows.iter())
11997 .filter_map(|highlight| {
11998 if highlight.should_autoscroll {
11999 Some(highlight.range.start.to_display_point(snapshot).row())
12000 } else {
12001 None
12002 }
12003 })
12004 .min()
12005 }
12006
12007 pub fn set_search_within_ranges(
12008 &mut self,
12009 ranges: &[Range<Anchor>],
12010 cx: &mut ViewContext<Self>,
12011 ) {
12012 self.highlight_background::<SearchWithinRange>(
12013 ranges,
12014 |colors| colors.editor_document_highlight_read_background,
12015 cx,
12016 )
12017 }
12018
12019 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12020 self.breadcrumb_header = Some(new_header);
12021 }
12022
12023 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12024 self.clear_background_highlights::<SearchWithinRange>(cx);
12025 }
12026
12027 pub fn highlight_background<T: 'static>(
12028 &mut self,
12029 ranges: &[Range<Anchor>],
12030 color_fetcher: fn(&ThemeColors) -> Hsla,
12031 cx: &mut ViewContext<Self>,
12032 ) {
12033 self.background_highlights
12034 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12035 self.scrollbar_marker_state.dirty = true;
12036 cx.notify();
12037 }
12038
12039 pub fn clear_background_highlights<T: 'static>(
12040 &mut self,
12041 cx: &mut ViewContext<Self>,
12042 ) -> Option<BackgroundHighlight> {
12043 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12044 if !text_highlights.1.is_empty() {
12045 self.scrollbar_marker_state.dirty = true;
12046 cx.notify();
12047 }
12048 Some(text_highlights)
12049 }
12050
12051 pub fn highlight_gutter<T: 'static>(
12052 &mut self,
12053 ranges: &[Range<Anchor>],
12054 color_fetcher: fn(&AppContext) -> Hsla,
12055 cx: &mut ViewContext<Self>,
12056 ) {
12057 self.gutter_highlights
12058 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12059 cx.notify();
12060 }
12061
12062 pub fn clear_gutter_highlights<T: 'static>(
12063 &mut self,
12064 cx: &mut ViewContext<Self>,
12065 ) -> Option<GutterHighlight> {
12066 cx.notify();
12067 self.gutter_highlights.remove(&TypeId::of::<T>())
12068 }
12069
12070 #[cfg(feature = "test-support")]
12071 pub fn all_text_background_highlights(
12072 &mut self,
12073 cx: &mut ViewContext<Self>,
12074 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12075 let snapshot = self.snapshot(cx);
12076 let buffer = &snapshot.buffer_snapshot;
12077 let start = buffer.anchor_before(0);
12078 let end = buffer.anchor_after(buffer.len());
12079 let theme = cx.theme().colors();
12080 self.background_highlights_in_range(start..end, &snapshot, theme)
12081 }
12082
12083 #[cfg(feature = "test-support")]
12084 pub fn search_background_highlights(
12085 &mut self,
12086 cx: &mut ViewContext<Self>,
12087 ) -> Vec<Range<Point>> {
12088 let snapshot = self.buffer().read(cx).snapshot(cx);
12089
12090 let highlights = self
12091 .background_highlights
12092 .get(&TypeId::of::<items::BufferSearchHighlights>());
12093
12094 if let Some((_color, ranges)) = highlights {
12095 ranges
12096 .iter()
12097 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12098 .collect_vec()
12099 } else {
12100 vec![]
12101 }
12102 }
12103
12104 fn document_highlights_for_position<'a>(
12105 &'a self,
12106 position: Anchor,
12107 buffer: &'a MultiBufferSnapshot,
12108 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12109 let read_highlights = self
12110 .background_highlights
12111 .get(&TypeId::of::<DocumentHighlightRead>())
12112 .map(|h| &h.1);
12113 let write_highlights = self
12114 .background_highlights
12115 .get(&TypeId::of::<DocumentHighlightWrite>())
12116 .map(|h| &h.1);
12117 let left_position = position.bias_left(buffer);
12118 let right_position = position.bias_right(buffer);
12119 read_highlights
12120 .into_iter()
12121 .chain(write_highlights)
12122 .flat_map(move |ranges| {
12123 let start_ix = match ranges.binary_search_by(|probe| {
12124 let cmp = probe.end.cmp(&left_position, buffer);
12125 if cmp.is_ge() {
12126 Ordering::Greater
12127 } else {
12128 Ordering::Less
12129 }
12130 }) {
12131 Ok(i) | Err(i) => i,
12132 };
12133
12134 ranges[start_ix..]
12135 .iter()
12136 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12137 })
12138 }
12139
12140 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12141 self.background_highlights
12142 .get(&TypeId::of::<T>())
12143 .map_or(false, |(_, highlights)| !highlights.is_empty())
12144 }
12145
12146 pub fn background_highlights_in_range(
12147 &self,
12148 search_range: Range<Anchor>,
12149 display_snapshot: &DisplaySnapshot,
12150 theme: &ThemeColors,
12151 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12152 let mut results = Vec::new();
12153 for (color_fetcher, ranges) in self.background_highlights.values() {
12154 let color = color_fetcher(theme);
12155 let start_ix = match ranges.binary_search_by(|probe| {
12156 let cmp = probe
12157 .end
12158 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12159 if cmp.is_gt() {
12160 Ordering::Greater
12161 } else {
12162 Ordering::Less
12163 }
12164 }) {
12165 Ok(i) | Err(i) => i,
12166 };
12167 for range in &ranges[start_ix..] {
12168 if range
12169 .start
12170 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12171 .is_ge()
12172 {
12173 break;
12174 }
12175
12176 let start = range.start.to_display_point(display_snapshot);
12177 let end = range.end.to_display_point(display_snapshot);
12178 results.push((start..end, color))
12179 }
12180 }
12181 results
12182 }
12183
12184 pub fn background_highlight_row_ranges<T: 'static>(
12185 &self,
12186 search_range: Range<Anchor>,
12187 display_snapshot: &DisplaySnapshot,
12188 count: usize,
12189 ) -> Vec<RangeInclusive<DisplayPoint>> {
12190 let mut results = Vec::new();
12191 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12192 return vec![];
12193 };
12194
12195 let start_ix = match ranges.binary_search_by(|probe| {
12196 let cmp = probe
12197 .end
12198 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12199 if cmp.is_gt() {
12200 Ordering::Greater
12201 } else {
12202 Ordering::Less
12203 }
12204 }) {
12205 Ok(i) | Err(i) => i,
12206 };
12207 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12208 if let (Some(start_display), Some(end_display)) = (start, end) {
12209 results.push(
12210 start_display.to_display_point(display_snapshot)
12211 ..=end_display.to_display_point(display_snapshot),
12212 );
12213 }
12214 };
12215 let mut start_row: Option<Point> = None;
12216 let mut end_row: Option<Point> = None;
12217 if ranges.len() > count {
12218 return Vec::new();
12219 }
12220 for range in &ranges[start_ix..] {
12221 if range
12222 .start
12223 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12224 .is_ge()
12225 {
12226 break;
12227 }
12228 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12229 if let Some(current_row) = &end_row {
12230 if end.row == current_row.row {
12231 continue;
12232 }
12233 }
12234 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12235 if start_row.is_none() {
12236 assert_eq!(end_row, None);
12237 start_row = Some(start);
12238 end_row = Some(end);
12239 continue;
12240 }
12241 if let Some(current_end) = end_row.as_mut() {
12242 if start.row > current_end.row + 1 {
12243 push_region(start_row, end_row);
12244 start_row = Some(start);
12245 end_row = Some(end);
12246 } else {
12247 // Merge two hunks.
12248 *current_end = end;
12249 }
12250 } else {
12251 unreachable!();
12252 }
12253 }
12254 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12255 push_region(start_row, end_row);
12256 results
12257 }
12258
12259 pub fn gutter_highlights_in_range(
12260 &self,
12261 search_range: Range<Anchor>,
12262 display_snapshot: &DisplaySnapshot,
12263 cx: &AppContext,
12264 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12265 let mut results = Vec::new();
12266 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12267 let color = color_fetcher(cx);
12268 let start_ix = match ranges.binary_search_by(|probe| {
12269 let cmp = probe
12270 .end
12271 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12272 if cmp.is_gt() {
12273 Ordering::Greater
12274 } else {
12275 Ordering::Less
12276 }
12277 }) {
12278 Ok(i) | Err(i) => i,
12279 };
12280 for range in &ranges[start_ix..] {
12281 if range
12282 .start
12283 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12284 .is_ge()
12285 {
12286 break;
12287 }
12288
12289 let start = range.start.to_display_point(display_snapshot);
12290 let end = range.end.to_display_point(display_snapshot);
12291 results.push((start..end, color))
12292 }
12293 }
12294 results
12295 }
12296
12297 /// Get the text ranges corresponding to the redaction query
12298 pub fn redacted_ranges(
12299 &self,
12300 search_range: Range<Anchor>,
12301 display_snapshot: &DisplaySnapshot,
12302 cx: &WindowContext,
12303 ) -> Vec<Range<DisplayPoint>> {
12304 display_snapshot
12305 .buffer_snapshot
12306 .redacted_ranges(search_range, |file| {
12307 if let Some(file) = file {
12308 file.is_private()
12309 && EditorSettings::get(
12310 Some(SettingsLocation {
12311 worktree_id: file.worktree_id(cx),
12312 path: file.path().as_ref(),
12313 }),
12314 cx,
12315 )
12316 .redact_private_values
12317 } else {
12318 false
12319 }
12320 })
12321 .map(|range| {
12322 range.start.to_display_point(display_snapshot)
12323 ..range.end.to_display_point(display_snapshot)
12324 })
12325 .collect()
12326 }
12327
12328 pub fn highlight_text<T: 'static>(
12329 &mut self,
12330 ranges: Vec<Range<Anchor>>,
12331 style: HighlightStyle,
12332 cx: &mut ViewContext<Self>,
12333 ) {
12334 self.display_map.update(cx, |map, _| {
12335 map.highlight_text(TypeId::of::<T>(), ranges, style)
12336 });
12337 cx.notify();
12338 }
12339
12340 pub(crate) fn highlight_inlays<T: 'static>(
12341 &mut self,
12342 highlights: Vec<InlayHighlight>,
12343 style: HighlightStyle,
12344 cx: &mut ViewContext<Self>,
12345 ) {
12346 self.display_map.update(cx, |map, _| {
12347 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12348 });
12349 cx.notify();
12350 }
12351
12352 pub fn text_highlights<'a, T: 'static>(
12353 &'a self,
12354 cx: &'a AppContext,
12355 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12356 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12357 }
12358
12359 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12360 let cleared = self
12361 .display_map
12362 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12363 if cleared {
12364 cx.notify();
12365 }
12366 }
12367
12368 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12369 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12370 && self.focus_handle.is_focused(cx)
12371 }
12372
12373 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12374 self.show_cursor_when_unfocused = is_enabled;
12375 cx.notify();
12376 }
12377
12378 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12379 self.project
12380 .as_ref()
12381 .map(|project| project.read(cx).lsp_store())
12382 }
12383
12384 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12385 cx.notify();
12386 }
12387
12388 fn on_buffer_event(
12389 &mut self,
12390 multibuffer: Model<MultiBuffer>,
12391 event: &multi_buffer::Event,
12392 cx: &mut ViewContext<Self>,
12393 ) {
12394 match event {
12395 multi_buffer::Event::Edited {
12396 singleton_buffer_edited,
12397 edited_buffer: buffer_edited,
12398 } => {
12399 self.scrollbar_marker_state.dirty = true;
12400 self.active_indent_guides_state.dirty = true;
12401 self.refresh_active_diagnostics(cx);
12402 self.refresh_code_actions(cx);
12403 if self.has_active_inline_completion() {
12404 self.update_visible_inline_completion(cx);
12405 }
12406 if let Some(buffer) = buffer_edited {
12407 let buffer_id = buffer.read(cx).remote_id();
12408 if !self.registered_buffers.contains_key(&buffer_id) {
12409 if let Some(lsp_store) = self.lsp_store(cx) {
12410 lsp_store.update(cx, |lsp_store, cx| {
12411 self.registered_buffers.insert(
12412 buffer_id,
12413 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12414 );
12415 })
12416 }
12417 }
12418 }
12419 cx.emit(EditorEvent::BufferEdited);
12420 cx.emit(SearchEvent::MatchesInvalidated);
12421 if *singleton_buffer_edited {
12422 if let Some(project) = &self.project {
12423 let project = project.read(cx);
12424 #[allow(clippy::mutable_key_type)]
12425 let languages_affected = multibuffer
12426 .read(cx)
12427 .all_buffers()
12428 .into_iter()
12429 .filter_map(|buffer| {
12430 let buffer = buffer.read(cx);
12431 let language = buffer.language()?;
12432 if project.is_local()
12433 && project
12434 .language_servers_for_local_buffer(buffer, cx)
12435 .count()
12436 == 0
12437 {
12438 None
12439 } else {
12440 Some(language)
12441 }
12442 })
12443 .cloned()
12444 .collect::<HashSet<_>>();
12445 if !languages_affected.is_empty() {
12446 self.refresh_inlay_hints(
12447 InlayHintRefreshReason::BufferEdited(languages_affected),
12448 cx,
12449 );
12450 }
12451 }
12452 }
12453
12454 let Some(project) = &self.project else { return };
12455 let (telemetry, is_via_ssh) = {
12456 let project = project.read(cx);
12457 let telemetry = project.client().telemetry().clone();
12458 let is_via_ssh = project.is_via_ssh();
12459 (telemetry, is_via_ssh)
12460 };
12461 refresh_linked_ranges(self, cx);
12462 telemetry.log_edit_event("editor", is_via_ssh);
12463 }
12464 multi_buffer::Event::ExcerptsAdded {
12465 buffer,
12466 predecessor,
12467 excerpts,
12468 } => {
12469 self.tasks_update_task = Some(self.refresh_runnables(cx));
12470 let buffer_id = buffer.read(cx).remote_id();
12471 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12472 if let Some(project) = &self.project {
12473 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12474 }
12475 }
12476 cx.emit(EditorEvent::ExcerptsAdded {
12477 buffer: buffer.clone(),
12478 predecessor: *predecessor,
12479 excerpts: excerpts.clone(),
12480 });
12481 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12482 }
12483 multi_buffer::Event::ExcerptsRemoved { ids } => {
12484 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12485 let buffer = self.buffer.read(cx);
12486 self.registered_buffers
12487 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12488 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12489 }
12490 multi_buffer::Event::ExcerptsEdited { ids } => {
12491 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12492 }
12493 multi_buffer::Event::ExcerptsExpanded { ids } => {
12494 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12495 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12496 }
12497 multi_buffer::Event::Reparsed(buffer_id) => {
12498 self.tasks_update_task = Some(self.refresh_runnables(cx));
12499
12500 cx.emit(EditorEvent::Reparsed(*buffer_id));
12501 }
12502 multi_buffer::Event::LanguageChanged(buffer_id) => {
12503 linked_editing_ranges::refresh_linked_ranges(self, cx);
12504 cx.emit(EditorEvent::Reparsed(*buffer_id));
12505 cx.notify();
12506 }
12507 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12508 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12509 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12510 cx.emit(EditorEvent::TitleChanged)
12511 }
12512 // multi_buffer::Event::DiffBaseChanged => {
12513 // self.scrollbar_marker_state.dirty = true;
12514 // cx.emit(EditorEvent::DiffBaseChanged);
12515 // cx.notify();
12516 // }
12517 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12518 multi_buffer::Event::DiagnosticsUpdated => {
12519 self.refresh_active_diagnostics(cx);
12520 self.scrollbar_marker_state.dirty = true;
12521 cx.notify();
12522 }
12523 _ => {}
12524 };
12525 }
12526
12527 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12528 cx.notify();
12529 }
12530
12531 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12532 self.tasks_update_task = Some(self.refresh_runnables(cx));
12533 self.refresh_inline_completion(true, false, cx);
12534 self.refresh_inlay_hints(
12535 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12536 self.selections.newest_anchor().head(),
12537 &self.buffer.read(cx).snapshot(cx),
12538 cx,
12539 )),
12540 cx,
12541 );
12542
12543 let old_cursor_shape = self.cursor_shape;
12544
12545 {
12546 let editor_settings = EditorSettings::get_global(cx);
12547 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12548 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12549 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12550 }
12551
12552 if old_cursor_shape != self.cursor_shape {
12553 cx.emit(EditorEvent::CursorShapeChanged);
12554 }
12555
12556 let project_settings = ProjectSettings::get_global(cx);
12557 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12558
12559 if self.mode == EditorMode::Full {
12560 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12561 if self.git_blame_inline_enabled != inline_blame_enabled {
12562 self.toggle_git_blame_inline_internal(false, cx);
12563 }
12564 }
12565
12566 cx.notify();
12567 }
12568
12569 pub fn set_searchable(&mut self, searchable: bool) {
12570 self.searchable = searchable;
12571 }
12572
12573 pub fn searchable(&self) -> bool {
12574 self.searchable
12575 }
12576
12577 fn open_proposed_changes_editor(
12578 &mut self,
12579 _: &OpenProposedChangesEditor,
12580 cx: &mut ViewContext<Self>,
12581 ) {
12582 let Some(workspace) = self.workspace() else {
12583 cx.propagate();
12584 return;
12585 };
12586
12587 let selections = self.selections.all::<usize>(cx);
12588 let multi_buffer = self.buffer.read(cx);
12589 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12590 let mut new_selections_by_buffer = HashMap::default();
12591 for selection in selections {
12592 for (excerpt, range) in
12593 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12594 {
12595 let mut range = range.to_point(excerpt.buffer());
12596 range.start.column = 0;
12597 range.end.column = excerpt.buffer().line_len(range.end.row);
12598 new_selections_by_buffer
12599 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12600 .or_insert(Vec::new())
12601 .push(range)
12602 }
12603 }
12604
12605 let proposed_changes_buffers = new_selections_by_buffer
12606 .into_iter()
12607 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12608 .collect::<Vec<_>>();
12609 let proposed_changes_editor = cx.new_view(|cx| {
12610 ProposedChangesEditor::new(
12611 "Proposed changes",
12612 proposed_changes_buffers,
12613 self.project.clone(),
12614 cx,
12615 )
12616 });
12617
12618 cx.window_context().defer(move |cx| {
12619 workspace.update(cx, |workspace, cx| {
12620 workspace.active_pane().update(cx, |pane, cx| {
12621 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12622 });
12623 });
12624 });
12625 }
12626
12627 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12628 self.open_excerpts_common(None, true, cx)
12629 }
12630
12631 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12632 self.open_excerpts_common(None, false, cx)
12633 }
12634
12635 fn open_excerpts_common(
12636 &mut self,
12637 jump_data: Option<JumpData>,
12638 split: bool,
12639 cx: &mut ViewContext<Self>,
12640 ) {
12641 let Some(workspace) = self.workspace() else {
12642 cx.propagate();
12643 return;
12644 };
12645
12646 if self.buffer.read(cx).is_singleton() {
12647 cx.propagate();
12648 return;
12649 }
12650
12651 let mut new_selections_by_buffer = HashMap::default();
12652 match &jump_data {
12653 Some(JumpData::MultiBufferPoint {
12654 excerpt_id,
12655 position,
12656 anchor,
12657 line_offset_from_top,
12658 }) => {
12659 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12660 if let Some(buffer) = multi_buffer_snapshot
12661 .buffer_id_for_excerpt(*excerpt_id)
12662 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12663 {
12664 let buffer_snapshot = buffer.read(cx).snapshot();
12665 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12666 language::ToPoint::to_point(anchor, &buffer_snapshot)
12667 } else {
12668 buffer_snapshot.clip_point(*position, Bias::Left)
12669 };
12670 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12671 new_selections_by_buffer.insert(
12672 buffer,
12673 (
12674 vec![jump_to_offset..jump_to_offset],
12675 Some(*line_offset_from_top),
12676 ),
12677 );
12678 }
12679 }
12680 Some(JumpData::MultiBufferRow {
12681 row,
12682 line_offset_from_top,
12683 }) => {
12684 let point = MultiBufferPoint::new(row.0, 0);
12685 if let Some((buffer, buffer_point, _)) =
12686 self.buffer.read(cx).point_to_buffer_point(point, cx)
12687 {
12688 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12689 new_selections_by_buffer
12690 .entry(buffer)
12691 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12692 .0
12693 .push(buffer_offset..buffer_offset)
12694 }
12695 }
12696 None => {
12697 let selections = self.selections.all::<usize>(cx);
12698 let multi_buffer = self.buffer.read(cx);
12699 for selection in selections {
12700 for (excerpt, mut range) in multi_buffer
12701 .snapshot(cx)
12702 .range_to_buffer_ranges(selection.range())
12703 {
12704 // When editing branch buffers, jump to the corresponding location
12705 // in their base buffer.
12706 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12707 let buffer = buffer_handle.read(cx);
12708 if let Some(base_buffer) = buffer.base_buffer() {
12709 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12710 buffer_handle = base_buffer;
12711 }
12712
12713 if selection.reversed {
12714 mem::swap(&mut range.start, &mut range.end);
12715 }
12716 new_selections_by_buffer
12717 .entry(buffer_handle)
12718 .or_insert((Vec::new(), None))
12719 .0
12720 .push(range)
12721 }
12722 }
12723 }
12724 }
12725
12726 if new_selections_by_buffer.is_empty() {
12727 return;
12728 }
12729
12730 // We defer the pane interaction because we ourselves are a workspace item
12731 // and activating a new item causes the pane to call a method on us reentrantly,
12732 // which panics if we're on the stack.
12733 cx.window_context().defer(move |cx| {
12734 workspace.update(cx, |workspace, cx| {
12735 let pane = if split {
12736 workspace.adjacent_pane(cx)
12737 } else {
12738 workspace.active_pane().clone()
12739 };
12740
12741 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12742 let editor = buffer
12743 .read(cx)
12744 .file()
12745 .is_none()
12746 .then(|| {
12747 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12748 // so `workspace.open_project_item` will never find them, always opening a new editor.
12749 // Instead, we try to activate the existing editor in the pane first.
12750 let (editor, pane_item_index) =
12751 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12752 let editor = item.downcast::<Editor>()?;
12753 let singleton_buffer =
12754 editor.read(cx).buffer().read(cx).as_singleton()?;
12755 if singleton_buffer == buffer {
12756 Some((editor, i))
12757 } else {
12758 None
12759 }
12760 })?;
12761 pane.update(cx, |pane, cx| {
12762 pane.activate_item(pane_item_index, true, true, cx)
12763 });
12764 Some(editor)
12765 })
12766 .flatten()
12767 .unwrap_or_else(|| {
12768 workspace.open_project_item::<Self>(
12769 pane.clone(),
12770 buffer,
12771 true,
12772 true,
12773 cx,
12774 )
12775 });
12776
12777 editor.update(cx, |editor, cx| {
12778 let autoscroll = match scroll_offset {
12779 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12780 None => Autoscroll::newest(),
12781 };
12782 let nav_history = editor.nav_history.take();
12783 editor.change_selections(Some(autoscroll), cx, |s| {
12784 s.select_ranges(ranges);
12785 });
12786 editor.nav_history = nav_history;
12787 });
12788 }
12789 })
12790 });
12791 }
12792
12793 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12794 let snapshot = self.buffer.read(cx).read(cx);
12795 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12796 Some(
12797 ranges
12798 .iter()
12799 .map(move |range| {
12800 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12801 })
12802 .collect(),
12803 )
12804 }
12805
12806 fn selection_replacement_ranges(
12807 &self,
12808 range: Range<OffsetUtf16>,
12809 cx: &mut AppContext,
12810 ) -> Vec<Range<OffsetUtf16>> {
12811 let selections = self.selections.all::<OffsetUtf16>(cx);
12812 let newest_selection = selections
12813 .iter()
12814 .max_by_key(|selection| selection.id)
12815 .unwrap();
12816 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12817 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12818 let snapshot = self.buffer.read(cx).read(cx);
12819 selections
12820 .into_iter()
12821 .map(|mut selection| {
12822 selection.start.0 =
12823 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12824 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12825 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12826 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12827 })
12828 .collect()
12829 }
12830
12831 fn report_editor_event(
12832 &self,
12833 event_type: &'static str,
12834 file_extension: Option<String>,
12835 cx: &AppContext,
12836 ) {
12837 if cfg!(any(test, feature = "test-support")) {
12838 return;
12839 }
12840
12841 let Some(project) = &self.project else { return };
12842
12843 // If None, we are in a file without an extension
12844 let file = self
12845 .buffer
12846 .read(cx)
12847 .as_singleton()
12848 .and_then(|b| b.read(cx).file());
12849 let file_extension = file_extension.or(file
12850 .as_ref()
12851 .and_then(|file| Path::new(file.file_name(cx)).extension())
12852 .and_then(|e| e.to_str())
12853 .map(|a| a.to_string()));
12854
12855 let vim_mode = cx
12856 .global::<SettingsStore>()
12857 .raw_user_settings()
12858 .get("vim_mode")
12859 == Some(&serde_json::Value::Bool(true));
12860
12861 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12862 == language::language_settings::InlineCompletionProvider::Copilot;
12863 let copilot_enabled_for_language = self
12864 .buffer
12865 .read(cx)
12866 .settings_at(0, cx)
12867 .show_inline_completions;
12868
12869 let project = project.read(cx);
12870 telemetry::event!(
12871 event_type,
12872 file_extension,
12873 vim_mode,
12874 copilot_enabled,
12875 copilot_enabled_for_language,
12876 is_via_ssh = project.is_via_ssh(),
12877 );
12878 }
12879
12880 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12881 /// with each line being an array of {text, highlight} objects.
12882 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12883 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12884 return;
12885 };
12886
12887 #[derive(Serialize)]
12888 struct Chunk<'a> {
12889 text: String,
12890 highlight: Option<&'a str>,
12891 }
12892
12893 let snapshot = buffer.read(cx).snapshot();
12894 let range = self
12895 .selected_text_range(false, cx)
12896 .and_then(|selection| {
12897 if selection.range.is_empty() {
12898 None
12899 } else {
12900 Some(selection.range)
12901 }
12902 })
12903 .unwrap_or_else(|| 0..snapshot.len());
12904
12905 let chunks = snapshot.chunks(range, true);
12906 let mut lines = Vec::new();
12907 let mut line: VecDeque<Chunk> = VecDeque::new();
12908
12909 let Some(style) = self.style.as_ref() else {
12910 return;
12911 };
12912
12913 for chunk in chunks {
12914 let highlight = chunk
12915 .syntax_highlight_id
12916 .and_then(|id| id.name(&style.syntax));
12917 let mut chunk_lines = chunk.text.split('\n').peekable();
12918 while let Some(text) = chunk_lines.next() {
12919 let mut merged_with_last_token = false;
12920 if let Some(last_token) = line.back_mut() {
12921 if last_token.highlight == highlight {
12922 last_token.text.push_str(text);
12923 merged_with_last_token = true;
12924 }
12925 }
12926
12927 if !merged_with_last_token {
12928 line.push_back(Chunk {
12929 text: text.into(),
12930 highlight,
12931 });
12932 }
12933
12934 if chunk_lines.peek().is_some() {
12935 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12936 line.pop_front();
12937 }
12938 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12939 line.pop_back();
12940 }
12941
12942 lines.push(mem::take(&mut line));
12943 }
12944 }
12945 }
12946
12947 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12948 return;
12949 };
12950 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12951 }
12952
12953 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12954 self.request_autoscroll(Autoscroll::newest(), cx);
12955 let position = self.selections.newest_display(cx).start;
12956 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12957 }
12958
12959 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12960 &self.inlay_hint_cache
12961 }
12962
12963 pub fn replay_insert_event(
12964 &mut self,
12965 text: &str,
12966 relative_utf16_range: Option<Range<isize>>,
12967 cx: &mut ViewContext<Self>,
12968 ) {
12969 if !self.input_enabled {
12970 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12971 return;
12972 }
12973 if let Some(relative_utf16_range) = relative_utf16_range {
12974 let selections = self.selections.all::<OffsetUtf16>(cx);
12975 self.change_selections(None, cx, |s| {
12976 let new_ranges = selections.into_iter().map(|range| {
12977 let start = OffsetUtf16(
12978 range
12979 .head()
12980 .0
12981 .saturating_add_signed(relative_utf16_range.start),
12982 );
12983 let end = OffsetUtf16(
12984 range
12985 .head()
12986 .0
12987 .saturating_add_signed(relative_utf16_range.end),
12988 );
12989 start..end
12990 });
12991 s.select_ranges(new_ranges);
12992 });
12993 }
12994
12995 self.handle_input(text, cx);
12996 }
12997
12998 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12999 let Some(provider) = self.semantics_provider.as_ref() else {
13000 return false;
13001 };
13002
13003 let mut supports = false;
13004 self.buffer().read(cx).for_each_buffer(|buffer| {
13005 supports |= provider.supports_inlay_hints(buffer, cx);
13006 });
13007 supports
13008 }
13009
13010 pub fn focus(&self, cx: &mut WindowContext) {
13011 cx.focus(&self.focus_handle)
13012 }
13013
13014 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13015 self.focus_handle.is_focused(cx)
13016 }
13017
13018 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13019 cx.emit(EditorEvent::Focused);
13020
13021 if let Some(descendant) = self
13022 .last_focused_descendant
13023 .take()
13024 .and_then(|descendant| descendant.upgrade())
13025 {
13026 cx.focus(&descendant);
13027 } else {
13028 if let Some(blame) = self.blame.as_ref() {
13029 blame.update(cx, GitBlame::focus)
13030 }
13031
13032 self.blink_manager.update(cx, BlinkManager::enable);
13033 self.show_cursor_names(cx);
13034 self.buffer.update(cx, |buffer, cx| {
13035 buffer.finalize_last_transaction(cx);
13036 if self.leader_peer_id.is_none() {
13037 buffer.set_active_selections(
13038 &self.selections.disjoint_anchors(),
13039 self.selections.line_mode,
13040 self.cursor_shape,
13041 cx,
13042 );
13043 }
13044 });
13045 }
13046 }
13047
13048 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13049 cx.emit(EditorEvent::FocusedIn)
13050 }
13051
13052 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13053 if event.blurred != self.focus_handle {
13054 self.last_focused_descendant = Some(event.blurred);
13055 }
13056 }
13057
13058 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13059 self.blink_manager.update(cx, BlinkManager::disable);
13060 self.buffer
13061 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13062
13063 if let Some(blame) = self.blame.as_ref() {
13064 blame.update(cx, GitBlame::blur)
13065 }
13066 if !self.hover_state.focused(cx) {
13067 hide_hover(self, cx);
13068 }
13069
13070 self.hide_context_menu(cx);
13071 cx.emit(EditorEvent::Blurred);
13072 cx.notify();
13073 }
13074
13075 pub fn register_action<A: Action>(
13076 &mut self,
13077 listener: impl Fn(&A, &mut WindowContext) + 'static,
13078 ) -> Subscription {
13079 let id = self.next_editor_action_id.post_inc();
13080 let listener = Arc::new(listener);
13081 self.editor_actions.borrow_mut().insert(
13082 id,
13083 Box::new(move |cx| {
13084 let cx = cx.window_context();
13085 let listener = listener.clone();
13086 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13087 let action = action.downcast_ref().unwrap();
13088 if phase == DispatchPhase::Bubble {
13089 listener(action, cx)
13090 }
13091 })
13092 }),
13093 );
13094
13095 let editor_actions = self.editor_actions.clone();
13096 Subscription::new(move || {
13097 editor_actions.borrow_mut().remove(&id);
13098 })
13099 }
13100
13101 pub fn file_header_size(&self) -> u32 {
13102 FILE_HEADER_HEIGHT
13103 }
13104
13105 pub fn revert(
13106 &mut self,
13107 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13108 cx: &mut ViewContext<Self>,
13109 ) {
13110 self.buffer().update(cx, |multi_buffer, cx| {
13111 for (buffer_id, changes) in revert_changes {
13112 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13113 buffer.update(cx, |buffer, cx| {
13114 buffer.edit(
13115 changes.into_iter().map(|(range, text)| {
13116 (range, text.to_string().map(Arc::<str>::from))
13117 }),
13118 None,
13119 cx,
13120 );
13121 });
13122 }
13123 }
13124 });
13125 self.change_selections(None, cx, |selections| selections.refresh());
13126 }
13127
13128 pub fn to_pixel_point(
13129 &mut self,
13130 source: multi_buffer::Anchor,
13131 editor_snapshot: &EditorSnapshot,
13132 cx: &mut ViewContext<Self>,
13133 ) -> Option<gpui::Point<Pixels>> {
13134 let source_point = source.to_display_point(editor_snapshot);
13135 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13136 }
13137
13138 pub fn display_to_pixel_point(
13139 &self,
13140 source: DisplayPoint,
13141 editor_snapshot: &EditorSnapshot,
13142 cx: &WindowContext,
13143 ) -> Option<gpui::Point<Pixels>> {
13144 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13145 let text_layout_details = self.text_layout_details(cx);
13146 let scroll_top = text_layout_details
13147 .scroll_anchor
13148 .scroll_position(editor_snapshot)
13149 .y;
13150
13151 if source.row().as_f32() < scroll_top.floor() {
13152 return None;
13153 }
13154 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13155 let source_y = line_height * (source.row().as_f32() - scroll_top);
13156 Some(gpui::Point::new(source_x, source_y))
13157 }
13158
13159 pub fn has_active_completions_menu(&self) -> bool {
13160 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13161 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13162 })
13163 }
13164
13165 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13166 self.addons
13167 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13168 }
13169
13170 pub fn unregister_addon<T: Addon>(&mut self) {
13171 self.addons.remove(&std::any::TypeId::of::<T>());
13172 }
13173
13174 pub fn addon<T: Addon>(&self) -> Option<&T> {
13175 let type_id = std::any::TypeId::of::<T>();
13176 self.addons
13177 .get(&type_id)
13178 .and_then(|item| item.to_any().downcast_ref::<T>())
13179 }
13180
13181 pub fn add_change_set(
13182 &mut self,
13183 change_set: Model<BufferChangeSet>,
13184 cx: &mut ViewContext<Self>,
13185 ) {
13186 self.diff_map.add_change_set(change_set, cx);
13187 }
13188
13189 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13190 let text_layout_details = self.text_layout_details(cx);
13191 let style = &text_layout_details.editor_style;
13192 let font_id = cx.text_system().resolve_font(&style.text.font());
13193 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13194 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13195
13196 let em_width = cx
13197 .text_system()
13198 .typographic_bounds(font_id, font_size, 'm')
13199 .unwrap()
13200 .size
13201 .width;
13202
13203 gpui::Point::new(em_width, line_height)
13204 }
13205}
13206
13207fn get_unstaged_changes_for_buffers(
13208 project: &Model<Project>,
13209 buffers: impl IntoIterator<Item = Model<Buffer>>,
13210 cx: &mut ViewContext<Editor>,
13211) {
13212 let mut tasks = Vec::new();
13213 project.update(cx, |project, cx| {
13214 for buffer in buffers {
13215 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13216 }
13217 });
13218 cx.spawn(|this, mut cx| async move {
13219 let change_sets = futures::future::join_all(tasks).await;
13220 this.update(&mut cx, |this, cx| {
13221 for change_set in change_sets {
13222 if let Some(change_set) = change_set.log_err() {
13223 this.diff_map.add_change_set(change_set, cx);
13224 }
13225 }
13226 })
13227 .ok();
13228 })
13229 .detach();
13230}
13231
13232fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13233 let tab_size = tab_size.get() as usize;
13234 let mut width = offset;
13235
13236 for ch in text.chars() {
13237 width += if ch == '\t' {
13238 tab_size - (width % tab_size)
13239 } else {
13240 1
13241 };
13242 }
13243
13244 width - offset
13245}
13246
13247#[cfg(test)]
13248mod tests {
13249 use super::*;
13250
13251 #[test]
13252 fn test_string_size_with_expanded_tabs() {
13253 let nz = |val| NonZeroU32::new(val).unwrap();
13254 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13255 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13256 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13257 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13258 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13259 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13260 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13261 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13262 }
13263}
13264
13265/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13266struct WordBreakingTokenizer<'a> {
13267 input: &'a str,
13268}
13269
13270impl<'a> WordBreakingTokenizer<'a> {
13271 fn new(input: &'a str) -> Self {
13272 Self { input }
13273 }
13274}
13275
13276fn is_char_ideographic(ch: char) -> bool {
13277 use unicode_script::Script::*;
13278 use unicode_script::UnicodeScript;
13279 matches!(ch.script(), Han | Tangut | Yi)
13280}
13281
13282fn is_grapheme_ideographic(text: &str) -> bool {
13283 text.chars().any(is_char_ideographic)
13284}
13285
13286fn is_grapheme_whitespace(text: &str) -> bool {
13287 text.chars().any(|x| x.is_whitespace())
13288}
13289
13290fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13291 text.chars().next().map_or(false, |ch| {
13292 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13293 })
13294}
13295
13296#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13297struct WordBreakToken<'a> {
13298 token: &'a str,
13299 grapheme_len: usize,
13300 is_whitespace: bool,
13301}
13302
13303impl<'a> Iterator for WordBreakingTokenizer<'a> {
13304 /// Yields a span, the count of graphemes in the token, and whether it was
13305 /// whitespace. Note that it also breaks at word boundaries.
13306 type Item = WordBreakToken<'a>;
13307
13308 fn next(&mut self) -> Option<Self::Item> {
13309 use unicode_segmentation::UnicodeSegmentation;
13310 if self.input.is_empty() {
13311 return None;
13312 }
13313
13314 let mut iter = self.input.graphemes(true).peekable();
13315 let mut offset = 0;
13316 let mut graphemes = 0;
13317 if let Some(first_grapheme) = iter.next() {
13318 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13319 offset += first_grapheme.len();
13320 graphemes += 1;
13321 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13322 if let Some(grapheme) = iter.peek().copied() {
13323 if should_stay_with_preceding_ideograph(grapheme) {
13324 offset += grapheme.len();
13325 graphemes += 1;
13326 }
13327 }
13328 } else {
13329 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13330 let mut next_word_bound = words.peek().copied();
13331 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13332 next_word_bound = words.next();
13333 }
13334 while let Some(grapheme) = iter.peek().copied() {
13335 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13336 break;
13337 };
13338 if is_grapheme_whitespace(grapheme) != is_whitespace {
13339 break;
13340 };
13341 offset += grapheme.len();
13342 graphemes += 1;
13343 iter.next();
13344 }
13345 }
13346 let token = &self.input[..offset];
13347 self.input = &self.input[offset..];
13348 if is_whitespace {
13349 Some(WordBreakToken {
13350 token: " ",
13351 grapheme_len: 1,
13352 is_whitespace: true,
13353 })
13354 } else {
13355 Some(WordBreakToken {
13356 token,
13357 grapheme_len: graphemes,
13358 is_whitespace: false,
13359 })
13360 }
13361 } else {
13362 None
13363 }
13364 }
13365}
13366
13367#[test]
13368fn test_word_breaking_tokenizer() {
13369 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13370 ("", &[]),
13371 (" ", &[(" ", 1, true)]),
13372 ("Ʒ", &[("Ʒ", 1, false)]),
13373 ("Ǽ", &[("Ǽ", 1, false)]),
13374 ("⋑", &[("⋑", 1, false)]),
13375 ("⋑⋑", &[("⋑⋑", 2, false)]),
13376 (
13377 "原理,进而",
13378 &[
13379 ("原", 1, false),
13380 ("理,", 2, false),
13381 ("进", 1, false),
13382 ("而", 1, false),
13383 ],
13384 ),
13385 (
13386 "hello world",
13387 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13388 ),
13389 (
13390 "hello, world",
13391 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13392 ),
13393 (
13394 " hello world",
13395 &[
13396 (" ", 1, true),
13397 ("hello", 5, false),
13398 (" ", 1, true),
13399 ("world", 5, false),
13400 ],
13401 ),
13402 (
13403 "这是什么 \n 钢笔",
13404 &[
13405 ("这", 1, false),
13406 ("是", 1, false),
13407 ("什", 1, false),
13408 ("么", 1, false),
13409 (" ", 1, true),
13410 ("钢", 1, false),
13411 ("笔", 1, false),
13412 ],
13413 ),
13414 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13415 ];
13416
13417 for (input, result) in tests {
13418 assert_eq!(
13419 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13420 result
13421 .iter()
13422 .copied()
13423 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13424 token,
13425 grapheme_len,
13426 is_whitespace,
13427 })
13428 .collect::<Vec<_>>()
13429 );
13430 }
13431}
13432
13433fn wrap_with_prefix(
13434 line_prefix: String,
13435 unwrapped_text: String,
13436 wrap_column: usize,
13437 tab_size: NonZeroU32,
13438) -> String {
13439 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13440 let mut wrapped_text = String::new();
13441 let mut current_line = line_prefix.clone();
13442
13443 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13444 let mut current_line_len = line_prefix_len;
13445 for WordBreakToken {
13446 token,
13447 grapheme_len,
13448 is_whitespace,
13449 } in tokenizer
13450 {
13451 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13452 wrapped_text.push_str(current_line.trim_end());
13453 wrapped_text.push('\n');
13454 current_line.truncate(line_prefix.len());
13455 current_line_len = line_prefix_len;
13456 if !is_whitespace {
13457 current_line.push_str(token);
13458 current_line_len += grapheme_len;
13459 }
13460 } else if !is_whitespace {
13461 current_line.push_str(token);
13462 current_line_len += grapheme_len;
13463 } else if current_line_len != line_prefix_len {
13464 current_line.push(' ');
13465 current_line_len += 1;
13466 }
13467 }
13468
13469 if !current_line.is_empty() {
13470 wrapped_text.push_str(¤t_line);
13471 }
13472 wrapped_text
13473}
13474
13475#[test]
13476fn test_wrap_with_prefix() {
13477 assert_eq!(
13478 wrap_with_prefix(
13479 "# ".to_string(),
13480 "abcdefg".to_string(),
13481 4,
13482 NonZeroU32::new(4).unwrap()
13483 ),
13484 "# abcdefg"
13485 );
13486 assert_eq!(
13487 wrap_with_prefix(
13488 "".to_string(),
13489 "\thello world".to_string(),
13490 8,
13491 NonZeroU32::new(4).unwrap()
13492 ),
13493 "hello\nworld"
13494 );
13495 assert_eq!(
13496 wrap_with_prefix(
13497 "// ".to_string(),
13498 "xx \nyy zz aa bb cc".to_string(),
13499 12,
13500 NonZeroU32::new(4).unwrap()
13501 ),
13502 "// xx yy zz\n// aa bb cc"
13503 );
13504 assert_eq!(
13505 wrap_with_prefix(
13506 String::new(),
13507 "这是什么 \n 钢笔".to_string(),
13508 3,
13509 NonZeroU32::new(4).unwrap()
13510 ),
13511 "这是什\n么 钢\n笔"
13512 );
13513}
13514
13515fn hunks_for_selections(
13516 snapshot: &EditorSnapshot,
13517 selections: &[Selection<Point>],
13518) -> Vec<MultiBufferDiffHunk> {
13519 hunks_for_ranges(
13520 selections.iter().map(|selection| selection.range()),
13521 snapshot,
13522 )
13523}
13524
13525pub fn hunks_for_ranges(
13526 ranges: impl Iterator<Item = Range<Point>>,
13527 snapshot: &EditorSnapshot,
13528) -> Vec<MultiBufferDiffHunk> {
13529 let mut hunks = Vec::new();
13530 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13531 HashMap::default();
13532 for query_range in ranges {
13533 let query_rows =
13534 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13535 for hunk in snapshot.diff_map.diff_hunks_in_range(
13536 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13537 &snapshot.buffer_snapshot,
13538 ) {
13539 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13540 // when the caret is just above or just below the deleted hunk.
13541 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13542 let related_to_selection = if allow_adjacent {
13543 hunk.row_range.overlaps(&query_rows)
13544 || hunk.row_range.start == query_rows.end
13545 || hunk.row_range.end == query_rows.start
13546 } else {
13547 hunk.row_range.overlaps(&query_rows)
13548 };
13549 if related_to_selection {
13550 if !processed_buffer_rows
13551 .entry(hunk.buffer_id)
13552 .or_default()
13553 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13554 {
13555 continue;
13556 }
13557 hunks.push(hunk);
13558 }
13559 }
13560 }
13561
13562 hunks
13563}
13564
13565pub trait CollaborationHub {
13566 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13567 fn user_participant_indices<'a>(
13568 &self,
13569 cx: &'a AppContext,
13570 ) -> &'a HashMap<u64, ParticipantIndex>;
13571 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13572}
13573
13574impl CollaborationHub for Model<Project> {
13575 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13576 self.read(cx).collaborators()
13577 }
13578
13579 fn user_participant_indices<'a>(
13580 &self,
13581 cx: &'a AppContext,
13582 ) -> &'a HashMap<u64, ParticipantIndex> {
13583 self.read(cx).user_store().read(cx).participant_indices()
13584 }
13585
13586 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13587 let this = self.read(cx);
13588 let user_ids = this.collaborators().values().map(|c| c.user_id);
13589 this.user_store().read_with(cx, |user_store, cx| {
13590 user_store.participant_names(user_ids, cx)
13591 })
13592 }
13593}
13594
13595pub trait SemanticsProvider {
13596 fn hover(
13597 &self,
13598 buffer: &Model<Buffer>,
13599 position: text::Anchor,
13600 cx: &mut AppContext,
13601 ) -> Option<Task<Vec<project::Hover>>>;
13602
13603 fn inlay_hints(
13604 &self,
13605 buffer_handle: Model<Buffer>,
13606 range: Range<text::Anchor>,
13607 cx: &mut AppContext,
13608 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13609
13610 fn resolve_inlay_hint(
13611 &self,
13612 hint: InlayHint,
13613 buffer_handle: Model<Buffer>,
13614 server_id: LanguageServerId,
13615 cx: &mut AppContext,
13616 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13617
13618 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13619
13620 fn document_highlights(
13621 &self,
13622 buffer: &Model<Buffer>,
13623 position: text::Anchor,
13624 cx: &mut AppContext,
13625 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13626
13627 fn definitions(
13628 &self,
13629 buffer: &Model<Buffer>,
13630 position: text::Anchor,
13631 kind: GotoDefinitionKind,
13632 cx: &mut AppContext,
13633 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13634
13635 fn range_for_rename(
13636 &self,
13637 buffer: &Model<Buffer>,
13638 position: text::Anchor,
13639 cx: &mut AppContext,
13640 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13641
13642 fn perform_rename(
13643 &self,
13644 buffer: &Model<Buffer>,
13645 position: text::Anchor,
13646 new_name: String,
13647 cx: &mut AppContext,
13648 ) -> Option<Task<Result<ProjectTransaction>>>;
13649}
13650
13651pub trait CompletionProvider {
13652 fn completions(
13653 &self,
13654 buffer: &Model<Buffer>,
13655 buffer_position: text::Anchor,
13656 trigger: CompletionContext,
13657 cx: &mut ViewContext<Editor>,
13658 ) -> Task<Result<Vec<Completion>>>;
13659
13660 fn resolve_completions(
13661 &self,
13662 buffer: Model<Buffer>,
13663 completion_indices: Vec<usize>,
13664 completions: Rc<RefCell<Box<[Completion]>>>,
13665 cx: &mut ViewContext<Editor>,
13666 ) -> Task<Result<bool>>;
13667
13668 fn apply_additional_edits_for_completion(
13669 &self,
13670 _buffer: Model<Buffer>,
13671 _completions: Rc<RefCell<Box<[Completion]>>>,
13672 _completion_index: usize,
13673 _push_to_history: bool,
13674 _cx: &mut ViewContext<Editor>,
13675 ) -> Task<Result<Option<language::Transaction>>> {
13676 Task::ready(Ok(None))
13677 }
13678
13679 fn is_completion_trigger(
13680 &self,
13681 buffer: &Model<Buffer>,
13682 position: language::Anchor,
13683 text: &str,
13684 trigger_in_words: bool,
13685 cx: &mut ViewContext<Editor>,
13686 ) -> bool;
13687
13688 fn sort_completions(&self) -> bool {
13689 true
13690 }
13691}
13692
13693pub trait CodeActionProvider {
13694 fn id(&self) -> Arc<str>;
13695
13696 fn code_actions(
13697 &self,
13698 buffer: &Model<Buffer>,
13699 range: Range<text::Anchor>,
13700 cx: &mut WindowContext,
13701 ) -> Task<Result<Vec<CodeAction>>>;
13702
13703 fn apply_code_action(
13704 &self,
13705 buffer_handle: Model<Buffer>,
13706 action: CodeAction,
13707 excerpt_id: ExcerptId,
13708 push_to_history: bool,
13709 cx: &mut WindowContext,
13710 ) -> Task<Result<ProjectTransaction>>;
13711}
13712
13713impl CodeActionProvider for Model<Project> {
13714 fn id(&self) -> Arc<str> {
13715 "project".into()
13716 }
13717
13718 fn code_actions(
13719 &self,
13720 buffer: &Model<Buffer>,
13721 range: Range<text::Anchor>,
13722 cx: &mut WindowContext,
13723 ) -> Task<Result<Vec<CodeAction>>> {
13724 self.update(cx, |project, cx| {
13725 project.code_actions(buffer, range, None, cx)
13726 })
13727 }
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 self.update(cx, |project, cx| {
13738 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13739 })
13740 }
13741}
13742
13743fn snippet_completions(
13744 project: &Project,
13745 buffer: &Model<Buffer>,
13746 buffer_position: text::Anchor,
13747 cx: &mut AppContext,
13748) -> Task<Result<Vec<Completion>>> {
13749 let language = buffer.read(cx).language_at(buffer_position);
13750 let language_name = language.as_ref().map(|language| language.lsp_id());
13751 let snippet_store = project.snippets().read(cx);
13752 let snippets = snippet_store.snippets_for(language_name, cx);
13753
13754 if snippets.is_empty() {
13755 return Task::ready(Ok(vec![]));
13756 }
13757 let snapshot = buffer.read(cx).text_snapshot();
13758 let chars: String = snapshot
13759 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13760 .collect();
13761
13762 let scope = language.map(|language| language.default_scope());
13763 let executor = cx.background_executor().clone();
13764
13765 cx.background_executor().spawn(async move {
13766 let classifier = CharClassifier::new(scope).for_completion(true);
13767 let mut last_word = chars
13768 .chars()
13769 .take_while(|c| classifier.is_word(*c))
13770 .collect::<String>();
13771 last_word = last_word.chars().rev().collect();
13772
13773 if last_word.is_empty() {
13774 return Ok(vec![]);
13775 }
13776
13777 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13778 let to_lsp = |point: &text::Anchor| {
13779 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13780 point_to_lsp(end)
13781 };
13782 let lsp_end = to_lsp(&buffer_position);
13783
13784 let candidates = snippets
13785 .iter()
13786 .enumerate()
13787 .flat_map(|(ix, snippet)| {
13788 snippet
13789 .prefix
13790 .iter()
13791 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13792 })
13793 .collect::<Vec<StringMatchCandidate>>();
13794
13795 let mut matches = fuzzy::match_strings(
13796 &candidates,
13797 &last_word,
13798 last_word.chars().any(|c| c.is_uppercase()),
13799 100,
13800 &Default::default(),
13801 executor,
13802 )
13803 .await;
13804
13805 // Remove all candidates where the query's start does not match the start of any word in the candidate
13806 if let Some(query_start) = last_word.chars().next() {
13807 matches.retain(|string_match| {
13808 split_words(&string_match.string).any(|word| {
13809 // Check that the first codepoint of the word as lowercase matches the first
13810 // codepoint of the query as lowercase
13811 word.chars()
13812 .flat_map(|codepoint| codepoint.to_lowercase())
13813 .zip(query_start.to_lowercase())
13814 .all(|(word_cp, query_cp)| word_cp == query_cp)
13815 })
13816 });
13817 }
13818
13819 let matched_strings = matches
13820 .into_iter()
13821 .map(|m| m.string)
13822 .collect::<HashSet<_>>();
13823
13824 let result: Vec<Completion> = snippets
13825 .into_iter()
13826 .filter_map(|snippet| {
13827 let matching_prefix = snippet
13828 .prefix
13829 .iter()
13830 .find(|prefix| matched_strings.contains(*prefix))?;
13831 let start = as_offset - last_word.len();
13832 let start = snapshot.anchor_before(start);
13833 let range = start..buffer_position;
13834 let lsp_start = to_lsp(&start);
13835 let lsp_range = lsp::Range {
13836 start: lsp_start,
13837 end: lsp_end,
13838 };
13839 Some(Completion {
13840 old_range: range,
13841 new_text: snippet.body.clone(),
13842 resolved: false,
13843 label: CodeLabel {
13844 text: matching_prefix.clone(),
13845 runs: vec![],
13846 filter_range: 0..matching_prefix.len(),
13847 },
13848 server_id: LanguageServerId(usize::MAX),
13849 documentation: snippet.description.clone().map(Documentation::SingleLine),
13850 lsp_completion: lsp::CompletionItem {
13851 label: snippet.prefix.first().unwrap().clone(),
13852 kind: Some(CompletionItemKind::SNIPPET),
13853 label_details: snippet.description.as_ref().map(|description| {
13854 lsp::CompletionItemLabelDetails {
13855 detail: Some(description.clone()),
13856 description: None,
13857 }
13858 }),
13859 insert_text_format: Some(InsertTextFormat::SNIPPET),
13860 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13861 lsp::InsertReplaceEdit {
13862 new_text: snippet.body.clone(),
13863 insert: lsp_range,
13864 replace: lsp_range,
13865 },
13866 )),
13867 filter_text: Some(snippet.body.clone()),
13868 sort_text: Some(char::MAX.to_string()),
13869 ..Default::default()
13870 },
13871 confirm: None,
13872 })
13873 })
13874 .collect();
13875
13876 Ok(result)
13877 })
13878}
13879
13880impl CompletionProvider for Model<Project> {
13881 fn completions(
13882 &self,
13883 buffer: &Model<Buffer>,
13884 buffer_position: text::Anchor,
13885 options: CompletionContext,
13886 cx: &mut ViewContext<Editor>,
13887 ) -> Task<Result<Vec<Completion>>> {
13888 self.update(cx, |project, cx| {
13889 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13890 let project_completions = project.completions(buffer, buffer_position, options, cx);
13891 cx.background_executor().spawn(async move {
13892 let mut completions = project_completions.await?;
13893 let snippets_completions = snippets.await?;
13894 completions.extend(snippets_completions);
13895 Ok(completions)
13896 })
13897 })
13898 }
13899
13900 fn resolve_completions(
13901 &self,
13902 buffer: Model<Buffer>,
13903 completion_indices: Vec<usize>,
13904 completions: Rc<RefCell<Box<[Completion]>>>,
13905 cx: &mut ViewContext<Editor>,
13906 ) -> Task<Result<bool>> {
13907 self.update(cx, |project, cx| {
13908 project.lsp_store().update(cx, |lsp_store, cx| {
13909 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13910 })
13911 })
13912 }
13913
13914 fn apply_additional_edits_for_completion(
13915 &self,
13916 buffer: Model<Buffer>,
13917 completions: Rc<RefCell<Box<[Completion]>>>,
13918 completion_index: usize,
13919 push_to_history: bool,
13920 cx: &mut ViewContext<Editor>,
13921 ) -> Task<Result<Option<language::Transaction>>> {
13922 self.update(cx, |project, cx| {
13923 project.lsp_store().update(cx, |lsp_store, cx| {
13924 lsp_store.apply_additional_edits_for_completion(
13925 buffer,
13926 completions,
13927 completion_index,
13928 push_to_history,
13929 cx,
13930 )
13931 })
13932 })
13933 }
13934
13935 fn is_completion_trigger(
13936 &self,
13937 buffer: &Model<Buffer>,
13938 position: language::Anchor,
13939 text: &str,
13940 trigger_in_words: bool,
13941 cx: &mut ViewContext<Editor>,
13942 ) -> bool {
13943 let mut chars = text.chars();
13944 let char = if let Some(char) = chars.next() {
13945 char
13946 } else {
13947 return false;
13948 };
13949 if chars.next().is_some() {
13950 return false;
13951 }
13952
13953 let buffer = buffer.read(cx);
13954 let snapshot = buffer.snapshot();
13955 if !snapshot.settings_at(position, cx).show_completions_on_input {
13956 return false;
13957 }
13958 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13959 if trigger_in_words && classifier.is_word(char) {
13960 return true;
13961 }
13962
13963 buffer.completion_triggers().contains(text)
13964 }
13965}
13966
13967impl SemanticsProvider for Model<Project> {
13968 fn hover(
13969 &self,
13970 buffer: &Model<Buffer>,
13971 position: text::Anchor,
13972 cx: &mut AppContext,
13973 ) -> Option<Task<Vec<project::Hover>>> {
13974 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13975 }
13976
13977 fn document_highlights(
13978 &self,
13979 buffer: &Model<Buffer>,
13980 position: text::Anchor,
13981 cx: &mut AppContext,
13982 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13983 Some(self.update(cx, |project, cx| {
13984 project.document_highlights(buffer, position, cx)
13985 }))
13986 }
13987
13988 fn definitions(
13989 &self,
13990 buffer: &Model<Buffer>,
13991 position: text::Anchor,
13992 kind: GotoDefinitionKind,
13993 cx: &mut AppContext,
13994 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13995 Some(self.update(cx, |project, cx| match kind {
13996 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13997 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13998 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13999 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14000 }))
14001 }
14002
14003 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14004 // TODO: make this work for remote projects
14005 self.read(cx)
14006 .language_servers_for_local_buffer(buffer.read(cx), cx)
14007 .any(
14008 |(_, server)| match server.capabilities().inlay_hint_provider {
14009 Some(lsp::OneOf::Left(enabled)) => enabled,
14010 Some(lsp::OneOf::Right(_)) => true,
14011 None => false,
14012 },
14013 )
14014 }
14015
14016 fn inlay_hints(
14017 &self,
14018 buffer_handle: Model<Buffer>,
14019 range: Range<text::Anchor>,
14020 cx: &mut AppContext,
14021 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14022 Some(self.update(cx, |project, cx| {
14023 project.inlay_hints(buffer_handle, range, cx)
14024 }))
14025 }
14026
14027 fn resolve_inlay_hint(
14028 &self,
14029 hint: InlayHint,
14030 buffer_handle: Model<Buffer>,
14031 server_id: LanguageServerId,
14032 cx: &mut AppContext,
14033 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14034 Some(self.update(cx, |project, cx| {
14035 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14036 }))
14037 }
14038
14039 fn range_for_rename(
14040 &self,
14041 buffer: &Model<Buffer>,
14042 position: text::Anchor,
14043 cx: &mut AppContext,
14044 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14045 Some(self.update(cx, |project, cx| {
14046 let buffer = buffer.clone();
14047 let task = project.prepare_rename(buffer.clone(), position, cx);
14048 cx.spawn(|_, mut cx| async move {
14049 Ok(match task.await? {
14050 PrepareRenameResponse::Success(range) => Some(range),
14051 PrepareRenameResponse::InvalidPosition => None,
14052 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14053 // Fallback on using TreeSitter info to determine identifier range
14054 buffer.update(&mut cx, |buffer, _| {
14055 let snapshot = buffer.snapshot();
14056 let (range, kind) = snapshot.surrounding_word(position);
14057 if kind != Some(CharKind::Word) {
14058 return None;
14059 }
14060 Some(
14061 snapshot.anchor_before(range.start)
14062 ..snapshot.anchor_after(range.end),
14063 )
14064 })?
14065 }
14066 })
14067 })
14068 }))
14069 }
14070
14071 fn perform_rename(
14072 &self,
14073 buffer: &Model<Buffer>,
14074 position: text::Anchor,
14075 new_name: String,
14076 cx: &mut AppContext,
14077 ) -> Option<Task<Result<ProjectTransaction>>> {
14078 Some(self.update(cx, |project, cx| {
14079 project.perform_rename(buffer.clone(), position, new_name, cx)
14080 }))
14081 }
14082}
14083
14084fn inlay_hint_settings(
14085 location: Anchor,
14086 snapshot: &MultiBufferSnapshot,
14087 cx: &mut ViewContext<Editor>,
14088) -> InlayHintSettings {
14089 let file = snapshot.file_at(location);
14090 let language = snapshot.language_at(location).map(|l| l.name());
14091 language_settings(language, file, cx).inlay_hints
14092}
14093
14094fn consume_contiguous_rows(
14095 contiguous_row_selections: &mut Vec<Selection<Point>>,
14096 selection: &Selection<Point>,
14097 display_map: &DisplaySnapshot,
14098 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14099) -> (MultiBufferRow, MultiBufferRow) {
14100 contiguous_row_selections.push(selection.clone());
14101 let start_row = MultiBufferRow(selection.start.row);
14102 let mut end_row = ending_row(selection, display_map);
14103
14104 while let Some(next_selection) = selections.peek() {
14105 if next_selection.start.row <= end_row.0 {
14106 end_row = ending_row(next_selection, display_map);
14107 contiguous_row_selections.push(selections.next().unwrap().clone());
14108 } else {
14109 break;
14110 }
14111 }
14112 (start_row, end_row)
14113}
14114
14115fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14116 if next_selection.end.column > 0 || next_selection.is_empty() {
14117 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14118 } else {
14119 MultiBufferRow(next_selection.end.row)
14120 }
14121}
14122
14123impl EditorSnapshot {
14124 pub fn remote_selections_in_range<'a>(
14125 &'a self,
14126 range: &'a Range<Anchor>,
14127 collaboration_hub: &dyn CollaborationHub,
14128 cx: &'a AppContext,
14129 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14130 let participant_names = collaboration_hub.user_names(cx);
14131 let participant_indices = collaboration_hub.user_participant_indices(cx);
14132 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14133 let collaborators_by_replica_id = collaborators_by_peer_id
14134 .iter()
14135 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14136 .collect::<HashMap<_, _>>();
14137 self.buffer_snapshot
14138 .selections_in_range(range, false)
14139 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14140 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14141 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14142 let user_name = participant_names.get(&collaborator.user_id).cloned();
14143 Some(RemoteSelection {
14144 replica_id,
14145 selection,
14146 cursor_shape,
14147 line_mode,
14148 participant_index,
14149 peer_id: collaborator.peer_id,
14150 user_name,
14151 })
14152 })
14153 }
14154
14155 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14156 self.display_snapshot.buffer_snapshot.language_at(position)
14157 }
14158
14159 pub fn is_focused(&self) -> bool {
14160 self.is_focused
14161 }
14162
14163 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14164 self.placeholder_text.as_ref()
14165 }
14166
14167 pub fn scroll_position(&self) -> gpui::Point<f32> {
14168 self.scroll_anchor.scroll_position(&self.display_snapshot)
14169 }
14170
14171 fn gutter_dimensions(
14172 &self,
14173 font_id: FontId,
14174 font_size: Pixels,
14175 em_width: Pixels,
14176 em_advance: Pixels,
14177 max_line_number_width: Pixels,
14178 cx: &AppContext,
14179 ) -> GutterDimensions {
14180 if !self.show_gutter {
14181 return GutterDimensions::default();
14182 }
14183 let descent = cx.text_system().descent(font_id, font_size);
14184
14185 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14186 matches!(
14187 ProjectSettings::get_global(cx).git.git_gutter,
14188 Some(GitGutterSetting::TrackedFiles)
14189 )
14190 });
14191 let gutter_settings = EditorSettings::get_global(cx).gutter;
14192 let show_line_numbers = self
14193 .show_line_numbers
14194 .unwrap_or(gutter_settings.line_numbers);
14195 let line_gutter_width = if show_line_numbers {
14196 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14197 let min_width_for_number_on_gutter = em_advance * 4.0;
14198 max_line_number_width.max(min_width_for_number_on_gutter)
14199 } else {
14200 0.0.into()
14201 };
14202
14203 let show_code_actions = self
14204 .show_code_actions
14205 .unwrap_or(gutter_settings.code_actions);
14206
14207 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14208
14209 let git_blame_entries_width =
14210 self.git_blame_gutter_max_author_length
14211 .map(|max_author_length| {
14212 // Length of the author name, but also space for the commit hash,
14213 // the spacing and the timestamp.
14214 let max_char_count = max_author_length
14215 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14216 + 7 // length of commit sha
14217 + 14 // length of max relative timestamp ("60 minutes ago")
14218 + 4; // gaps and margins
14219
14220 em_advance * max_char_count
14221 });
14222
14223 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14224 left_padding += if show_code_actions || show_runnables {
14225 em_width * 3.0
14226 } else if show_git_gutter && show_line_numbers {
14227 em_width * 2.0
14228 } else if show_git_gutter || show_line_numbers {
14229 em_width
14230 } else {
14231 px(0.)
14232 };
14233
14234 let right_padding = if gutter_settings.folds && show_line_numbers {
14235 em_width * 4.0
14236 } else if gutter_settings.folds {
14237 em_width * 3.0
14238 } else if show_line_numbers {
14239 em_width
14240 } else {
14241 px(0.)
14242 };
14243
14244 GutterDimensions {
14245 left_padding,
14246 right_padding,
14247 width: line_gutter_width + left_padding + right_padding,
14248 margin: -descent,
14249 git_blame_entries_width,
14250 }
14251 }
14252
14253 pub fn render_crease_toggle(
14254 &self,
14255 buffer_row: MultiBufferRow,
14256 row_contains_cursor: bool,
14257 editor: View<Editor>,
14258 cx: &mut WindowContext,
14259 ) -> Option<AnyElement> {
14260 let folded = self.is_line_folded(buffer_row);
14261 let mut is_foldable = false;
14262
14263 if let Some(crease) = self
14264 .crease_snapshot
14265 .query_row(buffer_row, &self.buffer_snapshot)
14266 {
14267 is_foldable = true;
14268 match crease {
14269 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14270 if let Some(render_toggle) = render_toggle {
14271 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14272 if folded {
14273 editor.update(cx, |editor, cx| {
14274 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14275 });
14276 } else {
14277 editor.update(cx, |editor, cx| {
14278 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14279 });
14280 }
14281 });
14282 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14283 }
14284 }
14285 }
14286 }
14287
14288 is_foldable |= self.starts_indent(buffer_row);
14289
14290 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14291 Some(
14292 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14293 .toggle_state(folded)
14294 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14295 if folded {
14296 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14297 } else {
14298 this.fold_at(&FoldAt { buffer_row }, cx);
14299 }
14300 }))
14301 .into_any_element(),
14302 )
14303 } else {
14304 None
14305 }
14306 }
14307
14308 pub fn render_crease_trailer(
14309 &self,
14310 buffer_row: MultiBufferRow,
14311 cx: &mut WindowContext,
14312 ) -> Option<AnyElement> {
14313 let folded = self.is_line_folded(buffer_row);
14314 if let Crease::Inline { render_trailer, .. } = self
14315 .crease_snapshot
14316 .query_row(buffer_row, &self.buffer_snapshot)?
14317 {
14318 let render_trailer = render_trailer.as_ref()?;
14319 Some(render_trailer(buffer_row, folded, cx))
14320 } else {
14321 None
14322 }
14323 }
14324}
14325
14326impl Deref for EditorSnapshot {
14327 type Target = DisplaySnapshot;
14328
14329 fn deref(&self) -> &Self::Target {
14330 &self.display_snapshot
14331 }
14332}
14333
14334#[derive(Clone, Debug, PartialEq, Eq)]
14335pub enum EditorEvent {
14336 InputIgnored {
14337 text: Arc<str>,
14338 },
14339 InputHandled {
14340 utf16_range_to_replace: Option<Range<isize>>,
14341 text: Arc<str>,
14342 },
14343 ExcerptsAdded {
14344 buffer: Model<Buffer>,
14345 predecessor: ExcerptId,
14346 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14347 },
14348 ExcerptsRemoved {
14349 ids: Vec<ExcerptId>,
14350 },
14351 BufferFoldToggled {
14352 ids: Vec<ExcerptId>,
14353 folded: bool,
14354 },
14355 ExcerptsEdited {
14356 ids: Vec<ExcerptId>,
14357 },
14358 ExcerptsExpanded {
14359 ids: Vec<ExcerptId>,
14360 },
14361 BufferEdited,
14362 Edited {
14363 transaction_id: clock::Lamport,
14364 },
14365 Reparsed(BufferId),
14366 Focused,
14367 FocusedIn,
14368 Blurred,
14369 DirtyChanged,
14370 Saved,
14371 TitleChanged,
14372 DiffBaseChanged,
14373 SelectionsChanged {
14374 local: bool,
14375 },
14376 ScrollPositionChanged {
14377 local: bool,
14378 autoscroll: bool,
14379 },
14380 Closed,
14381 TransactionUndone {
14382 transaction_id: clock::Lamport,
14383 },
14384 TransactionBegun {
14385 transaction_id: clock::Lamport,
14386 },
14387 Reloaded,
14388 CursorShapeChanged,
14389}
14390
14391impl EventEmitter<EditorEvent> for Editor {}
14392
14393impl FocusableView for Editor {
14394 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14395 self.focus_handle.clone()
14396 }
14397}
14398
14399impl Render for Editor {
14400 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14401 let settings = ThemeSettings::get_global(cx);
14402
14403 let mut text_style = match self.mode {
14404 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14405 color: cx.theme().colors().editor_foreground,
14406 font_family: settings.ui_font.family.clone(),
14407 font_features: settings.ui_font.features.clone(),
14408 font_fallbacks: settings.ui_font.fallbacks.clone(),
14409 font_size: rems(0.875).into(),
14410 font_weight: settings.ui_font.weight,
14411 line_height: relative(settings.buffer_line_height.value()),
14412 ..Default::default()
14413 },
14414 EditorMode::Full => TextStyle {
14415 color: cx.theme().colors().editor_foreground,
14416 font_family: settings.buffer_font.family.clone(),
14417 font_features: settings.buffer_font.features.clone(),
14418 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14419 font_size: settings.buffer_font_size().into(),
14420 font_weight: settings.buffer_font.weight,
14421 line_height: relative(settings.buffer_line_height.value()),
14422 ..Default::default()
14423 },
14424 };
14425 if let Some(text_style_refinement) = &self.text_style_refinement {
14426 text_style.refine(text_style_refinement)
14427 }
14428
14429 let background = match self.mode {
14430 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14431 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14432 EditorMode::Full => cx.theme().colors().editor_background,
14433 };
14434
14435 EditorElement::new(
14436 cx.view(),
14437 EditorStyle {
14438 background,
14439 local_player: cx.theme().players().local(),
14440 text: text_style,
14441 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14442 syntax: cx.theme().syntax().clone(),
14443 status: cx.theme().status().clone(),
14444 inlay_hints_style: make_inlay_hints_style(cx),
14445 inline_completion_styles: make_suggestion_styles(cx),
14446 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14447 },
14448 )
14449 }
14450}
14451
14452impl ViewInputHandler for Editor {
14453 fn text_for_range(
14454 &mut self,
14455 range_utf16: Range<usize>,
14456 adjusted_range: &mut Option<Range<usize>>,
14457 cx: &mut ViewContext<Self>,
14458 ) -> Option<String> {
14459 let snapshot = self.buffer.read(cx).read(cx);
14460 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14461 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14462 if (start.0..end.0) != range_utf16 {
14463 adjusted_range.replace(start.0..end.0);
14464 }
14465 Some(snapshot.text_for_range(start..end).collect())
14466 }
14467
14468 fn selected_text_range(
14469 &mut self,
14470 ignore_disabled_input: bool,
14471 cx: &mut ViewContext<Self>,
14472 ) -> Option<UTF16Selection> {
14473 // Prevent the IME menu from appearing when holding down an alphabetic key
14474 // while input is disabled.
14475 if !ignore_disabled_input && !self.input_enabled {
14476 return None;
14477 }
14478
14479 let selection = self.selections.newest::<OffsetUtf16>(cx);
14480 let range = selection.range();
14481
14482 Some(UTF16Selection {
14483 range: range.start.0..range.end.0,
14484 reversed: selection.reversed,
14485 })
14486 }
14487
14488 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14489 let snapshot = self.buffer.read(cx).read(cx);
14490 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14491 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14492 }
14493
14494 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14495 self.clear_highlights::<InputComposition>(cx);
14496 self.ime_transaction.take();
14497 }
14498
14499 fn replace_text_in_range(
14500 &mut self,
14501 range_utf16: Option<Range<usize>>,
14502 text: &str,
14503 cx: &mut ViewContext<Self>,
14504 ) {
14505 if !self.input_enabled {
14506 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14507 return;
14508 }
14509
14510 self.transact(cx, |this, cx| {
14511 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14512 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14513 Some(this.selection_replacement_ranges(range_utf16, cx))
14514 } else {
14515 this.marked_text_ranges(cx)
14516 };
14517
14518 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14519 let newest_selection_id = this.selections.newest_anchor().id;
14520 this.selections
14521 .all::<OffsetUtf16>(cx)
14522 .iter()
14523 .zip(ranges_to_replace.iter())
14524 .find_map(|(selection, range)| {
14525 if selection.id == newest_selection_id {
14526 Some(
14527 (range.start.0 as isize - selection.head().0 as isize)
14528 ..(range.end.0 as isize - selection.head().0 as isize),
14529 )
14530 } else {
14531 None
14532 }
14533 })
14534 });
14535
14536 cx.emit(EditorEvent::InputHandled {
14537 utf16_range_to_replace: range_to_replace,
14538 text: text.into(),
14539 });
14540
14541 if let Some(new_selected_ranges) = new_selected_ranges {
14542 this.change_selections(None, cx, |selections| {
14543 selections.select_ranges(new_selected_ranges)
14544 });
14545 this.backspace(&Default::default(), cx);
14546 }
14547
14548 this.handle_input(text, cx);
14549 });
14550
14551 if let Some(transaction) = self.ime_transaction {
14552 self.buffer.update(cx, |buffer, cx| {
14553 buffer.group_until_transaction(transaction, cx);
14554 });
14555 }
14556
14557 self.unmark_text(cx);
14558 }
14559
14560 fn replace_and_mark_text_in_range(
14561 &mut self,
14562 range_utf16: Option<Range<usize>>,
14563 text: &str,
14564 new_selected_range_utf16: Option<Range<usize>>,
14565 cx: &mut ViewContext<Self>,
14566 ) {
14567 if !self.input_enabled {
14568 return;
14569 }
14570
14571 let transaction = self.transact(cx, |this, cx| {
14572 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14573 let snapshot = this.buffer.read(cx).read(cx);
14574 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14575 for marked_range in &mut marked_ranges {
14576 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14577 marked_range.start.0 += relative_range_utf16.start;
14578 marked_range.start =
14579 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14580 marked_range.end =
14581 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14582 }
14583 }
14584 Some(marked_ranges)
14585 } else if let Some(range_utf16) = range_utf16 {
14586 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14587 Some(this.selection_replacement_ranges(range_utf16, cx))
14588 } else {
14589 None
14590 };
14591
14592 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14593 let newest_selection_id = this.selections.newest_anchor().id;
14594 this.selections
14595 .all::<OffsetUtf16>(cx)
14596 .iter()
14597 .zip(ranges_to_replace.iter())
14598 .find_map(|(selection, range)| {
14599 if selection.id == newest_selection_id {
14600 Some(
14601 (range.start.0 as isize - selection.head().0 as isize)
14602 ..(range.end.0 as isize - selection.head().0 as isize),
14603 )
14604 } else {
14605 None
14606 }
14607 })
14608 });
14609
14610 cx.emit(EditorEvent::InputHandled {
14611 utf16_range_to_replace: range_to_replace,
14612 text: text.into(),
14613 });
14614
14615 if let Some(ranges) = ranges_to_replace {
14616 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14617 }
14618
14619 let marked_ranges = {
14620 let snapshot = this.buffer.read(cx).read(cx);
14621 this.selections
14622 .disjoint_anchors()
14623 .iter()
14624 .map(|selection| {
14625 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14626 })
14627 .collect::<Vec<_>>()
14628 };
14629
14630 if text.is_empty() {
14631 this.unmark_text(cx);
14632 } else {
14633 this.highlight_text::<InputComposition>(
14634 marked_ranges.clone(),
14635 HighlightStyle {
14636 underline: Some(UnderlineStyle {
14637 thickness: px(1.),
14638 color: None,
14639 wavy: false,
14640 }),
14641 ..Default::default()
14642 },
14643 cx,
14644 );
14645 }
14646
14647 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14648 let use_autoclose = this.use_autoclose;
14649 let use_auto_surround = this.use_auto_surround;
14650 this.set_use_autoclose(false);
14651 this.set_use_auto_surround(false);
14652 this.handle_input(text, cx);
14653 this.set_use_autoclose(use_autoclose);
14654 this.set_use_auto_surround(use_auto_surround);
14655
14656 if let Some(new_selected_range) = new_selected_range_utf16 {
14657 let snapshot = this.buffer.read(cx).read(cx);
14658 let new_selected_ranges = marked_ranges
14659 .into_iter()
14660 .map(|marked_range| {
14661 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14662 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14663 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14664 snapshot.clip_offset_utf16(new_start, Bias::Left)
14665 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14666 })
14667 .collect::<Vec<_>>();
14668
14669 drop(snapshot);
14670 this.change_selections(None, cx, |selections| {
14671 selections.select_ranges(new_selected_ranges)
14672 });
14673 }
14674 });
14675
14676 self.ime_transaction = self.ime_transaction.or(transaction);
14677 if let Some(transaction) = self.ime_transaction {
14678 self.buffer.update(cx, |buffer, cx| {
14679 buffer.group_until_transaction(transaction, cx);
14680 });
14681 }
14682
14683 if self.text_highlights::<InputComposition>(cx).is_none() {
14684 self.ime_transaction.take();
14685 }
14686 }
14687
14688 fn bounds_for_range(
14689 &mut self,
14690 range_utf16: Range<usize>,
14691 element_bounds: gpui::Bounds<Pixels>,
14692 cx: &mut ViewContext<Self>,
14693 ) -> Option<gpui::Bounds<Pixels>> {
14694 let text_layout_details = self.text_layout_details(cx);
14695 let gpui::Point {
14696 x: em_width,
14697 y: line_height,
14698 } = self.character_size(cx);
14699
14700 let snapshot = self.snapshot(cx);
14701 let scroll_position = snapshot.scroll_position();
14702 let scroll_left = scroll_position.x * em_width;
14703
14704 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14705 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14706 + self.gutter_dimensions.width
14707 + self.gutter_dimensions.margin;
14708 let y = line_height * (start.row().as_f32() - scroll_position.y);
14709
14710 Some(Bounds {
14711 origin: element_bounds.origin + point(x, y),
14712 size: size(em_width, line_height),
14713 })
14714 }
14715}
14716
14717trait SelectionExt {
14718 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14719 fn spanned_rows(
14720 &self,
14721 include_end_if_at_line_start: bool,
14722 map: &DisplaySnapshot,
14723 ) -> Range<MultiBufferRow>;
14724}
14725
14726impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14727 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14728 let start = self
14729 .start
14730 .to_point(&map.buffer_snapshot)
14731 .to_display_point(map);
14732 let end = self
14733 .end
14734 .to_point(&map.buffer_snapshot)
14735 .to_display_point(map);
14736 if self.reversed {
14737 end..start
14738 } else {
14739 start..end
14740 }
14741 }
14742
14743 fn spanned_rows(
14744 &self,
14745 include_end_if_at_line_start: bool,
14746 map: &DisplaySnapshot,
14747 ) -> Range<MultiBufferRow> {
14748 let start = self.start.to_point(&map.buffer_snapshot);
14749 let mut end = self.end.to_point(&map.buffer_snapshot);
14750 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14751 end.row -= 1;
14752 }
14753
14754 let buffer_start = map.prev_line_boundary(start).0;
14755 let buffer_end = map.next_line_boundary(end).0;
14756 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14757 }
14758}
14759
14760impl<T: InvalidationRegion> InvalidationStack<T> {
14761 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14762 where
14763 S: Clone + ToOffset,
14764 {
14765 while let Some(region) = self.last() {
14766 let all_selections_inside_invalidation_ranges =
14767 if selections.len() == region.ranges().len() {
14768 selections
14769 .iter()
14770 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14771 .all(|(selection, invalidation_range)| {
14772 let head = selection.head().to_offset(buffer);
14773 invalidation_range.start <= head && invalidation_range.end >= head
14774 })
14775 } else {
14776 false
14777 };
14778
14779 if all_selections_inside_invalidation_ranges {
14780 break;
14781 } else {
14782 self.pop();
14783 }
14784 }
14785 }
14786}
14787
14788impl<T> Default for InvalidationStack<T> {
14789 fn default() -> Self {
14790 Self(Default::default())
14791 }
14792}
14793
14794impl<T> Deref for InvalidationStack<T> {
14795 type Target = Vec<T>;
14796
14797 fn deref(&self) -> &Self::Target {
14798 &self.0
14799 }
14800}
14801
14802impl<T> DerefMut for InvalidationStack<T> {
14803 fn deref_mut(&mut self) -> &mut Self::Target {
14804 &mut self.0
14805 }
14806}
14807
14808impl InvalidationRegion for SnippetState {
14809 fn ranges(&self) -> &[Range<Anchor>] {
14810 &self.ranges[self.active_index]
14811 }
14812}
14813
14814pub fn diagnostic_block_renderer(
14815 diagnostic: Diagnostic,
14816 max_message_rows: Option<u8>,
14817 allow_closing: bool,
14818 _is_valid: bool,
14819) -> RenderBlock {
14820 let (text_without_backticks, code_ranges) =
14821 highlight_diagnostic_message(&diagnostic, max_message_rows);
14822
14823 Arc::new(move |cx: &mut BlockContext| {
14824 let group_id: SharedString = cx.block_id.to_string().into();
14825
14826 let mut text_style = cx.text_style().clone();
14827 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14828 let theme_settings = ThemeSettings::get_global(cx);
14829 text_style.font_family = theme_settings.buffer_font.family.clone();
14830 text_style.font_style = theme_settings.buffer_font.style;
14831 text_style.font_features = theme_settings.buffer_font.features.clone();
14832 text_style.font_weight = theme_settings.buffer_font.weight;
14833
14834 let multi_line_diagnostic = diagnostic.message.contains('\n');
14835
14836 let buttons = |diagnostic: &Diagnostic| {
14837 if multi_line_diagnostic {
14838 v_flex()
14839 } else {
14840 h_flex()
14841 }
14842 .when(allow_closing, |div| {
14843 div.children(diagnostic.is_primary.then(|| {
14844 IconButton::new("close-block", IconName::XCircle)
14845 .icon_color(Color::Muted)
14846 .size(ButtonSize::Compact)
14847 .style(ButtonStyle::Transparent)
14848 .visible_on_hover(group_id.clone())
14849 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14850 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14851 }))
14852 })
14853 .child(
14854 IconButton::new("copy-block", IconName::Copy)
14855 .icon_color(Color::Muted)
14856 .size(ButtonSize::Compact)
14857 .style(ButtonStyle::Transparent)
14858 .visible_on_hover(group_id.clone())
14859 .on_click({
14860 let message = diagnostic.message.clone();
14861 move |_click, cx| {
14862 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14863 }
14864 })
14865 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14866 )
14867 };
14868
14869 let icon_size = buttons(&diagnostic)
14870 .into_any_element()
14871 .layout_as_root(AvailableSpace::min_size(), cx);
14872
14873 h_flex()
14874 .id(cx.block_id)
14875 .group(group_id.clone())
14876 .relative()
14877 .size_full()
14878 .block_mouse_down()
14879 .pl(cx.gutter_dimensions.width)
14880 .w(cx.max_width - cx.gutter_dimensions.full_width())
14881 .child(
14882 div()
14883 .flex()
14884 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14885 .flex_shrink(),
14886 )
14887 .child(buttons(&diagnostic))
14888 .child(div().flex().flex_shrink_0().child(
14889 StyledText::new(text_without_backticks.clone()).with_highlights(
14890 &text_style,
14891 code_ranges.iter().map(|range| {
14892 (
14893 range.clone(),
14894 HighlightStyle {
14895 font_weight: Some(FontWeight::BOLD),
14896 ..Default::default()
14897 },
14898 )
14899 }),
14900 ),
14901 ))
14902 .into_any_element()
14903 })
14904}
14905
14906fn inline_completion_edit_text(
14907 editor_snapshot: &EditorSnapshot,
14908 edits: &Vec<(Range<Anchor>, String)>,
14909 include_deletions: bool,
14910 cx: &WindowContext,
14911) -> InlineCompletionText {
14912 let edit_start = edits
14913 .first()
14914 .unwrap()
14915 .0
14916 .start
14917 .to_display_point(editor_snapshot);
14918
14919 let mut text = String::new();
14920 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14921 let mut highlights = Vec::new();
14922 for (old_range, new_text) in edits {
14923 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14924 text.extend(
14925 editor_snapshot
14926 .buffer_snapshot
14927 .chunks(offset..old_offset_range.start, false)
14928 .map(|chunk| chunk.text),
14929 );
14930 offset = old_offset_range.end;
14931
14932 let start = text.len();
14933 let color = if include_deletions && new_text.is_empty() {
14934 text.extend(
14935 editor_snapshot
14936 .buffer_snapshot
14937 .chunks(old_offset_range.start..offset, false)
14938 .map(|chunk| chunk.text),
14939 );
14940 cx.theme().status().deleted_background
14941 } else {
14942 text.push_str(new_text);
14943 cx.theme().status().created_background
14944 };
14945 let end = text.len();
14946
14947 highlights.push((
14948 start..end,
14949 HighlightStyle {
14950 background_color: Some(color),
14951 ..Default::default()
14952 },
14953 ));
14954 }
14955
14956 let edit_end = edits
14957 .last()
14958 .unwrap()
14959 .0
14960 .end
14961 .to_display_point(editor_snapshot);
14962 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14963 .to_offset(editor_snapshot, Bias::Right);
14964 text.extend(
14965 editor_snapshot
14966 .buffer_snapshot
14967 .chunks(offset..end_of_line, false)
14968 .map(|chunk| chunk.text),
14969 );
14970
14971 InlineCompletionText::Edit {
14972 text: text.into(),
14973 highlights,
14974 }
14975}
14976
14977pub fn highlight_diagnostic_message(
14978 diagnostic: &Diagnostic,
14979 mut max_message_rows: Option<u8>,
14980) -> (SharedString, Vec<Range<usize>>) {
14981 let mut text_without_backticks = String::new();
14982 let mut code_ranges = Vec::new();
14983
14984 if let Some(source) = &diagnostic.source {
14985 text_without_backticks.push_str(source);
14986 code_ranges.push(0..source.len());
14987 text_without_backticks.push_str(": ");
14988 }
14989
14990 let mut prev_offset = 0;
14991 let mut in_code_block = false;
14992 let has_row_limit = max_message_rows.is_some();
14993 let mut newline_indices = diagnostic
14994 .message
14995 .match_indices('\n')
14996 .filter(|_| has_row_limit)
14997 .map(|(ix, _)| ix)
14998 .fuse()
14999 .peekable();
15000
15001 for (quote_ix, _) in diagnostic
15002 .message
15003 .match_indices('`')
15004 .chain([(diagnostic.message.len(), "")])
15005 {
15006 let mut first_newline_ix = None;
15007 let mut last_newline_ix = None;
15008 while let Some(newline_ix) = newline_indices.peek() {
15009 if *newline_ix < quote_ix {
15010 if first_newline_ix.is_none() {
15011 first_newline_ix = Some(*newline_ix);
15012 }
15013 last_newline_ix = Some(*newline_ix);
15014
15015 if let Some(rows_left) = &mut max_message_rows {
15016 if *rows_left == 0 {
15017 break;
15018 } else {
15019 *rows_left -= 1;
15020 }
15021 }
15022 let _ = newline_indices.next();
15023 } else {
15024 break;
15025 }
15026 }
15027 let prev_len = text_without_backticks.len();
15028 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15029 text_without_backticks.push_str(new_text);
15030 if in_code_block {
15031 code_ranges.push(prev_len..text_without_backticks.len());
15032 }
15033 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15034 in_code_block = !in_code_block;
15035 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15036 text_without_backticks.push_str("...");
15037 break;
15038 }
15039 }
15040
15041 (text_without_backticks.into(), code_ranges)
15042}
15043
15044fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15045 match severity {
15046 DiagnosticSeverity::ERROR => colors.error,
15047 DiagnosticSeverity::WARNING => colors.warning,
15048 DiagnosticSeverity::INFORMATION => colors.info,
15049 DiagnosticSeverity::HINT => colors.info,
15050 _ => colors.ignored,
15051 }
15052}
15053
15054pub fn styled_runs_for_code_label<'a>(
15055 label: &'a CodeLabel,
15056 syntax_theme: &'a theme::SyntaxTheme,
15057) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15058 let fade_out = HighlightStyle {
15059 fade_out: Some(0.35),
15060 ..Default::default()
15061 };
15062
15063 let mut prev_end = label.filter_range.end;
15064 label
15065 .runs
15066 .iter()
15067 .enumerate()
15068 .flat_map(move |(ix, (range, highlight_id))| {
15069 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15070 style
15071 } else {
15072 return Default::default();
15073 };
15074 let mut muted_style = style;
15075 muted_style.highlight(fade_out);
15076
15077 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15078 if range.start >= label.filter_range.end {
15079 if range.start > prev_end {
15080 runs.push((prev_end..range.start, fade_out));
15081 }
15082 runs.push((range.clone(), muted_style));
15083 } else if range.end <= label.filter_range.end {
15084 runs.push((range.clone(), style));
15085 } else {
15086 runs.push((range.start..label.filter_range.end, style));
15087 runs.push((label.filter_range.end..range.end, muted_style));
15088 }
15089 prev_end = cmp::max(prev_end, range.end);
15090
15091 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15092 runs.push((prev_end..label.text.len(), fade_out));
15093 }
15094
15095 runs
15096 })
15097}
15098
15099pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15100 let mut prev_index = 0;
15101 let mut prev_codepoint: Option<char> = None;
15102 text.char_indices()
15103 .chain([(text.len(), '\0')])
15104 .filter_map(move |(index, codepoint)| {
15105 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15106 let is_boundary = index == text.len()
15107 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15108 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15109 if is_boundary {
15110 let chunk = &text[prev_index..index];
15111 prev_index = index;
15112 Some(chunk)
15113 } else {
15114 None
15115 }
15116 })
15117}
15118
15119pub trait RangeToAnchorExt: Sized {
15120 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15121
15122 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15123 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15124 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15125 }
15126}
15127
15128impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15129 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15130 let start_offset = self.start.to_offset(snapshot);
15131 let end_offset = self.end.to_offset(snapshot);
15132 if start_offset == end_offset {
15133 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15134 } else {
15135 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15136 }
15137 }
15138}
15139
15140pub trait RowExt {
15141 fn as_f32(&self) -> f32;
15142
15143 fn next_row(&self) -> Self;
15144
15145 fn previous_row(&self) -> Self;
15146
15147 fn minus(&self, other: Self) -> u32;
15148}
15149
15150impl RowExt for DisplayRow {
15151 fn as_f32(&self) -> f32 {
15152 self.0 as f32
15153 }
15154
15155 fn next_row(&self) -> Self {
15156 Self(self.0 + 1)
15157 }
15158
15159 fn previous_row(&self) -> Self {
15160 Self(self.0.saturating_sub(1))
15161 }
15162
15163 fn minus(&self, other: Self) -> u32 {
15164 self.0 - other.0
15165 }
15166}
15167
15168impl RowExt for MultiBufferRow {
15169 fn as_f32(&self) -> f32 {
15170 self.0 as f32
15171 }
15172
15173 fn next_row(&self) -> Self {
15174 Self(self.0 + 1)
15175 }
15176
15177 fn previous_row(&self) -> Self {
15178 Self(self.0.saturating_sub(1))
15179 }
15180
15181 fn minus(&self, other: Self) -> u32 {
15182 self.0 - other.0
15183 }
15184}
15185
15186trait RowRangeExt {
15187 type Row;
15188
15189 fn len(&self) -> usize;
15190
15191 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15192}
15193
15194impl RowRangeExt for Range<MultiBufferRow> {
15195 type Row = MultiBufferRow;
15196
15197 fn len(&self) -> usize {
15198 (self.end.0 - self.start.0) as usize
15199 }
15200
15201 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15202 (self.start.0..self.end.0).map(MultiBufferRow)
15203 }
15204}
15205
15206impl RowRangeExt for Range<DisplayRow> {
15207 type Row = DisplayRow;
15208
15209 fn len(&self) -> usize {
15210 (self.end.0 - self.start.0) as usize
15211 }
15212
15213 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15214 (self.start.0..self.end.0).map(DisplayRow)
15215 }
15216}
15217
15218fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15219 if hunk.diff_base_byte_range.is_empty() {
15220 DiffHunkStatus::Added
15221 } else if hunk.row_range.is_empty() {
15222 DiffHunkStatus::Removed
15223 } else {
15224 DiffHunkStatus::Modified
15225 }
15226}
15227
15228/// If select range has more than one line, we
15229/// just point the cursor to range.start.
15230fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15231 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15232 range
15233 } else {
15234 range.start..range.start
15235 }
15236}
15237
15238pub struct KillRing(ClipboardItem);
15239impl Global for KillRing {}
15240
15241const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);