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;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
103 Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{
163 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
164 ThemeColors, ThemeSettings,
165};
166use ui::{
167 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
168 PopoverMenuHandle, Tooltip,
169};
170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
171use workspace::item::{ItemHandle, PreviewTabsSettings};
172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
173use workspace::{
174 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
175};
176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
177
178use crate::hover_links::{find_url, find_url_from_range};
179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
180
181pub const FILE_HEADER_HEIGHT: u32 = 2;
182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
186const MAX_LINE_LEN: usize = 1024;
187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
190#[doc(hidden)]
191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
192
193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
195
196pub fn render_parsed_markdown(
197 element_id: impl Into<ElementId>,
198 parsed: &language::ParsedMarkdown,
199 editor_style: &EditorStyle,
200 workspace: Option<WeakView<Workspace>>,
201 cx: &mut WindowContext,
202) -> InteractiveText {
203 let code_span_background_color = cx
204 .theme()
205 .colors()
206 .editor_document_highlight_read_background;
207
208 let highlights = gpui::combine_highlights(
209 parsed.highlights.iter().filter_map(|(range, highlight)| {
210 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
211 Some((range.clone(), highlight))
212 }),
213 parsed
214 .regions
215 .iter()
216 .zip(&parsed.region_ranges)
217 .filter_map(|(region, range)| {
218 if region.code {
219 Some((
220 range.clone(),
221 HighlightStyle {
222 background_color: Some(code_span_background_color),
223 ..Default::default()
224 },
225 ))
226 } else {
227 None
228 }
229 }),
230 );
231
232 let mut links = Vec::new();
233 let mut link_ranges = Vec::new();
234 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
235 if let Some(link) = region.link.clone() {
236 links.push(link);
237 link_ranges.push(range.clone());
238 }
239 }
240
241 InteractiveText::new(
242 element_id,
243 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
244 )
245 .on_click(link_ranges, move |clicked_range_ix, cx| {
246 match &links[clicked_range_ix] {
247 markdown::Link::Web { url } => cx.open_url(url),
248 markdown::Link::Path { path } => {
249 if let Some(workspace) = &workspace {
250 _ = workspace.update(cx, |workspace, cx| {
251 workspace.open_abs_path(path.clone(), false, cx).detach();
252 });
253 }
254 }
255 }
256 })
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
260pub(crate) enum InlayId {
261 InlineCompletion(usize),
262 Hint(usize),
263}
264
265impl InlayId {
266 fn id(&self) -> usize {
267 match self {
268 Self::InlineCompletion(id) => *id,
269 Self::Hint(id) => *id,
270 }
271 }
272}
273
274enum DiffRowHighlight {}
275enum DocumentHighlightRead {}
276enum DocumentHighlightWrite {}
277enum InputComposition {}
278
279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
280pub enum Navigated {
281 Yes,
282 No,
283}
284
285impl Navigated {
286 pub fn from_bool(yes: bool) -> Navigated {
287 if yes {
288 Navigated::Yes
289 } else {
290 Navigated::No
291 }
292 }
293}
294
295pub fn init_settings(cx: &mut AppContext) {
296 EditorSettings::register(cx);
297}
298
299pub fn init(cx: &mut AppContext) {
300 init_settings(cx);
301
302 workspace::register_project_item::<Editor>(cx);
303 workspace::FollowableViewRegistry::register::<Editor>(cx);
304 workspace::register_serializable_item::<Editor>(cx);
305
306 cx.observe_new_views(
307 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
308 workspace.register_action(Editor::new_file);
309 workspace.register_action(Editor::new_file_vertical);
310 workspace.register_action(Editor::new_file_horizontal);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324 cx.on_action(move |_: &workspace::NewWindow, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
328 Editor::new_file(workspace, &Default::default(), cx)
329 })
330 .detach();
331 }
332 });
333 git::project_diff::init(cx);
334}
335
336pub struct SearchWithinRange;
337
338trait InvalidationRegion {
339 fn ranges(&self) -> &[Range<Anchor>];
340}
341
342#[derive(Clone, Debug, PartialEq)]
343pub enum SelectPhase {
344 Begin {
345 position: DisplayPoint,
346 add: bool,
347 click_count: usize,
348 },
349 BeginColumnar {
350 position: DisplayPoint,
351 reset: bool,
352 goal_column: u32,
353 },
354 Extend {
355 position: DisplayPoint,
356 click_count: usize,
357 },
358 Update {
359 position: DisplayPoint,
360 goal_column: u32,
361 scroll_delta: gpui::Point<f32>,
362 },
363 End,
364}
365
366#[derive(Clone, Debug)]
367pub enum SelectMode {
368 Character,
369 Word(Range<Anchor>),
370 Line(Range<Anchor>),
371 All,
372}
373
374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
375pub enum EditorMode {
376 SingleLine { auto_width: bool },
377 AutoHeight { max_lines: usize },
378 Full,
379}
380
381#[derive(Copy, Clone, Debug)]
382pub enum SoftWrap {
383 /// Prefer not to wrap at all.
384 ///
385 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
386 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
387 GitDiff,
388 /// Prefer a single line generally, unless an overly long line is encountered.
389 None,
390 /// Soft wrap lines that exceed the editor width.
391 EditorWidth,
392 /// Soft wrap lines at the preferred line length.
393 Column(u32),
394 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
395 Bounded(u32),
396}
397
398#[derive(Clone)]
399pub struct EditorStyle {
400 pub background: Hsla,
401 pub local_player: PlayerColor,
402 pub text: TextStyle,
403 pub scrollbar_width: Pixels,
404 pub syntax: Arc<SyntaxTheme>,
405 pub status: StatusColors,
406 pub inlay_hints_style: HighlightStyle,
407 pub inline_completion_styles: InlineCompletionStyles,
408 pub unnecessary_code_fade: f32,
409}
410
411impl Default for EditorStyle {
412 fn default() -> Self {
413 Self {
414 background: Hsla::default(),
415 local_player: PlayerColor::default(),
416 text: TextStyle::default(),
417 scrollbar_width: Pixels::default(),
418 syntax: Default::default(),
419 // HACK: Status colors don't have a real default.
420 // We should look into removing the status colors from the editor
421 // style and retrieve them directly from the theme.
422 status: StatusColors::dark(),
423 inlay_hints_style: HighlightStyle::default(),
424 inline_completion_styles: InlineCompletionStyles {
425 insertion: HighlightStyle::default(),
426 whitespace: HighlightStyle::default(),
427 },
428 unnecessary_code_fade: Default::default(),
429 }
430 }
431}
432
433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
434 let show_background = language_settings::language_settings(None, None, cx)
435 .inlay_hints
436 .show_background;
437
438 HighlightStyle {
439 color: Some(cx.theme().status().hint),
440 background_color: show_background.then(|| cx.theme().status().hint_background),
441 ..HighlightStyle::default()
442 }
443}
444
445pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
446 InlineCompletionStyles {
447 insertion: HighlightStyle {
448 color: Some(cx.theme().status().predictive),
449 ..HighlightStyle::default()
450 },
451 whitespace: HighlightStyle {
452 background_color: Some(cx.theme().status().created_background),
453 ..HighlightStyle::default()
454 },
455 }
456}
457
458type CompletionId = usize;
459
460#[derive(Debug, Clone)]
461struct InlineCompletionMenuHint {
462 provider_name: &'static str,
463 text: InlineCompletionText,
464}
465
466#[derive(Clone, Debug)]
467enum InlineCompletionText {
468 Move(SharedString),
469 Edit {
470 text: SharedString,
471 highlights: Vec<(Range<usize>, HighlightStyle)>,
472 },
473}
474
475enum InlineCompletion {
476 Edit(Vec<(Range<Anchor>, String)>),
477 Move(Anchor),
478}
479
480struct InlineCompletionState {
481 inlay_ids: Vec<InlayId>,
482 completion: InlineCompletion,
483 invalidation_range: Range<Anchor>,
484}
485
486enum InlineCompletionHighlight {}
487
488#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
489struct EditorActionId(usize);
490
491impl EditorActionId {
492 pub fn post_inc(&mut self) -> Self {
493 let answer = self.0;
494
495 *self = Self(answer + 1);
496
497 Self(answer)
498 }
499}
500
501// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
502// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
503
504type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
505type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
506
507#[derive(Default)]
508struct ScrollbarMarkerState {
509 scrollbar_size: Size<Pixels>,
510 dirty: bool,
511 markers: Arc<[PaintQuad]>,
512 pending_refresh: Option<Task<Result<()>>>,
513}
514
515impl ScrollbarMarkerState {
516 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
517 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
518 }
519}
520
521#[derive(Clone, Debug)]
522struct RunnableTasks {
523 templates: Vec<(TaskSourceKind, TaskTemplate)>,
524 offset: MultiBufferOffset,
525 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
526 column: u32,
527 // Values of all named captures, including those starting with '_'
528 extra_variables: HashMap<String, String>,
529 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
530 context_range: Range<BufferOffset>,
531}
532
533impl RunnableTasks {
534 fn resolve<'a>(
535 &'a self,
536 cx: &'a task::TaskContext,
537 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
538 self.templates.iter().filter_map(|(kind, template)| {
539 template
540 .resolve_task(&kind.to_id_base(), cx)
541 .map(|task| (kind.clone(), task))
542 })
543 }
544}
545
546#[derive(Clone)]
547struct ResolvedTasks {
548 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
549 position: Anchor,
550}
551#[derive(Copy, Clone, Debug)]
552struct MultiBufferOffset(usize);
553#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
554struct BufferOffset(usize);
555
556// Addons allow storing per-editor state in other crates (e.g. Vim)
557pub trait Addon: 'static {
558 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
559
560 fn to_any(&self) -> &dyn std::any::Any;
561}
562
563#[derive(Debug, Copy, Clone, PartialEq, Eq)]
564pub enum IsVimMode {
565 Yes,
566 No,
567}
568
569/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
570///
571/// See the [module level documentation](self) for more information.
572pub struct Editor {
573 focus_handle: FocusHandle,
574 last_focused_descendant: Option<WeakFocusHandle>,
575 /// The text buffer being edited
576 buffer: Model<MultiBuffer>,
577 /// Map of how text in the buffer should be displayed.
578 /// Handles soft wraps, folds, fake inlay text insertions, etc.
579 pub display_map: Model<DisplayMap>,
580 pub selections: SelectionsCollection,
581 pub scroll_manager: ScrollManager,
582 /// When inline assist editors are linked, they all render cursors because
583 /// typing enters text into each of them, even the ones that aren't focused.
584 pub(crate) show_cursor_when_unfocused: bool,
585 columnar_selection_tail: Option<Anchor>,
586 add_selections_state: Option<AddSelectionsState>,
587 select_next_state: Option<SelectNextState>,
588 select_prev_state: Option<SelectNextState>,
589 selection_history: SelectionHistory,
590 autoclose_regions: Vec<AutocloseRegion>,
591 snippet_stack: InvalidationStack<SnippetState>,
592 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
593 ime_transaction: Option<TransactionId>,
594 active_diagnostics: Option<ActiveDiagnosticGroup>,
595 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
596
597 project: Option<Model<Project>>,
598 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
599 completion_provider: Option<Box<dyn CompletionProvider>>,
600 collaboration_hub: Option<Box<dyn CollaborationHub>>,
601 blink_manager: Model<BlinkManager>,
602 show_cursor_names: bool,
603 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
604 pub show_local_selections: bool,
605 mode: EditorMode,
606 show_breadcrumbs: bool,
607 show_gutter: bool,
608 show_line_numbers: Option<bool>,
609 use_relative_line_numbers: Option<bool>,
610 show_git_diff_gutter: Option<bool>,
611 show_code_actions: Option<bool>,
612 show_runnables: Option<bool>,
613 show_wrap_guides: Option<bool>,
614 show_indent_guides: Option<bool>,
615 placeholder_text: Option<Arc<str>>,
616 highlight_order: usize,
617 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
618 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
619 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
620 scrollbar_marker_state: ScrollbarMarkerState,
621 active_indent_guides_state: ActiveIndentGuidesState,
622 nav_history: Option<ItemNavHistory>,
623 context_menu: RefCell<Option<CodeContextMenu>>,
624 mouse_context_menu: Option<MouseContextMenu>,
625 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
626 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
627 signature_help_state: SignatureHelpState,
628 auto_signature_help: Option<bool>,
629 find_all_references_task_sources: Vec<Anchor>,
630 next_completion_id: CompletionId,
631 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
632 code_actions_task: Option<Task<Result<()>>>,
633 document_highlights_task: Option<Task<()>>,
634 linked_editing_range_task: Option<Task<Option<()>>>,
635 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
636 pending_rename: Option<RenameState>,
637 searchable: bool,
638 cursor_shape: CursorShape,
639 current_line_highlight: Option<CurrentLineHighlight>,
640 collapse_matches: bool,
641 autoindent_mode: Option<AutoindentMode>,
642 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
643 input_enabled: bool,
644 use_modal_editing: bool,
645 read_only: bool,
646 leader_peer_id: Option<PeerId>,
647 remote_id: Option<ViewId>,
648 hover_state: HoverState,
649 gutter_hovered: bool,
650 hovered_link_state: Option<HoveredLinkState>,
651 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
652 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
653 active_inline_completion: Option<InlineCompletionState>,
654 // enable_inline_completions is a switch that Vim can use to disable
655 // inline completions based on its mode.
656 enable_inline_completions: bool,
657 show_inline_completions_override: Option<bool>,
658 inlay_hint_cache: InlayHintCache,
659 diff_map: DiffMap,
660 next_inlay_id: usize,
661 _subscriptions: Vec<Subscription>,
662 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
663 gutter_dimensions: GutterDimensions,
664 style: Option<EditorStyle>,
665 text_style_refinement: Option<TextStyleRefinement>,
666 next_editor_action_id: EditorActionId,
667 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
668 use_autoclose: bool,
669 use_auto_surround: bool,
670 auto_replace_emoji_shortcode: bool,
671 show_git_blame_gutter: bool,
672 show_git_blame_inline: bool,
673 show_git_blame_inline_delay_task: Option<Task<()>>,
674 git_blame_inline_enabled: bool,
675 serialize_dirty_buffers: bool,
676 show_selection_menu: Option<bool>,
677 blame: Option<Model<GitBlame>>,
678 blame_subscription: Option<Subscription>,
679 custom_context_menu: Option<
680 Box<
681 dyn 'static
682 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
683 >,
684 >,
685 last_bounds: Option<Bounds<Pixels>>,
686 expect_bounds_change: Option<Bounds<Pixels>>,
687 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
688 tasks_update_task: Option<Task<()>>,
689 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
690 breadcrumb_header: Option<String>,
691 focused_block: Option<FocusedBlock>,
692 next_scroll_position: NextScrollCursorCenterTopBottom,
693 addons: HashMap<TypeId, Box<dyn Addon>>,
694 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
695 toggle_fold_multiple_buffers: Task<()>,
696 _scroll_cursor_center_top_bottom_task: Task<()>,
697}
698
699#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
700enum NextScrollCursorCenterTopBottom {
701 #[default]
702 Center,
703 Top,
704 Bottom,
705}
706
707impl NextScrollCursorCenterTopBottom {
708 fn next(&self) -> Self {
709 match self {
710 Self::Center => Self::Top,
711 Self::Top => Self::Bottom,
712 Self::Bottom => Self::Center,
713 }
714 }
715}
716
717#[derive(Clone)]
718pub struct EditorSnapshot {
719 pub mode: EditorMode,
720 show_gutter: bool,
721 show_line_numbers: Option<bool>,
722 show_git_diff_gutter: Option<bool>,
723 show_code_actions: Option<bool>,
724 show_runnables: Option<bool>,
725 git_blame_gutter_max_author_length: Option<usize>,
726 pub display_snapshot: DisplaySnapshot,
727 pub placeholder_text: Option<Arc<str>>,
728 diff_map: DiffMapSnapshot,
729 is_focused: bool,
730 scroll_anchor: ScrollAnchor,
731 ongoing_scroll: OngoingScroll,
732 current_line_highlight: CurrentLineHighlight,
733 gutter_hovered: bool,
734}
735
736const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
737
738#[derive(Default, Debug, Clone, Copy)]
739pub struct GutterDimensions {
740 pub left_padding: Pixels,
741 pub right_padding: Pixels,
742 pub width: Pixels,
743 pub margin: Pixels,
744 pub git_blame_entries_width: Option<Pixels>,
745}
746
747impl GutterDimensions {
748 /// The full width of the space taken up by the gutter.
749 pub fn full_width(&self) -> Pixels {
750 self.margin + self.width
751 }
752
753 /// The width of the space reserved for the fold indicators,
754 /// use alongside 'justify_end' and `gutter_width` to
755 /// right align content with the line numbers
756 pub fn fold_area_width(&self) -> Pixels {
757 self.margin + self.right_padding
758 }
759}
760
761#[derive(Debug)]
762pub struct RemoteSelection {
763 pub replica_id: ReplicaId,
764 pub selection: Selection<Anchor>,
765 pub cursor_shape: CursorShape,
766 pub peer_id: PeerId,
767 pub line_mode: bool,
768 pub participant_index: Option<ParticipantIndex>,
769 pub user_name: Option<SharedString>,
770}
771
772#[derive(Clone, Debug)]
773struct SelectionHistoryEntry {
774 selections: Arc<[Selection<Anchor>]>,
775 select_next_state: Option<SelectNextState>,
776 select_prev_state: Option<SelectNextState>,
777 add_selections_state: Option<AddSelectionsState>,
778}
779
780enum SelectionHistoryMode {
781 Normal,
782 Undoing,
783 Redoing,
784}
785
786#[derive(Clone, PartialEq, Eq, Hash)]
787struct HoveredCursor {
788 replica_id: u16,
789 selection_id: usize,
790}
791
792impl Default for SelectionHistoryMode {
793 fn default() -> Self {
794 Self::Normal
795 }
796}
797
798#[derive(Default)]
799struct SelectionHistory {
800 #[allow(clippy::type_complexity)]
801 selections_by_transaction:
802 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
803 mode: SelectionHistoryMode,
804 undo_stack: VecDeque<SelectionHistoryEntry>,
805 redo_stack: VecDeque<SelectionHistoryEntry>,
806}
807
808impl SelectionHistory {
809 fn insert_transaction(
810 &mut self,
811 transaction_id: TransactionId,
812 selections: Arc<[Selection<Anchor>]>,
813 ) {
814 self.selections_by_transaction
815 .insert(transaction_id, (selections, None));
816 }
817
818 #[allow(clippy::type_complexity)]
819 fn transaction(
820 &self,
821 transaction_id: TransactionId,
822 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
823 self.selections_by_transaction.get(&transaction_id)
824 }
825
826 #[allow(clippy::type_complexity)]
827 fn transaction_mut(
828 &mut self,
829 transaction_id: TransactionId,
830 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
831 self.selections_by_transaction.get_mut(&transaction_id)
832 }
833
834 fn push(&mut self, entry: SelectionHistoryEntry) {
835 if !entry.selections.is_empty() {
836 match self.mode {
837 SelectionHistoryMode::Normal => {
838 self.push_undo(entry);
839 self.redo_stack.clear();
840 }
841 SelectionHistoryMode::Undoing => self.push_redo(entry),
842 SelectionHistoryMode::Redoing => self.push_undo(entry),
843 }
844 }
845 }
846
847 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
848 if self
849 .undo_stack
850 .back()
851 .map_or(true, |e| e.selections != entry.selections)
852 {
853 self.undo_stack.push_back(entry);
854 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
855 self.undo_stack.pop_front();
856 }
857 }
858 }
859
860 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
861 if self
862 .redo_stack
863 .back()
864 .map_or(true, |e| e.selections != entry.selections)
865 {
866 self.redo_stack.push_back(entry);
867 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
868 self.redo_stack.pop_front();
869 }
870 }
871 }
872}
873
874struct RowHighlight {
875 index: usize,
876 range: Range<Anchor>,
877 color: Hsla,
878 should_autoscroll: bool,
879}
880
881#[derive(Clone, Debug)]
882struct AddSelectionsState {
883 above: bool,
884 stack: Vec<usize>,
885}
886
887#[derive(Clone)]
888struct SelectNextState {
889 query: AhoCorasick,
890 wordwise: bool,
891 done: bool,
892}
893
894impl std::fmt::Debug for SelectNextState {
895 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
896 f.debug_struct(std::any::type_name::<Self>())
897 .field("wordwise", &self.wordwise)
898 .field("done", &self.done)
899 .finish()
900 }
901}
902
903#[derive(Debug)]
904struct AutocloseRegion {
905 selection_id: usize,
906 range: Range<Anchor>,
907 pair: BracketPair,
908}
909
910#[derive(Debug)]
911struct SnippetState {
912 ranges: Vec<Vec<Range<Anchor>>>,
913 active_index: usize,
914 choices: Vec<Option<Vec<String>>>,
915}
916
917#[doc(hidden)]
918pub struct RenameState {
919 pub range: Range<Anchor>,
920 pub old_name: Arc<str>,
921 pub editor: View<Editor>,
922 block_id: CustomBlockId,
923}
924
925struct InvalidationStack<T>(Vec<T>);
926
927struct RegisteredInlineCompletionProvider {
928 provider: Arc<dyn InlineCompletionProviderHandle>,
929 _subscription: Subscription,
930}
931
932#[derive(Debug)]
933struct ActiveDiagnosticGroup {
934 primary_range: Range<Anchor>,
935 primary_message: String,
936 group_id: usize,
937 blocks: HashMap<CustomBlockId, Diagnostic>,
938 is_valid: bool,
939}
940
941#[derive(Serialize, Deserialize, Clone, Debug)]
942pub struct ClipboardSelection {
943 pub len: usize,
944 pub is_entire_line: bool,
945 pub first_line_indent: u32,
946}
947
948#[derive(Debug)]
949pub(crate) struct NavigationData {
950 cursor_anchor: Anchor,
951 cursor_position: Point,
952 scroll_anchor: ScrollAnchor,
953 scroll_top_row: u32,
954}
955
956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957pub enum GotoDefinitionKind {
958 Symbol,
959 Declaration,
960 Type,
961 Implementation,
962}
963
964#[derive(Debug, Clone)]
965enum InlayHintRefreshReason {
966 Toggle(bool),
967 SettingsChange(InlayHintSettings),
968 NewLinesShown,
969 BufferEdited(HashSet<Arc<Language>>),
970 RefreshRequested,
971 ExcerptsRemoved(Vec<ExcerptId>),
972}
973
974impl InlayHintRefreshReason {
975 fn description(&self) -> &'static str {
976 match self {
977 Self::Toggle(_) => "toggle",
978 Self::SettingsChange(_) => "settings change",
979 Self::NewLinesShown => "new lines shown",
980 Self::BufferEdited(_) => "buffer edited",
981 Self::RefreshRequested => "refresh requested",
982 Self::ExcerptsRemoved(_) => "excerpts removed",
983 }
984 }
985}
986
987pub(crate) struct FocusedBlock {
988 id: BlockId,
989 focus_handle: WeakFocusHandle,
990}
991
992#[derive(Clone)]
993struct JumpData {
994 excerpt_id: ExcerptId,
995 position: Point,
996 anchor: text::Anchor,
997 path: Option<project::ProjectPath>,
998 line_offset_from_top: u32,
999}
1000
1001impl Editor {
1002 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1003 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1004 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1005 Self::new(
1006 EditorMode::SingleLine { auto_width: false },
1007 buffer,
1008 None,
1009 false,
1010 cx,
1011 )
1012 }
1013
1014 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1015 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1016 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1017 Self::new(EditorMode::Full, buffer, None, false, cx)
1018 }
1019
1020 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1021 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1022 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1023 Self::new(
1024 EditorMode::SingleLine { auto_width: true },
1025 buffer,
1026 None,
1027 false,
1028 cx,
1029 )
1030 }
1031
1032 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1033 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1034 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1035 Self::new(
1036 EditorMode::AutoHeight { max_lines },
1037 buffer,
1038 None,
1039 false,
1040 cx,
1041 )
1042 }
1043
1044 pub fn for_buffer(
1045 buffer: Model<Buffer>,
1046 project: Option<Model<Project>>,
1047 cx: &mut ViewContext<Self>,
1048 ) -> Self {
1049 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1050 Self::new(EditorMode::Full, buffer, project, false, cx)
1051 }
1052
1053 pub fn for_multibuffer(
1054 buffer: Model<MultiBuffer>,
1055 project: Option<Model<Project>>,
1056 show_excerpt_controls: bool,
1057 cx: &mut ViewContext<Self>,
1058 ) -> Self {
1059 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1060 }
1061
1062 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1063 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1064 let mut clone = Self::new(
1065 self.mode,
1066 self.buffer.clone(),
1067 self.project.clone(),
1068 show_excerpt_controls,
1069 cx,
1070 );
1071 self.display_map.update(cx, |display_map, cx| {
1072 let snapshot = display_map.snapshot(cx);
1073 clone.display_map.update(cx, |display_map, cx| {
1074 display_map.set_state(&snapshot, cx);
1075 });
1076 });
1077 clone.selections.clone_state(&self.selections);
1078 clone.scroll_manager.clone_state(&self.scroll_manager);
1079 clone.searchable = self.searchable;
1080 clone
1081 }
1082
1083 pub fn new(
1084 mode: EditorMode,
1085 buffer: Model<MultiBuffer>,
1086 project: Option<Model<Project>>,
1087 show_excerpt_controls: bool,
1088 cx: &mut ViewContext<Self>,
1089 ) -> Self {
1090 let style = cx.text_style();
1091 let font_size = style.font_size.to_pixels(cx.rem_size());
1092 let editor = cx.view().downgrade();
1093 let fold_placeholder = FoldPlaceholder {
1094 constrain_width: true,
1095 render: Arc::new(move |fold_id, fold_range, cx| {
1096 let editor = editor.clone();
1097 div()
1098 .id(fold_id)
1099 .bg(cx.theme().colors().ghost_element_background)
1100 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1101 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1102 .rounded_sm()
1103 .size_full()
1104 .cursor_pointer()
1105 .child("⋯")
1106 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1107 .on_click(move |_, cx| {
1108 editor
1109 .update(cx, |editor, cx| {
1110 editor.unfold_ranges(
1111 &[fold_range.start..fold_range.end],
1112 true,
1113 false,
1114 cx,
1115 );
1116 cx.stop_propagation();
1117 })
1118 .ok();
1119 })
1120 .into_any()
1121 }),
1122 merge_adjacent: true,
1123 ..Default::default()
1124 };
1125 let display_map = cx.new_model(|cx| {
1126 DisplayMap::new(
1127 buffer.clone(),
1128 style.font(),
1129 font_size,
1130 None,
1131 show_excerpt_controls,
1132 FILE_HEADER_HEIGHT,
1133 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1134 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1135 fold_placeholder,
1136 cx,
1137 )
1138 });
1139
1140 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1141
1142 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1143
1144 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1145 .then(|| language_settings::SoftWrap::None);
1146
1147 let mut project_subscriptions = Vec::new();
1148 if mode == EditorMode::Full {
1149 if let Some(project) = project.as_ref() {
1150 if buffer.read(cx).is_singleton() {
1151 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1152 cx.emit(EditorEvent::TitleChanged);
1153 }));
1154 }
1155 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1156 if let project::Event::RefreshInlayHints = event {
1157 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1158 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1159 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1160 let focus_handle = editor.focus_handle(cx);
1161 if focus_handle.is_focused(cx) {
1162 let snapshot = buffer.read(cx).snapshot();
1163 for (range, snippet) in snippet_edits {
1164 let editor_range =
1165 language::range_from_lsp(*range).to_offset(&snapshot);
1166 editor
1167 .insert_snippet(&[editor_range], snippet.clone(), cx)
1168 .ok();
1169 }
1170 }
1171 }
1172 }
1173 }));
1174 if let Some(task_inventory) = project
1175 .read(cx)
1176 .task_store()
1177 .read(cx)
1178 .task_inventory()
1179 .cloned()
1180 {
1181 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1182 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1183 }));
1184 }
1185 }
1186 }
1187
1188 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1189
1190 let inlay_hint_settings =
1191 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1192 let focus_handle = cx.focus_handle();
1193 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1194 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1195 .detach();
1196 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1197 .detach();
1198 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1199
1200 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1201 Some(false)
1202 } else {
1203 None
1204 };
1205
1206 let mut code_action_providers = Vec::new();
1207 if let Some(project) = project.clone() {
1208 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1209 code_action_providers.push(Rc::new(project) as Rc<_>);
1210 }
1211
1212 let mut this = Self {
1213 focus_handle,
1214 show_cursor_when_unfocused: false,
1215 last_focused_descendant: None,
1216 buffer: buffer.clone(),
1217 display_map: display_map.clone(),
1218 selections,
1219 scroll_manager: ScrollManager::new(cx),
1220 columnar_selection_tail: None,
1221 add_selections_state: None,
1222 select_next_state: None,
1223 select_prev_state: None,
1224 selection_history: Default::default(),
1225 autoclose_regions: Default::default(),
1226 snippet_stack: Default::default(),
1227 select_larger_syntax_node_stack: Vec::new(),
1228 ime_transaction: Default::default(),
1229 active_diagnostics: None,
1230 soft_wrap_mode_override,
1231 completion_provider: project.clone().map(|project| Box::new(project) as _),
1232 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1233 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1234 project,
1235 blink_manager: blink_manager.clone(),
1236 show_local_selections: true,
1237 mode,
1238 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1239 show_gutter: mode == EditorMode::Full,
1240 show_line_numbers: None,
1241 use_relative_line_numbers: None,
1242 show_git_diff_gutter: None,
1243 show_code_actions: None,
1244 show_runnables: None,
1245 show_wrap_guides: None,
1246 show_indent_guides,
1247 placeholder_text: None,
1248 highlight_order: 0,
1249 highlighted_rows: HashMap::default(),
1250 background_highlights: Default::default(),
1251 gutter_highlights: TreeMap::default(),
1252 scrollbar_marker_state: ScrollbarMarkerState::default(),
1253 active_indent_guides_state: ActiveIndentGuidesState::default(),
1254 nav_history: None,
1255 context_menu: RefCell::new(None),
1256 mouse_context_menu: None,
1257 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1258 completion_tasks: Default::default(),
1259 signature_help_state: SignatureHelpState::default(),
1260 auto_signature_help: None,
1261 find_all_references_task_sources: Vec::new(),
1262 next_completion_id: 0,
1263 next_inlay_id: 0,
1264 code_action_providers,
1265 available_code_actions: Default::default(),
1266 code_actions_task: Default::default(),
1267 document_highlights_task: Default::default(),
1268 linked_editing_range_task: Default::default(),
1269 pending_rename: Default::default(),
1270 searchable: true,
1271 cursor_shape: EditorSettings::get_global(cx)
1272 .cursor_shape
1273 .unwrap_or_default(),
1274 current_line_highlight: None,
1275 autoindent_mode: Some(AutoindentMode::EachLine),
1276 collapse_matches: false,
1277 workspace: None,
1278 input_enabled: true,
1279 use_modal_editing: mode == EditorMode::Full,
1280 read_only: false,
1281 use_autoclose: true,
1282 use_auto_surround: true,
1283 auto_replace_emoji_shortcode: false,
1284 leader_peer_id: None,
1285 remote_id: None,
1286 hover_state: Default::default(),
1287 hovered_link_state: Default::default(),
1288 inline_completion_provider: None,
1289 active_inline_completion: None,
1290 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1291 diff_map: DiffMap::default(),
1292 gutter_hovered: false,
1293 pixel_position_of_newest_cursor: None,
1294 last_bounds: None,
1295 expect_bounds_change: None,
1296 gutter_dimensions: GutterDimensions::default(),
1297 style: None,
1298 show_cursor_names: false,
1299 hovered_cursors: Default::default(),
1300 next_editor_action_id: EditorActionId::default(),
1301 editor_actions: Rc::default(),
1302 show_inline_completions_override: None,
1303 enable_inline_completions: true,
1304 custom_context_menu: None,
1305 show_git_blame_gutter: false,
1306 show_git_blame_inline: false,
1307 show_selection_menu: None,
1308 show_git_blame_inline_delay_task: None,
1309 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1310 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1311 .session
1312 .restore_unsaved_buffers,
1313 blame: None,
1314 blame_subscription: None,
1315 tasks: Default::default(),
1316 _subscriptions: vec![
1317 cx.observe(&buffer, Self::on_buffer_changed),
1318 cx.subscribe(&buffer, Self::on_buffer_event),
1319 cx.observe(&display_map, Self::on_display_map_changed),
1320 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1321 cx.observe_global::<SettingsStore>(Self::settings_changed),
1322 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1323 cx.observe_window_activation(|editor, cx| {
1324 let active = cx.is_window_active();
1325 editor.blink_manager.update(cx, |blink_manager, cx| {
1326 if active {
1327 blink_manager.enable(cx);
1328 } else {
1329 blink_manager.disable(cx);
1330 }
1331 });
1332 }),
1333 ],
1334 tasks_update_task: None,
1335 linked_edit_ranges: Default::default(),
1336 previous_search_ranges: None,
1337 breadcrumb_header: None,
1338 focused_block: None,
1339 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1340 addons: HashMap::default(),
1341 registered_buffers: HashMap::default(),
1342 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1343 toggle_fold_multiple_buffers: Task::ready(()),
1344 text_style_refinement: None,
1345 };
1346 this.tasks_update_task = Some(this.refresh_runnables(cx));
1347 this._subscriptions.extend(project_subscriptions);
1348
1349 this.end_selection(cx);
1350 this.scroll_manager.show_scrollbar(cx);
1351
1352 if mode == EditorMode::Full {
1353 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1354 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1355
1356 if this.git_blame_inline_enabled {
1357 this.git_blame_inline_enabled = true;
1358 this.start_git_blame_inline(false, cx);
1359 }
1360
1361 if let Some(buffer) = buffer.read(cx).as_singleton() {
1362 if let Some(project) = this.project.as_ref() {
1363 let lsp_store = project.read(cx).lsp_store();
1364 let handle = lsp_store.update(cx, |lsp_store, cx| {
1365 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1366 });
1367 this.registered_buffers
1368 .insert(buffer.read(cx).remote_id(), handle);
1369 }
1370 }
1371 }
1372
1373 this.report_editor_event("Editor Opened", None, cx);
1374 this
1375 }
1376
1377 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1378 self.mouse_context_menu
1379 .as_ref()
1380 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1381 }
1382
1383 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1384 let mut key_context = KeyContext::new_with_defaults();
1385 key_context.add("Editor");
1386 let mode = match self.mode {
1387 EditorMode::SingleLine { .. } => "single_line",
1388 EditorMode::AutoHeight { .. } => "auto_height",
1389 EditorMode::Full => "full",
1390 };
1391
1392 if EditorSettings::jupyter_enabled(cx) {
1393 key_context.add("jupyter");
1394 }
1395
1396 key_context.set("mode", mode);
1397 if self.pending_rename.is_some() {
1398 key_context.add("renaming");
1399 }
1400 match self.context_menu.borrow().as_ref() {
1401 Some(CodeContextMenu::Completions(_)) => {
1402 key_context.add("menu");
1403 key_context.add("showing_completions")
1404 }
1405 Some(CodeContextMenu::CodeActions(_)) => {
1406 key_context.add("menu");
1407 key_context.add("showing_code_actions")
1408 }
1409 None => {}
1410 }
1411
1412 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1413 if !self.focus_handle(cx).contains_focused(cx)
1414 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1415 {
1416 for addon in self.addons.values() {
1417 addon.extend_key_context(&mut key_context, cx)
1418 }
1419 }
1420
1421 if let Some(extension) = self
1422 .buffer
1423 .read(cx)
1424 .as_singleton()
1425 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1426 {
1427 key_context.set("extension", extension.to_string());
1428 }
1429
1430 if self.has_active_inline_completion() {
1431 key_context.add("copilot_suggestion");
1432 key_context.add("inline_completion");
1433 }
1434
1435 if !self
1436 .selections
1437 .disjoint
1438 .iter()
1439 .all(|selection| selection.start == selection.end)
1440 {
1441 key_context.add("selection");
1442 }
1443
1444 key_context
1445 }
1446
1447 pub fn new_file(
1448 workspace: &mut Workspace,
1449 _: &workspace::NewFile,
1450 cx: &mut ViewContext<Workspace>,
1451 ) {
1452 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1453 "Failed to create buffer",
1454 cx,
1455 |e, _| match e.error_code() {
1456 ErrorCode::RemoteUpgradeRequired => Some(format!(
1457 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1458 e.error_tag("required").unwrap_or("the latest version")
1459 )),
1460 _ => None,
1461 },
1462 );
1463 }
1464
1465 pub fn new_in_workspace(
1466 workspace: &mut Workspace,
1467 cx: &mut ViewContext<Workspace>,
1468 ) -> Task<Result<View<Editor>>> {
1469 let project = workspace.project().clone();
1470 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1471
1472 cx.spawn(|workspace, mut cx| async move {
1473 let buffer = create.await?;
1474 workspace.update(&mut cx, |workspace, cx| {
1475 let editor =
1476 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1477 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1478 editor
1479 })
1480 })
1481 }
1482
1483 fn new_file_vertical(
1484 workspace: &mut Workspace,
1485 _: &workspace::NewFileSplitVertical,
1486 cx: &mut ViewContext<Workspace>,
1487 ) {
1488 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1489 }
1490
1491 fn new_file_horizontal(
1492 workspace: &mut Workspace,
1493 _: &workspace::NewFileSplitHorizontal,
1494 cx: &mut ViewContext<Workspace>,
1495 ) {
1496 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1497 }
1498
1499 fn new_file_in_direction(
1500 workspace: &mut Workspace,
1501 direction: SplitDirection,
1502 cx: &mut ViewContext<Workspace>,
1503 ) {
1504 let project = workspace.project().clone();
1505 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1506
1507 cx.spawn(|workspace, mut cx| async move {
1508 let buffer = create.await?;
1509 workspace.update(&mut cx, move |workspace, cx| {
1510 workspace.split_item(
1511 direction,
1512 Box::new(
1513 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1514 ),
1515 cx,
1516 )
1517 })?;
1518 anyhow::Ok(())
1519 })
1520 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1521 ErrorCode::RemoteUpgradeRequired => Some(format!(
1522 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1523 e.error_tag("required").unwrap_or("the latest version")
1524 )),
1525 _ => None,
1526 });
1527 }
1528
1529 pub fn leader_peer_id(&self) -> Option<PeerId> {
1530 self.leader_peer_id
1531 }
1532
1533 pub fn buffer(&self) -> &Model<MultiBuffer> {
1534 &self.buffer
1535 }
1536
1537 pub fn workspace(&self) -> Option<View<Workspace>> {
1538 self.workspace.as_ref()?.0.upgrade()
1539 }
1540
1541 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1542 self.buffer().read(cx).title(cx)
1543 }
1544
1545 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1546 let git_blame_gutter_max_author_length = self
1547 .render_git_blame_gutter(cx)
1548 .then(|| {
1549 if let Some(blame) = self.blame.as_ref() {
1550 let max_author_length =
1551 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1552 Some(max_author_length)
1553 } else {
1554 None
1555 }
1556 })
1557 .flatten();
1558
1559 EditorSnapshot {
1560 mode: self.mode,
1561 show_gutter: self.show_gutter,
1562 show_line_numbers: self.show_line_numbers,
1563 show_git_diff_gutter: self.show_git_diff_gutter,
1564 show_code_actions: self.show_code_actions,
1565 show_runnables: self.show_runnables,
1566 git_blame_gutter_max_author_length,
1567 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1568 scroll_anchor: self.scroll_manager.anchor(),
1569 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1570 placeholder_text: self.placeholder_text.clone(),
1571 diff_map: self.diff_map.snapshot(),
1572 is_focused: self.focus_handle.is_focused(cx),
1573 current_line_highlight: self
1574 .current_line_highlight
1575 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1576 gutter_hovered: self.gutter_hovered,
1577 }
1578 }
1579
1580 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1581 self.buffer.read(cx).language_at(point, cx)
1582 }
1583
1584 pub fn file_at<T: ToOffset>(
1585 &self,
1586 point: T,
1587 cx: &AppContext,
1588 ) -> Option<Arc<dyn language::File>> {
1589 self.buffer.read(cx).read(cx).file_at(point).cloned()
1590 }
1591
1592 pub fn active_excerpt(
1593 &self,
1594 cx: &AppContext,
1595 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1596 self.buffer
1597 .read(cx)
1598 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1599 }
1600
1601 pub fn mode(&self) -> EditorMode {
1602 self.mode
1603 }
1604
1605 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1606 self.collaboration_hub.as_deref()
1607 }
1608
1609 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1610 self.collaboration_hub = Some(hub);
1611 }
1612
1613 pub fn set_custom_context_menu(
1614 &mut self,
1615 f: impl 'static
1616 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1617 ) {
1618 self.custom_context_menu = Some(Box::new(f))
1619 }
1620
1621 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1622 self.completion_provider = provider;
1623 }
1624
1625 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1626 self.semantics_provider.clone()
1627 }
1628
1629 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1630 self.semantics_provider = provider;
1631 }
1632
1633 pub fn set_inline_completion_provider<T>(
1634 &mut self,
1635 provider: Option<Model<T>>,
1636 cx: &mut ViewContext<Self>,
1637 ) where
1638 T: InlineCompletionProvider,
1639 {
1640 self.inline_completion_provider =
1641 provider.map(|provider| RegisteredInlineCompletionProvider {
1642 _subscription: cx.observe(&provider, |this, _, cx| {
1643 if this.focus_handle.is_focused(cx) {
1644 this.update_visible_inline_completion(cx);
1645 }
1646 }),
1647 provider: Arc::new(provider),
1648 });
1649 self.refresh_inline_completion(false, false, cx);
1650 }
1651
1652 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1653 self.placeholder_text.as_deref()
1654 }
1655
1656 pub fn set_placeholder_text(
1657 &mut self,
1658 placeholder_text: impl Into<Arc<str>>,
1659 cx: &mut ViewContext<Self>,
1660 ) {
1661 let placeholder_text = Some(placeholder_text.into());
1662 if self.placeholder_text != placeholder_text {
1663 self.placeholder_text = placeholder_text;
1664 cx.notify();
1665 }
1666 }
1667
1668 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1669 self.cursor_shape = cursor_shape;
1670
1671 // Disrupt blink for immediate user feedback that the cursor shape has changed
1672 self.blink_manager.update(cx, BlinkManager::show_cursor);
1673
1674 cx.notify();
1675 }
1676
1677 pub fn set_current_line_highlight(
1678 &mut self,
1679 current_line_highlight: Option<CurrentLineHighlight>,
1680 ) {
1681 self.current_line_highlight = current_line_highlight;
1682 }
1683
1684 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1685 self.collapse_matches = collapse_matches;
1686 }
1687
1688 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1689 let buffers = self.buffer.read(cx).all_buffers();
1690 let Some(lsp_store) = self.lsp_store(cx) else {
1691 return;
1692 };
1693 lsp_store.update(cx, |lsp_store, cx| {
1694 for buffer in buffers {
1695 self.registered_buffers
1696 .entry(buffer.read(cx).remote_id())
1697 .or_insert_with(|| {
1698 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1699 });
1700 }
1701 })
1702 }
1703
1704 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1705 if self.collapse_matches {
1706 return range.start..range.start;
1707 }
1708 range.clone()
1709 }
1710
1711 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1712 if self.display_map.read(cx).clip_at_line_ends != clip {
1713 self.display_map
1714 .update(cx, |map, _| map.clip_at_line_ends = clip);
1715 }
1716 }
1717
1718 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1719 self.input_enabled = input_enabled;
1720 }
1721
1722 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1723 self.enable_inline_completions = enabled;
1724 }
1725
1726 pub fn set_autoindent(&mut self, autoindent: bool) {
1727 if autoindent {
1728 self.autoindent_mode = Some(AutoindentMode::EachLine);
1729 } else {
1730 self.autoindent_mode = None;
1731 }
1732 }
1733
1734 pub fn read_only(&self, cx: &AppContext) -> bool {
1735 self.read_only || self.buffer.read(cx).read_only()
1736 }
1737
1738 pub fn set_read_only(&mut self, read_only: bool) {
1739 self.read_only = read_only;
1740 }
1741
1742 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1743 self.use_autoclose = autoclose;
1744 }
1745
1746 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1747 self.use_auto_surround = auto_surround;
1748 }
1749
1750 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1751 self.auto_replace_emoji_shortcode = auto_replace;
1752 }
1753
1754 pub fn toggle_inline_completions(
1755 &mut self,
1756 _: &ToggleInlineCompletions,
1757 cx: &mut ViewContext<Self>,
1758 ) {
1759 if self.show_inline_completions_override.is_some() {
1760 self.set_show_inline_completions(None, cx);
1761 } else {
1762 let cursor = self.selections.newest_anchor().head();
1763 if let Some((buffer, cursor_buffer_position)) =
1764 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1765 {
1766 let show_inline_completions =
1767 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1768 self.set_show_inline_completions(Some(show_inline_completions), cx);
1769 }
1770 }
1771 }
1772
1773 pub fn set_show_inline_completions(
1774 &mut self,
1775 show_inline_completions: Option<bool>,
1776 cx: &mut ViewContext<Self>,
1777 ) {
1778 self.show_inline_completions_override = show_inline_completions;
1779 self.refresh_inline_completion(false, true, cx);
1780 }
1781
1782 fn should_show_inline_completions(
1783 &self,
1784 buffer: &Model<Buffer>,
1785 buffer_position: language::Anchor,
1786 cx: &AppContext,
1787 ) -> bool {
1788 if !self.snippet_stack.is_empty() {
1789 return false;
1790 }
1791
1792 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1793 return false;
1794 }
1795
1796 if let Some(provider) = self.inline_completion_provider() {
1797 if let Some(show_inline_completions) = self.show_inline_completions_override {
1798 show_inline_completions
1799 } else {
1800 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1801 }
1802 } else {
1803 false
1804 }
1805 }
1806
1807 fn inline_completions_disabled_in_scope(
1808 &self,
1809 buffer: &Model<Buffer>,
1810 buffer_position: language::Anchor,
1811 cx: &AppContext,
1812 ) -> bool {
1813 let snapshot = buffer.read(cx).snapshot();
1814 let settings = snapshot.settings_at(buffer_position, cx);
1815
1816 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1817 return false;
1818 };
1819
1820 scope.override_name().map_or(false, |scope_name| {
1821 settings
1822 .inline_completions_disabled_in
1823 .iter()
1824 .any(|s| s == scope_name)
1825 })
1826 }
1827
1828 pub fn set_use_modal_editing(&mut self, to: bool) {
1829 self.use_modal_editing = to;
1830 }
1831
1832 pub fn use_modal_editing(&self) -> bool {
1833 self.use_modal_editing
1834 }
1835
1836 fn selections_did_change(
1837 &mut self,
1838 local: bool,
1839 old_cursor_position: &Anchor,
1840 show_completions: bool,
1841 cx: &mut ViewContext<Self>,
1842 ) {
1843 cx.invalidate_character_coordinates();
1844
1845 // Copy selections to primary selection buffer
1846 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1847 if local {
1848 let selections = self.selections.all::<usize>(cx);
1849 let buffer_handle = self.buffer.read(cx).read(cx);
1850
1851 let mut text = String::new();
1852 for (index, selection) in selections.iter().enumerate() {
1853 let text_for_selection = buffer_handle
1854 .text_for_range(selection.start..selection.end)
1855 .collect::<String>();
1856
1857 text.push_str(&text_for_selection);
1858 if index != selections.len() - 1 {
1859 text.push('\n');
1860 }
1861 }
1862
1863 if !text.is_empty() {
1864 cx.write_to_primary(ClipboardItem::new_string(text));
1865 }
1866 }
1867
1868 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1869 self.buffer.update(cx, |buffer, cx| {
1870 buffer.set_active_selections(
1871 &self.selections.disjoint_anchors(),
1872 self.selections.line_mode,
1873 self.cursor_shape,
1874 cx,
1875 )
1876 });
1877 }
1878 let display_map = self
1879 .display_map
1880 .update(cx, |display_map, cx| display_map.snapshot(cx));
1881 let buffer = &display_map.buffer_snapshot;
1882 self.add_selections_state = None;
1883 self.select_next_state = None;
1884 self.select_prev_state = None;
1885 self.select_larger_syntax_node_stack.clear();
1886 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1887 self.snippet_stack
1888 .invalidate(&self.selections.disjoint_anchors(), buffer);
1889 self.take_rename(false, cx);
1890
1891 let new_cursor_position = self.selections.newest_anchor().head();
1892
1893 self.push_to_nav_history(
1894 *old_cursor_position,
1895 Some(new_cursor_position.to_point(buffer)),
1896 cx,
1897 );
1898
1899 if local {
1900 let new_cursor_position = self.selections.newest_anchor().head();
1901 let mut context_menu = self.context_menu.borrow_mut();
1902 let completion_menu = match context_menu.as_ref() {
1903 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1904 _ => {
1905 *context_menu = None;
1906 None
1907 }
1908 };
1909
1910 if let Some(completion_menu) = completion_menu {
1911 let cursor_position = new_cursor_position.to_offset(buffer);
1912 let (word_range, kind) =
1913 buffer.surrounding_word(completion_menu.initial_position, true);
1914 if kind == Some(CharKind::Word)
1915 && word_range.to_inclusive().contains(&cursor_position)
1916 {
1917 let mut completion_menu = completion_menu.clone();
1918 drop(context_menu);
1919
1920 let query = Self::completion_query(buffer, cursor_position);
1921 cx.spawn(move |this, mut cx| async move {
1922 completion_menu
1923 .filter(query.as_deref(), cx.background_executor().clone())
1924 .await;
1925
1926 this.update(&mut cx, |this, cx| {
1927 let mut context_menu = this.context_menu.borrow_mut();
1928 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1929 else {
1930 return;
1931 };
1932
1933 if menu.id > completion_menu.id {
1934 return;
1935 }
1936
1937 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1938 drop(context_menu);
1939 cx.notify();
1940 })
1941 })
1942 .detach();
1943
1944 if show_completions {
1945 self.show_completions(&ShowCompletions { trigger: None }, cx);
1946 }
1947 } else {
1948 drop(context_menu);
1949 self.hide_context_menu(cx);
1950 }
1951 } else {
1952 drop(context_menu);
1953 }
1954
1955 hide_hover(self, cx);
1956
1957 if old_cursor_position.to_display_point(&display_map).row()
1958 != new_cursor_position.to_display_point(&display_map).row()
1959 {
1960 self.available_code_actions.take();
1961 }
1962 self.refresh_code_actions(cx);
1963 self.refresh_document_highlights(cx);
1964 refresh_matching_bracket_highlights(self, cx);
1965 self.update_visible_inline_completion(cx);
1966 linked_editing_ranges::refresh_linked_ranges(self, cx);
1967 if self.git_blame_inline_enabled {
1968 self.start_inline_blame_timer(cx);
1969 }
1970 }
1971
1972 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1973 cx.emit(EditorEvent::SelectionsChanged { local });
1974
1975 if self.selections.disjoint_anchors().len() == 1 {
1976 cx.emit(SearchEvent::ActiveMatchChanged)
1977 }
1978 cx.notify();
1979 }
1980
1981 pub fn change_selections<R>(
1982 &mut self,
1983 autoscroll: Option<Autoscroll>,
1984 cx: &mut ViewContext<Self>,
1985 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1986 ) -> R {
1987 self.change_selections_inner(autoscroll, true, cx, change)
1988 }
1989
1990 pub fn change_selections_inner<R>(
1991 &mut self,
1992 autoscroll: Option<Autoscroll>,
1993 request_completions: bool,
1994 cx: &mut ViewContext<Self>,
1995 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1996 ) -> R {
1997 let old_cursor_position = self.selections.newest_anchor().head();
1998 self.push_to_selection_history();
1999
2000 let (changed, result) = self.selections.change_with(cx, change);
2001
2002 if changed {
2003 if let Some(autoscroll) = autoscroll {
2004 self.request_autoscroll(autoscroll, cx);
2005 }
2006 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2007
2008 if self.should_open_signature_help_automatically(
2009 &old_cursor_position,
2010 self.signature_help_state.backspace_pressed(),
2011 cx,
2012 ) {
2013 self.show_signature_help(&ShowSignatureHelp, cx);
2014 }
2015 self.signature_help_state.set_backspace_pressed(false);
2016 }
2017
2018 result
2019 }
2020
2021 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2022 where
2023 I: IntoIterator<Item = (Range<S>, T)>,
2024 S: ToOffset,
2025 T: Into<Arc<str>>,
2026 {
2027 if self.read_only(cx) {
2028 return;
2029 }
2030
2031 self.buffer
2032 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2033 }
2034
2035 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2036 where
2037 I: IntoIterator<Item = (Range<S>, T)>,
2038 S: ToOffset,
2039 T: Into<Arc<str>>,
2040 {
2041 if self.read_only(cx) {
2042 return;
2043 }
2044
2045 self.buffer.update(cx, |buffer, cx| {
2046 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2047 });
2048 }
2049
2050 pub fn edit_with_block_indent<I, S, T>(
2051 &mut self,
2052 edits: I,
2053 original_indent_columns: Vec<u32>,
2054 cx: &mut ViewContext<Self>,
2055 ) where
2056 I: IntoIterator<Item = (Range<S>, T)>,
2057 S: ToOffset,
2058 T: Into<Arc<str>>,
2059 {
2060 if self.read_only(cx) {
2061 return;
2062 }
2063
2064 self.buffer.update(cx, |buffer, cx| {
2065 buffer.edit(
2066 edits,
2067 Some(AutoindentMode::Block {
2068 original_indent_columns,
2069 }),
2070 cx,
2071 )
2072 });
2073 }
2074
2075 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2076 self.hide_context_menu(cx);
2077
2078 match phase {
2079 SelectPhase::Begin {
2080 position,
2081 add,
2082 click_count,
2083 } => self.begin_selection(position, add, click_count, cx),
2084 SelectPhase::BeginColumnar {
2085 position,
2086 goal_column,
2087 reset,
2088 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2089 SelectPhase::Extend {
2090 position,
2091 click_count,
2092 } => self.extend_selection(position, click_count, cx),
2093 SelectPhase::Update {
2094 position,
2095 goal_column,
2096 scroll_delta,
2097 } => self.update_selection(position, goal_column, scroll_delta, cx),
2098 SelectPhase::End => self.end_selection(cx),
2099 }
2100 }
2101
2102 fn extend_selection(
2103 &mut self,
2104 position: DisplayPoint,
2105 click_count: usize,
2106 cx: &mut ViewContext<Self>,
2107 ) {
2108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2109 let tail = self.selections.newest::<usize>(cx).tail();
2110 self.begin_selection(position, false, click_count, cx);
2111
2112 let position = position.to_offset(&display_map, Bias::Left);
2113 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2114
2115 let mut pending_selection = self
2116 .selections
2117 .pending_anchor()
2118 .expect("extend_selection not called with pending selection");
2119 if position >= tail {
2120 pending_selection.start = tail_anchor;
2121 } else {
2122 pending_selection.end = tail_anchor;
2123 pending_selection.reversed = true;
2124 }
2125
2126 let mut pending_mode = self.selections.pending_mode().unwrap();
2127 match &mut pending_mode {
2128 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2129 _ => {}
2130 }
2131
2132 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2133 s.set_pending(pending_selection, pending_mode)
2134 });
2135 }
2136
2137 fn begin_selection(
2138 &mut self,
2139 position: DisplayPoint,
2140 add: bool,
2141 click_count: usize,
2142 cx: &mut ViewContext<Self>,
2143 ) {
2144 if !self.focus_handle.is_focused(cx) {
2145 self.last_focused_descendant = None;
2146 cx.focus(&self.focus_handle);
2147 }
2148
2149 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2150 let buffer = &display_map.buffer_snapshot;
2151 let newest_selection = self.selections.newest_anchor().clone();
2152 let position = display_map.clip_point(position, Bias::Left);
2153
2154 let start;
2155 let end;
2156 let mode;
2157 let mut auto_scroll;
2158 match click_count {
2159 1 => {
2160 start = buffer.anchor_before(position.to_point(&display_map));
2161 end = start;
2162 mode = SelectMode::Character;
2163 auto_scroll = true;
2164 }
2165 2 => {
2166 let range = movement::surrounding_word(&display_map, position);
2167 start = buffer.anchor_before(range.start.to_point(&display_map));
2168 end = buffer.anchor_before(range.end.to_point(&display_map));
2169 mode = SelectMode::Word(start..end);
2170 auto_scroll = true;
2171 }
2172 3 => {
2173 let position = display_map
2174 .clip_point(position, Bias::Left)
2175 .to_point(&display_map);
2176 let line_start = display_map.prev_line_boundary(position).0;
2177 let next_line_start = buffer.clip_point(
2178 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2179 Bias::Left,
2180 );
2181 start = buffer.anchor_before(line_start);
2182 end = buffer.anchor_before(next_line_start);
2183 mode = SelectMode::Line(start..end);
2184 auto_scroll = true;
2185 }
2186 _ => {
2187 start = buffer.anchor_before(0);
2188 end = buffer.anchor_before(buffer.len());
2189 mode = SelectMode::All;
2190 auto_scroll = false;
2191 }
2192 }
2193 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2194
2195 let point_to_delete: Option<usize> = {
2196 let selected_points: Vec<Selection<Point>> =
2197 self.selections.disjoint_in_range(start..end, cx);
2198
2199 if !add || click_count > 1 {
2200 None
2201 } else if !selected_points.is_empty() {
2202 Some(selected_points[0].id)
2203 } else {
2204 let clicked_point_already_selected =
2205 self.selections.disjoint.iter().find(|selection| {
2206 selection.start.to_point(buffer) == start.to_point(buffer)
2207 || selection.end.to_point(buffer) == end.to_point(buffer)
2208 });
2209
2210 clicked_point_already_selected.map(|selection| selection.id)
2211 }
2212 };
2213
2214 let selections_count = self.selections.count();
2215
2216 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2217 if let Some(point_to_delete) = point_to_delete {
2218 s.delete(point_to_delete);
2219
2220 if selections_count == 1 {
2221 s.set_pending_anchor_range(start..end, mode);
2222 }
2223 } else {
2224 if !add {
2225 s.clear_disjoint();
2226 } else if click_count > 1 {
2227 s.delete(newest_selection.id)
2228 }
2229
2230 s.set_pending_anchor_range(start..end, mode);
2231 }
2232 });
2233 }
2234
2235 fn begin_columnar_selection(
2236 &mut self,
2237 position: DisplayPoint,
2238 goal_column: u32,
2239 reset: bool,
2240 cx: &mut ViewContext<Self>,
2241 ) {
2242 if !self.focus_handle.is_focused(cx) {
2243 self.last_focused_descendant = None;
2244 cx.focus(&self.focus_handle);
2245 }
2246
2247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2248
2249 if reset {
2250 let pointer_position = display_map
2251 .buffer_snapshot
2252 .anchor_before(position.to_point(&display_map));
2253
2254 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2255 s.clear_disjoint();
2256 s.set_pending_anchor_range(
2257 pointer_position..pointer_position,
2258 SelectMode::Character,
2259 );
2260 });
2261 }
2262
2263 let tail = self.selections.newest::<Point>(cx).tail();
2264 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2265
2266 if !reset {
2267 self.select_columns(
2268 tail.to_display_point(&display_map),
2269 position,
2270 goal_column,
2271 &display_map,
2272 cx,
2273 );
2274 }
2275 }
2276
2277 fn update_selection(
2278 &mut self,
2279 position: DisplayPoint,
2280 goal_column: u32,
2281 scroll_delta: gpui::Point<f32>,
2282 cx: &mut ViewContext<Self>,
2283 ) {
2284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2285
2286 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2287 let tail = tail.to_display_point(&display_map);
2288 self.select_columns(tail, position, goal_column, &display_map, cx);
2289 } else if let Some(mut pending) = self.selections.pending_anchor() {
2290 let buffer = self.buffer.read(cx).snapshot(cx);
2291 let head;
2292 let tail;
2293 let mode = self.selections.pending_mode().unwrap();
2294 match &mode {
2295 SelectMode::Character => {
2296 head = position.to_point(&display_map);
2297 tail = pending.tail().to_point(&buffer);
2298 }
2299 SelectMode::Word(original_range) => {
2300 let original_display_range = original_range.start.to_display_point(&display_map)
2301 ..original_range.end.to_display_point(&display_map);
2302 let original_buffer_range = original_display_range.start.to_point(&display_map)
2303 ..original_display_range.end.to_point(&display_map);
2304 if movement::is_inside_word(&display_map, position)
2305 || original_display_range.contains(&position)
2306 {
2307 let word_range = movement::surrounding_word(&display_map, position);
2308 if word_range.start < original_display_range.start {
2309 head = word_range.start.to_point(&display_map);
2310 } else {
2311 head = word_range.end.to_point(&display_map);
2312 }
2313 } else {
2314 head = position.to_point(&display_map);
2315 }
2316
2317 if head <= original_buffer_range.start {
2318 tail = original_buffer_range.end;
2319 } else {
2320 tail = original_buffer_range.start;
2321 }
2322 }
2323 SelectMode::Line(original_range) => {
2324 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2325
2326 let position = display_map
2327 .clip_point(position, Bias::Left)
2328 .to_point(&display_map);
2329 let line_start = display_map.prev_line_boundary(position).0;
2330 let next_line_start = buffer.clip_point(
2331 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2332 Bias::Left,
2333 );
2334
2335 if line_start < original_range.start {
2336 head = line_start
2337 } else {
2338 head = next_line_start
2339 }
2340
2341 if head <= original_range.start {
2342 tail = original_range.end;
2343 } else {
2344 tail = original_range.start;
2345 }
2346 }
2347 SelectMode::All => {
2348 return;
2349 }
2350 };
2351
2352 if head < tail {
2353 pending.start = buffer.anchor_before(head);
2354 pending.end = buffer.anchor_before(tail);
2355 pending.reversed = true;
2356 } else {
2357 pending.start = buffer.anchor_before(tail);
2358 pending.end = buffer.anchor_before(head);
2359 pending.reversed = false;
2360 }
2361
2362 self.change_selections(None, cx, |s| {
2363 s.set_pending(pending, mode);
2364 });
2365 } else {
2366 log::error!("update_selection dispatched with no pending selection");
2367 return;
2368 }
2369
2370 self.apply_scroll_delta(scroll_delta, cx);
2371 cx.notify();
2372 }
2373
2374 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2375 self.columnar_selection_tail.take();
2376 if self.selections.pending_anchor().is_some() {
2377 let selections = self.selections.all::<usize>(cx);
2378 self.change_selections(None, cx, |s| {
2379 s.select(selections);
2380 s.clear_pending();
2381 });
2382 }
2383 }
2384
2385 fn select_columns(
2386 &mut self,
2387 tail: DisplayPoint,
2388 head: DisplayPoint,
2389 goal_column: u32,
2390 display_map: &DisplaySnapshot,
2391 cx: &mut ViewContext<Self>,
2392 ) {
2393 let start_row = cmp::min(tail.row(), head.row());
2394 let end_row = cmp::max(tail.row(), head.row());
2395 let start_column = cmp::min(tail.column(), goal_column);
2396 let end_column = cmp::max(tail.column(), goal_column);
2397 let reversed = start_column < tail.column();
2398
2399 let selection_ranges = (start_row.0..=end_row.0)
2400 .map(DisplayRow)
2401 .filter_map(|row| {
2402 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2403 let start = display_map
2404 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2405 .to_point(display_map);
2406 let end = display_map
2407 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2408 .to_point(display_map);
2409 if reversed {
2410 Some(end..start)
2411 } else {
2412 Some(start..end)
2413 }
2414 } else {
2415 None
2416 }
2417 })
2418 .collect::<Vec<_>>();
2419
2420 self.change_selections(None, cx, |s| {
2421 s.select_ranges(selection_ranges);
2422 });
2423 cx.notify();
2424 }
2425
2426 pub fn has_pending_nonempty_selection(&self) -> bool {
2427 let pending_nonempty_selection = match self.selections.pending_anchor() {
2428 Some(Selection { start, end, .. }) => start != end,
2429 None => false,
2430 };
2431
2432 pending_nonempty_selection
2433 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2434 }
2435
2436 pub fn has_pending_selection(&self) -> bool {
2437 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2438 }
2439
2440 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2441 if self.clear_expanded_diff_hunks(cx) {
2442 cx.notify();
2443 return;
2444 }
2445 if self.dismiss_menus_and_popups(true, cx) {
2446 return;
2447 }
2448
2449 if self.mode == EditorMode::Full
2450 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2451 {
2452 return;
2453 }
2454
2455 cx.propagate();
2456 }
2457
2458 pub fn dismiss_menus_and_popups(
2459 &mut self,
2460 should_report_inline_completion_event: bool,
2461 cx: &mut ViewContext<Self>,
2462 ) -> bool {
2463 if self.take_rename(false, cx).is_some() {
2464 return true;
2465 }
2466
2467 if hide_hover(self, cx) {
2468 return true;
2469 }
2470
2471 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2472 return true;
2473 }
2474
2475 if self.hide_context_menu(cx).is_some() {
2476 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2477 self.update_visible_inline_completion(cx);
2478 }
2479 return true;
2480 }
2481
2482 if self.mouse_context_menu.take().is_some() {
2483 return true;
2484 }
2485
2486 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2487 return true;
2488 }
2489
2490 if self.snippet_stack.pop().is_some() {
2491 return true;
2492 }
2493
2494 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2495 self.dismiss_diagnostics(cx);
2496 return true;
2497 }
2498
2499 false
2500 }
2501
2502 fn linked_editing_ranges_for(
2503 &self,
2504 selection: Range<text::Anchor>,
2505 cx: &AppContext,
2506 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2507 if self.linked_edit_ranges.is_empty() {
2508 return None;
2509 }
2510 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2511 selection.end.buffer_id.and_then(|end_buffer_id| {
2512 if selection.start.buffer_id != Some(end_buffer_id) {
2513 return None;
2514 }
2515 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2516 let snapshot = buffer.read(cx).snapshot();
2517 self.linked_edit_ranges
2518 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2519 .map(|ranges| (ranges, snapshot, buffer))
2520 })?;
2521 use text::ToOffset as TO;
2522 // find offset from the start of current range to current cursor position
2523 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2524
2525 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2526 let start_difference = start_offset - start_byte_offset;
2527 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2528 let end_difference = end_offset - start_byte_offset;
2529 // Current range has associated linked ranges.
2530 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2531 for range in linked_ranges.iter() {
2532 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2533 let end_offset = start_offset + end_difference;
2534 let start_offset = start_offset + start_difference;
2535 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2536 continue;
2537 }
2538 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2539 if s.start.buffer_id != selection.start.buffer_id
2540 || s.end.buffer_id != selection.end.buffer_id
2541 {
2542 return false;
2543 }
2544 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2545 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2546 }) {
2547 continue;
2548 }
2549 let start = buffer_snapshot.anchor_after(start_offset);
2550 let end = buffer_snapshot.anchor_after(end_offset);
2551 linked_edits
2552 .entry(buffer.clone())
2553 .or_default()
2554 .push(start..end);
2555 }
2556 Some(linked_edits)
2557 }
2558
2559 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2560 let text: Arc<str> = text.into();
2561
2562 if self.read_only(cx) {
2563 return;
2564 }
2565
2566 let selections = self.selections.all_adjusted(cx);
2567 let mut bracket_inserted = false;
2568 let mut edits = Vec::new();
2569 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2570 let mut new_selections = Vec::with_capacity(selections.len());
2571 let mut new_autoclose_regions = Vec::new();
2572 let snapshot = self.buffer.read(cx).read(cx);
2573
2574 for (selection, autoclose_region) in
2575 self.selections_with_autoclose_regions(selections, &snapshot)
2576 {
2577 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2578 // Determine if the inserted text matches the opening or closing
2579 // bracket of any of this language's bracket pairs.
2580 let mut bracket_pair = None;
2581 let mut is_bracket_pair_start = false;
2582 let mut is_bracket_pair_end = false;
2583 if !text.is_empty() {
2584 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2585 // and they are removing the character that triggered IME popup.
2586 for (pair, enabled) in scope.brackets() {
2587 if !pair.close && !pair.surround {
2588 continue;
2589 }
2590
2591 if enabled && pair.start.ends_with(text.as_ref()) {
2592 let prefix_len = pair.start.len() - text.len();
2593 let preceding_text_matches_prefix = prefix_len == 0
2594 || (selection.start.column >= (prefix_len as u32)
2595 && snapshot.contains_str_at(
2596 Point::new(
2597 selection.start.row,
2598 selection.start.column - (prefix_len as u32),
2599 ),
2600 &pair.start[..prefix_len],
2601 ));
2602 if preceding_text_matches_prefix {
2603 bracket_pair = Some(pair.clone());
2604 is_bracket_pair_start = true;
2605 break;
2606 }
2607 }
2608 if pair.end.as_str() == text.as_ref() {
2609 bracket_pair = Some(pair.clone());
2610 is_bracket_pair_end = true;
2611 break;
2612 }
2613 }
2614 }
2615
2616 if let Some(bracket_pair) = bracket_pair {
2617 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2618 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2619 let auto_surround =
2620 self.use_auto_surround && snapshot_settings.use_auto_surround;
2621 if selection.is_empty() {
2622 if is_bracket_pair_start {
2623 // If the inserted text is a suffix of an opening bracket and the
2624 // selection is preceded by the rest of the opening bracket, then
2625 // insert the closing bracket.
2626 let following_text_allows_autoclose = snapshot
2627 .chars_at(selection.start)
2628 .next()
2629 .map_or(true, |c| scope.should_autoclose_before(c));
2630
2631 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2632 && bracket_pair.start.len() == 1
2633 {
2634 let target = bracket_pair.start.chars().next().unwrap();
2635 let current_line_count = snapshot
2636 .reversed_chars_at(selection.start)
2637 .take_while(|&c| c != '\n')
2638 .filter(|&c| c == target)
2639 .count();
2640 current_line_count % 2 == 1
2641 } else {
2642 false
2643 };
2644
2645 if autoclose
2646 && bracket_pair.close
2647 && following_text_allows_autoclose
2648 && !is_closing_quote
2649 {
2650 let anchor = snapshot.anchor_before(selection.end);
2651 new_selections.push((selection.map(|_| anchor), text.len()));
2652 new_autoclose_regions.push((
2653 anchor,
2654 text.len(),
2655 selection.id,
2656 bracket_pair.clone(),
2657 ));
2658 edits.push((
2659 selection.range(),
2660 format!("{}{}", text, bracket_pair.end).into(),
2661 ));
2662 bracket_inserted = true;
2663 continue;
2664 }
2665 }
2666
2667 if let Some(region) = autoclose_region {
2668 // If the selection is followed by an auto-inserted closing bracket,
2669 // then don't insert that closing bracket again; just move the selection
2670 // past the closing bracket.
2671 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2672 && text.as_ref() == region.pair.end.as_str();
2673 if should_skip {
2674 let anchor = snapshot.anchor_after(selection.end);
2675 new_selections
2676 .push((selection.map(|_| anchor), region.pair.end.len()));
2677 continue;
2678 }
2679 }
2680
2681 let always_treat_brackets_as_autoclosed = snapshot
2682 .settings_at(selection.start, cx)
2683 .always_treat_brackets_as_autoclosed;
2684 if always_treat_brackets_as_autoclosed
2685 && is_bracket_pair_end
2686 && snapshot.contains_str_at(selection.end, text.as_ref())
2687 {
2688 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2689 // and the inserted text is a closing bracket and the selection is followed
2690 // by the closing bracket then move the selection past the closing bracket.
2691 let anchor = snapshot.anchor_after(selection.end);
2692 new_selections.push((selection.map(|_| anchor), text.len()));
2693 continue;
2694 }
2695 }
2696 // If an opening bracket is 1 character long and is typed while
2697 // text is selected, then surround that text with the bracket pair.
2698 else if auto_surround
2699 && bracket_pair.surround
2700 && is_bracket_pair_start
2701 && bracket_pair.start.chars().count() == 1
2702 {
2703 edits.push((selection.start..selection.start, text.clone()));
2704 edits.push((
2705 selection.end..selection.end,
2706 bracket_pair.end.as_str().into(),
2707 ));
2708 bracket_inserted = true;
2709 new_selections.push((
2710 Selection {
2711 id: selection.id,
2712 start: snapshot.anchor_after(selection.start),
2713 end: snapshot.anchor_before(selection.end),
2714 reversed: selection.reversed,
2715 goal: selection.goal,
2716 },
2717 0,
2718 ));
2719 continue;
2720 }
2721 }
2722 }
2723
2724 if self.auto_replace_emoji_shortcode
2725 && selection.is_empty()
2726 && text.as_ref().ends_with(':')
2727 {
2728 if let Some(possible_emoji_short_code) =
2729 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2730 {
2731 if !possible_emoji_short_code.is_empty() {
2732 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2733 let emoji_shortcode_start = Point::new(
2734 selection.start.row,
2735 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2736 );
2737
2738 // Remove shortcode from buffer
2739 edits.push((
2740 emoji_shortcode_start..selection.start,
2741 "".to_string().into(),
2742 ));
2743 new_selections.push((
2744 Selection {
2745 id: selection.id,
2746 start: snapshot.anchor_after(emoji_shortcode_start),
2747 end: snapshot.anchor_before(selection.start),
2748 reversed: selection.reversed,
2749 goal: selection.goal,
2750 },
2751 0,
2752 ));
2753
2754 // Insert emoji
2755 let selection_start_anchor = snapshot.anchor_after(selection.start);
2756 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2757 edits.push((selection.start..selection.end, emoji.to_string().into()));
2758
2759 continue;
2760 }
2761 }
2762 }
2763 }
2764
2765 // If not handling any auto-close operation, then just replace the selected
2766 // text with the given input and move the selection to the end of the
2767 // newly inserted text.
2768 let anchor = snapshot.anchor_after(selection.end);
2769 if !self.linked_edit_ranges.is_empty() {
2770 let start_anchor = snapshot.anchor_before(selection.start);
2771
2772 let is_word_char = text.chars().next().map_or(true, |char| {
2773 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2774 classifier.is_word(char)
2775 });
2776
2777 if is_word_char {
2778 if let Some(ranges) = self
2779 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2780 {
2781 for (buffer, edits) in ranges {
2782 linked_edits
2783 .entry(buffer.clone())
2784 .or_default()
2785 .extend(edits.into_iter().map(|range| (range, text.clone())));
2786 }
2787 }
2788 }
2789 }
2790
2791 new_selections.push((selection.map(|_| anchor), 0));
2792 edits.push((selection.start..selection.end, text.clone()));
2793 }
2794
2795 drop(snapshot);
2796
2797 self.transact(cx, |this, cx| {
2798 this.buffer.update(cx, |buffer, cx| {
2799 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2800 });
2801 for (buffer, edits) in linked_edits {
2802 buffer.update(cx, |buffer, cx| {
2803 let snapshot = buffer.snapshot();
2804 let edits = edits
2805 .into_iter()
2806 .map(|(range, text)| {
2807 use text::ToPoint as TP;
2808 let end_point = TP::to_point(&range.end, &snapshot);
2809 let start_point = TP::to_point(&range.start, &snapshot);
2810 (start_point..end_point, text)
2811 })
2812 .sorted_by_key(|(range, _)| range.start)
2813 .collect::<Vec<_>>();
2814 buffer.edit(edits, None, cx);
2815 })
2816 }
2817 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2818 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2819 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2820 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2821 .zip(new_selection_deltas)
2822 .map(|(selection, delta)| Selection {
2823 id: selection.id,
2824 start: selection.start + delta,
2825 end: selection.end + delta,
2826 reversed: selection.reversed,
2827 goal: SelectionGoal::None,
2828 })
2829 .collect::<Vec<_>>();
2830
2831 let mut i = 0;
2832 for (position, delta, selection_id, pair) in new_autoclose_regions {
2833 let position = position.to_offset(&map.buffer_snapshot) + delta;
2834 let start = map.buffer_snapshot.anchor_before(position);
2835 let end = map.buffer_snapshot.anchor_after(position);
2836 while let Some(existing_state) = this.autoclose_regions.get(i) {
2837 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2838 Ordering::Less => i += 1,
2839 Ordering::Greater => break,
2840 Ordering::Equal => {
2841 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2842 Ordering::Less => i += 1,
2843 Ordering::Equal => break,
2844 Ordering::Greater => break,
2845 }
2846 }
2847 }
2848 }
2849 this.autoclose_regions.insert(
2850 i,
2851 AutocloseRegion {
2852 selection_id,
2853 range: start..end,
2854 pair,
2855 },
2856 );
2857 }
2858
2859 let had_active_inline_completion = this.has_active_inline_completion();
2860 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2861 s.select(new_selections)
2862 });
2863
2864 if !bracket_inserted {
2865 if let Some(on_type_format_task) =
2866 this.trigger_on_type_formatting(text.to_string(), cx)
2867 {
2868 on_type_format_task.detach_and_log_err(cx);
2869 }
2870 }
2871
2872 let editor_settings = EditorSettings::get_global(cx);
2873 if bracket_inserted
2874 && (editor_settings.auto_signature_help
2875 || editor_settings.show_signature_help_after_edits)
2876 {
2877 this.show_signature_help(&ShowSignatureHelp, cx);
2878 }
2879
2880 let trigger_in_words =
2881 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2882 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2883 linked_editing_ranges::refresh_linked_ranges(this, cx);
2884 this.refresh_inline_completion(true, false, cx);
2885 });
2886 }
2887
2888 fn find_possible_emoji_shortcode_at_position(
2889 snapshot: &MultiBufferSnapshot,
2890 position: Point,
2891 ) -> Option<String> {
2892 let mut chars = Vec::new();
2893 let mut found_colon = false;
2894 for char in snapshot.reversed_chars_at(position).take(100) {
2895 // Found a possible emoji shortcode in the middle of the buffer
2896 if found_colon {
2897 if char.is_whitespace() {
2898 chars.reverse();
2899 return Some(chars.iter().collect());
2900 }
2901 // If the previous character is not a whitespace, we are in the middle of a word
2902 // and we only want to complete the shortcode if the word is made up of other emojis
2903 let mut containing_word = String::new();
2904 for ch in snapshot
2905 .reversed_chars_at(position)
2906 .skip(chars.len() + 1)
2907 .take(100)
2908 {
2909 if ch.is_whitespace() {
2910 break;
2911 }
2912 containing_word.push(ch);
2913 }
2914 let containing_word = containing_word.chars().rev().collect::<String>();
2915 if util::word_consists_of_emojis(containing_word.as_str()) {
2916 chars.reverse();
2917 return Some(chars.iter().collect());
2918 }
2919 }
2920
2921 if char.is_whitespace() || !char.is_ascii() {
2922 return None;
2923 }
2924 if char == ':' {
2925 found_colon = true;
2926 } else {
2927 chars.push(char);
2928 }
2929 }
2930 // Found a possible emoji shortcode at the beginning of the buffer
2931 chars.reverse();
2932 Some(chars.iter().collect())
2933 }
2934
2935 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2936 self.transact(cx, |this, cx| {
2937 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2938 let selections = this.selections.all::<usize>(cx);
2939 let multi_buffer = this.buffer.read(cx);
2940 let buffer = multi_buffer.snapshot(cx);
2941 selections
2942 .iter()
2943 .map(|selection| {
2944 let start_point = selection.start.to_point(&buffer);
2945 let mut indent =
2946 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2947 indent.len = cmp::min(indent.len, start_point.column);
2948 let start = selection.start;
2949 let end = selection.end;
2950 let selection_is_empty = start == end;
2951 let language_scope = buffer.language_scope_at(start);
2952 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2953 &language_scope
2954 {
2955 let leading_whitespace_len = buffer
2956 .reversed_chars_at(start)
2957 .take_while(|c| c.is_whitespace() && *c != '\n')
2958 .map(|c| c.len_utf8())
2959 .sum::<usize>();
2960
2961 let trailing_whitespace_len = buffer
2962 .chars_at(end)
2963 .take_while(|c| c.is_whitespace() && *c != '\n')
2964 .map(|c| c.len_utf8())
2965 .sum::<usize>();
2966
2967 let insert_extra_newline =
2968 language.brackets().any(|(pair, enabled)| {
2969 let pair_start = pair.start.trim_end();
2970 let pair_end = pair.end.trim_start();
2971
2972 enabled
2973 && pair.newline
2974 && buffer.contains_str_at(
2975 end + trailing_whitespace_len,
2976 pair_end,
2977 )
2978 && buffer.contains_str_at(
2979 (start - leading_whitespace_len)
2980 .saturating_sub(pair_start.len()),
2981 pair_start,
2982 )
2983 });
2984
2985 // Comment extension on newline is allowed only for cursor selections
2986 let comment_delimiter = maybe!({
2987 if !selection_is_empty {
2988 return None;
2989 }
2990
2991 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2992 return None;
2993 }
2994
2995 let delimiters = language.line_comment_prefixes();
2996 let max_len_of_delimiter =
2997 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2998 let (snapshot, range) =
2999 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3000
3001 let mut index_of_first_non_whitespace = 0;
3002 let comment_candidate = snapshot
3003 .chars_for_range(range)
3004 .skip_while(|c| {
3005 let should_skip = c.is_whitespace();
3006 if should_skip {
3007 index_of_first_non_whitespace += 1;
3008 }
3009 should_skip
3010 })
3011 .take(max_len_of_delimiter)
3012 .collect::<String>();
3013 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3014 comment_candidate.starts_with(comment_prefix.as_ref())
3015 })?;
3016 let cursor_is_placed_after_comment_marker =
3017 index_of_first_non_whitespace + comment_prefix.len()
3018 <= start_point.column as usize;
3019 if cursor_is_placed_after_comment_marker {
3020 Some(comment_prefix.clone())
3021 } else {
3022 None
3023 }
3024 });
3025 (comment_delimiter, insert_extra_newline)
3026 } else {
3027 (None, false)
3028 };
3029
3030 let capacity_for_delimiter = comment_delimiter
3031 .as_deref()
3032 .map(str::len)
3033 .unwrap_or_default();
3034 let mut new_text =
3035 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3036 new_text.push('\n');
3037 new_text.extend(indent.chars());
3038 if let Some(delimiter) = &comment_delimiter {
3039 new_text.push_str(delimiter);
3040 }
3041 if insert_extra_newline {
3042 new_text = new_text.repeat(2);
3043 }
3044
3045 let anchor = buffer.anchor_after(end);
3046 let new_selection = selection.map(|_| anchor);
3047 (
3048 (start..end, new_text),
3049 (insert_extra_newline, new_selection),
3050 )
3051 })
3052 .unzip()
3053 };
3054
3055 this.edit_with_autoindent(edits, cx);
3056 let buffer = this.buffer.read(cx).snapshot(cx);
3057 let new_selections = selection_fixup_info
3058 .into_iter()
3059 .map(|(extra_newline_inserted, new_selection)| {
3060 let mut cursor = new_selection.end.to_point(&buffer);
3061 if extra_newline_inserted {
3062 cursor.row -= 1;
3063 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3064 }
3065 new_selection.map(|_| cursor)
3066 })
3067 .collect();
3068
3069 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3070 this.refresh_inline_completion(true, false, cx);
3071 });
3072 }
3073
3074 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3075 let buffer = self.buffer.read(cx);
3076 let snapshot = buffer.snapshot(cx);
3077
3078 let mut edits = Vec::new();
3079 let mut rows = Vec::new();
3080
3081 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3082 let cursor = selection.head();
3083 let row = cursor.row;
3084
3085 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3086
3087 let newline = "\n".to_string();
3088 edits.push((start_of_line..start_of_line, newline));
3089
3090 rows.push(row + rows_inserted as u32);
3091 }
3092
3093 self.transact(cx, |editor, cx| {
3094 editor.edit(edits, cx);
3095
3096 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3097 let mut index = 0;
3098 s.move_cursors_with(|map, _, _| {
3099 let row = rows[index];
3100 index += 1;
3101
3102 let point = Point::new(row, 0);
3103 let boundary = map.next_line_boundary(point).1;
3104 let clipped = map.clip_point(boundary, Bias::Left);
3105
3106 (clipped, SelectionGoal::None)
3107 });
3108 });
3109
3110 let mut indent_edits = Vec::new();
3111 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3112 for row in rows {
3113 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3114 for (row, indent) in indents {
3115 if indent.len == 0 {
3116 continue;
3117 }
3118
3119 let text = match indent.kind {
3120 IndentKind::Space => " ".repeat(indent.len as usize),
3121 IndentKind::Tab => "\t".repeat(indent.len as usize),
3122 };
3123 let point = Point::new(row.0, 0);
3124 indent_edits.push((point..point, text));
3125 }
3126 }
3127 editor.edit(indent_edits, cx);
3128 });
3129 }
3130
3131 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3132 let buffer = self.buffer.read(cx);
3133 let snapshot = buffer.snapshot(cx);
3134
3135 let mut edits = Vec::new();
3136 let mut rows = Vec::new();
3137 let mut rows_inserted = 0;
3138
3139 for selection in self.selections.all_adjusted(cx) {
3140 let cursor = selection.head();
3141 let row = cursor.row;
3142
3143 let point = Point::new(row + 1, 0);
3144 let start_of_line = snapshot.clip_point(point, Bias::Left);
3145
3146 let newline = "\n".to_string();
3147 edits.push((start_of_line..start_of_line, newline));
3148
3149 rows_inserted += 1;
3150 rows.push(row + rows_inserted);
3151 }
3152
3153 self.transact(cx, |editor, cx| {
3154 editor.edit(edits, cx);
3155
3156 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3157 let mut index = 0;
3158 s.move_cursors_with(|map, _, _| {
3159 let row = rows[index];
3160 index += 1;
3161
3162 let point = Point::new(row, 0);
3163 let boundary = map.next_line_boundary(point).1;
3164 let clipped = map.clip_point(boundary, Bias::Left);
3165
3166 (clipped, SelectionGoal::None)
3167 });
3168 });
3169
3170 let mut indent_edits = Vec::new();
3171 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3172 for row in rows {
3173 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3174 for (row, indent) in indents {
3175 if indent.len == 0 {
3176 continue;
3177 }
3178
3179 let text = match indent.kind {
3180 IndentKind::Space => " ".repeat(indent.len as usize),
3181 IndentKind::Tab => "\t".repeat(indent.len as usize),
3182 };
3183 let point = Point::new(row.0, 0);
3184 indent_edits.push((point..point, text));
3185 }
3186 }
3187 editor.edit(indent_edits, cx);
3188 });
3189 }
3190
3191 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3192 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3193 original_indent_columns: Vec::new(),
3194 });
3195 self.insert_with_autoindent_mode(text, autoindent, cx);
3196 }
3197
3198 fn insert_with_autoindent_mode(
3199 &mut self,
3200 text: &str,
3201 autoindent_mode: Option<AutoindentMode>,
3202 cx: &mut ViewContext<Self>,
3203 ) {
3204 if self.read_only(cx) {
3205 return;
3206 }
3207
3208 let text: Arc<str> = text.into();
3209 self.transact(cx, |this, cx| {
3210 let old_selections = this.selections.all_adjusted(cx);
3211 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3212 let anchors = {
3213 let snapshot = buffer.read(cx);
3214 old_selections
3215 .iter()
3216 .map(|s| {
3217 let anchor = snapshot.anchor_after(s.head());
3218 s.map(|_| anchor)
3219 })
3220 .collect::<Vec<_>>()
3221 };
3222 buffer.edit(
3223 old_selections
3224 .iter()
3225 .map(|s| (s.start..s.end, text.clone())),
3226 autoindent_mode,
3227 cx,
3228 );
3229 anchors
3230 });
3231
3232 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3233 s.select_anchors(selection_anchors);
3234 })
3235 });
3236 }
3237
3238 fn trigger_completion_on_input(
3239 &mut self,
3240 text: &str,
3241 trigger_in_words: bool,
3242 cx: &mut ViewContext<Self>,
3243 ) {
3244 if self.is_completion_trigger(text, trigger_in_words, cx) {
3245 self.show_completions(
3246 &ShowCompletions {
3247 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3248 },
3249 cx,
3250 );
3251 } else {
3252 self.hide_context_menu(cx);
3253 }
3254 }
3255
3256 fn is_completion_trigger(
3257 &self,
3258 text: &str,
3259 trigger_in_words: bool,
3260 cx: &mut ViewContext<Self>,
3261 ) -> bool {
3262 let position = self.selections.newest_anchor().head();
3263 let multibuffer = self.buffer.read(cx);
3264 let Some(buffer) = position
3265 .buffer_id
3266 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3267 else {
3268 return false;
3269 };
3270
3271 if let Some(completion_provider) = &self.completion_provider {
3272 completion_provider.is_completion_trigger(
3273 &buffer,
3274 position.text_anchor,
3275 text,
3276 trigger_in_words,
3277 cx,
3278 )
3279 } else {
3280 false
3281 }
3282 }
3283
3284 /// If any empty selections is touching the start of its innermost containing autoclose
3285 /// region, expand it to select the brackets.
3286 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3287 let selections = self.selections.all::<usize>(cx);
3288 let buffer = self.buffer.read(cx).read(cx);
3289 let new_selections = self
3290 .selections_with_autoclose_regions(selections, &buffer)
3291 .map(|(mut selection, region)| {
3292 if !selection.is_empty() {
3293 return selection;
3294 }
3295
3296 if let Some(region) = region {
3297 let mut range = region.range.to_offset(&buffer);
3298 if selection.start == range.start && range.start >= region.pair.start.len() {
3299 range.start -= region.pair.start.len();
3300 if buffer.contains_str_at(range.start, ®ion.pair.start)
3301 && buffer.contains_str_at(range.end, ®ion.pair.end)
3302 {
3303 range.end += region.pair.end.len();
3304 selection.start = range.start;
3305 selection.end = range.end;
3306
3307 return selection;
3308 }
3309 }
3310 }
3311
3312 let always_treat_brackets_as_autoclosed = buffer
3313 .settings_at(selection.start, cx)
3314 .always_treat_brackets_as_autoclosed;
3315
3316 if !always_treat_brackets_as_autoclosed {
3317 return selection;
3318 }
3319
3320 if let Some(scope) = buffer.language_scope_at(selection.start) {
3321 for (pair, enabled) in scope.brackets() {
3322 if !enabled || !pair.close {
3323 continue;
3324 }
3325
3326 if buffer.contains_str_at(selection.start, &pair.end) {
3327 let pair_start_len = pair.start.len();
3328 if buffer.contains_str_at(
3329 selection.start.saturating_sub(pair_start_len),
3330 &pair.start,
3331 ) {
3332 selection.start -= pair_start_len;
3333 selection.end += pair.end.len();
3334
3335 return selection;
3336 }
3337 }
3338 }
3339 }
3340
3341 selection
3342 })
3343 .collect();
3344
3345 drop(buffer);
3346 self.change_selections(None, cx, |selections| selections.select(new_selections));
3347 }
3348
3349 /// Iterate the given selections, and for each one, find the smallest surrounding
3350 /// autoclose region. This uses the ordering of the selections and the autoclose
3351 /// regions to avoid repeated comparisons.
3352 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3353 &'a self,
3354 selections: impl IntoIterator<Item = Selection<D>>,
3355 buffer: &'a MultiBufferSnapshot,
3356 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3357 let mut i = 0;
3358 let mut regions = self.autoclose_regions.as_slice();
3359 selections.into_iter().map(move |selection| {
3360 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3361
3362 let mut enclosing = None;
3363 while let Some(pair_state) = regions.get(i) {
3364 if pair_state.range.end.to_offset(buffer) < range.start {
3365 regions = ®ions[i + 1..];
3366 i = 0;
3367 } else if pair_state.range.start.to_offset(buffer) > range.end {
3368 break;
3369 } else {
3370 if pair_state.selection_id == selection.id {
3371 enclosing = Some(pair_state);
3372 }
3373 i += 1;
3374 }
3375 }
3376
3377 (selection, enclosing)
3378 })
3379 }
3380
3381 /// Remove any autoclose regions that no longer contain their selection.
3382 fn invalidate_autoclose_regions(
3383 &mut self,
3384 mut selections: &[Selection<Anchor>],
3385 buffer: &MultiBufferSnapshot,
3386 ) {
3387 self.autoclose_regions.retain(|state| {
3388 let mut i = 0;
3389 while let Some(selection) = selections.get(i) {
3390 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3391 selections = &selections[1..];
3392 continue;
3393 }
3394 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3395 break;
3396 }
3397 if selection.id == state.selection_id {
3398 return true;
3399 } else {
3400 i += 1;
3401 }
3402 }
3403 false
3404 });
3405 }
3406
3407 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3408 let offset = position.to_offset(buffer);
3409 let (word_range, kind) = buffer.surrounding_word(offset, true);
3410 if offset > word_range.start && kind == Some(CharKind::Word) {
3411 Some(
3412 buffer
3413 .text_for_range(word_range.start..offset)
3414 .collect::<String>(),
3415 )
3416 } else {
3417 None
3418 }
3419 }
3420
3421 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3422 self.refresh_inlay_hints(
3423 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3424 cx,
3425 );
3426 }
3427
3428 pub fn inlay_hints_enabled(&self) -> bool {
3429 self.inlay_hint_cache.enabled
3430 }
3431
3432 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3433 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3434 return;
3435 }
3436
3437 let reason_description = reason.description();
3438 let ignore_debounce = matches!(
3439 reason,
3440 InlayHintRefreshReason::SettingsChange(_)
3441 | InlayHintRefreshReason::Toggle(_)
3442 | InlayHintRefreshReason::ExcerptsRemoved(_)
3443 );
3444 let (invalidate_cache, required_languages) = match reason {
3445 InlayHintRefreshReason::Toggle(enabled) => {
3446 self.inlay_hint_cache.enabled = enabled;
3447 if enabled {
3448 (InvalidationStrategy::RefreshRequested, None)
3449 } else {
3450 self.inlay_hint_cache.clear();
3451 self.splice_inlays(
3452 self.visible_inlay_hints(cx)
3453 .iter()
3454 .map(|inlay| inlay.id)
3455 .collect(),
3456 Vec::new(),
3457 cx,
3458 );
3459 return;
3460 }
3461 }
3462 InlayHintRefreshReason::SettingsChange(new_settings) => {
3463 match self.inlay_hint_cache.update_settings(
3464 &self.buffer,
3465 new_settings,
3466 self.visible_inlay_hints(cx),
3467 cx,
3468 ) {
3469 ControlFlow::Break(Some(InlaySplice {
3470 to_remove,
3471 to_insert,
3472 })) => {
3473 self.splice_inlays(to_remove, to_insert, cx);
3474 return;
3475 }
3476 ControlFlow::Break(None) => return,
3477 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3478 }
3479 }
3480 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3481 if let Some(InlaySplice {
3482 to_remove,
3483 to_insert,
3484 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3485 {
3486 self.splice_inlays(to_remove, to_insert, cx);
3487 }
3488 return;
3489 }
3490 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3491 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3492 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3493 }
3494 InlayHintRefreshReason::RefreshRequested => {
3495 (InvalidationStrategy::RefreshRequested, None)
3496 }
3497 };
3498
3499 if let Some(InlaySplice {
3500 to_remove,
3501 to_insert,
3502 }) = self.inlay_hint_cache.spawn_hint_refresh(
3503 reason_description,
3504 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3505 invalidate_cache,
3506 ignore_debounce,
3507 cx,
3508 ) {
3509 self.splice_inlays(to_remove, to_insert, cx);
3510 }
3511 }
3512
3513 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3514 self.display_map
3515 .read(cx)
3516 .current_inlays()
3517 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3518 .cloned()
3519 .collect()
3520 }
3521
3522 pub fn excerpts_for_inlay_hints_query(
3523 &self,
3524 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3525 cx: &mut ViewContext<Editor>,
3526 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3527 let Some(project) = self.project.as_ref() else {
3528 return HashMap::default();
3529 };
3530 let project = project.read(cx);
3531 let multi_buffer = self.buffer().read(cx);
3532 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3533 let multi_buffer_visible_start = self
3534 .scroll_manager
3535 .anchor()
3536 .anchor
3537 .to_point(&multi_buffer_snapshot);
3538 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3539 multi_buffer_visible_start
3540 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3541 Bias::Left,
3542 );
3543 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3544 multi_buffer
3545 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3546 .into_iter()
3547 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3548 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3549 let buffer = buffer_handle.read(cx);
3550 let buffer_file = project::File::from_dyn(buffer.file())?;
3551 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3552 let worktree_entry = buffer_worktree
3553 .read(cx)
3554 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3555 if worktree_entry.is_ignored {
3556 return None;
3557 }
3558
3559 let language = buffer.language()?;
3560 if let Some(restrict_to_languages) = restrict_to_languages {
3561 if !restrict_to_languages.contains(language) {
3562 return None;
3563 }
3564 }
3565 Some((
3566 excerpt_id,
3567 (
3568 buffer_handle,
3569 buffer.version().clone(),
3570 excerpt_visible_range,
3571 ),
3572 ))
3573 })
3574 .collect()
3575 }
3576
3577 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3578 TextLayoutDetails {
3579 text_system: cx.text_system().clone(),
3580 editor_style: self.style.clone().unwrap(),
3581 rem_size: cx.rem_size(),
3582 scroll_anchor: self.scroll_manager.anchor(),
3583 visible_rows: self.visible_line_count(),
3584 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3585 }
3586 }
3587
3588 fn splice_inlays(
3589 &self,
3590 to_remove: Vec<InlayId>,
3591 to_insert: Vec<Inlay>,
3592 cx: &mut ViewContext<Self>,
3593 ) {
3594 self.display_map.update(cx, |display_map, cx| {
3595 display_map.splice_inlays(to_remove, to_insert, cx)
3596 });
3597 cx.notify();
3598 }
3599
3600 fn trigger_on_type_formatting(
3601 &self,
3602 input: String,
3603 cx: &mut ViewContext<Self>,
3604 ) -> Option<Task<Result<()>>> {
3605 if input.len() != 1 {
3606 return None;
3607 }
3608
3609 let project = self.project.as_ref()?;
3610 let position = self.selections.newest_anchor().head();
3611 let (buffer, buffer_position) = self
3612 .buffer
3613 .read(cx)
3614 .text_anchor_for_position(position, cx)?;
3615
3616 let settings = language_settings::language_settings(
3617 buffer
3618 .read(cx)
3619 .language_at(buffer_position)
3620 .map(|l| l.name()),
3621 buffer.read(cx).file(),
3622 cx,
3623 );
3624 if !settings.use_on_type_format {
3625 return None;
3626 }
3627
3628 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3629 // hence we do LSP request & edit on host side only — add formats to host's history.
3630 let push_to_lsp_host_history = true;
3631 // If this is not the host, append its history with new edits.
3632 let push_to_client_history = project.read(cx).is_via_collab();
3633
3634 let on_type_formatting = project.update(cx, |project, cx| {
3635 project.on_type_format(
3636 buffer.clone(),
3637 buffer_position,
3638 input,
3639 push_to_lsp_host_history,
3640 cx,
3641 )
3642 });
3643 Some(cx.spawn(|editor, mut cx| async move {
3644 if let Some(transaction) = on_type_formatting.await? {
3645 if push_to_client_history {
3646 buffer
3647 .update(&mut cx, |buffer, _| {
3648 buffer.push_transaction(transaction, Instant::now());
3649 })
3650 .ok();
3651 }
3652 editor.update(&mut cx, |editor, cx| {
3653 editor.refresh_document_highlights(cx);
3654 })?;
3655 }
3656 Ok(())
3657 }))
3658 }
3659
3660 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3661 if self.pending_rename.is_some() {
3662 return;
3663 }
3664
3665 let Some(provider) = self.completion_provider.as_ref() else {
3666 return;
3667 };
3668
3669 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3670 return;
3671 }
3672
3673 let position = self.selections.newest_anchor().head();
3674 let (buffer, buffer_position) =
3675 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3676 output
3677 } else {
3678 return;
3679 };
3680 let show_completion_documentation = buffer
3681 .read(cx)
3682 .snapshot()
3683 .settings_at(buffer_position, cx)
3684 .show_completion_documentation;
3685
3686 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3687
3688 let trigger_kind = match &options.trigger {
3689 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3690 CompletionTriggerKind::TRIGGER_CHARACTER
3691 }
3692 _ => CompletionTriggerKind::INVOKED,
3693 };
3694 let completion_context = CompletionContext {
3695 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3696 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3697 Some(String::from(trigger))
3698 } else {
3699 None
3700 }
3701 }),
3702 trigger_kind,
3703 };
3704 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3705 let sort_completions = provider.sort_completions();
3706
3707 let id = post_inc(&mut self.next_completion_id);
3708 let task = cx.spawn(|editor, mut cx| {
3709 async move {
3710 editor.update(&mut cx, |this, _| {
3711 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3712 })?;
3713 let completions = completions.await.log_err();
3714 let menu = if let Some(completions) = completions {
3715 let mut menu = CompletionsMenu::new(
3716 id,
3717 sort_completions,
3718 show_completion_documentation,
3719 position,
3720 buffer.clone(),
3721 completions.into(),
3722 );
3723
3724 menu.filter(query.as_deref(), cx.background_executor().clone())
3725 .await;
3726
3727 menu.visible().then_some(menu)
3728 } else {
3729 None
3730 };
3731
3732 editor.update(&mut cx, |editor, cx| {
3733 match editor.context_menu.borrow().as_ref() {
3734 None => {}
3735 Some(CodeContextMenu::Completions(prev_menu)) => {
3736 if prev_menu.id > id {
3737 return;
3738 }
3739 }
3740 _ => return,
3741 }
3742
3743 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3744 let mut menu = menu.unwrap();
3745 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
3746
3747 if editor.show_inline_completions_in_menu(cx) {
3748 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3749 editor.hide_active_inline_completion(cx);
3750 menu.show_inline_completion_hint(hint);
3751 }
3752 } else {
3753 editor.discard_inline_completion(false, cx);
3754 }
3755
3756 *editor.context_menu.borrow_mut() =
3757 Some(CodeContextMenu::Completions(menu));
3758
3759 cx.notify();
3760 } else if editor.completion_tasks.len() <= 1 {
3761 // If there are no more completion tasks and the last menu was
3762 // empty, we should hide it.
3763 let was_hidden = editor.hide_context_menu(cx).is_none();
3764 // If it was already hidden and we don't show inline
3765 // completions in the menu, we should also show the
3766 // inline-completion when available.
3767 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3768 editor.update_visible_inline_completion(cx);
3769 }
3770 }
3771 })?;
3772
3773 Ok::<_, anyhow::Error>(())
3774 }
3775 .log_err()
3776 });
3777
3778 self.completion_tasks.push((id, task));
3779 }
3780
3781 pub fn confirm_completion(
3782 &mut self,
3783 action: &ConfirmCompletion,
3784 cx: &mut ViewContext<Self>,
3785 ) -> Option<Task<Result<()>>> {
3786 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3787 }
3788
3789 pub fn compose_completion(
3790 &mut self,
3791 action: &ComposeCompletion,
3792 cx: &mut ViewContext<Self>,
3793 ) -> Option<Task<Result<()>>> {
3794 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3795 }
3796
3797 fn do_completion(
3798 &mut self,
3799 item_ix: Option<usize>,
3800 intent: CompletionIntent,
3801 cx: &mut ViewContext<Editor>,
3802 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3803 use language::ToOffset as _;
3804
3805 let completions_menu =
3806 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3807 menu
3808 } else {
3809 return None;
3810 };
3811
3812 let mat = completions_menu
3813 .entries
3814 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3815
3816 let mat = match mat {
3817 CompletionEntry::InlineCompletionHint { .. } => {
3818 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3819 cx.stop_propagation();
3820 return Some(Task::ready(Ok(())));
3821 }
3822 CompletionEntry::Match(mat) => {
3823 if self.show_inline_completions_in_menu(cx) {
3824 self.discard_inline_completion(true, cx);
3825 }
3826 mat
3827 }
3828 };
3829
3830 let buffer_handle = completions_menu.buffer;
3831 let completion = completions_menu
3832 .completions
3833 .borrow()
3834 .get(mat.candidate_id)?
3835 .clone();
3836 cx.stop_propagation();
3837
3838 let snippet;
3839 let text;
3840
3841 if completion.is_snippet() {
3842 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3843 text = snippet.as_ref().unwrap().text.clone();
3844 } else {
3845 snippet = None;
3846 text = completion.new_text.clone();
3847 };
3848 let selections = self.selections.all::<usize>(cx);
3849 let buffer = buffer_handle.read(cx);
3850 let old_range = completion.old_range.to_offset(buffer);
3851 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3852
3853 let newest_selection = self.selections.newest_anchor();
3854 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3855 return None;
3856 }
3857
3858 let lookbehind = newest_selection
3859 .start
3860 .text_anchor
3861 .to_offset(buffer)
3862 .saturating_sub(old_range.start);
3863 let lookahead = old_range
3864 .end
3865 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3866 let mut common_prefix_len = old_text
3867 .bytes()
3868 .zip(text.bytes())
3869 .take_while(|(a, b)| a == b)
3870 .count();
3871
3872 let snapshot = self.buffer.read(cx).snapshot(cx);
3873 let mut range_to_replace: Option<Range<isize>> = None;
3874 let mut ranges = Vec::new();
3875 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3876 for selection in &selections {
3877 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3878 let start = selection.start.saturating_sub(lookbehind);
3879 let end = selection.end + lookahead;
3880 if selection.id == newest_selection.id {
3881 range_to_replace = Some(
3882 ((start + common_prefix_len) as isize - selection.start as isize)
3883 ..(end as isize - selection.start as isize),
3884 );
3885 }
3886 ranges.push(start + common_prefix_len..end);
3887 } else {
3888 common_prefix_len = 0;
3889 ranges.clear();
3890 ranges.extend(selections.iter().map(|s| {
3891 if s.id == newest_selection.id {
3892 range_to_replace = Some(
3893 old_range.start.to_offset_utf16(&snapshot).0 as isize
3894 - selection.start as isize
3895 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3896 - selection.start as isize,
3897 );
3898 old_range.clone()
3899 } else {
3900 s.start..s.end
3901 }
3902 }));
3903 break;
3904 }
3905 if !self.linked_edit_ranges.is_empty() {
3906 let start_anchor = snapshot.anchor_before(selection.head());
3907 let end_anchor = snapshot.anchor_after(selection.tail());
3908 if let Some(ranges) = self
3909 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3910 {
3911 for (buffer, edits) in ranges {
3912 linked_edits.entry(buffer.clone()).or_default().extend(
3913 edits
3914 .into_iter()
3915 .map(|range| (range, text[common_prefix_len..].to_owned())),
3916 );
3917 }
3918 }
3919 }
3920 }
3921 let text = &text[common_prefix_len..];
3922
3923 cx.emit(EditorEvent::InputHandled {
3924 utf16_range_to_replace: range_to_replace,
3925 text: text.into(),
3926 });
3927
3928 self.transact(cx, |this, cx| {
3929 if let Some(mut snippet) = snippet {
3930 snippet.text = text.to_string();
3931 for tabstop in snippet
3932 .tabstops
3933 .iter_mut()
3934 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3935 {
3936 tabstop.start -= common_prefix_len as isize;
3937 tabstop.end -= common_prefix_len as isize;
3938 }
3939
3940 this.insert_snippet(&ranges, snippet, cx).log_err();
3941 } else {
3942 this.buffer.update(cx, |buffer, cx| {
3943 buffer.edit(
3944 ranges.iter().map(|range| (range.clone(), text)),
3945 this.autoindent_mode.clone(),
3946 cx,
3947 );
3948 });
3949 }
3950 for (buffer, edits) in linked_edits {
3951 buffer.update(cx, |buffer, cx| {
3952 let snapshot = buffer.snapshot();
3953 let edits = edits
3954 .into_iter()
3955 .map(|(range, text)| {
3956 use text::ToPoint as TP;
3957 let end_point = TP::to_point(&range.end, &snapshot);
3958 let start_point = TP::to_point(&range.start, &snapshot);
3959 (start_point..end_point, text)
3960 })
3961 .sorted_by_key(|(range, _)| range.start)
3962 .collect::<Vec<_>>();
3963 buffer.edit(edits, None, cx);
3964 })
3965 }
3966
3967 this.refresh_inline_completion(true, false, cx);
3968 });
3969
3970 let show_new_completions_on_confirm = completion
3971 .confirm
3972 .as_ref()
3973 .map_or(false, |confirm| confirm(intent, cx));
3974 if show_new_completions_on_confirm {
3975 self.show_completions(&ShowCompletions { trigger: None }, cx);
3976 }
3977
3978 let provider = self.completion_provider.as_ref()?;
3979 drop(completion);
3980 let apply_edits = provider.apply_additional_edits_for_completion(
3981 buffer_handle,
3982 completions_menu.completions.clone(),
3983 mat.candidate_id,
3984 true,
3985 cx,
3986 );
3987
3988 let editor_settings = EditorSettings::get_global(cx);
3989 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3990 // After the code completion is finished, users often want to know what signatures are needed.
3991 // so we should automatically call signature_help
3992 self.show_signature_help(&ShowSignatureHelp, cx);
3993 }
3994
3995 Some(cx.foreground_executor().spawn(async move {
3996 apply_edits.await?;
3997 Ok(())
3998 }))
3999 }
4000
4001 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4002 let mut context_menu = self.context_menu.borrow_mut();
4003 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4004 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4005 // Toggle if we're selecting the same one
4006 *context_menu = None;
4007 cx.notify();
4008 return;
4009 } else {
4010 // Otherwise, clear it and start a new one
4011 *context_menu = None;
4012 cx.notify();
4013 }
4014 }
4015 drop(context_menu);
4016 let snapshot = self.snapshot(cx);
4017 let deployed_from_indicator = action.deployed_from_indicator;
4018 let mut task = self.code_actions_task.take();
4019 let action = action.clone();
4020 cx.spawn(|editor, mut cx| async move {
4021 while let Some(prev_task) = task {
4022 prev_task.await.log_err();
4023 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4024 }
4025
4026 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4027 if editor.focus_handle.is_focused(cx) {
4028 let multibuffer_point = action
4029 .deployed_from_indicator
4030 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4031 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4032 let (buffer, buffer_row) = snapshot
4033 .buffer_snapshot
4034 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4035 .and_then(|(buffer_snapshot, range)| {
4036 editor
4037 .buffer
4038 .read(cx)
4039 .buffer(buffer_snapshot.remote_id())
4040 .map(|buffer| (buffer, range.start.row))
4041 })?;
4042 let (_, code_actions) = editor
4043 .available_code_actions
4044 .clone()
4045 .and_then(|(location, code_actions)| {
4046 let snapshot = location.buffer.read(cx).snapshot();
4047 let point_range = location.range.to_point(&snapshot);
4048 let point_range = point_range.start.row..=point_range.end.row;
4049 if point_range.contains(&buffer_row) {
4050 Some((location, code_actions))
4051 } else {
4052 None
4053 }
4054 })
4055 .unzip();
4056 let buffer_id = buffer.read(cx).remote_id();
4057 let tasks = editor
4058 .tasks
4059 .get(&(buffer_id, buffer_row))
4060 .map(|t| Arc::new(t.to_owned()));
4061 if tasks.is_none() && code_actions.is_none() {
4062 return None;
4063 }
4064
4065 editor.completion_tasks.clear();
4066 editor.discard_inline_completion(false, cx);
4067 let task_context =
4068 tasks
4069 .as_ref()
4070 .zip(editor.project.clone())
4071 .map(|(tasks, project)| {
4072 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4073 });
4074
4075 Some(cx.spawn(|editor, mut cx| async move {
4076 let task_context = match task_context {
4077 Some(task_context) => task_context.await,
4078 None => None,
4079 };
4080 let resolved_tasks =
4081 tasks.zip(task_context).map(|(tasks, task_context)| {
4082 Rc::new(ResolvedTasks {
4083 templates: tasks.resolve(&task_context).collect(),
4084 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4085 multibuffer_point.row,
4086 tasks.column,
4087 )),
4088 })
4089 });
4090 let spawn_straight_away = resolved_tasks
4091 .as_ref()
4092 .map_or(false, |tasks| tasks.templates.len() == 1)
4093 && code_actions
4094 .as_ref()
4095 .map_or(true, |actions| actions.is_empty());
4096 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4097 *editor.context_menu.borrow_mut() =
4098 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4099 buffer,
4100 actions: CodeActionContents {
4101 tasks: resolved_tasks,
4102 actions: code_actions,
4103 },
4104 selected_item: Default::default(),
4105 scroll_handle: UniformListScrollHandle::default(),
4106 deployed_from_indicator,
4107 }));
4108 if spawn_straight_away {
4109 if let Some(task) = editor.confirm_code_action(
4110 &ConfirmCodeAction { item_ix: Some(0) },
4111 cx,
4112 ) {
4113 cx.notify();
4114 return task;
4115 }
4116 }
4117 cx.notify();
4118 Task::ready(Ok(()))
4119 }) {
4120 task.await
4121 } else {
4122 Ok(())
4123 }
4124 }))
4125 } else {
4126 Some(Task::ready(Ok(())))
4127 }
4128 })?;
4129 if let Some(task) = spawned_test_task {
4130 task.await?;
4131 }
4132
4133 Ok::<_, anyhow::Error>(())
4134 })
4135 .detach_and_log_err(cx);
4136 }
4137
4138 pub fn confirm_code_action(
4139 &mut self,
4140 action: &ConfirmCodeAction,
4141 cx: &mut ViewContext<Self>,
4142 ) -> Option<Task<Result<()>>> {
4143 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4144 menu
4145 } else {
4146 return None;
4147 };
4148 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4149 let action = actions_menu.actions.get(action_ix)?;
4150 let title = action.label();
4151 let buffer = actions_menu.buffer;
4152 let workspace = self.workspace()?;
4153
4154 match action {
4155 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4156 workspace.update(cx, |workspace, cx| {
4157 workspace::tasks::schedule_resolved_task(
4158 workspace,
4159 task_source_kind,
4160 resolved_task,
4161 false,
4162 cx,
4163 );
4164
4165 Some(Task::ready(Ok(())))
4166 })
4167 }
4168 CodeActionsItem::CodeAction {
4169 excerpt_id,
4170 action,
4171 provider,
4172 } => {
4173 let apply_code_action =
4174 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4175 let workspace = workspace.downgrade();
4176 Some(cx.spawn(|editor, cx| async move {
4177 let project_transaction = apply_code_action.await?;
4178 Self::open_project_transaction(
4179 &editor,
4180 workspace,
4181 project_transaction,
4182 title,
4183 cx,
4184 )
4185 .await
4186 }))
4187 }
4188 }
4189 }
4190
4191 pub async fn open_project_transaction(
4192 this: &WeakView<Editor>,
4193 workspace: WeakView<Workspace>,
4194 transaction: ProjectTransaction,
4195 title: String,
4196 mut cx: AsyncWindowContext,
4197 ) -> Result<()> {
4198 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4199 cx.update(|cx| {
4200 entries.sort_unstable_by_key(|(buffer, _)| {
4201 buffer.read(cx).file().map(|f| f.path().clone())
4202 });
4203 })?;
4204
4205 // If the project transaction's edits are all contained within this editor, then
4206 // avoid opening a new editor to display them.
4207
4208 if let Some((buffer, transaction)) = entries.first() {
4209 if entries.len() == 1 {
4210 let excerpt = this.update(&mut cx, |editor, cx| {
4211 editor
4212 .buffer()
4213 .read(cx)
4214 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4215 })?;
4216 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4217 if excerpted_buffer == *buffer {
4218 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4219 let excerpt_range = excerpt_range.to_offset(buffer);
4220 buffer
4221 .edited_ranges_for_transaction::<usize>(transaction)
4222 .all(|range| {
4223 excerpt_range.start <= range.start
4224 && excerpt_range.end >= range.end
4225 })
4226 })?;
4227
4228 if all_edits_within_excerpt {
4229 return Ok(());
4230 }
4231 }
4232 }
4233 }
4234 } else {
4235 return Ok(());
4236 }
4237
4238 let mut ranges_to_highlight = Vec::new();
4239 let excerpt_buffer = cx.new_model(|cx| {
4240 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4241 for (buffer_handle, transaction) in &entries {
4242 let buffer = buffer_handle.read(cx);
4243 ranges_to_highlight.extend(
4244 multibuffer.push_excerpts_with_context_lines(
4245 buffer_handle.clone(),
4246 buffer
4247 .edited_ranges_for_transaction::<usize>(transaction)
4248 .collect(),
4249 DEFAULT_MULTIBUFFER_CONTEXT,
4250 cx,
4251 ),
4252 );
4253 }
4254 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4255 multibuffer
4256 })?;
4257
4258 workspace.update(&mut cx, |workspace, cx| {
4259 let project = workspace.project().clone();
4260 let editor =
4261 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4262 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4263 editor.update(cx, |editor, cx| {
4264 editor.highlight_background::<Self>(
4265 &ranges_to_highlight,
4266 |theme| theme.editor_highlighted_line_background,
4267 cx,
4268 );
4269 });
4270 })?;
4271
4272 Ok(())
4273 }
4274
4275 pub fn clear_code_action_providers(&mut self) {
4276 self.code_action_providers.clear();
4277 self.available_code_actions.take();
4278 }
4279
4280 pub fn push_code_action_provider(
4281 &mut self,
4282 provider: Rc<dyn CodeActionProvider>,
4283 cx: &mut ViewContext<Self>,
4284 ) {
4285 self.code_action_providers.push(provider);
4286 self.refresh_code_actions(cx);
4287 }
4288
4289 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4290 let buffer = self.buffer.read(cx);
4291 let newest_selection = self.selections.newest_anchor().clone();
4292 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4293 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4294 if start_buffer != end_buffer {
4295 return None;
4296 }
4297
4298 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4299 cx.background_executor()
4300 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4301 .await;
4302
4303 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4304 let providers = this.code_action_providers.clone();
4305 let tasks = this
4306 .code_action_providers
4307 .iter()
4308 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4309 .collect::<Vec<_>>();
4310 (providers, tasks)
4311 })?;
4312
4313 let mut actions = Vec::new();
4314 for (provider, provider_actions) in
4315 providers.into_iter().zip(future::join_all(tasks).await)
4316 {
4317 if let Some(provider_actions) = provider_actions.log_err() {
4318 actions.extend(provider_actions.into_iter().map(|action| {
4319 AvailableCodeAction {
4320 excerpt_id: newest_selection.start.excerpt_id,
4321 action,
4322 provider: provider.clone(),
4323 }
4324 }));
4325 }
4326 }
4327
4328 this.update(&mut cx, |this, cx| {
4329 this.available_code_actions = if actions.is_empty() {
4330 None
4331 } else {
4332 Some((
4333 Location {
4334 buffer: start_buffer,
4335 range: start..end,
4336 },
4337 actions.into(),
4338 ))
4339 };
4340 cx.notify();
4341 })
4342 }));
4343 None
4344 }
4345
4346 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4347 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4348 self.show_git_blame_inline = false;
4349
4350 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4351 cx.background_executor().timer(delay).await;
4352
4353 this.update(&mut cx, |this, cx| {
4354 this.show_git_blame_inline = true;
4355 cx.notify();
4356 })
4357 .log_err();
4358 }));
4359 }
4360 }
4361
4362 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4363 if self.pending_rename.is_some() {
4364 return None;
4365 }
4366
4367 let provider = self.semantics_provider.clone()?;
4368 let buffer = self.buffer.read(cx);
4369 let newest_selection = self.selections.newest_anchor().clone();
4370 let cursor_position = newest_selection.head();
4371 let (cursor_buffer, cursor_buffer_position) =
4372 buffer.text_anchor_for_position(cursor_position, cx)?;
4373 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4374 if cursor_buffer != tail_buffer {
4375 return None;
4376 }
4377 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4378 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4379 cx.background_executor()
4380 .timer(Duration::from_millis(debounce))
4381 .await;
4382
4383 let highlights = if let Some(highlights) = cx
4384 .update(|cx| {
4385 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4386 })
4387 .ok()
4388 .flatten()
4389 {
4390 highlights.await.log_err()
4391 } else {
4392 None
4393 };
4394
4395 if let Some(highlights) = highlights {
4396 this.update(&mut cx, |this, cx| {
4397 if this.pending_rename.is_some() {
4398 return;
4399 }
4400
4401 let buffer_id = cursor_position.buffer_id;
4402 let buffer = this.buffer.read(cx);
4403 if !buffer
4404 .text_anchor_for_position(cursor_position, cx)
4405 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4406 {
4407 return;
4408 }
4409
4410 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4411 let mut write_ranges = Vec::new();
4412 let mut read_ranges = Vec::new();
4413 for highlight in highlights {
4414 for (excerpt_id, excerpt_range) in
4415 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4416 {
4417 let start = highlight
4418 .range
4419 .start
4420 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4421 let end = highlight
4422 .range
4423 .end
4424 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4425 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4426 continue;
4427 }
4428
4429 let range = Anchor {
4430 buffer_id,
4431 excerpt_id,
4432 text_anchor: start,
4433 }..Anchor {
4434 buffer_id,
4435 excerpt_id,
4436 text_anchor: end,
4437 };
4438 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4439 write_ranges.push(range);
4440 } else {
4441 read_ranges.push(range);
4442 }
4443 }
4444 }
4445
4446 this.highlight_background::<DocumentHighlightRead>(
4447 &read_ranges,
4448 |theme| theme.editor_document_highlight_read_background,
4449 cx,
4450 );
4451 this.highlight_background::<DocumentHighlightWrite>(
4452 &write_ranges,
4453 |theme| theme.editor_document_highlight_write_background,
4454 cx,
4455 );
4456 cx.notify();
4457 })
4458 .log_err();
4459 }
4460 }));
4461 None
4462 }
4463
4464 pub fn refresh_inline_completion(
4465 &mut self,
4466 debounce: bool,
4467 user_requested: bool,
4468 cx: &mut ViewContext<Self>,
4469 ) -> Option<()> {
4470 let provider = self.inline_completion_provider()?;
4471 let cursor = self.selections.newest_anchor().head();
4472 let (buffer, cursor_buffer_position) =
4473 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4474
4475 if !user_requested
4476 && (!self.enable_inline_completions
4477 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4478 || !self.is_focused(cx))
4479 {
4480 self.discard_inline_completion(false, cx);
4481 return None;
4482 }
4483
4484 self.update_visible_inline_completion(cx);
4485 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4486 Some(())
4487 }
4488
4489 fn cycle_inline_completion(
4490 &mut self,
4491 direction: Direction,
4492 cx: &mut ViewContext<Self>,
4493 ) -> Option<()> {
4494 let provider = self.inline_completion_provider()?;
4495 let cursor = self.selections.newest_anchor().head();
4496 let (buffer, cursor_buffer_position) =
4497 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4498 if !self.enable_inline_completions
4499 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4500 {
4501 return None;
4502 }
4503
4504 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4505 self.update_visible_inline_completion(cx);
4506
4507 Some(())
4508 }
4509
4510 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4511 if !self.has_active_inline_completion() {
4512 self.refresh_inline_completion(false, true, cx);
4513 return;
4514 }
4515
4516 self.update_visible_inline_completion(cx);
4517 }
4518
4519 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4520 self.show_cursor_names(cx);
4521 }
4522
4523 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4524 self.show_cursor_names = true;
4525 cx.notify();
4526 cx.spawn(|this, mut cx| async move {
4527 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4528 this.update(&mut cx, |this, cx| {
4529 this.show_cursor_names = false;
4530 cx.notify()
4531 })
4532 .ok()
4533 })
4534 .detach();
4535 }
4536
4537 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4538 if self.has_active_inline_completion() {
4539 self.cycle_inline_completion(Direction::Next, cx);
4540 } else {
4541 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4542 if is_copilot_disabled {
4543 cx.propagate();
4544 }
4545 }
4546 }
4547
4548 pub fn previous_inline_completion(
4549 &mut self,
4550 _: &PreviousInlineCompletion,
4551 cx: &mut ViewContext<Self>,
4552 ) {
4553 if self.has_active_inline_completion() {
4554 self.cycle_inline_completion(Direction::Prev, cx);
4555 } else {
4556 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4557 if is_copilot_disabled {
4558 cx.propagate();
4559 }
4560 }
4561 }
4562
4563 pub fn accept_inline_completion(
4564 &mut self,
4565 _: &AcceptInlineCompletion,
4566 cx: &mut ViewContext<Self>,
4567 ) {
4568 if self.show_inline_completions_in_menu(cx) {
4569 self.hide_context_menu(cx);
4570 }
4571
4572 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4573 return;
4574 };
4575
4576 self.report_inline_completion_event(true, cx);
4577
4578 match &active_inline_completion.completion {
4579 InlineCompletion::Move(position) => {
4580 let position = *position;
4581 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4582 selections.select_anchor_ranges([position..position]);
4583 });
4584 }
4585 InlineCompletion::Edit(edits) => {
4586 if let Some(provider) = self.inline_completion_provider() {
4587 provider.accept(cx);
4588 }
4589
4590 let snapshot = self.buffer.read(cx).snapshot(cx);
4591 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4592
4593 self.buffer.update(cx, |buffer, cx| {
4594 buffer.edit(edits.iter().cloned(), None, cx)
4595 });
4596
4597 self.change_selections(None, cx, |s| {
4598 s.select_anchor_ranges([last_edit_end..last_edit_end])
4599 });
4600
4601 self.update_visible_inline_completion(cx);
4602 if self.active_inline_completion.is_none() {
4603 self.refresh_inline_completion(true, true, cx);
4604 }
4605
4606 cx.notify();
4607 }
4608 }
4609 }
4610
4611 pub fn accept_partial_inline_completion(
4612 &mut self,
4613 _: &AcceptPartialInlineCompletion,
4614 cx: &mut ViewContext<Self>,
4615 ) {
4616 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4617 return;
4618 };
4619 if self.selections.count() != 1 {
4620 return;
4621 }
4622
4623 self.report_inline_completion_event(true, cx);
4624
4625 match &active_inline_completion.completion {
4626 InlineCompletion::Move(position) => {
4627 let position = *position;
4628 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4629 selections.select_anchor_ranges([position..position]);
4630 });
4631 }
4632 InlineCompletion::Edit(edits) => {
4633 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4634 let text = edits[0].1.as_str();
4635 let mut partial_completion = text
4636 .chars()
4637 .by_ref()
4638 .take_while(|c| c.is_alphabetic())
4639 .collect::<String>();
4640 if partial_completion.is_empty() {
4641 partial_completion = text
4642 .chars()
4643 .by_ref()
4644 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4645 .collect::<String>();
4646 }
4647
4648 cx.emit(EditorEvent::InputHandled {
4649 utf16_range_to_replace: None,
4650 text: partial_completion.clone().into(),
4651 });
4652
4653 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4654
4655 self.refresh_inline_completion(true, true, cx);
4656 cx.notify();
4657 }
4658 }
4659 }
4660 }
4661
4662 fn discard_inline_completion(
4663 &mut self,
4664 should_report_inline_completion_event: bool,
4665 cx: &mut ViewContext<Self>,
4666 ) -> bool {
4667 if should_report_inline_completion_event {
4668 self.report_inline_completion_event(false, cx);
4669 }
4670
4671 if let Some(provider) = self.inline_completion_provider() {
4672 provider.discard(cx);
4673 }
4674
4675 self.take_active_inline_completion(cx).is_some()
4676 }
4677
4678 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4679 let Some(provider) = self.inline_completion_provider() else {
4680 return;
4681 };
4682 let Some(project) = self.project.as_ref() else {
4683 return;
4684 };
4685 let Some((_, buffer, _)) = self
4686 .buffer
4687 .read(cx)
4688 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4689 else {
4690 return;
4691 };
4692
4693 let project = project.read(cx);
4694 let extension = buffer
4695 .read(cx)
4696 .file()
4697 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4698 project.client().telemetry().report_inline_completion_event(
4699 provider.name().into(),
4700 accepted,
4701 extension,
4702 );
4703 }
4704
4705 pub fn has_active_inline_completion(&self) -> bool {
4706 self.active_inline_completion.is_some()
4707 }
4708
4709 fn take_active_inline_completion(
4710 &mut self,
4711 cx: &mut ViewContext<Self>,
4712 ) -> Option<InlineCompletion> {
4713 let active_inline_completion = self.active_inline_completion.take()?;
4714 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4715 self.clear_highlights::<InlineCompletionHighlight>(cx);
4716 Some(active_inline_completion.completion)
4717 }
4718
4719 fn hide_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
4720 if let Some(active_inline_completion) = self.active_inline_completion.as_ref() {
4721 self.splice_inlays(
4722 active_inline_completion.inlay_ids.clone(),
4723 Default::default(),
4724 cx,
4725 );
4726 self.clear_highlights::<InlineCompletionHighlight>(cx);
4727 }
4728 }
4729
4730 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4731 let selection = self.selections.newest_anchor();
4732 let cursor = selection.head();
4733 let multibuffer = self.buffer.read(cx).snapshot(cx);
4734 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4735 let excerpt_id = cursor.excerpt_id;
4736
4737 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4738 && (self.context_menu.borrow().is_some()
4739 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4740 if completions_menu_has_precedence
4741 || !offset_selection.is_empty()
4742 || self
4743 .active_inline_completion
4744 .as_ref()
4745 .map_or(false, |completion| {
4746 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4747 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4748 !invalidation_range.contains(&offset_selection.head())
4749 })
4750 {
4751 self.discard_inline_completion(false, cx);
4752 return None;
4753 }
4754
4755 self.take_active_inline_completion(cx);
4756 let provider = self.inline_completion_provider()?;
4757
4758 let (buffer, cursor_buffer_position) =
4759 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4760
4761 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4762 let edits = completion
4763 .edits
4764 .into_iter()
4765 .flat_map(|(range, new_text)| {
4766 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4767 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4768 Some((start..end, new_text))
4769 })
4770 .collect::<Vec<_>>();
4771 if edits.is_empty() {
4772 return None;
4773 }
4774
4775 let first_edit_start = edits.first().unwrap().0.start;
4776 let edit_start_row = first_edit_start
4777 .to_point(&multibuffer)
4778 .row
4779 .saturating_sub(2);
4780
4781 let last_edit_end = edits.last().unwrap().0.end;
4782 let edit_end_row = cmp::min(
4783 multibuffer.max_point().row,
4784 last_edit_end.to_point(&multibuffer).row + 2,
4785 );
4786
4787 let cursor_row = cursor.to_point(&multibuffer).row;
4788
4789 let mut inlay_ids = Vec::new();
4790 let invalidation_row_range;
4791 let completion;
4792 if cursor_row < edit_start_row {
4793 invalidation_row_range = cursor_row..edit_end_row;
4794 completion = InlineCompletion::Move(first_edit_start);
4795 } else if cursor_row > edit_end_row {
4796 invalidation_row_range = edit_start_row..cursor_row;
4797 completion = InlineCompletion::Move(first_edit_start);
4798 } else {
4799 if !self.show_inline_completions_in_menu(cx) || !self.has_active_completions_menu() {
4800 if edits
4801 .iter()
4802 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4803 {
4804 let mut inlays = Vec::new();
4805 for (range, new_text) in &edits {
4806 let inlay = Inlay::inline_completion(
4807 post_inc(&mut self.next_inlay_id),
4808 range.start,
4809 new_text.as_str(),
4810 );
4811 inlay_ids.push(inlay.id);
4812 inlays.push(inlay);
4813 }
4814
4815 self.splice_inlays(vec![], inlays, cx);
4816 } else {
4817 let background_color = cx.theme().status().deleted_background;
4818 self.highlight_text::<InlineCompletionHighlight>(
4819 edits.iter().map(|(range, _)| range.clone()).collect(),
4820 HighlightStyle {
4821 background_color: Some(background_color),
4822 ..Default::default()
4823 },
4824 cx,
4825 );
4826 }
4827 }
4828
4829 invalidation_row_range = edit_start_row..edit_end_row;
4830 completion = InlineCompletion::Edit(edits);
4831 };
4832
4833 let invalidation_range = multibuffer
4834 .anchor_before(Point::new(invalidation_row_range.start, 0))
4835 ..multibuffer.anchor_after(Point::new(
4836 invalidation_row_range.end,
4837 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4838 ));
4839
4840 self.active_inline_completion = Some(InlineCompletionState {
4841 inlay_ids,
4842 completion,
4843 invalidation_range,
4844 });
4845
4846 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4847 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4848 match self.context_menu.borrow_mut().as_mut() {
4849 Some(CodeContextMenu::Completions(menu)) => {
4850 menu.show_inline_completion_hint(hint);
4851 }
4852 _ => {}
4853 }
4854 }
4855 }
4856
4857 cx.notify();
4858
4859 Some(())
4860 }
4861
4862 fn inline_completion_menu_hint(
4863 &mut self,
4864 cx: &mut ViewContext<Self>,
4865 ) -> Option<InlineCompletionMenuHint> {
4866 if self.has_active_inline_completion() {
4867 let provider_name = self.inline_completion_provider()?.display_name();
4868 let editor_snapshot = self.snapshot(cx);
4869
4870 let text = match &self.active_inline_completion.as_ref()?.completion {
4871 InlineCompletion::Edit(edits) => {
4872 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4873 }
4874 InlineCompletion::Move(target) => {
4875 let target_point =
4876 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4877 let target_line = target_point.row + 1;
4878 InlineCompletionText::Move(
4879 format!("Jump to edit in line {}", target_line).into(),
4880 )
4881 }
4882 };
4883
4884 Some(InlineCompletionMenuHint {
4885 provider_name,
4886 text,
4887 })
4888 } else {
4889 None
4890 }
4891 }
4892
4893 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4894 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4895 }
4896
4897 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4898 EditorSettings::get_global(cx).show_inline_completions_in_menu
4899 && self
4900 .inline_completion_provider()
4901 .map_or(false, |provider| provider.show_completions_in_menu())
4902 }
4903
4904 fn render_code_actions_indicator(
4905 &self,
4906 _style: &EditorStyle,
4907 row: DisplayRow,
4908 is_active: bool,
4909 cx: &mut ViewContext<Self>,
4910 ) -> Option<IconButton> {
4911 if self.available_code_actions.is_some() {
4912 Some(
4913 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4914 .shape(ui::IconButtonShape::Square)
4915 .icon_size(IconSize::XSmall)
4916 .icon_color(Color::Muted)
4917 .toggle_state(is_active)
4918 .tooltip({
4919 let focus_handle = self.focus_handle.clone();
4920 move |cx| {
4921 Tooltip::for_action_in(
4922 "Toggle Code Actions",
4923 &ToggleCodeActions {
4924 deployed_from_indicator: None,
4925 },
4926 &focus_handle,
4927 cx,
4928 )
4929 }
4930 })
4931 .on_click(cx.listener(move |editor, _e, cx| {
4932 editor.focus(cx);
4933 editor.toggle_code_actions(
4934 &ToggleCodeActions {
4935 deployed_from_indicator: Some(row),
4936 },
4937 cx,
4938 );
4939 })),
4940 )
4941 } else {
4942 None
4943 }
4944 }
4945
4946 fn clear_tasks(&mut self) {
4947 self.tasks.clear()
4948 }
4949
4950 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4951 if self.tasks.insert(key, value).is_some() {
4952 // This case should hopefully be rare, but just in case...
4953 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4954 }
4955 }
4956
4957 fn build_tasks_context(
4958 project: &Model<Project>,
4959 buffer: &Model<Buffer>,
4960 buffer_row: u32,
4961 tasks: &Arc<RunnableTasks>,
4962 cx: &mut ViewContext<Self>,
4963 ) -> Task<Option<task::TaskContext>> {
4964 let position = Point::new(buffer_row, tasks.column);
4965 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4966 let location = Location {
4967 buffer: buffer.clone(),
4968 range: range_start..range_start,
4969 };
4970 // Fill in the environmental variables from the tree-sitter captures
4971 let mut captured_task_variables = TaskVariables::default();
4972 for (capture_name, value) in tasks.extra_variables.clone() {
4973 captured_task_variables.insert(
4974 task::VariableName::Custom(capture_name.into()),
4975 value.clone(),
4976 );
4977 }
4978 project.update(cx, |project, cx| {
4979 project.task_store().update(cx, |task_store, cx| {
4980 task_store.task_context_for_location(captured_task_variables, location, cx)
4981 })
4982 })
4983 }
4984
4985 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4986 let Some((workspace, _)) = self.workspace.clone() else {
4987 return;
4988 };
4989 let Some(project) = self.project.clone() else {
4990 return;
4991 };
4992
4993 // Try to find a closest, enclosing node using tree-sitter that has a
4994 // task
4995 let Some((buffer, buffer_row, tasks)) = self
4996 .find_enclosing_node_task(cx)
4997 // Or find the task that's closest in row-distance.
4998 .or_else(|| self.find_closest_task(cx))
4999 else {
5000 return;
5001 };
5002
5003 let reveal_strategy = action.reveal;
5004 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5005 cx.spawn(|_, mut cx| async move {
5006 let context = task_context.await?;
5007 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5008
5009 let resolved = resolved_task.resolved.as_mut()?;
5010 resolved.reveal = reveal_strategy;
5011
5012 workspace
5013 .update(&mut cx, |workspace, cx| {
5014 workspace::tasks::schedule_resolved_task(
5015 workspace,
5016 task_source_kind,
5017 resolved_task,
5018 false,
5019 cx,
5020 );
5021 })
5022 .ok()
5023 })
5024 .detach();
5025 }
5026
5027 fn find_closest_task(
5028 &mut self,
5029 cx: &mut ViewContext<Self>,
5030 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5031 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5032
5033 let ((buffer_id, row), tasks) = self
5034 .tasks
5035 .iter()
5036 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5037
5038 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5039 let tasks = Arc::new(tasks.to_owned());
5040 Some((buffer, *row, tasks))
5041 }
5042
5043 fn find_enclosing_node_task(
5044 &mut self,
5045 cx: &mut ViewContext<Self>,
5046 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5047 let snapshot = self.buffer.read(cx).snapshot(cx);
5048 let offset = self.selections.newest::<usize>(cx).head();
5049 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5050 let buffer_id = excerpt.buffer().remote_id();
5051
5052 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5053 let mut cursor = layer.node().walk();
5054
5055 while cursor.goto_first_child_for_byte(offset).is_some() {
5056 if cursor.node().end_byte() == offset {
5057 cursor.goto_next_sibling();
5058 }
5059 }
5060
5061 // Ascend to the smallest ancestor that contains the range and has a task.
5062 loop {
5063 let node = cursor.node();
5064 let node_range = node.byte_range();
5065 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5066
5067 // Check if this node contains our offset
5068 if node_range.start <= offset && node_range.end >= offset {
5069 // If it contains offset, check for task
5070 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5071 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5072 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5073 }
5074 }
5075
5076 if !cursor.goto_parent() {
5077 break;
5078 }
5079 }
5080 None
5081 }
5082
5083 fn render_run_indicator(
5084 &self,
5085 _style: &EditorStyle,
5086 is_active: bool,
5087 row: DisplayRow,
5088 cx: &mut ViewContext<Self>,
5089 ) -> IconButton {
5090 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5091 .shape(ui::IconButtonShape::Square)
5092 .icon_size(IconSize::XSmall)
5093 .icon_color(Color::Muted)
5094 .toggle_state(is_active)
5095 .on_click(cx.listener(move |editor, _e, cx| {
5096 editor.focus(cx);
5097 editor.toggle_code_actions(
5098 &ToggleCodeActions {
5099 deployed_from_indicator: Some(row),
5100 },
5101 cx,
5102 );
5103 }))
5104 }
5105
5106 #[cfg(any(feature = "test-support", test))]
5107 pub fn context_menu_visible(&self) -> bool {
5108 self.context_menu
5109 .borrow()
5110 .as_ref()
5111 .map_or(false, |menu| menu.visible())
5112 }
5113
5114 #[cfg(feature = "test-support")]
5115 pub fn context_menu_contains_inline_completion(&self) -> bool {
5116 self.context_menu
5117 .borrow()
5118 .as_ref()
5119 .map_or(false, |menu| match menu {
5120 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5121 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5122 }),
5123 CodeContextMenu::CodeActions(_) => false,
5124 })
5125 }
5126
5127 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5128 self.context_menu
5129 .borrow()
5130 .as_ref()
5131 .map(|menu| menu.origin(cursor_position))
5132 }
5133
5134 fn render_context_menu(
5135 &self,
5136 style: &EditorStyle,
5137 max_height_in_lines: u32,
5138 cx: &mut ViewContext<Editor>,
5139 ) -> Option<AnyElement> {
5140 self.context_menu.borrow().as_ref().and_then(|menu| {
5141 if menu.visible() {
5142 Some(menu.render(style, max_height_in_lines, cx))
5143 } else {
5144 None
5145 }
5146 })
5147 }
5148
5149 fn render_context_menu_aside(
5150 &self,
5151 style: &EditorStyle,
5152 max_height: Pixels,
5153 cx: &mut ViewContext<Editor>,
5154 ) -> Option<AnyElement> {
5155 self.context_menu.borrow().as_ref().and_then(|menu| {
5156 if menu.visible() {
5157 menu.render_aside(
5158 style,
5159 max_height,
5160 self.workspace.as_ref().map(|(w, _)| w.clone()),
5161 cx,
5162 )
5163 } else {
5164 None
5165 }
5166 })
5167 }
5168
5169 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5170 cx.notify();
5171 self.completion_tasks.clear();
5172 let context_menu = self.context_menu.borrow_mut().take();
5173 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5174 self.update_visible_inline_completion(cx);
5175 }
5176 context_menu
5177 }
5178
5179 fn show_snippet_choices(
5180 &mut self,
5181 choices: &Vec<String>,
5182 selection: Range<Anchor>,
5183 cx: &mut ViewContext<Self>,
5184 ) {
5185 if selection.start.buffer_id.is_none() {
5186 return;
5187 }
5188 let buffer_id = selection.start.buffer_id.unwrap();
5189 let buffer = self.buffer().read(cx).buffer(buffer_id);
5190 let id = post_inc(&mut self.next_completion_id);
5191
5192 if let Some(buffer) = buffer {
5193 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5194 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5195 ));
5196 }
5197 }
5198
5199 pub fn insert_snippet(
5200 &mut self,
5201 insertion_ranges: &[Range<usize>],
5202 snippet: Snippet,
5203 cx: &mut ViewContext<Self>,
5204 ) -> Result<()> {
5205 struct Tabstop<T> {
5206 is_end_tabstop: bool,
5207 ranges: Vec<Range<T>>,
5208 choices: Option<Vec<String>>,
5209 }
5210
5211 let tabstops = self.buffer.update(cx, |buffer, cx| {
5212 let snippet_text: Arc<str> = snippet.text.clone().into();
5213 buffer.edit(
5214 insertion_ranges
5215 .iter()
5216 .cloned()
5217 .map(|range| (range, snippet_text.clone())),
5218 Some(AutoindentMode::EachLine),
5219 cx,
5220 );
5221
5222 let snapshot = &*buffer.read(cx);
5223 let snippet = &snippet;
5224 snippet
5225 .tabstops
5226 .iter()
5227 .map(|tabstop| {
5228 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5229 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5230 });
5231 let mut tabstop_ranges = tabstop
5232 .ranges
5233 .iter()
5234 .flat_map(|tabstop_range| {
5235 let mut delta = 0_isize;
5236 insertion_ranges.iter().map(move |insertion_range| {
5237 let insertion_start = insertion_range.start as isize + delta;
5238 delta +=
5239 snippet.text.len() as isize - insertion_range.len() as isize;
5240
5241 let start = ((insertion_start + tabstop_range.start) as usize)
5242 .min(snapshot.len());
5243 let end = ((insertion_start + tabstop_range.end) as usize)
5244 .min(snapshot.len());
5245 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5246 })
5247 })
5248 .collect::<Vec<_>>();
5249 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5250
5251 Tabstop {
5252 is_end_tabstop,
5253 ranges: tabstop_ranges,
5254 choices: tabstop.choices.clone(),
5255 }
5256 })
5257 .collect::<Vec<_>>()
5258 });
5259 if let Some(tabstop) = tabstops.first() {
5260 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5261 s.select_ranges(tabstop.ranges.iter().cloned());
5262 });
5263
5264 if let Some(choices) = &tabstop.choices {
5265 if let Some(selection) = tabstop.ranges.first() {
5266 self.show_snippet_choices(choices, selection.clone(), cx)
5267 }
5268 }
5269
5270 // If we're already at the last tabstop and it's at the end of the snippet,
5271 // we're done, we don't need to keep the state around.
5272 if !tabstop.is_end_tabstop {
5273 let choices = tabstops
5274 .iter()
5275 .map(|tabstop| tabstop.choices.clone())
5276 .collect();
5277
5278 let ranges = tabstops
5279 .into_iter()
5280 .map(|tabstop| tabstop.ranges)
5281 .collect::<Vec<_>>();
5282
5283 self.snippet_stack.push(SnippetState {
5284 active_index: 0,
5285 ranges,
5286 choices,
5287 });
5288 }
5289
5290 // Check whether the just-entered snippet ends with an auto-closable bracket.
5291 if self.autoclose_regions.is_empty() {
5292 let snapshot = self.buffer.read(cx).snapshot(cx);
5293 for selection in &mut self.selections.all::<Point>(cx) {
5294 let selection_head = selection.head();
5295 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5296 continue;
5297 };
5298
5299 let mut bracket_pair = None;
5300 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5301 let prev_chars = snapshot
5302 .reversed_chars_at(selection_head)
5303 .collect::<String>();
5304 for (pair, enabled) in scope.brackets() {
5305 if enabled
5306 && pair.close
5307 && prev_chars.starts_with(pair.start.as_str())
5308 && next_chars.starts_with(pair.end.as_str())
5309 {
5310 bracket_pair = Some(pair.clone());
5311 break;
5312 }
5313 }
5314 if let Some(pair) = bracket_pair {
5315 let start = snapshot.anchor_after(selection_head);
5316 let end = snapshot.anchor_after(selection_head);
5317 self.autoclose_regions.push(AutocloseRegion {
5318 selection_id: selection.id,
5319 range: start..end,
5320 pair,
5321 });
5322 }
5323 }
5324 }
5325 }
5326 Ok(())
5327 }
5328
5329 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5330 self.move_to_snippet_tabstop(Bias::Right, cx)
5331 }
5332
5333 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5334 self.move_to_snippet_tabstop(Bias::Left, cx)
5335 }
5336
5337 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5338 if let Some(mut snippet) = self.snippet_stack.pop() {
5339 match bias {
5340 Bias::Left => {
5341 if snippet.active_index > 0 {
5342 snippet.active_index -= 1;
5343 } else {
5344 self.snippet_stack.push(snippet);
5345 return false;
5346 }
5347 }
5348 Bias::Right => {
5349 if snippet.active_index + 1 < snippet.ranges.len() {
5350 snippet.active_index += 1;
5351 } else {
5352 self.snippet_stack.push(snippet);
5353 return false;
5354 }
5355 }
5356 }
5357 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5358 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5359 s.select_anchor_ranges(current_ranges.iter().cloned())
5360 });
5361
5362 if let Some(choices) = &snippet.choices[snippet.active_index] {
5363 if let Some(selection) = current_ranges.first() {
5364 self.show_snippet_choices(&choices, selection.clone(), cx);
5365 }
5366 }
5367
5368 // If snippet state is not at the last tabstop, push it back on the stack
5369 if snippet.active_index + 1 < snippet.ranges.len() {
5370 self.snippet_stack.push(snippet);
5371 }
5372 return true;
5373 }
5374 }
5375
5376 false
5377 }
5378
5379 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5380 self.transact(cx, |this, cx| {
5381 this.select_all(&SelectAll, cx);
5382 this.insert("", cx);
5383 });
5384 }
5385
5386 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5387 self.transact(cx, |this, cx| {
5388 this.select_autoclose_pair(cx);
5389 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5390 if !this.linked_edit_ranges.is_empty() {
5391 let selections = this.selections.all::<MultiBufferPoint>(cx);
5392 let snapshot = this.buffer.read(cx).snapshot(cx);
5393
5394 for selection in selections.iter() {
5395 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5396 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5397 if selection_start.buffer_id != selection_end.buffer_id {
5398 continue;
5399 }
5400 if let Some(ranges) =
5401 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5402 {
5403 for (buffer, entries) in ranges {
5404 linked_ranges.entry(buffer).or_default().extend(entries);
5405 }
5406 }
5407 }
5408 }
5409
5410 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5411 if !this.selections.line_mode {
5412 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5413 for selection in &mut selections {
5414 if selection.is_empty() {
5415 let old_head = selection.head();
5416 let mut new_head =
5417 movement::left(&display_map, old_head.to_display_point(&display_map))
5418 .to_point(&display_map);
5419 if let Some((buffer, line_buffer_range)) = display_map
5420 .buffer_snapshot
5421 .buffer_line_for_row(MultiBufferRow(old_head.row))
5422 {
5423 let indent_size =
5424 buffer.indent_size_for_line(line_buffer_range.start.row);
5425 let indent_len = match indent_size.kind {
5426 IndentKind::Space => {
5427 buffer.settings_at(line_buffer_range.start, cx).tab_size
5428 }
5429 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5430 };
5431 if old_head.column <= indent_size.len && old_head.column > 0 {
5432 let indent_len = indent_len.get();
5433 new_head = cmp::min(
5434 new_head,
5435 MultiBufferPoint::new(
5436 old_head.row,
5437 ((old_head.column - 1) / indent_len) * indent_len,
5438 ),
5439 );
5440 }
5441 }
5442
5443 selection.set_head(new_head, SelectionGoal::None);
5444 }
5445 }
5446 }
5447
5448 this.signature_help_state.set_backspace_pressed(true);
5449 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5450 this.insert("", cx);
5451 let empty_str: Arc<str> = Arc::from("");
5452 for (buffer, edits) in linked_ranges {
5453 let snapshot = buffer.read(cx).snapshot();
5454 use text::ToPoint as TP;
5455
5456 let edits = edits
5457 .into_iter()
5458 .map(|range| {
5459 let end_point = TP::to_point(&range.end, &snapshot);
5460 let mut start_point = TP::to_point(&range.start, &snapshot);
5461
5462 if end_point == start_point {
5463 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5464 .saturating_sub(1);
5465 start_point =
5466 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5467 };
5468
5469 (start_point..end_point, empty_str.clone())
5470 })
5471 .sorted_by_key(|(range, _)| range.start)
5472 .collect::<Vec<_>>();
5473 buffer.update(cx, |this, cx| {
5474 this.edit(edits, None, cx);
5475 })
5476 }
5477 this.refresh_inline_completion(true, false, cx);
5478 linked_editing_ranges::refresh_linked_ranges(this, cx);
5479 });
5480 }
5481
5482 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5483 self.transact(cx, |this, cx| {
5484 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5485 let line_mode = s.line_mode;
5486 s.move_with(|map, selection| {
5487 if selection.is_empty() && !line_mode {
5488 let cursor = movement::right(map, selection.head());
5489 selection.end = cursor;
5490 selection.reversed = true;
5491 selection.goal = SelectionGoal::None;
5492 }
5493 })
5494 });
5495 this.insert("", cx);
5496 this.refresh_inline_completion(true, false, cx);
5497 });
5498 }
5499
5500 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5501 if self.move_to_prev_snippet_tabstop(cx) {
5502 return;
5503 }
5504
5505 self.outdent(&Outdent, cx);
5506 }
5507
5508 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5509 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5510 return;
5511 }
5512
5513 let mut selections = self.selections.all_adjusted(cx);
5514 let buffer = self.buffer.read(cx);
5515 let snapshot = buffer.snapshot(cx);
5516 let rows_iter = selections.iter().map(|s| s.head().row);
5517 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5518
5519 let mut edits = Vec::new();
5520 let mut prev_edited_row = 0;
5521 let mut row_delta = 0;
5522 for selection in &mut selections {
5523 if selection.start.row != prev_edited_row {
5524 row_delta = 0;
5525 }
5526 prev_edited_row = selection.end.row;
5527
5528 // If the selection is non-empty, then increase the indentation of the selected lines.
5529 if !selection.is_empty() {
5530 row_delta =
5531 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5532 continue;
5533 }
5534
5535 // If the selection is empty and the cursor is in the leading whitespace before the
5536 // suggested indentation, then auto-indent the line.
5537 let cursor = selection.head();
5538 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5539 if let Some(suggested_indent) =
5540 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5541 {
5542 if cursor.column < suggested_indent.len
5543 && cursor.column <= current_indent.len
5544 && current_indent.len <= suggested_indent.len
5545 {
5546 selection.start = Point::new(cursor.row, suggested_indent.len);
5547 selection.end = selection.start;
5548 if row_delta == 0 {
5549 edits.extend(Buffer::edit_for_indent_size_adjustment(
5550 cursor.row,
5551 current_indent,
5552 suggested_indent,
5553 ));
5554 row_delta = suggested_indent.len - current_indent.len;
5555 }
5556 continue;
5557 }
5558 }
5559
5560 // Otherwise, insert a hard or soft tab.
5561 let settings = buffer.settings_at(cursor, cx);
5562 let tab_size = if settings.hard_tabs {
5563 IndentSize::tab()
5564 } else {
5565 let tab_size = settings.tab_size.get();
5566 let char_column = snapshot
5567 .text_for_range(Point::new(cursor.row, 0)..cursor)
5568 .flat_map(str::chars)
5569 .count()
5570 + row_delta as usize;
5571 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5572 IndentSize::spaces(chars_to_next_tab_stop)
5573 };
5574 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5575 selection.end = selection.start;
5576 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5577 row_delta += tab_size.len;
5578 }
5579
5580 self.transact(cx, |this, cx| {
5581 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5582 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5583 this.refresh_inline_completion(true, false, cx);
5584 });
5585 }
5586
5587 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5588 if self.read_only(cx) {
5589 return;
5590 }
5591 let mut selections = self.selections.all::<Point>(cx);
5592 let mut prev_edited_row = 0;
5593 let mut row_delta = 0;
5594 let mut edits = Vec::new();
5595 let buffer = self.buffer.read(cx);
5596 let snapshot = buffer.snapshot(cx);
5597 for selection in &mut selections {
5598 if selection.start.row != prev_edited_row {
5599 row_delta = 0;
5600 }
5601 prev_edited_row = selection.end.row;
5602
5603 row_delta =
5604 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5605 }
5606
5607 self.transact(cx, |this, cx| {
5608 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5609 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5610 });
5611 }
5612
5613 fn indent_selection(
5614 buffer: &MultiBuffer,
5615 snapshot: &MultiBufferSnapshot,
5616 selection: &mut Selection<Point>,
5617 edits: &mut Vec<(Range<Point>, String)>,
5618 delta_for_start_row: u32,
5619 cx: &AppContext,
5620 ) -> u32 {
5621 let settings = buffer.settings_at(selection.start, cx);
5622 let tab_size = settings.tab_size.get();
5623 let indent_kind = if settings.hard_tabs {
5624 IndentKind::Tab
5625 } else {
5626 IndentKind::Space
5627 };
5628 let mut start_row = selection.start.row;
5629 let mut end_row = selection.end.row + 1;
5630
5631 // If a selection ends at the beginning of a line, don't indent
5632 // that last line.
5633 if selection.end.column == 0 && selection.end.row > selection.start.row {
5634 end_row -= 1;
5635 }
5636
5637 // Avoid re-indenting a row that has already been indented by a
5638 // previous selection, but still update this selection's column
5639 // to reflect that indentation.
5640 if delta_for_start_row > 0 {
5641 start_row += 1;
5642 selection.start.column += delta_for_start_row;
5643 if selection.end.row == selection.start.row {
5644 selection.end.column += delta_for_start_row;
5645 }
5646 }
5647
5648 let mut delta_for_end_row = 0;
5649 let has_multiple_rows = start_row + 1 != end_row;
5650 for row in start_row..end_row {
5651 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5652 let indent_delta = match (current_indent.kind, indent_kind) {
5653 (IndentKind::Space, IndentKind::Space) => {
5654 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5655 IndentSize::spaces(columns_to_next_tab_stop)
5656 }
5657 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5658 (_, IndentKind::Tab) => IndentSize::tab(),
5659 };
5660
5661 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5662 0
5663 } else {
5664 selection.start.column
5665 };
5666 let row_start = Point::new(row, start);
5667 edits.push((
5668 row_start..row_start,
5669 indent_delta.chars().collect::<String>(),
5670 ));
5671
5672 // Update this selection's endpoints to reflect the indentation.
5673 if row == selection.start.row {
5674 selection.start.column += indent_delta.len;
5675 }
5676 if row == selection.end.row {
5677 selection.end.column += indent_delta.len;
5678 delta_for_end_row = indent_delta.len;
5679 }
5680 }
5681
5682 if selection.start.row == selection.end.row {
5683 delta_for_start_row + delta_for_end_row
5684 } else {
5685 delta_for_end_row
5686 }
5687 }
5688
5689 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5690 if self.read_only(cx) {
5691 return;
5692 }
5693 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5694 let selections = self.selections.all::<Point>(cx);
5695 let mut deletion_ranges = Vec::new();
5696 let mut last_outdent = None;
5697 {
5698 let buffer = self.buffer.read(cx);
5699 let snapshot = buffer.snapshot(cx);
5700 for selection in &selections {
5701 let settings = buffer.settings_at(selection.start, cx);
5702 let tab_size = settings.tab_size.get();
5703 let mut rows = selection.spanned_rows(false, &display_map);
5704
5705 // Avoid re-outdenting a row that has already been outdented by a
5706 // previous selection.
5707 if let Some(last_row) = last_outdent {
5708 if last_row == rows.start {
5709 rows.start = rows.start.next_row();
5710 }
5711 }
5712 let has_multiple_rows = rows.len() > 1;
5713 for row in rows.iter_rows() {
5714 let indent_size = snapshot.indent_size_for_line(row);
5715 if indent_size.len > 0 {
5716 let deletion_len = match indent_size.kind {
5717 IndentKind::Space => {
5718 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5719 if columns_to_prev_tab_stop == 0 {
5720 tab_size
5721 } else {
5722 columns_to_prev_tab_stop
5723 }
5724 }
5725 IndentKind::Tab => 1,
5726 };
5727 let start = if has_multiple_rows
5728 || deletion_len > selection.start.column
5729 || indent_size.len < selection.start.column
5730 {
5731 0
5732 } else {
5733 selection.start.column - deletion_len
5734 };
5735 deletion_ranges.push(
5736 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5737 );
5738 last_outdent = Some(row);
5739 }
5740 }
5741 }
5742 }
5743
5744 self.transact(cx, |this, cx| {
5745 this.buffer.update(cx, |buffer, cx| {
5746 let empty_str: Arc<str> = Arc::default();
5747 buffer.edit(
5748 deletion_ranges
5749 .into_iter()
5750 .map(|range| (range, empty_str.clone())),
5751 None,
5752 cx,
5753 );
5754 });
5755 let selections = this.selections.all::<usize>(cx);
5756 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5757 });
5758 }
5759
5760 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5761 if self.read_only(cx) {
5762 return;
5763 }
5764 let selections = self
5765 .selections
5766 .all::<usize>(cx)
5767 .into_iter()
5768 .map(|s| s.range());
5769
5770 self.transact(cx, |this, cx| {
5771 this.buffer.update(cx, |buffer, cx| {
5772 buffer.autoindent_ranges(selections, cx);
5773 });
5774 let selections = this.selections.all::<usize>(cx);
5775 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5776 });
5777 }
5778
5779 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5781 let selections = self.selections.all::<Point>(cx);
5782
5783 let mut new_cursors = Vec::new();
5784 let mut edit_ranges = Vec::new();
5785 let mut selections = selections.iter().peekable();
5786 while let Some(selection) = selections.next() {
5787 let mut rows = selection.spanned_rows(false, &display_map);
5788 let goal_display_column = selection.head().to_display_point(&display_map).column();
5789
5790 // Accumulate contiguous regions of rows that we want to delete.
5791 while let Some(next_selection) = selections.peek() {
5792 let next_rows = next_selection.spanned_rows(false, &display_map);
5793 if next_rows.start <= rows.end {
5794 rows.end = next_rows.end;
5795 selections.next().unwrap();
5796 } else {
5797 break;
5798 }
5799 }
5800
5801 let buffer = &display_map.buffer_snapshot;
5802 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5803 let edit_end;
5804 let cursor_buffer_row;
5805 if buffer.max_point().row >= rows.end.0 {
5806 // If there's a line after the range, delete the \n from the end of the row range
5807 // and position the cursor on the next line.
5808 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5809 cursor_buffer_row = rows.end;
5810 } else {
5811 // If there isn't a line after the range, delete the \n from the line before the
5812 // start of the row range and position the cursor there.
5813 edit_start = edit_start.saturating_sub(1);
5814 edit_end = buffer.len();
5815 cursor_buffer_row = rows.start.previous_row();
5816 }
5817
5818 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5819 *cursor.column_mut() =
5820 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5821
5822 new_cursors.push((
5823 selection.id,
5824 buffer.anchor_after(cursor.to_point(&display_map)),
5825 ));
5826 edit_ranges.push(edit_start..edit_end);
5827 }
5828
5829 self.transact(cx, |this, cx| {
5830 let buffer = this.buffer.update(cx, |buffer, cx| {
5831 let empty_str: Arc<str> = Arc::default();
5832 buffer.edit(
5833 edit_ranges
5834 .into_iter()
5835 .map(|range| (range, empty_str.clone())),
5836 None,
5837 cx,
5838 );
5839 buffer.snapshot(cx)
5840 });
5841 let new_selections = new_cursors
5842 .into_iter()
5843 .map(|(id, cursor)| {
5844 let cursor = cursor.to_point(&buffer);
5845 Selection {
5846 id,
5847 start: cursor,
5848 end: cursor,
5849 reversed: false,
5850 goal: SelectionGoal::None,
5851 }
5852 })
5853 .collect();
5854
5855 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5856 s.select(new_selections);
5857 });
5858 });
5859 }
5860
5861 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5862 if self.read_only(cx) {
5863 return;
5864 }
5865 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5866 for selection in self.selections.all::<Point>(cx) {
5867 let start = MultiBufferRow(selection.start.row);
5868 // Treat single line selections as if they include the next line. Otherwise this action
5869 // would do nothing for single line selections individual cursors.
5870 let end = if selection.start.row == selection.end.row {
5871 MultiBufferRow(selection.start.row + 1)
5872 } else {
5873 MultiBufferRow(selection.end.row)
5874 };
5875
5876 if let Some(last_row_range) = row_ranges.last_mut() {
5877 if start <= last_row_range.end {
5878 last_row_range.end = end;
5879 continue;
5880 }
5881 }
5882 row_ranges.push(start..end);
5883 }
5884
5885 let snapshot = self.buffer.read(cx).snapshot(cx);
5886 let mut cursor_positions = Vec::new();
5887 for row_range in &row_ranges {
5888 let anchor = snapshot.anchor_before(Point::new(
5889 row_range.end.previous_row().0,
5890 snapshot.line_len(row_range.end.previous_row()),
5891 ));
5892 cursor_positions.push(anchor..anchor);
5893 }
5894
5895 self.transact(cx, |this, cx| {
5896 for row_range in row_ranges.into_iter().rev() {
5897 for row in row_range.iter_rows().rev() {
5898 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5899 let next_line_row = row.next_row();
5900 let indent = snapshot.indent_size_for_line(next_line_row);
5901 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5902
5903 let replace = if snapshot.line_len(next_line_row) > indent.len {
5904 " "
5905 } else {
5906 ""
5907 };
5908
5909 this.buffer.update(cx, |buffer, cx| {
5910 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5911 });
5912 }
5913 }
5914
5915 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5916 s.select_anchor_ranges(cursor_positions)
5917 });
5918 });
5919 }
5920
5921 pub fn sort_lines_case_sensitive(
5922 &mut self,
5923 _: &SortLinesCaseSensitive,
5924 cx: &mut ViewContext<Self>,
5925 ) {
5926 self.manipulate_lines(cx, |lines| lines.sort())
5927 }
5928
5929 pub fn sort_lines_case_insensitive(
5930 &mut self,
5931 _: &SortLinesCaseInsensitive,
5932 cx: &mut ViewContext<Self>,
5933 ) {
5934 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5935 }
5936
5937 pub fn unique_lines_case_insensitive(
5938 &mut self,
5939 _: &UniqueLinesCaseInsensitive,
5940 cx: &mut ViewContext<Self>,
5941 ) {
5942 self.manipulate_lines(cx, |lines| {
5943 let mut seen = HashSet::default();
5944 lines.retain(|line| seen.insert(line.to_lowercase()));
5945 })
5946 }
5947
5948 pub fn unique_lines_case_sensitive(
5949 &mut self,
5950 _: &UniqueLinesCaseSensitive,
5951 cx: &mut ViewContext<Self>,
5952 ) {
5953 self.manipulate_lines(cx, |lines| {
5954 let mut seen = HashSet::default();
5955 lines.retain(|line| seen.insert(*line));
5956 })
5957 }
5958
5959 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5960 let mut revert_changes = HashMap::default();
5961 let snapshot = self.snapshot(cx);
5962 for hunk in hunks_for_ranges(
5963 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5964 &snapshot,
5965 ) {
5966 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5967 }
5968 if !revert_changes.is_empty() {
5969 self.transact(cx, |editor, cx| {
5970 editor.revert(revert_changes, cx);
5971 });
5972 }
5973 }
5974
5975 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5976 let Some(project) = self.project.clone() else {
5977 return;
5978 };
5979 self.reload(project, cx).detach_and_notify_err(cx);
5980 }
5981
5982 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5983 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5984 if !revert_changes.is_empty() {
5985 self.transact(cx, |editor, cx| {
5986 editor.revert(revert_changes, cx);
5987 });
5988 }
5989 }
5990
5991 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5992 let snapshot = self.buffer.read(cx).read(cx);
5993 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5994 drop(snapshot);
5995 let mut revert_changes = HashMap::default();
5996 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5997 if !revert_changes.is_empty() {
5998 self.revert(revert_changes, cx)
5999 }
6000 }
6001 }
6002
6003 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6004 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6005 let project_path = buffer.read(cx).project_path(cx)?;
6006 let project = self.project.as_ref()?.read(cx);
6007 let entry = project.entry_for_path(&project_path, cx)?;
6008 let parent = match &entry.canonical_path {
6009 Some(canonical_path) => canonical_path.to_path_buf(),
6010 None => project.absolute_path(&project_path, cx)?,
6011 }
6012 .parent()?
6013 .to_path_buf();
6014 Some(parent)
6015 }) {
6016 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6017 }
6018 }
6019
6020 fn gather_revert_changes(
6021 &mut self,
6022 selections: &[Selection<Point>],
6023 cx: &mut ViewContext<'_, Editor>,
6024 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6025 let mut revert_changes = HashMap::default();
6026 let snapshot = self.snapshot(cx);
6027 for hunk in hunks_for_selections(&snapshot, selections) {
6028 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6029 }
6030 revert_changes
6031 }
6032
6033 pub fn prepare_revert_change(
6034 &mut self,
6035 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6036 hunk: &MultiBufferDiffHunk,
6037 cx: &AppContext,
6038 ) -> Option<()> {
6039 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6040 let buffer = buffer.read(cx);
6041 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6042 let original_text = change_set
6043 .read(cx)
6044 .base_text
6045 .as_ref()?
6046 .read(cx)
6047 .as_rope()
6048 .slice(hunk.diff_base_byte_range.clone());
6049 let buffer_snapshot = buffer.snapshot();
6050 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6051 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6052 probe
6053 .0
6054 .start
6055 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6056 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6057 }) {
6058 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6059 Some(())
6060 } else {
6061 None
6062 }
6063 }
6064
6065 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6066 self.manipulate_lines(cx, |lines| lines.reverse())
6067 }
6068
6069 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6070 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6071 }
6072
6073 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6074 where
6075 Fn: FnMut(&mut Vec<&str>),
6076 {
6077 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6078 let buffer = self.buffer.read(cx).snapshot(cx);
6079
6080 let mut edits = Vec::new();
6081
6082 let selections = self.selections.all::<Point>(cx);
6083 let mut selections = selections.iter().peekable();
6084 let mut contiguous_row_selections = Vec::new();
6085 let mut new_selections = Vec::new();
6086 let mut added_lines = 0;
6087 let mut removed_lines = 0;
6088
6089 while let Some(selection) = selections.next() {
6090 let (start_row, end_row) = consume_contiguous_rows(
6091 &mut contiguous_row_selections,
6092 selection,
6093 &display_map,
6094 &mut selections,
6095 );
6096
6097 let start_point = Point::new(start_row.0, 0);
6098 let end_point = Point::new(
6099 end_row.previous_row().0,
6100 buffer.line_len(end_row.previous_row()),
6101 );
6102 let text = buffer
6103 .text_for_range(start_point..end_point)
6104 .collect::<String>();
6105
6106 let mut lines = text.split('\n').collect_vec();
6107
6108 let lines_before = lines.len();
6109 callback(&mut lines);
6110 let lines_after = lines.len();
6111
6112 edits.push((start_point..end_point, lines.join("\n")));
6113
6114 // Selections must change based on added and removed line count
6115 let start_row =
6116 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6117 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6118 new_selections.push(Selection {
6119 id: selection.id,
6120 start: start_row,
6121 end: end_row,
6122 goal: SelectionGoal::None,
6123 reversed: selection.reversed,
6124 });
6125
6126 if lines_after > lines_before {
6127 added_lines += lines_after - lines_before;
6128 } else if lines_before > lines_after {
6129 removed_lines += lines_before - lines_after;
6130 }
6131 }
6132
6133 self.transact(cx, |this, cx| {
6134 let buffer = this.buffer.update(cx, |buffer, cx| {
6135 buffer.edit(edits, None, cx);
6136 buffer.snapshot(cx)
6137 });
6138
6139 // Recalculate offsets on newly edited buffer
6140 let new_selections = new_selections
6141 .iter()
6142 .map(|s| {
6143 let start_point = Point::new(s.start.0, 0);
6144 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6145 Selection {
6146 id: s.id,
6147 start: buffer.point_to_offset(start_point),
6148 end: buffer.point_to_offset(end_point),
6149 goal: s.goal,
6150 reversed: s.reversed,
6151 }
6152 })
6153 .collect();
6154
6155 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6156 s.select(new_selections);
6157 });
6158
6159 this.request_autoscroll(Autoscroll::fit(), cx);
6160 });
6161 }
6162
6163 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6164 self.manipulate_text(cx, |text| text.to_uppercase())
6165 }
6166
6167 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6168 self.manipulate_text(cx, |text| text.to_lowercase())
6169 }
6170
6171 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6172 self.manipulate_text(cx, |text| {
6173 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6174 // https://github.com/rutrum/convert-case/issues/16
6175 text.split('\n')
6176 .map(|line| line.to_case(Case::Title))
6177 .join("\n")
6178 })
6179 }
6180
6181 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6182 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6183 }
6184
6185 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6186 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6187 }
6188
6189 pub fn convert_to_upper_camel_case(
6190 &mut self,
6191 _: &ConvertToUpperCamelCase,
6192 cx: &mut ViewContext<Self>,
6193 ) {
6194 self.manipulate_text(cx, |text| {
6195 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6196 // https://github.com/rutrum/convert-case/issues/16
6197 text.split('\n')
6198 .map(|line| line.to_case(Case::UpperCamel))
6199 .join("\n")
6200 })
6201 }
6202
6203 pub fn convert_to_lower_camel_case(
6204 &mut self,
6205 _: &ConvertToLowerCamelCase,
6206 cx: &mut ViewContext<Self>,
6207 ) {
6208 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6209 }
6210
6211 pub fn convert_to_opposite_case(
6212 &mut self,
6213 _: &ConvertToOppositeCase,
6214 cx: &mut ViewContext<Self>,
6215 ) {
6216 self.manipulate_text(cx, |text| {
6217 text.chars()
6218 .fold(String::with_capacity(text.len()), |mut t, c| {
6219 if c.is_uppercase() {
6220 t.extend(c.to_lowercase());
6221 } else {
6222 t.extend(c.to_uppercase());
6223 }
6224 t
6225 })
6226 })
6227 }
6228
6229 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6230 where
6231 Fn: FnMut(&str) -> String,
6232 {
6233 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6234 let buffer = self.buffer.read(cx).snapshot(cx);
6235
6236 let mut new_selections = Vec::new();
6237 let mut edits = Vec::new();
6238 let mut selection_adjustment = 0i32;
6239
6240 for selection in self.selections.all::<usize>(cx) {
6241 let selection_is_empty = selection.is_empty();
6242
6243 let (start, end) = if selection_is_empty {
6244 let word_range = movement::surrounding_word(
6245 &display_map,
6246 selection.start.to_display_point(&display_map),
6247 );
6248 let start = word_range.start.to_offset(&display_map, Bias::Left);
6249 let end = word_range.end.to_offset(&display_map, Bias::Left);
6250 (start, end)
6251 } else {
6252 (selection.start, selection.end)
6253 };
6254
6255 let text = buffer.text_for_range(start..end).collect::<String>();
6256 let old_length = text.len() as i32;
6257 let text = callback(&text);
6258
6259 new_selections.push(Selection {
6260 start: (start as i32 - selection_adjustment) as usize,
6261 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6262 goal: SelectionGoal::None,
6263 ..selection
6264 });
6265
6266 selection_adjustment += old_length - text.len() as i32;
6267
6268 edits.push((start..end, text));
6269 }
6270
6271 self.transact(cx, |this, cx| {
6272 this.buffer.update(cx, |buffer, cx| {
6273 buffer.edit(edits, None, cx);
6274 });
6275
6276 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6277 s.select(new_selections);
6278 });
6279
6280 this.request_autoscroll(Autoscroll::fit(), cx);
6281 });
6282 }
6283
6284 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6286 let buffer = &display_map.buffer_snapshot;
6287 let selections = self.selections.all::<Point>(cx);
6288
6289 let mut edits = Vec::new();
6290 let mut selections_iter = selections.iter().peekable();
6291 while let Some(selection) = selections_iter.next() {
6292 let mut rows = selection.spanned_rows(false, &display_map);
6293 // duplicate line-wise
6294 if whole_lines || selection.start == selection.end {
6295 // Avoid duplicating the same lines twice.
6296 while let Some(next_selection) = selections_iter.peek() {
6297 let next_rows = next_selection.spanned_rows(false, &display_map);
6298 if next_rows.start < rows.end {
6299 rows.end = next_rows.end;
6300 selections_iter.next().unwrap();
6301 } else {
6302 break;
6303 }
6304 }
6305
6306 // Copy the text from the selected row region and splice it either at the start
6307 // or end of the region.
6308 let start = Point::new(rows.start.0, 0);
6309 let end = Point::new(
6310 rows.end.previous_row().0,
6311 buffer.line_len(rows.end.previous_row()),
6312 );
6313 let text = buffer
6314 .text_for_range(start..end)
6315 .chain(Some("\n"))
6316 .collect::<String>();
6317 let insert_location = if upwards {
6318 Point::new(rows.end.0, 0)
6319 } else {
6320 start
6321 };
6322 edits.push((insert_location..insert_location, text));
6323 } else {
6324 // duplicate character-wise
6325 let start = selection.start;
6326 let end = selection.end;
6327 let text = buffer.text_for_range(start..end).collect::<String>();
6328 edits.push((selection.end..selection.end, text));
6329 }
6330 }
6331
6332 self.transact(cx, |this, cx| {
6333 this.buffer.update(cx, |buffer, cx| {
6334 buffer.edit(edits, None, cx);
6335 });
6336
6337 this.request_autoscroll(Autoscroll::fit(), cx);
6338 });
6339 }
6340
6341 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6342 self.duplicate(true, true, cx);
6343 }
6344
6345 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6346 self.duplicate(false, true, cx);
6347 }
6348
6349 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6350 self.duplicate(false, false, cx);
6351 }
6352
6353 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6354 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6355 let buffer = self.buffer.read(cx).snapshot(cx);
6356
6357 let mut edits = Vec::new();
6358 let mut unfold_ranges = Vec::new();
6359 let mut refold_creases = Vec::new();
6360
6361 let selections = self.selections.all::<Point>(cx);
6362 let mut selections = selections.iter().peekable();
6363 let mut contiguous_row_selections = Vec::new();
6364 let mut new_selections = Vec::new();
6365
6366 while let Some(selection) = selections.next() {
6367 // Find all the selections that span a contiguous row range
6368 let (start_row, end_row) = consume_contiguous_rows(
6369 &mut contiguous_row_selections,
6370 selection,
6371 &display_map,
6372 &mut selections,
6373 );
6374
6375 // Move the text spanned by the row range to be before the line preceding the row range
6376 if start_row.0 > 0 {
6377 let range_to_move = Point::new(
6378 start_row.previous_row().0,
6379 buffer.line_len(start_row.previous_row()),
6380 )
6381 ..Point::new(
6382 end_row.previous_row().0,
6383 buffer.line_len(end_row.previous_row()),
6384 );
6385 let insertion_point = display_map
6386 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6387 .0;
6388
6389 // Don't move lines across excerpts
6390 if buffer
6391 .excerpt_boundaries_in_range((
6392 Bound::Excluded(insertion_point),
6393 Bound::Included(range_to_move.end),
6394 ))
6395 .next()
6396 .is_none()
6397 {
6398 let text = buffer
6399 .text_for_range(range_to_move.clone())
6400 .flat_map(|s| s.chars())
6401 .skip(1)
6402 .chain(['\n'])
6403 .collect::<String>();
6404
6405 edits.push((
6406 buffer.anchor_after(range_to_move.start)
6407 ..buffer.anchor_before(range_to_move.end),
6408 String::new(),
6409 ));
6410 let insertion_anchor = buffer.anchor_after(insertion_point);
6411 edits.push((insertion_anchor..insertion_anchor, text));
6412
6413 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6414
6415 // Move selections up
6416 new_selections.extend(contiguous_row_selections.drain(..).map(
6417 |mut selection| {
6418 selection.start.row -= row_delta;
6419 selection.end.row -= row_delta;
6420 selection
6421 },
6422 ));
6423
6424 // Move folds up
6425 unfold_ranges.push(range_to_move.clone());
6426 for fold in display_map.folds_in_range(
6427 buffer.anchor_before(range_to_move.start)
6428 ..buffer.anchor_after(range_to_move.end),
6429 ) {
6430 let mut start = fold.range.start.to_point(&buffer);
6431 let mut end = fold.range.end.to_point(&buffer);
6432 start.row -= row_delta;
6433 end.row -= row_delta;
6434 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6435 }
6436 }
6437 }
6438
6439 // If we didn't move line(s), preserve the existing selections
6440 new_selections.append(&mut contiguous_row_selections);
6441 }
6442
6443 self.transact(cx, |this, cx| {
6444 this.unfold_ranges(&unfold_ranges, true, true, cx);
6445 this.buffer.update(cx, |buffer, cx| {
6446 for (range, text) in edits {
6447 buffer.edit([(range, text)], None, cx);
6448 }
6449 });
6450 this.fold_creases(refold_creases, true, cx);
6451 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6452 s.select(new_selections);
6453 })
6454 });
6455 }
6456
6457 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6458 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6459 let buffer = self.buffer.read(cx).snapshot(cx);
6460
6461 let mut edits = Vec::new();
6462 let mut unfold_ranges = Vec::new();
6463 let mut refold_creases = Vec::new();
6464
6465 let selections = self.selections.all::<Point>(cx);
6466 let mut selections = selections.iter().peekable();
6467 let mut contiguous_row_selections = Vec::new();
6468 let mut new_selections = Vec::new();
6469
6470 while let Some(selection) = selections.next() {
6471 // Find all the selections that span a contiguous row range
6472 let (start_row, end_row) = consume_contiguous_rows(
6473 &mut contiguous_row_selections,
6474 selection,
6475 &display_map,
6476 &mut selections,
6477 );
6478
6479 // Move the text spanned by the row range to be after the last line of the row range
6480 if end_row.0 <= buffer.max_point().row {
6481 let range_to_move =
6482 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6483 let insertion_point = display_map
6484 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6485 .0;
6486
6487 // Don't move lines across excerpt boundaries
6488 if buffer
6489 .excerpt_boundaries_in_range((
6490 Bound::Excluded(range_to_move.start),
6491 Bound::Included(insertion_point),
6492 ))
6493 .next()
6494 .is_none()
6495 {
6496 let mut text = String::from("\n");
6497 text.extend(buffer.text_for_range(range_to_move.clone()));
6498 text.pop(); // Drop trailing newline
6499 edits.push((
6500 buffer.anchor_after(range_to_move.start)
6501 ..buffer.anchor_before(range_to_move.end),
6502 String::new(),
6503 ));
6504 let insertion_anchor = buffer.anchor_after(insertion_point);
6505 edits.push((insertion_anchor..insertion_anchor, text));
6506
6507 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6508
6509 // Move selections down
6510 new_selections.extend(contiguous_row_selections.drain(..).map(
6511 |mut selection| {
6512 selection.start.row += row_delta;
6513 selection.end.row += row_delta;
6514 selection
6515 },
6516 ));
6517
6518 // Move folds down
6519 unfold_ranges.push(range_to_move.clone());
6520 for fold in display_map.folds_in_range(
6521 buffer.anchor_before(range_to_move.start)
6522 ..buffer.anchor_after(range_to_move.end),
6523 ) {
6524 let mut start = fold.range.start.to_point(&buffer);
6525 let mut end = fold.range.end.to_point(&buffer);
6526 start.row += row_delta;
6527 end.row += row_delta;
6528 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6529 }
6530 }
6531 }
6532
6533 // If we didn't move line(s), preserve the existing selections
6534 new_selections.append(&mut contiguous_row_selections);
6535 }
6536
6537 self.transact(cx, |this, cx| {
6538 this.unfold_ranges(&unfold_ranges, true, true, cx);
6539 this.buffer.update(cx, |buffer, cx| {
6540 for (range, text) in edits {
6541 buffer.edit([(range, text)], None, cx);
6542 }
6543 });
6544 this.fold_creases(refold_creases, true, cx);
6545 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6546 });
6547 }
6548
6549 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6550 let text_layout_details = &self.text_layout_details(cx);
6551 self.transact(cx, |this, cx| {
6552 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6553 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6554 let line_mode = s.line_mode;
6555 s.move_with(|display_map, selection| {
6556 if !selection.is_empty() || line_mode {
6557 return;
6558 }
6559
6560 let mut head = selection.head();
6561 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6562 if head.column() == display_map.line_len(head.row()) {
6563 transpose_offset = display_map
6564 .buffer_snapshot
6565 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6566 }
6567
6568 if transpose_offset == 0 {
6569 return;
6570 }
6571
6572 *head.column_mut() += 1;
6573 head = display_map.clip_point(head, Bias::Right);
6574 let goal = SelectionGoal::HorizontalPosition(
6575 display_map
6576 .x_for_display_point(head, text_layout_details)
6577 .into(),
6578 );
6579 selection.collapse_to(head, goal);
6580
6581 let transpose_start = display_map
6582 .buffer_snapshot
6583 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6584 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6585 let transpose_end = display_map
6586 .buffer_snapshot
6587 .clip_offset(transpose_offset + 1, Bias::Right);
6588 if let Some(ch) =
6589 display_map.buffer_snapshot.chars_at(transpose_start).next()
6590 {
6591 edits.push((transpose_start..transpose_offset, String::new()));
6592 edits.push((transpose_end..transpose_end, ch.to_string()));
6593 }
6594 }
6595 });
6596 edits
6597 });
6598 this.buffer
6599 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6600 let selections = this.selections.all::<usize>(cx);
6601 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6602 s.select(selections);
6603 });
6604 });
6605 }
6606
6607 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6608 self.rewrap_impl(IsVimMode::No, cx)
6609 }
6610
6611 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6612 let buffer = self.buffer.read(cx).snapshot(cx);
6613 let selections = self.selections.all::<Point>(cx);
6614 let mut selections = selections.iter().peekable();
6615
6616 let mut edits = Vec::new();
6617 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6618
6619 while let Some(selection) = selections.next() {
6620 let mut start_row = selection.start.row;
6621 let mut end_row = selection.end.row;
6622
6623 // Skip selections that overlap with a range that has already been rewrapped.
6624 let selection_range = start_row..end_row;
6625 if rewrapped_row_ranges
6626 .iter()
6627 .any(|range| range.overlaps(&selection_range))
6628 {
6629 continue;
6630 }
6631
6632 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6633
6634 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6635 match language_scope.language_name().0.as_ref() {
6636 "Markdown" | "Plain Text" => {
6637 should_rewrap = true;
6638 }
6639 _ => {}
6640 }
6641 }
6642
6643 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6644
6645 // Since not all lines in the selection may be at the same indent
6646 // level, choose the indent size that is the most common between all
6647 // of the lines.
6648 //
6649 // If there is a tie, we use the deepest indent.
6650 let (indent_size, indent_end) = {
6651 let mut indent_size_occurrences = HashMap::default();
6652 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6653
6654 for row in start_row..=end_row {
6655 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6656 rows_by_indent_size.entry(indent).or_default().push(row);
6657 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6658 }
6659
6660 let indent_size = indent_size_occurrences
6661 .into_iter()
6662 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6663 .map(|(indent, _)| indent)
6664 .unwrap_or_default();
6665 let row = rows_by_indent_size[&indent_size][0];
6666 let indent_end = Point::new(row, indent_size.len);
6667
6668 (indent_size, indent_end)
6669 };
6670
6671 let mut line_prefix = indent_size.chars().collect::<String>();
6672
6673 if let Some(comment_prefix) =
6674 buffer
6675 .language_scope_at(selection.head())
6676 .and_then(|language| {
6677 language
6678 .line_comment_prefixes()
6679 .iter()
6680 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6681 .cloned()
6682 })
6683 {
6684 line_prefix.push_str(&comment_prefix);
6685 should_rewrap = true;
6686 }
6687
6688 if !should_rewrap {
6689 continue;
6690 }
6691
6692 if selection.is_empty() {
6693 'expand_upwards: while start_row > 0 {
6694 let prev_row = start_row - 1;
6695 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6696 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6697 {
6698 start_row = prev_row;
6699 } else {
6700 break 'expand_upwards;
6701 }
6702 }
6703
6704 'expand_downwards: while end_row < buffer.max_point().row {
6705 let next_row = end_row + 1;
6706 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6707 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6708 {
6709 end_row = next_row;
6710 } else {
6711 break 'expand_downwards;
6712 }
6713 }
6714 }
6715
6716 let start = Point::new(start_row, 0);
6717 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6718 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6719 let Some(lines_without_prefixes) = selection_text
6720 .lines()
6721 .map(|line| {
6722 line.strip_prefix(&line_prefix)
6723 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6724 .ok_or_else(|| {
6725 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6726 })
6727 })
6728 .collect::<Result<Vec<_>, _>>()
6729 .log_err()
6730 else {
6731 continue;
6732 };
6733
6734 let wrap_column = buffer
6735 .settings_at(Point::new(start_row, 0), cx)
6736 .preferred_line_length as usize;
6737 let wrapped_text = wrap_with_prefix(
6738 line_prefix,
6739 lines_without_prefixes.join(" "),
6740 wrap_column,
6741 tab_size,
6742 );
6743
6744 // TODO: should always use char-based diff while still supporting cursor behavior that
6745 // matches vim.
6746 let diff = match is_vim_mode {
6747 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6748 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6749 };
6750 let mut offset = start.to_offset(&buffer);
6751 let mut moved_since_edit = true;
6752
6753 for change in diff.iter_all_changes() {
6754 let value = change.value();
6755 match change.tag() {
6756 ChangeTag::Equal => {
6757 offset += value.len();
6758 moved_since_edit = true;
6759 }
6760 ChangeTag::Delete => {
6761 let start = buffer.anchor_after(offset);
6762 let end = buffer.anchor_before(offset + value.len());
6763
6764 if moved_since_edit {
6765 edits.push((start..end, String::new()));
6766 } else {
6767 edits.last_mut().unwrap().0.end = end;
6768 }
6769
6770 offset += value.len();
6771 moved_since_edit = false;
6772 }
6773 ChangeTag::Insert => {
6774 if moved_since_edit {
6775 let anchor = buffer.anchor_after(offset);
6776 edits.push((anchor..anchor, value.to_string()));
6777 } else {
6778 edits.last_mut().unwrap().1.push_str(value);
6779 }
6780
6781 moved_since_edit = false;
6782 }
6783 }
6784 }
6785
6786 rewrapped_row_ranges.push(start_row..=end_row);
6787 }
6788
6789 self.buffer
6790 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6791 }
6792
6793 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6794 let mut text = String::new();
6795 let buffer = self.buffer.read(cx).snapshot(cx);
6796 let mut selections = self.selections.all::<Point>(cx);
6797 let mut clipboard_selections = Vec::with_capacity(selections.len());
6798 {
6799 let max_point = buffer.max_point();
6800 let mut is_first = true;
6801 for selection in &mut selections {
6802 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6803 if is_entire_line {
6804 selection.start = Point::new(selection.start.row, 0);
6805 if !selection.is_empty() && selection.end.column == 0 {
6806 selection.end = cmp::min(max_point, selection.end);
6807 } else {
6808 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6809 }
6810 selection.goal = SelectionGoal::None;
6811 }
6812 if is_first {
6813 is_first = false;
6814 } else {
6815 text += "\n";
6816 }
6817 let mut len = 0;
6818 for chunk in buffer.text_for_range(selection.start..selection.end) {
6819 text.push_str(chunk);
6820 len += chunk.len();
6821 }
6822 clipboard_selections.push(ClipboardSelection {
6823 len,
6824 is_entire_line,
6825 first_line_indent: buffer
6826 .indent_size_for_line(MultiBufferRow(selection.start.row))
6827 .len,
6828 });
6829 }
6830 }
6831
6832 self.transact(cx, |this, cx| {
6833 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6834 s.select(selections);
6835 });
6836 this.insert("", cx);
6837 });
6838 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6839 }
6840
6841 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6842 let item = self.cut_common(cx);
6843 cx.write_to_clipboard(item);
6844 }
6845
6846 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6847 self.change_selections(None, cx, |s| {
6848 s.move_with(|snapshot, sel| {
6849 if sel.is_empty() {
6850 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6851 }
6852 });
6853 });
6854 let item = self.cut_common(cx);
6855 cx.set_global(KillRing(item))
6856 }
6857
6858 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6859 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6860 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6861 (kill_ring.text().to_string(), kill_ring.metadata_json())
6862 } else {
6863 return;
6864 }
6865 } else {
6866 return;
6867 };
6868 self.do_paste(&text, metadata, false, cx);
6869 }
6870
6871 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6872 let selections = self.selections.all::<Point>(cx);
6873 let buffer = self.buffer.read(cx).read(cx);
6874 let mut text = String::new();
6875
6876 let mut clipboard_selections = Vec::with_capacity(selections.len());
6877 {
6878 let max_point = buffer.max_point();
6879 let mut is_first = true;
6880 for selection in selections.iter() {
6881 let mut start = selection.start;
6882 let mut end = selection.end;
6883 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6884 if is_entire_line {
6885 start = Point::new(start.row, 0);
6886 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6887 }
6888 if is_first {
6889 is_first = false;
6890 } else {
6891 text += "\n";
6892 }
6893 let mut len = 0;
6894 for chunk in buffer.text_for_range(start..end) {
6895 text.push_str(chunk);
6896 len += chunk.len();
6897 }
6898 clipboard_selections.push(ClipboardSelection {
6899 len,
6900 is_entire_line,
6901 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6902 });
6903 }
6904 }
6905
6906 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6907 text,
6908 clipboard_selections,
6909 ));
6910 }
6911
6912 pub fn do_paste(
6913 &mut self,
6914 text: &String,
6915 clipboard_selections: Option<Vec<ClipboardSelection>>,
6916 handle_entire_lines: bool,
6917 cx: &mut ViewContext<Self>,
6918 ) {
6919 if self.read_only(cx) {
6920 return;
6921 }
6922
6923 let clipboard_text = Cow::Borrowed(text);
6924
6925 self.transact(cx, |this, cx| {
6926 if let Some(mut clipboard_selections) = clipboard_selections {
6927 let old_selections = this.selections.all::<usize>(cx);
6928 let all_selections_were_entire_line =
6929 clipboard_selections.iter().all(|s| s.is_entire_line);
6930 let first_selection_indent_column =
6931 clipboard_selections.first().map(|s| s.first_line_indent);
6932 if clipboard_selections.len() != old_selections.len() {
6933 clipboard_selections.drain(..);
6934 }
6935 let cursor_offset = this.selections.last::<usize>(cx).head();
6936 let mut auto_indent_on_paste = true;
6937
6938 this.buffer.update(cx, |buffer, cx| {
6939 let snapshot = buffer.read(cx);
6940 auto_indent_on_paste =
6941 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6942
6943 let mut start_offset = 0;
6944 let mut edits = Vec::new();
6945 let mut original_indent_columns = Vec::new();
6946 for (ix, selection) in old_selections.iter().enumerate() {
6947 let to_insert;
6948 let entire_line;
6949 let original_indent_column;
6950 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6951 let end_offset = start_offset + clipboard_selection.len;
6952 to_insert = &clipboard_text[start_offset..end_offset];
6953 entire_line = clipboard_selection.is_entire_line;
6954 start_offset = end_offset + 1;
6955 original_indent_column = Some(clipboard_selection.first_line_indent);
6956 } else {
6957 to_insert = clipboard_text.as_str();
6958 entire_line = all_selections_were_entire_line;
6959 original_indent_column = first_selection_indent_column
6960 }
6961
6962 // If the corresponding selection was empty when this slice of the
6963 // clipboard text was written, then the entire line containing the
6964 // selection was copied. If this selection is also currently empty,
6965 // then paste the line before the current line of the buffer.
6966 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6967 let column = selection.start.to_point(&snapshot).column as usize;
6968 let line_start = selection.start - column;
6969 line_start..line_start
6970 } else {
6971 selection.range()
6972 };
6973
6974 edits.push((range, to_insert));
6975 original_indent_columns.extend(original_indent_column);
6976 }
6977 drop(snapshot);
6978
6979 buffer.edit(
6980 edits,
6981 if auto_indent_on_paste {
6982 Some(AutoindentMode::Block {
6983 original_indent_columns,
6984 })
6985 } else {
6986 None
6987 },
6988 cx,
6989 );
6990 });
6991
6992 let selections = this.selections.all::<usize>(cx);
6993 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6994 } else {
6995 this.insert(&clipboard_text, cx);
6996 }
6997 });
6998 }
6999
7000 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7001 if let Some(item) = cx.read_from_clipboard() {
7002 let entries = item.entries();
7003
7004 match entries.first() {
7005 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7006 // of all the pasted entries.
7007 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7008 .do_paste(
7009 clipboard_string.text(),
7010 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7011 true,
7012 cx,
7013 ),
7014 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7015 }
7016 }
7017 }
7018
7019 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7020 if self.read_only(cx) {
7021 return;
7022 }
7023
7024 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7025 if let Some((selections, _)) =
7026 self.selection_history.transaction(transaction_id).cloned()
7027 {
7028 self.change_selections(None, cx, |s| {
7029 s.select_anchors(selections.to_vec());
7030 });
7031 }
7032 self.request_autoscroll(Autoscroll::fit(), cx);
7033 self.unmark_text(cx);
7034 self.refresh_inline_completion(true, false, cx);
7035 cx.emit(EditorEvent::Edited { transaction_id });
7036 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7037 }
7038 }
7039
7040 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7041 if self.read_only(cx) {
7042 return;
7043 }
7044
7045 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7046 if let Some((_, Some(selections))) =
7047 self.selection_history.transaction(transaction_id).cloned()
7048 {
7049 self.change_selections(None, cx, |s| {
7050 s.select_anchors(selections.to_vec());
7051 });
7052 }
7053 self.request_autoscroll(Autoscroll::fit(), cx);
7054 self.unmark_text(cx);
7055 self.refresh_inline_completion(true, false, cx);
7056 cx.emit(EditorEvent::Edited { transaction_id });
7057 }
7058 }
7059
7060 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7061 self.buffer
7062 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7063 }
7064
7065 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7066 self.buffer
7067 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7068 }
7069
7070 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7071 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7072 let line_mode = s.line_mode;
7073 s.move_with(|map, selection| {
7074 let cursor = if selection.is_empty() && !line_mode {
7075 movement::left(map, selection.start)
7076 } else {
7077 selection.start
7078 };
7079 selection.collapse_to(cursor, SelectionGoal::None);
7080 });
7081 })
7082 }
7083
7084 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7085 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7086 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7087 })
7088 }
7089
7090 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7091 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7092 let line_mode = s.line_mode;
7093 s.move_with(|map, selection| {
7094 let cursor = if selection.is_empty() && !line_mode {
7095 movement::right(map, selection.end)
7096 } else {
7097 selection.end
7098 };
7099 selection.collapse_to(cursor, SelectionGoal::None)
7100 });
7101 })
7102 }
7103
7104 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7105 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7106 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7107 })
7108 }
7109
7110 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7111 if self.take_rename(true, cx).is_some() {
7112 return;
7113 }
7114
7115 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7116 cx.propagate();
7117 return;
7118 }
7119
7120 let text_layout_details = &self.text_layout_details(cx);
7121 let selection_count = self.selections.count();
7122 let first_selection = self.selections.first_anchor();
7123
7124 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7125 let line_mode = s.line_mode;
7126 s.move_with(|map, selection| {
7127 if !selection.is_empty() && !line_mode {
7128 selection.goal = SelectionGoal::None;
7129 }
7130 let (cursor, goal) = movement::up(
7131 map,
7132 selection.start,
7133 selection.goal,
7134 false,
7135 text_layout_details,
7136 );
7137 selection.collapse_to(cursor, goal);
7138 });
7139 });
7140
7141 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7142 {
7143 cx.propagate();
7144 }
7145 }
7146
7147 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7148 if self.take_rename(true, cx).is_some() {
7149 return;
7150 }
7151
7152 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7153 cx.propagate();
7154 return;
7155 }
7156
7157 let text_layout_details = &self.text_layout_details(cx);
7158
7159 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7160 let line_mode = s.line_mode;
7161 s.move_with(|map, selection| {
7162 if !selection.is_empty() && !line_mode {
7163 selection.goal = SelectionGoal::None;
7164 }
7165 let (cursor, goal) = movement::up_by_rows(
7166 map,
7167 selection.start,
7168 action.lines,
7169 selection.goal,
7170 false,
7171 text_layout_details,
7172 );
7173 selection.collapse_to(cursor, goal);
7174 });
7175 })
7176 }
7177
7178 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7179 if self.take_rename(true, cx).is_some() {
7180 return;
7181 }
7182
7183 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7184 cx.propagate();
7185 return;
7186 }
7187
7188 let text_layout_details = &self.text_layout_details(cx);
7189
7190 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7191 let line_mode = s.line_mode;
7192 s.move_with(|map, selection| {
7193 if !selection.is_empty() && !line_mode {
7194 selection.goal = SelectionGoal::None;
7195 }
7196 let (cursor, goal) = movement::down_by_rows(
7197 map,
7198 selection.start,
7199 action.lines,
7200 selection.goal,
7201 false,
7202 text_layout_details,
7203 );
7204 selection.collapse_to(cursor, goal);
7205 });
7206 })
7207 }
7208
7209 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7210 let text_layout_details = &self.text_layout_details(cx);
7211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7212 s.move_heads_with(|map, head, goal| {
7213 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7214 })
7215 })
7216 }
7217
7218 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7219 let text_layout_details = &self.text_layout_details(cx);
7220 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7221 s.move_heads_with(|map, head, goal| {
7222 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7223 })
7224 })
7225 }
7226
7227 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7228 let Some(row_count) = self.visible_row_count() else {
7229 return;
7230 };
7231
7232 let text_layout_details = &self.text_layout_details(cx);
7233
7234 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7235 s.move_heads_with(|map, head, goal| {
7236 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7237 })
7238 })
7239 }
7240
7241 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7242 if self.take_rename(true, cx).is_some() {
7243 return;
7244 }
7245
7246 if self
7247 .context_menu
7248 .borrow_mut()
7249 .as_mut()
7250 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7251 .unwrap_or(false)
7252 {
7253 return;
7254 }
7255
7256 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7257 cx.propagate();
7258 return;
7259 }
7260
7261 let Some(row_count) = self.visible_row_count() else {
7262 return;
7263 };
7264
7265 let autoscroll = if action.center_cursor {
7266 Autoscroll::center()
7267 } else {
7268 Autoscroll::fit()
7269 };
7270
7271 let text_layout_details = &self.text_layout_details(cx);
7272
7273 self.change_selections(Some(autoscroll), cx, |s| {
7274 let line_mode = s.line_mode;
7275 s.move_with(|map, selection| {
7276 if !selection.is_empty() && !line_mode {
7277 selection.goal = SelectionGoal::None;
7278 }
7279 let (cursor, goal) = movement::up_by_rows(
7280 map,
7281 selection.end,
7282 row_count,
7283 selection.goal,
7284 false,
7285 text_layout_details,
7286 );
7287 selection.collapse_to(cursor, goal);
7288 });
7289 });
7290 }
7291
7292 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7293 let text_layout_details = &self.text_layout_details(cx);
7294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7295 s.move_heads_with(|map, head, goal| {
7296 movement::up(map, head, goal, false, text_layout_details)
7297 })
7298 })
7299 }
7300
7301 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7302 self.take_rename(true, cx);
7303
7304 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7305 cx.propagate();
7306 return;
7307 }
7308
7309 let text_layout_details = &self.text_layout_details(cx);
7310 let selection_count = self.selections.count();
7311 let first_selection = self.selections.first_anchor();
7312
7313 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7314 let line_mode = s.line_mode;
7315 s.move_with(|map, selection| {
7316 if !selection.is_empty() && !line_mode {
7317 selection.goal = SelectionGoal::None;
7318 }
7319 let (cursor, goal) = movement::down(
7320 map,
7321 selection.end,
7322 selection.goal,
7323 false,
7324 text_layout_details,
7325 );
7326 selection.collapse_to(cursor, goal);
7327 });
7328 });
7329
7330 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7331 {
7332 cx.propagate();
7333 }
7334 }
7335
7336 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7337 let Some(row_count) = self.visible_row_count() else {
7338 return;
7339 };
7340
7341 let text_layout_details = &self.text_layout_details(cx);
7342
7343 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7344 s.move_heads_with(|map, head, goal| {
7345 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7346 })
7347 })
7348 }
7349
7350 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7351 if self.take_rename(true, cx).is_some() {
7352 return;
7353 }
7354
7355 if self
7356 .context_menu
7357 .borrow_mut()
7358 .as_mut()
7359 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7360 .unwrap_or(false)
7361 {
7362 return;
7363 }
7364
7365 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7366 cx.propagate();
7367 return;
7368 }
7369
7370 let Some(row_count) = self.visible_row_count() else {
7371 return;
7372 };
7373
7374 let autoscroll = if action.center_cursor {
7375 Autoscroll::center()
7376 } else {
7377 Autoscroll::fit()
7378 };
7379
7380 let text_layout_details = &self.text_layout_details(cx);
7381 self.change_selections(Some(autoscroll), cx, |s| {
7382 let line_mode = s.line_mode;
7383 s.move_with(|map, selection| {
7384 if !selection.is_empty() && !line_mode {
7385 selection.goal = SelectionGoal::None;
7386 }
7387 let (cursor, goal) = movement::down_by_rows(
7388 map,
7389 selection.end,
7390 row_count,
7391 selection.goal,
7392 false,
7393 text_layout_details,
7394 );
7395 selection.collapse_to(cursor, goal);
7396 });
7397 });
7398 }
7399
7400 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7401 let text_layout_details = &self.text_layout_details(cx);
7402 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7403 s.move_heads_with(|map, head, goal| {
7404 movement::down(map, head, goal, false, text_layout_details)
7405 })
7406 });
7407 }
7408
7409 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7410 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7411 context_menu.select_first(self.completion_provider.as_deref(), cx);
7412 }
7413 }
7414
7415 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7416 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7417 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7418 }
7419 }
7420
7421 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7422 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7423 context_menu.select_next(self.completion_provider.as_deref(), cx);
7424 }
7425 }
7426
7427 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7428 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7429 context_menu.select_last(self.completion_provider.as_deref(), cx);
7430 }
7431 }
7432
7433 pub fn move_to_previous_word_start(
7434 &mut self,
7435 _: &MoveToPreviousWordStart,
7436 cx: &mut ViewContext<Self>,
7437 ) {
7438 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7439 s.move_cursors_with(|map, head, _| {
7440 (
7441 movement::previous_word_start(map, head),
7442 SelectionGoal::None,
7443 )
7444 });
7445 })
7446 }
7447
7448 pub fn move_to_previous_subword_start(
7449 &mut self,
7450 _: &MoveToPreviousSubwordStart,
7451 cx: &mut ViewContext<Self>,
7452 ) {
7453 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7454 s.move_cursors_with(|map, head, _| {
7455 (
7456 movement::previous_subword_start(map, head),
7457 SelectionGoal::None,
7458 )
7459 });
7460 })
7461 }
7462
7463 pub fn select_to_previous_word_start(
7464 &mut self,
7465 _: &SelectToPreviousWordStart,
7466 cx: &mut ViewContext<Self>,
7467 ) {
7468 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7469 s.move_heads_with(|map, head, _| {
7470 (
7471 movement::previous_word_start(map, head),
7472 SelectionGoal::None,
7473 )
7474 });
7475 })
7476 }
7477
7478 pub fn select_to_previous_subword_start(
7479 &mut self,
7480 _: &SelectToPreviousSubwordStart,
7481 cx: &mut ViewContext<Self>,
7482 ) {
7483 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7484 s.move_heads_with(|map, head, _| {
7485 (
7486 movement::previous_subword_start(map, head),
7487 SelectionGoal::None,
7488 )
7489 });
7490 })
7491 }
7492
7493 pub fn delete_to_previous_word_start(
7494 &mut self,
7495 action: &DeleteToPreviousWordStart,
7496 cx: &mut ViewContext<Self>,
7497 ) {
7498 self.transact(cx, |this, cx| {
7499 this.select_autoclose_pair(cx);
7500 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7501 let line_mode = s.line_mode;
7502 s.move_with(|map, selection| {
7503 if selection.is_empty() && !line_mode {
7504 let cursor = if action.ignore_newlines {
7505 movement::previous_word_start(map, selection.head())
7506 } else {
7507 movement::previous_word_start_or_newline(map, selection.head())
7508 };
7509 selection.set_head(cursor, SelectionGoal::None);
7510 }
7511 });
7512 });
7513 this.insert("", cx);
7514 });
7515 }
7516
7517 pub fn delete_to_previous_subword_start(
7518 &mut self,
7519 _: &DeleteToPreviousSubwordStart,
7520 cx: &mut ViewContext<Self>,
7521 ) {
7522 self.transact(cx, |this, cx| {
7523 this.select_autoclose_pair(cx);
7524 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7525 let line_mode = s.line_mode;
7526 s.move_with(|map, selection| {
7527 if selection.is_empty() && !line_mode {
7528 let cursor = movement::previous_subword_start(map, selection.head());
7529 selection.set_head(cursor, SelectionGoal::None);
7530 }
7531 });
7532 });
7533 this.insert("", cx);
7534 });
7535 }
7536
7537 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7538 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7539 s.move_cursors_with(|map, head, _| {
7540 (movement::next_word_end(map, head), SelectionGoal::None)
7541 });
7542 })
7543 }
7544
7545 pub fn move_to_next_subword_end(
7546 &mut self,
7547 _: &MoveToNextSubwordEnd,
7548 cx: &mut ViewContext<Self>,
7549 ) {
7550 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7551 s.move_cursors_with(|map, head, _| {
7552 (movement::next_subword_end(map, head), SelectionGoal::None)
7553 });
7554 })
7555 }
7556
7557 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7558 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7559 s.move_heads_with(|map, head, _| {
7560 (movement::next_word_end(map, head), SelectionGoal::None)
7561 });
7562 })
7563 }
7564
7565 pub fn select_to_next_subword_end(
7566 &mut self,
7567 _: &SelectToNextSubwordEnd,
7568 cx: &mut ViewContext<Self>,
7569 ) {
7570 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7571 s.move_heads_with(|map, head, _| {
7572 (movement::next_subword_end(map, head), SelectionGoal::None)
7573 });
7574 })
7575 }
7576
7577 pub fn delete_to_next_word_end(
7578 &mut self,
7579 action: &DeleteToNextWordEnd,
7580 cx: &mut ViewContext<Self>,
7581 ) {
7582 self.transact(cx, |this, cx| {
7583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7584 let line_mode = s.line_mode;
7585 s.move_with(|map, selection| {
7586 if selection.is_empty() && !line_mode {
7587 let cursor = if action.ignore_newlines {
7588 movement::next_word_end(map, selection.head())
7589 } else {
7590 movement::next_word_end_or_newline(map, selection.head())
7591 };
7592 selection.set_head(cursor, SelectionGoal::None);
7593 }
7594 });
7595 });
7596 this.insert("", cx);
7597 });
7598 }
7599
7600 pub fn delete_to_next_subword_end(
7601 &mut self,
7602 _: &DeleteToNextSubwordEnd,
7603 cx: &mut ViewContext<Self>,
7604 ) {
7605 self.transact(cx, |this, cx| {
7606 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7607 s.move_with(|map, selection| {
7608 if selection.is_empty() {
7609 let cursor = movement::next_subword_end(map, selection.head());
7610 selection.set_head(cursor, SelectionGoal::None);
7611 }
7612 });
7613 });
7614 this.insert("", cx);
7615 });
7616 }
7617
7618 pub fn move_to_beginning_of_line(
7619 &mut self,
7620 action: &MoveToBeginningOfLine,
7621 cx: &mut ViewContext<Self>,
7622 ) {
7623 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 s.move_cursors_with(|map, head, _| {
7625 (
7626 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7627 SelectionGoal::None,
7628 )
7629 });
7630 })
7631 }
7632
7633 pub fn select_to_beginning_of_line(
7634 &mut self,
7635 action: &SelectToBeginningOfLine,
7636 cx: &mut ViewContext<Self>,
7637 ) {
7638 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7639 s.move_heads_with(|map, head, _| {
7640 (
7641 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7642 SelectionGoal::None,
7643 )
7644 });
7645 });
7646 }
7647
7648 pub fn delete_to_beginning_of_line(
7649 &mut self,
7650 _: &DeleteToBeginningOfLine,
7651 cx: &mut ViewContext<Self>,
7652 ) {
7653 self.transact(cx, |this, cx| {
7654 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7655 s.move_with(|_, selection| {
7656 selection.reversed = true;
7657 });
7658 });
7659
7660 this.select_to_beginning_of_line(
7661 &SelectToBeginningOfLine {
7662 stop_at_soft_wraps: false,
7663 },
7664 cx,
7665 );
7666 this.backspace(&Backspace, cx);
7667 });
7668 }
7669
7670 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7671 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 s.move_cursors_with(|map, head, _| {
7673 (
7674 movement::line_end(map, head, action.stop_at_soft_wraps),
7675 SelectionGoal::None,
7676 )
7677 });
7678 })
7679 }
7680
7681 pub fn select_to_end_of_line(
7682 &mut self,
7683 action: &SelectToEndOfLine,
7684 cx: &mut ViewContext<Self>,
7685 ) {
7686 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7687 s.move_heads_with(|map, head, _| {
7688 (
7689 movement::line_end(map, head, action.stop_at_soft_wraps),
7690 SelectionGoal::None,
7691 )
7692 });
7693 })
7694 }
7695
7696 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7697 self.transact(cx, |this, cx| {
7698 this.select_to_end_of_line(
7699 &SelectToEndOfLine {
7700 stop_at_soft_wraps: false,
7701 },
7702 cx,
7703 );
7704 this.delete(&Delete, cx);
7705 });
7706 }
7707
7708 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7709 self.transact(cx, |this, cx| {
7710 this.select_to_end_of_line(
7711 &SelectToEndOfLine {
7712 stop_at_soft_wraps: false,
7713 },
7714 cx,
7715 );
7716 this.cut(&Cut, cx);
7717 });
7718 }
7719
7720 pub fn move_to_start_of_paragraph(
7721 &mut self,
7722 _: &MoveToStartOfParagraph,
7723 cx: &mut ViewContext<Self>,
7724 ) {
7725 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7726 cx.propagate();
7727 return;
7728 }
7729
7730 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7731 s.move_with(|map, selection| {
7732 selection.collapse_to(
7733 movement::start_of_paragraph(map, selection.head(), 1),
7734 SelectionGoal::None,
7735 )
7736 });
7737 })
7738 }
7739
7740 pub fn move_to_end_of_paragraph(
7741 &mut self,
7742 _: &MoveToEndOfParagraph,
7743 cx: &mut ViewContext<Self>,
7744 ) {
7745 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7746 cx.propagate();
7747 return;
7748 }
7749
7750 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 s.move_with(|map, selection| {
7752 selection.collapse_to(
7753 movement::end_of_paragraph(map, selection.head(), 1),
7754 SelectionGoal::None,
7755 )
7756 });
7757 })
7758 }
7759
7760 pub fn select_to_start_of_paragraph(
7761 &mut self,
7762 _: &SelectToStartOfParagraph,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7766 cx.propagate();
7767 return;
7768 }
7769
7770 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7771 s.move_heads_with(|map, head, _| {
7772 (
7773 movement::start_of_paragraph(map, head, 1),
7774 SelectionGoal::None,
7775 )
7776 });
7777 })
7778 }
7779
7780 pub fn select_to_end_of_paragraph(
7781 &mut self,
7782 _: &SelectToEndOfParagraph,
7783 cx: &mut ViewContext<Self>,
7784 ) {
7785 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7786 cx.propagate();
7787 return;
7788 }
7789
7790 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7791 s.move_heads_with(|map, head, _| {
7792 (
7793 movement::end_of_paragraph(map, head, 1),
7794 SelectionGoal::None,
7795 )
7796 });
7797 })
7798 }
7799
7800 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7801 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7802 cx.propagate();
7803 return;
7804 }
7805
7806 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7807 s.select_ranges(vec![0..0]);
7808 });
7809 }
7810
7811 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7812 let mut selection = self.selections.last::<Point>(cx);
7813 selection.set_head(Point::zero(), SelectionGoal::None);
7814
7815 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7816 s.select(vec![selection]);
7817 });
7818 }
7819
7820 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7821 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7822 cx.propagate();
7823 return;
7824 }
7825
7826 let cursor = self.buffer.read(cx).read(cx).len();
7827 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7828 s.select_ranges(vec![cursor..cursor])
7829 });
7830 }
7831
7832 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7833 self.nav_history = nav_history;
7834 }
7835
7836 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7837 self.nav_history.as_ref()
7838 }
7839
7840 fn push_to_nav_history(
7841 &mut self,
7842 cursor_anchor: Anchor,
7843 new_position: Option<Point>,
7844 cx: &mut ViewContext<Self>,
7845 ) {
7846 if let Some(nav_history) = self.nav_history.as_mut() {
7847 let buffer = self.buffer.read(cx).read(cx);
7848 let cursor_position = cursor_anchor.to_point(&buffer);
7849 let scroll_state = self.scroll_manager.anchor();
7850 let scroll_top_row = scroll_state.top_row(&buffer);
7851 drop(buffer);
7852
7853 if let Some(new_position) = new_position {
7854 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7855 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7856 return;
7857 }
7858 }
7859
7860 nav_history.push(
7861 Some(NavigationData {
7862 cursor_anchor,
7863 cursor_position,
7864 scroll_anchor: scroll_state,
7865 scroll_top_row,
7866 }),
7867 cx,
7868 );
7869 }
7870 }
7871
7872 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7873 let buffer = self.buffer.read(cx).snapshot(cx);
7874 let mut selection = self.selections.first::<usize>(cx);
7875 selection.set_head(buffer.len(), SelectionGoal::None);
7876 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7877 s.select(vec![selection]);
7878 });
7879 }
7880
7881 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7882 let end = self.buffer.read(cx).read(cx).len();
7883 self.change_selections(None, cx, |s| {
7884 s.select_ranges(vec![0..end]);
7885 });
7886 }
7887
7888 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7890 let mut selections = self.selections.all::<Point>(cx);
7891 let max_point = display_map.buffer_snapshot.max_point();
7892 for selection in &mut selections {
7893 let rows = selection.spanned_rows(true, &display_map);
7894 selection.start = Point::new(rows.start.0, 0);
7895 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7896 selection.reversed = false;
7897 }
7898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7899 s.select(selections);
7900 });
7901 }
7902
7903 pub fn split_selection_into_lines(
7904 &mut self,
7905 _: &SplitSelectionIntoLines,
7906 cx: &mut ViewContext<Self>,
7907 ) {
7908 let mut to_unfold = Vec::new();
7909 let mut new_selection_ranges = Vec::new();
7910 {
7911 let selections = self.selections.all::<Point>(cx);
7912 let buffer = self.buffer.read(cx).read(cx);
7913 for selection in selections {
7914 for row in selection.start.row..selection.end.row {
7915 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7916 new_selection_ranges.push(cursor..cursor);
7917 }
7918 new_selection_ranges.push(selection.end..selection.end);
7919 to_unfold.push(selection.start..selection.end);
7920 }
7921 }
7922 self.unfold_ranges(&to_unfold, true, true, cx);
7923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7924 s.select_ranges(new_selection_ranges);
7925 });
7926 }
7927
7928 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7929 self.add_selection(true, cx);
7930 }
7931
7932 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7933 self.add_selection(false, cx);
7934 }
7935
7936 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7937 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7938 let mut selections = self.selections.all::<Point>(cx);
7939 let text_layout_details = self.text_layout_details(cx);
7940 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7941 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7942 let range = oldest_selection.display_range(&display_map).sorted();
7943
7944 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7945 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7946 let positions = start_x.min(end_x)..start_x.max(end_x);
7947
7948 selections.clear();
7949 let mut stack = Vec::new();
7950 for row in range.start.row().0..=range.end.row().0 {
7951 if let Some(selection) = self.selections.build_columnar_selection(
7952 &display_map,
7953 DisplayRow(row),
7954 &positions,
7955 oldest_selection.reversed,
7956 &text_layout_details,
7957 ) {
7958 stack.push(selection.id);
7959 selections.push(selection);
7960 }
7961 }
7962
7963 if above {
7964 stack.reverse();
7965 }
7966
7967 AddSelectionsState { above, stack }
7968 });
7969
7970 let last_added_selection = *state.stack.last().unwrap();
7971 let mut new_selections = Vec::new();
7972 if above == state.above {
7973 let end_row = if above {
7974 DisplayRow(0)
7975 } else {
7976 display_map.max_point().row()
7977 };
7978
7979 'outer: for selection in selections {
7980 if selection.id == last_added_selection {
7981 let range = selection.display_range(&display_map).sorted();
7982 debug_assert_eq!(range.start.row(), range.end.row());
7983 let mut row = range.start.row();
7984 let positions =
7985 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7986 px(start)..px(end)
7987 } else {
7988 let start_x =
7989 display_map.x_for_display_point(range.start, &text_layout_details);
7990 let end_x =
7991 display_map.x_for_display_point(range.end, &text_layout_details);
7992 start_x.min(end_x)..start_x.max(end_x)
7993 };
7994
7995 while row != end_row {
7996 if above {
7997 row.0 -= 1;
7998 } else {
7999 row.0 += 1;
8000 }
8001
8002 if let Some(new_selection) = self.selections.build_columnar_selection(
8003 &display_map,
8004 row,
8005 &positions,
8006 selection.reversed,
8007 &text_layout_details,
8008 ) {
8009 state.stack.push(new_selection.id);
8010 if above {
8011 new_selections.push(new_selection);
8012 new_selections.push(selection);
8013 } else {
8014 new_selections.push(selection);
8015 new_selections.push(new_selection);
8016 }
8017
8018 continue 'outer;
8019 }
8020 }
8021 }
8022
8023 new_selections.push(selection);
8024 }
8025 } else {
8026 new_selections = selections;
8027 new_selections.retain(|s| s.id != last_added_selection);
8028 state.stack.pop();
8029 }
8030
8031 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8032 s.select(new_selections);
8033 });
8034 if state.stack.len() > 1 {
8035 self.add_selections_state = Some(state);
8036 }
8037 }
8038
8039 pub fn select_next_match_internal(
8040 &mut self,
8041 display_map: &DisplaySnapshot,
8042 replace_newest: bool,
8043 autoscroll: Option<Autoscroll>,
8044 cx: &mut ViewContext<Self>,
8045 ) -> Result<()> {
8046 fn select_next_match_ranges(
8047 this: &mut Editor,
8048 range: Range<usize>,
8049 replace_newest: bool,
8050 auto_scroll: Option<Autoscroll>,
8051 cx: &mut ViewContext<Editor>,
8052 ) {
8053 this.unfold_ranges(&[range.clone()], false, true, cx);
8054 this.change_selections(auto_scroll, cx, |s| {
8055 if replace_newest {
8056 s.delete(s.newest_anchor().id);
8057 }
8058 s.insert_range(range.clone());
8059 });
8060 }
8061
8062 let buffer = &display_map.buffer_snapshot;
8063 let mut selections = self.selections.all::<usize>(cx);
8064 if let Some(mut select_next_state) = self.select_next_state.take() {
8065 let query = &select_next_state.query;
8066 if !select_next_state.done {
8067 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8068 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8069 let mut next_selected_range = None;
8070
8071 let bytes_after_last_selection =
8072 buffer.bytes_in_range(last_selection.end..buffer.len());
8073 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8074 let query_matches = query
8075 .stream_find_iter(bytes_after_last_selection)
8076 .map(|result| (last_selection.end, result))
8077 .chain(
8078 query
8079 .stream_find_iter(bytes_before_first_selection)
8080 .map(|result| (0, result)),
8081 );
8082
8083 for (start_offset, query_match) in query_matches {
8084 let query_match = query_match.unwrap(); // can only fail due to I/O
8085 let offset_range =
8086 start_offset + query_match.start()..start_offset + query_match.end();
8087 let display_range = offset_range.start.to_display_point(display_map)
8088 ..offset_range.end.to_display_point(display_map);
8089
8090 if !select_next_state.wordwise
8091 || (!movement::is_inside_word(display_map, display_range.start)
8092 && !movement::is_inside_word(display_map, display_range.end))
8093 {
8094 // TODO: This is n^2, because we might check all the selections
8095 if !selections
8096 .iter()
8097 .any(|selection| selection.range().overlaps(&offset_range))
8098 {
8099 next_selected_range = Some(offset_range);
8100 break;
8101 }
8102 }
8103 }
8104
8105 if let Some(next_selected_range) = next_selected_range {
8106 select_next_match_ranges(
8107 self,
8108 next_selected_range,
8109 replace_newest,
8110 autoscroll,
8111 cx,
8112 );
8113 } else {
8114 select_next_state.done = true;
8115 }
8116 }
8117
8118 self.select_next_state = Some(select_next_state);
8119 } else {
8120 let mut only_carets = true;
8121 let mut same_text_selected = true;
8122 let mut selected_text = None;
8123
8124 let mut selections_iter = selections.iter().peekable();
8125 while let Some(selection) = selections_iter.next() {
8126 if selection.start != selection.end {
8127 only_carets = false;
8128 }
8129
8130 if same_text_selected {
8131 if selected_text.is_none() {
8132 selected_text =
8133 Some(buffer.text_for_range(selection.range()).collect::<String>());
8134 }
8135
8136 if let Some(next_selection) = selections_iter.peek() {
8137 if next_selection.range().len() == selection.range().len() {
8138 let next_selected_text = buffer
8139 .text_for_range(next_selection.range())
8140 .collect::<String>();
8141 if Some(next_selected_text) != selected_text {
8142 same_text_selected = false;
8143 selected_text = None;
8144 }
8145 } else {
8146 same_text_selected = false;
8147 selected_text = None;
8148 }
8149 }
8150 }
8151 }
8152
8153 if only_carets {
8154 for selection in &mut selections {
8155 let word_range = movement::surrounding_word(
8156 display_map,
8157 selection.start.to_display_point(display_map),
8158 );
8159 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8160 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8161 selection.goal = SelectionGoal::None;
8162 selection.reversed = false;
8163 select_next_match_ranges(
8164 self,
8165 selection.start..selection.end,
8166 replace_newest,
8167 autoscroll,
8168 cx,
8169 );
8170 }
8171
8172 if selections.len() == 1 {
8173 let selection = selections
8174 .last()
8175 .expect("ensured that there's only one selection");
8176 let query = buffer
8177 .text_for_range(selection.start..selection.end)
8178 .collect::<String>();
8179 let is_empty = query.is_empty();
8180 let select_state = SelectNextState {
8181 query: AhoCorasick::new(&[query])?,
8182 wordwise: true,
8183 done: is_empty,
8184 };
8185 self.select_next_state = Some(select_state);
8186 } else {
8187 self.select_next_state = None;
8188 }
8189 } else if let Some(selected_text) = selected_text {
8190 self.select_next_state = Some(SelectNextState {
8191 query: AhoCorasick::new(&[selected_text])?,
8192 wordwise: false,
8193 done: false,
8194 });
8195 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8196 }
8197 }
8198 Ok(())
8199 }
8200
8201 pub fn select_all_matches(
8202 &mut self,
8203 _action: &SelectAllMatches,
8204 cx: &mut ViewContext<Self>,
8205 ) -> Result<()> {
8206 self.push_to_selection_history();
8207 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8208
8209 self.select_next_match_internal(&display_map, false, None, cx)?;
8210 let Some(select_next_state) = self.select_next_state.as_mut() else {
8211 return Ok(());
8212 };
8213 if select_next_state.done {
8214 return Ok(());
8215 }
8216
8217 let mut new_selections = self.selections.all::<usize>(cx);
8218
8219 let buffer = &display_map.buffer_snapshot;
8220 let query_matches = select_next_state
8221 .query
8222 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8223
8224 for query_match in query_matches {
8225 let query_match = query_match.unwrap(); // can only fail due to I/O
8226 let offset_range = query_match.start()..query_match.end();
8227 let display_range = offset_range.start.to_display_point(&display_map)
8228 ..offset_range.end.to_display_point(&display_map);
8229
8230 if !select_next_state.wordwise
8231 || (!movement::is_inside_word(&display_map, display_range.start)
8232 && !movement::is_inside_word(&display_map, display_range.end))
8233 {
8234 self.selections.change_with(cx, |selections| {
8235 new_selections.push(Selection {
8236 id: selections.new_selection_id(),
8237 start: offset_range.start,
8238 end: offset_range.end,
8239 reversed: false,
8240 goal: SelectionGoal::None,
8241 });
8242 });
8243 }
8244 }
8245
8246 new_selections.sort_by_key(|selection| selection.start);
8247 let mut ix = 0;
8248 while ix + 1 < new_selections.len() {
8249 let current_selection = &new_selections[ix];
8250 let next_selection = &new_selections[ix + 1];
8251 if current_selection.range().overlaps(&next_selection.range()) {
8252 if current_selection.id < next_selection.id {
8253 new_selections.remove(ix + 1);
8254 } else {
8255 new_selections.remove(ix);
8256 }
8257 } else {
8258 ix += 1;
8259 }
8260 }
8261
8262 select_next_state.done = true;
8263 self.unfold_ranges(
8264 &new_selections
8265 .iter()
8266 .map(|selection| selection.range())
8267 .collect::<Vec<_>>(),
8268 false,
8269 false,
8270 cx,
8271 );
8272 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8273 selections.select(new_selections)
8274 });
8275
8276 Ok(())
8277 }
8278
8279 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8280 self.push_to_selection_history();
8281 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8282 self.select_next_match_internal(
8283 &display_map,
8284 action.replace_newest,
8285 Some(Autoscroll::newest()),
8286 cx,
8287 )?;
8288 Ok(())
8289 }
8290
8291 pub fn select_previous(
8292 &mut self,
8293 action: &SelectPrevious,
8294 cx: &mut ViewContext<Self>,
8295 ) -> Result<()> {
8296 self.push_to_selection_history();
8297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8298 let buffer = &display_map.buffer_snapshot;
8299 let mut selections = self.selections.all::<usize>(cx);
8300 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8301 let query = &select_prev_state.query;
8302 if !select_prev_state.done {
8303 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8304 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8305 let mut next_selected_range = None;
8306 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8307 let bytes_before_last_selection =
8308 buffer.reversed_bytes_in_range(0..last_selection.start);
8309 let bytes_after_first_selection =
8310 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8311 let query_matches = query
8312 .stream_find_iter(bytes_before_last_selection)
8313 .map(|result| (last_selection.start, result))
8314 .chain(
8315 query
8316 .stream_find_iter(bytes_after_first_selection)
8317 .map(|result| (buffer.len(), result)),
8318 );
8319 for (end_offset, query_match) in query_matches {
8320 let query_match = query_match.unwrap(); // can only fail due to I/O
8321 let offset_range =
8322 end_offset - query_match.end()..end_offset - query_match.start();
8323 let display_range = offset_range.start.to_display_point(&display_map)
8324 ..offset_range.end.to_display_point(&display_map);
8325
8326 if !select_prev_state.wordwise
8327 || (!movement::is_inside_word(&display_map, display_range.start)
8328 && !movement::is_inside_word(&display_map, display_range.end))
8329 {
8330 next_selected_range = Some(offset_range);
8331 break;
8332 }
8333 }
8334
8335 if let Some(next_selected_range) = next_selected_range {
8336 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8337 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8338 if action.replace_newest {
8339 s.delete(s.newest_anchor().id);
8340 }
8341 s.insert_range(next_selected_range);
8342 });
8343 } else {
8344 select_prev_state.done = true;
8345 }
8346 }
8347
8348 self.select_prev_state = Some(select_prev_state);
8349 } else {
8350 let mut only_carets = true;
8351 let mut same_text_selected = true;
8352 let mut selected_text = None;
8353
8354 let mut selections_iter = selections.iter().peekable();
8355 while let Some(selection) = selections_iter.next() {
8356 if selection.start != selection.end {
8357 only_carets = false;
8358 }
8359
8360 if same_text_selected {
8361 if selected_text.is_none() {
8362 selected_text =
8363 Some(buffer.text_for_range(selection.range()).collect::<String>());
8364 }
8365
8366 if let Some(next_selection) = selections_iter.peek() {
8367 if next_selection.range().len() == selection.range().len() {
8368 let next_selected_text = buffer
8369 .text_for_range(next_selection.range())
8370 .collect::<String>();
8371 if Some(next_selected_text) != selected_text {
8372 same_text_selected = false;
8373 selected_text = None;
8374 }
8375 } else {
8376 same_text_selected = false;
8377 selected_text = None;
8378 }
8379 }
8380 }
8381 }
8382
8383 if only_carets {
8384 for selection in &mut selections {
8385 let word_range = movement::surrounding_word(
8386 &display_map,
8387 selection.start.to_display_point(&display_map),
8388 );
8389 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8390 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8391 selection.goal = SelectionGoal::None;
8392 selection.reversed = false;
8393 }
8394 if selections.len() == 1 {
8395 let selection = selections
8396 .last()
8397 .expect("ensured that there's only one selection");
8398 let query = buffer
8399 .text_for_range(selection.start..selection.end)
8400 .collect::<String>();
8401 let is_empty = query.is_empty();
8402 let select_state = SelectNextState {
8403 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8404 wordwise: true,
8405 done: is_empty,
8406 };
8407 self.select_prev_state = Some(select_state);
8408 } else {
8409 self.select_prev_state = None;
8410 }
8411
8412 self.unfold_ranges(
8413 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8414 false,
8415 true,
8416 cx,
8417 );
8418 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8419 s.select(selections);
8420 });
8421 } else if let Some(selected_text) = selected_text {
8422 self.select_prev_state = Some(SelectNextState {
8423 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8424 wordwise: false,
8425 done: false,
8426 });
8427 self.select_previous(action, cx)?;
8428 }
8429 }
8430 Ok(())
8431 }
8432
8433 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8434 if self.read_only(cx) {
8435 return;
8436 }
8437 let text_layout_details = &self.text_layout_details(cx);
8438 self.transact(cx, |this, cx| {
8439 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8440 let mut edits = Vec::new();
8441 let mut selection_edit_ranges = Vec::new();
8442 let mut last_toggled_row = None;
8443 let snapshot = this.buffer.read(cx).read(cx);
8444 let empty_str: Arc<str> = Arc::default();
8445 let mut suffixes_inserted = Vec::new();
8446 let ignore_indent = action.ignore_indent;
8447
8448 fn comment_prefix_range(
8449 snapshot: &MultiBufferSnapshot,
8450 row: MultiBufferRow,
8451 comment_prefix: &str,
8452 comment_prefix_whitespace: &str,
8453 ignore_indent: bool,
8454 ) -> Range<Point> {
8455 let indent_size = if ignore_indent {
8456 0
8457 } else {
8458 snapshot.indent_size_for_line(row).len
8459 };
8460
8461 let start = Point::new(row.0, indent_size);
8462
8463 let mut line_bytes = snapshot
8464 .bytes_in_range(start..snapshot.max_point())
8465 .flatten()
8466 .copied();
8467
8468 // If this line currently begins with the line comment prefix, then record
8469 // the range containing the prefix.
8470 if line_bytes
8471 .by_ref()
8472 .take(comment_prefix.len())
8473 .eq(comment_prefix.bytes())
8474 {
8475 // Include any whitespace that matches the comment prefix.
8476 let matching_whitespace_len = line_bytes
8477 .zip(comment_prefix_whitespace.bytes())
8478 .take_while(|(a, b)| a == b)
8479 .count() as u32;
8480 let end = Point::new(
8481 start.row,
8482 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8483 );
8484 start..end
8485 } else {
8486 start..start
8487 }
8488 }
8489
8490 fn comment_suffix_range(
8491 snapshot: &MultiBufferSnapshot,
8492 row: MultiBufferRow,
8493 comment_suffix: &str,
8494 comment_suffix_has_leading_space: bool,
8495 ) -> Range<Point> {
8496 let end = Point::new(row.0, snapshot.line_len(row));
8497 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8498
8499 let mut line_end_bytes = snapshot
8500 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8501 .flatten()
8502 .copied();
8503
8504 let leading_space_len = if suffix_start_column > 0
8505 && line_end_bytes.next() == Some(b' ')
8506 && comment_suffix_has_leading_space
8507 {
8508 1
8509 } else {
8510 0
8511 };
8512
8513 // If this line currently begins with the line comment prefix, then record
8514 // the range containing the prefix.
8515 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8516 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8517 start..end
8518 } else {
8519 end..end
8520 }
8521 }
8522
8523 // TODO: Handle selections that cross excerpts
8524 for selection in &mut selections {
8525 let start_column = snapshot
8526 .indent_size_for_line(MultiBufferRow(selection.start.row))
8527 .len;
8528 let language = if let Some(language) =
8529 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8530 {
8531 language
8532 } else {
8533 continue;
8534 };
8535
8536 selection_edit_ranges.clear();
8537
8538 // If multiple selections contain a given row, avoid processing that
8539 // row more than once.
8540 let mut start_row = MultiBufferRow(selection.start.row);
8541 if last_toggled_row == Some(start_row) {
8542 start_row = start_row.next_row();
8543 }
8544 let end_row =
8545 if selection.end.row > selection.start.row && selection.end.column == 0 {
8546 MultiBufferRow(selection.end.row - 1)
8547 } else {
8548 MultiBufferRow(selection.end.row)
8549 };
8550 last_toggled_row = Some(end_row);
8551
8552 if start_row > end_row {
8553 continue;
8554 }
8555
8556 // If the language has line comments, toggle those.
8557 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8558
8559 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8560 if ignore_indent {
8561 full_comment_prefixes = full_comment_prefixes
8562 .into_iter()
8563 .map(|s| Arc::from(s.trim_end()))
8564 .collect();
8565 }
8566
8567 if !full_comment_prefixes.is_empty() {
8568 let first_prefix = full_comment_prefixes
8569 .first()
8570 .expect("prefixes is non-empty");
8571 let prefix_trimmed_lengths = full_comment_prefixes
8572 .iter()
8573 .map(|p| p.trim_end_matches(' ').len())
8574 .collect::<SmallVec<[usize; 4]>>();
8575
8576 let mut all_selection_lines_are_comments = true;
8577
8578 for row in start_row.0..=end_row.0 {
8579 let row = MultiBufferRow(row);
8580 if start_row < end_row && snapshot.is_line_blank(row) {
8581 continue;
8582 }
8583
8584 let prefix_range = full_comment_prefixes
8585 .iter()
8586 .zip(prefix_trimmed_lengths.iter().copied())
8587 .map(|(prefix, trimmed_prefix_len)| {
8588 comment_prefix_range(
8589 snapshot.deref(),
8590 row,
8591 &prefix[..trimmed_prefix_len],
8592 &prefix[trimmed_prefix_len..],
8593 ignore_indent,
8594 )
8595 })
8596 .max_by_key(|range| range.end.column - range.start.column)
8597 .expect("prefixes is non-empty");
8598
8599 if prefix_range.is_empty() {
8600 all_selection_lines_are_comments = false;
8601 }
8602
8603 selection_edit_ranges.push(prefix_range);
8604 }
8605
8606 if all_selection_lines_are_comments {
8607 edits.extend(
8608 selection_edit_ranges
8609 .iter()
8610 .cloned()
8611 .map(|range| (range, empty_str.clone())),
8612 );
8613 } else {
8614 let min_column = selection_edit_ranges
8615 .iter()
8616 .map(|range| range.start.column)
8617 .min()
8618 .unwrap_or(0);
8619 edits.extend(selection_edit_ranges.iter().map(|range| {
8620 let position = Point::new(range.start.row, min_column);
8621 (position..position, first_prefix.clone())
8622 }));
8623 }
8624 } else if let Some((full_comment_prefix, comment_suffix)) =
8625 language.block_comment_delimiters()
8626 {
8627 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8628 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8629 let prefix_range = comment_prefix_range(
8630 snapshot.deref(),
8631 start_row,
8632 comment_prefix,
8633 comment_prefix_whitespace,
8634 ignore_indent,
8635 );
8636 let suffix_range = comment_suffix_range(
8637 snapshot.deref(),
8638 end_row,
8639 comment_suffix.trim_start_matches(' '),
8640 comment_suffix.starts_with(' '),
8641 );
8642
8643 if prefix_range.is_empty() || suffix_range.is_empty() {
8644 edits.push((
8645 prefix_range.start..prefix_range.start,
8646 full_comment_prefix.clone(),
8647 ));
8648 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8649 suffixes_inserted.push((end_row, comment_suffix.len()));
8650 } else {
8651 edits.push((prefix_range, empty_str.clone()));
8652 edits.push((suffix_range, empty_str.clone()));
8653 }
8654 } else {
8655 continue;
8656 }
8657 }
8658
8659 drop(snapshot);
8660 this.buffer.update(cx, |buffer, cx| {
8661 buffer.edit(edits, None, cx);
8662 });
8663
8664 // Adjust selections so that they end before any comment suffixes that
8665 // were inserted.
8666 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8667 let mut selections = this.selections.all::<Point>(cx);
8668 let snapshot = this.buffer.read(cx).read(cx);
8669 for selection in &mut selections {
8670 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8671 match row.cmp(&MultiBufferRow(selection.end.row)) {
8672 Ordering::Less => {
8673 suffixes_inserted.next();
8674 continue;
8675 }
8676 Ordering::Greater => break,
8677 Ordering::Equal => {
8678 if selection.end.column == snapshot.line_len(row) {
8679 if selection.is_empty() {
8680 selection.start.column -= suffix_len as u32;
8681 }
8682 selection.end.column -= suffix_len as u32;
8683 }
8684 break;
8685 }
8686 }
8687 }
8688 }
8689
8690 drop(snapshot);
8691 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8692
8693 let selections = this.selections.all::<Point>(cx);
8694 let selections_on_single_row = selections.windows(2).all(|selections| {
8695 selections[0].start.row == selections[1].start.row
8696 && selections[0].end.row == selections[1].end.row
8697 && selections[0].start.row == selections[0].end.row
8698 });
8699 let selections_selecting = selections
8700 .iter()
8701 .any(|selection| selection.start != selection.end);
8702 let advance_downwards = action.advance_downwards
8703 && selections_on_single_row
8704 && !selections_selecting
8705 && !matches!(this.mode, EditorMode::SingleLine { .. });
8706
8707 if advance_downwards {
8708 let snapshot = this.buffer.read(cx).snapshot(cx);
8709
8710 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8711 s.move_cursors_with(|display_snapshot, display_point, _| {
8712 let mut point = display_point.to_point(display_snapshot);
8713 point.row += 1;
8714 point = snapshot.clip_point(point, Bias::Left);
8715 let display_point = point.to_display_point(display_snapshot);
8716 let goal = SelectionGoal::HorizontalPosition(
8717 display_snapshot
8718 .x_for_display_point(display_point, text_layout_details)
8719 .into(),
8720 );
8721 (display_point, goal)
8722 })
8723 });
8724 }
8725 });
8726 }
8727
8728 pub fn select_enclosing_symbol(
8729 &mut self,
8730 _: &SelectEnclosingSymbol,
8731 cx: &mut ViewContext<Self>,
8732 ) {
8733 let buffer = self.buffer.read(cx).snapshot(cx);
8734 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8735
8736 fn update_selection(
8737 selection: &Selection<usize>,
8738 buffer_snap: &MultiBufferSnapshot,
8739 ) -> Option<Selection<usize>> {
8740 let cursor = selection.head();
8741 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8742 for symbol in symbols.iter().rev() {
8743 let start = symbol.range.start.to_offset(buffer_snap);
8744 let end = symbol.range.end.to_offset(buffer_snap);
8745 let new_range = start..end;
8746 if start < selection.start || end > selection.end {
8747 return Some(Selection {
8748 id: selection.id,
8749 start: new_range.start,
8750 end: new_range.end,
8751 goal: SelectionGoal::None,
8752 reversed: selection.reversed,
8753 });
8754 }
8755 }
8756 None
8757 }
8758
8759 let mut selected_larger_symbol = false;
8760 let new_selections = old_selections
8761 .iter()
8762 .map(|selection| match update_selection(selection, &buffer) {
8763 Some(new_selection) => {
8764 if new_selection.range() != selection.range() {
8765 selected_larger_symbol = true;
8766 }
8767 new_selection
8768 }
8769 None => selection.clone(),
8770 })
8771 .collect::<Vec<_>>();
8772
8773 if selected_larger_symbol {
8774 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8775 s.select(new_selections);
8776 });
8777 }
8778 }
8779
8780 pub fn select_larger_syntax_node(
8781 &mut self,
8782 _: &SelectLargerSyntaxNode,
8783 cx: &mut ViewContext<Self>,
8784 ) {
8785 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8786 let buffer = self.buffer.read(cx).snapshot(cx);
8787 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8788
8789 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8790 let mut selected_larger_node = false;
8791 let new_selections = old_selections
8792 .iter()
8793 .map(|selection| {
8794 let old_range = selection.start..selection.end;
8795 let mut new_range = old_range.clone();
8796 while let Some(containing_range) =
8797 buffer.range_for_syntax_ancestor(new_range.clone())
8798 {
8799 new_range = containing_range;
8800 if !display_map.intersects_fold(new_range.start)
8801 && !display_map.intersects_fold(new_range.end)
8802 {
8803 break;
8804 }
8805 }
8806
8807 selected_larger_node |= new_range != old_range;
8808 Selection {
8809 id: selection.id,
8810 start: new_range.start,
8811 end: new_range.end,
8812 goal: SelectionGoal::None,
8813 reversed: selection.reversed,
8814 }
8815 })
8816 .collect::<Vec<_>>();
8817
8818 if selected_larger_node {
8819 stack.push(old_selections);
8820 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8821 s.select(new_selections);
8822 });
8823 }
8824 self.select_larger_syntax_node_stack = stack;
8825 }
8826
8827 pub fn select_smaller_syntax_node(
8828 &mut self,
8829 _: &SelectSmallerSyntaxNode,
8830 cx: &mut ViewContext<Self>,
8831 ) {
8832 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8833 if let Some(selections) = stack.pop() {
8834 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8835 s.select(selections.to_vec());
8836 });
8837 }
8838 self.select_larger_syntax_node_stack = stack;
8839 }
8840
8841 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8842 if !EditorSettings::get_global(cx).gutter.runnables {
8843 self.clear_tasks();
8844 return Task::ready(());
8845 }
8846 let project = self.project.as_ref().map(Model::downgrade);
8847 cx.spawn(|this, mut cx| async move {
8848 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8849 let Some(project) = project.and_then(|p| p.upgrade()) else {
8850 return;
8851 };
8852 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8853 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8854 }) else {
8855 return;
8856 };
8857
8858 let hide_runnables = project
8859 .update(&mut cx, |project, cx| {
8860 // Do not display any test indicators in non-dev server remote projects.
8861 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8862 })
8863 .unwrap_or(true);
8864 if hide_runnables {
8865 return;
8866 }
8867 let new_rows =
8868 cx.background_executor()
8869 .spawn({
8870 let snapshot = display_snapshot.clone();
8871 async move {
8872 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8873 }
8874 })
8875 .await;
8876 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8877
8878 this.update(&mut cx, |this, _| {
8879 this.clear_tasks();
8880 for (key, value) in rows {
8881 this.insert_tasks(key, value);
8882 }
8883 })
8884 .ok();
8885 })
8886 }
8887 fn fetch_runnable_ranges(
8888 snapshot: &DisplaySnapshot,
8889 range: Range<Anchor>,
8890 ) -> Vec<language::RunnableRange> {
8891 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8892 }
8893
8894 fn runnable_rows(
8895 project: Model<Project>,
8896 snapshot: DisplaySnapshot,
8897 runnable_ranges: Vec<RunnableRange>,
8898 mut cx: AsyncWindowContext,
8899 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8900 runnable_ranges
8901 .into_iter()
8902 .filter_map(|mut runnable| {
8903 let tasks = cx
8904 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8905 .ok()?;
8906 if tasks.is_empty() {
8907 return None;
8908 }
8909
8910 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8911
8912 let row = snapshot
8913 .buffer_snapshot
8914 .buffer_line_for_row(MultiBufferRow(point.row))?
8915 .1
8916 .start
8917 .row;
8918
8919 let context_range =
8920 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8921 Some((
8922 (runnable.buffer_id, row),
8923 RunnableTasks {
8924 templates: tasks,
8925 offset: MultiBufferOffset(runnable.run_range.start),
8926 context_range,
8927 column: point.column,
8928 extra_variables: runnable.extra_captures,
8929 },
8930 ))
8931 })
8932 .collect()
8933 }
8934
8935 fn templates_with_tags(
8936 project: &Model<Project>,
8937 runnable: &mut Runnable,
8938 cx: &WindowContext<'_>,
8939 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8940 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8941 let (worktree_id, file) = project
8942 .buffer_for_id(runnable.buffer, cx)
8943 .and_then(|buffer| buffer.read(cx).file())
8944 .map(|file| (file.worktree_id(cx), file.clone()))
8945 .unzip();
8946
8947 (
8948 project.task_store().read(cx).task_inventory().cloned(),
8949 worktree_id,
8950 file,
8951 )
8952 });
8953
8954 let tags = mem::take(&mut runnable.tags);
8955 let mut tags: Vec<_> = tags
8956 .into_iter()
8957 .flat_map(|tag| {
8958 let tag = tag.0.clone();
8959 inventory
8960 .as_ref()
8961 .into_iter()
8962 .flat_map(|inventory| {
8963 inventory.read(cx).list_tasks(
8964 file.clone(),
8965 Some(runnable.language.clone()),
8966 worktree_id,
8967 cx,
8968 )
8969 })
8970 .filter(move |(_, template)| {
8971 template.tags.iter().any(|source_tag| source_tag == &tag)
8972 })
8973 })
8974 .sorted_by_key(|(kind, _)| kind.to_owned())
8975 .collect();
8976 if let Some((leading_tag_source, _)) = tags.first() {
8977 // Strongest source wins; if we have worktree tag binding, prefer that to
8978 // global and language bindings;
8979 // if we have a global binding, prefer that to language binding.
8980 let first_mismatch = tags
8981 .iter()
8982 .position(|(tag_source, _)| tag_source != leading_tag_source);
8983 if let Some(index) = first_mismatch {
8984 tags.truncate(index);
8985 }
8986 }
8987
8988 tags
8989 }
8990
8991 pub fn move_to_enclosing_bracket(
8992 &mut self,
8993 _: &MoveToEnclosingBracket,
8994 cx: &mut ViewContext<Self>,
8995 ) {
8996 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8997 s.move_offsets_with(|snapshot, selection| {
8998 let Some(enclosing_bracket_ranges) =
8999 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9000 else {
9001 return;
9002 };
9003
9004 let mut best_length = usize::MAX;
9005 let mut best_inside = false;
9006 let mut best_in_bracket_range = false;
9007 let mut best_destination = None;
9008 for (open, close) in enclosing_bracket_ranges {
9009 let close = close.to_inclusive();
9010 let length = close.end() - open.start;
9011 let inside = selection.start >= open.end && selection.end <= *close.start();
9012 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9013 || close.contains(&selection.head());
9014
9015 // If best is next to a bracket and current isn't, skip
9016 if !in_bracket_range && best_in_bracket_range {
9017 continue;
9018 }
9019
9020 // Prefer smaller lengths unless best is inside and current isn't
9021 if length > best_length && (best_inside || !inside) {
9022 continue;
9023 }
9024
9025 best_length = length;
9026 best_inside = inside;
9027 best_in_bracket_range = in_bracket_range;
9028 best_destination = Some(
9029 if close.contains(&selection.start) && close.contains(&selection.end) {
9030 if inside {
9031 open.end
9032 } else {
9033 open.start
9034 }
9035 } else if inside {
9036 *close.start()
9037 } else {
9038 *close.end()
9039 },
9040 );
9041 }
9042
9043 if let Some(destination) = best_destination {
9044 selection.collapse_to(destination, SelectionGoal::None);
9045 }
9046 })
9047 });
9048 }
9049
9050 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9051 self.end_selection(cx);
9052 self.selection_history.mode = SelectionHistoryMode::Undoing;
9053 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9054 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9055 self.select_next_state = entry.select_next_state;
9056 self.select_prev_state = entry.select_prev_state;
9057 self.add_selections_state = entry.add_selections_state;
9058 self.request_autoscroll(Autoscroll::newest(), cx);
9059 }
9060 self.selection_history.mode = SelectionHistoryMode::Normal;
9061 }
9062
9063 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9064 self.end_selection(cx);
9065 self.selection_history.mode = SelectionHistoryMode::Redoing;
9066 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9067 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9068 self.select_next_state = entry.select_next_state;
9069 self.select_prev_state = entry.select_prev_state;
9070 self.add_selections_state = entry.add_selections_state;
9071 self.request_autoscroll(Autoscroll::newest(), cx);
9072 }
9073 self.selection_history.mode = SelectionHistoryMode::Normal;
9074 }
9075
9076 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9077 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9078 }
9079
9080 pub fn expand_excerpts_down(
9081 &mut self,
9082 action: &ExpandExcerptsDown,
9083 cx: &mut ViewContext<Self>,
9084 ) {
9085 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9086 }
9087
9088 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9089 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9090 }
9091
9092 pub fn expand_excerpts_for_direction(
9093 &mut self,
9094 lines: u32,
9095 direction: ExpandExcerptDirection,
9096 cx: &mut ViewContext<Self>,
9097 ) {
9098 let selections = self.selections.disjoint_anchors();
9099
9100 let lines = if lines == 0 {
9101 EditorSettings::get_global(cx).expand_excerpt_lines
9102 } else {
9103 lines
9104 };
9105
9106 self.buffer.update(cx, |buffer, cx| {
9107 buffer.expand_excerpts(
9108 selections
9109 .iter()
9110 .map(|selection| selection.head().excerpt_id)
9111 .dedup(),
9112 lines,
9113 direction,
9114 cx,
9115 )
9116 })
9117 }
9118
9119 pub fn expand_excerpt(
9120 &mut self,
9121 excerpt: ExcerptId,
9122 direction: ExpandExcerptDirection,
9123 cx: &mut ViewContext<Self>,
9124 ) {
9125 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9126 self.buffer.update(cx, |buffer, cx| {
9127 buffer.expand_excerpts([excerpt], lines, direction, cx)
9128 })
9129 }
9130
9131 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9132 self.go_to_diagnostic_impl(Direction::Next, cx)
9133 }
9134
9135 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9136 self.go_to_diagnostic_impl(Direction::Prev, cx)
9137 }
9138
9139 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9140 let buffer = self.buffer.read(cx).snapshot(cx);
9141 let selection = self.selections.newest::<usize>(cx);
9142
9143 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9144 if direction == Direction::Next {
9145 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9146 let (group_id, jump_to) = popover.activation_info();
9147 if self.activate_diagnostics(group_id, cx) {
9148 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9149 let mut new_selection = s.newest_anchor().clone();
9150 new_selection.collapse_to(jump_to, SelectionGoal::None);
9151 s.select_anchors(vec![new_selection.clone()]);
9152 });
9153 }
9154 return;
9155 }
9156 }
9157
9158 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9159 active_diagnostics
9160 .primary_range
9161 .to_offset(&buffer)
9162 .to_inclusive()
9163 });
9164 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9165 if active_primary_range.contains(&selection.head()) {
9166 *active_primary_range.start()
9167 } else {
9168 selection.head()
9169 }
9170 } else {
9171 selection.head()
9172 };
9173 let snapshot = self.snapshot(cx);
9174 loop {
9175 let diagnostics = if direction == Direction::Prev {
9176 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9177 } else {
9178 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9179 }
9180 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9181 let group = diagnostics
9182 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9183 // be sorted in a stable way
9184 // skip until we are at current active diagnostic, if it exists
9185 .skip_while(|entry| {
9186 (match direction {
9187 Direction::Prev => entry.range.start >= search_start,
9188 Direction::Next => entry.range.start <= search_start,
9189 }) && self
9190 .active_diagnostics
9191 .as_ref()
9192 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9193 })
9194 .find_map(|entry| {
9195 if entry.diagnostic.is_primary
9196 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9197 && !entry.range.is_empty()
9198 // if we match with the active diagnostic, skip it
9199 && Some(entry.diagnostic.group_id)
9200 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9201 {
9202 Some((entry.range, entry.diagnostic.group_id))
9203 } else {
9204 None
9205 }
9206 });
9207
9208 if let Some((primary_range, group_id)) = group {
9209 if self.activate_diagnostics(group_id, cx) {
9210 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9211 s.select(vec![Selection {
9212 id: selection.id,
9213 start: primary_range.start,
9214 end: primary_range.start,
9215 reversed: false,
9216 goal: SelectionGoal::None,
9217 }]);
9218 });
9219 }
9220 break;
9221 } else {
9222 // Cycle around to the start of the buffer, potentially moving back to the start of
9223 // the currently active diagnostic.
9224 active_primary_range.take();
9225 if direction == Direction::Prev {
9226 if search_start == buffer.len() {
9227 break;
9228 } else {
9229 search_start = buffer.len();
9230 }
9231 } else if search_start == 0 {
9232 break;
9233 } else {
9234 search_start = 0;
9235 }
9236 }
9237 }
9238 }
9239
9240 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9241 let snapshot = self.snapshot(cx);
9242 let selection = self.selections.newest::<Point>(cx);
9243 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9244 }
9245
9246 fn go_to_hunk_after_position(
9247 &mut self,
9248 snapshot: &EditorSnapshot,
9249 position: Point,
9250 cx: &mut ViewContext<'_, Editor>,
9251 ) -> Option<MultiBufferDiffHunk> {
9252 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9253 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9254 snapshot,
9255 position,
9256 ix > 0,
9257 snapshot.diff_map.diff_hunks_in_range(
9258 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9259 &snapshot.buffer_snapshot,
9260 ),
9261 cx,
9262 ) {
9263 return Some(hunk);
9264 }
9265 }
9266 None
9267 }
9268
9269 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9270 let snapshot = self.snapshot(cx);
9271 let selection = self.selections.newest::<Point>(cx);
9272 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9273 }
9274
9275 fn go_to_hunk_before_position(
9276 &mut self,
9277 snapshot: &EditorSnapshot,
9278 position: Point,
9279 cx: &mut ViewContext<'_, Editor>,
9280 ) -> Option<MultiBufferDiffHunk> {
9281 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9282 .into_iter()
9283 .enumerate()
9284 {
9285 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9286 snapshot,
9287 position,
9288 ix > 0,
9289 snapshot
9290 .diff_map
9291 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9292 cx,
9293 ) {
9294 return Some(hunk);
9295 }
9296 }
9297 None
9298 }
9299
9300 fn go_to_next_hunk_in_direction(
9301 &mut self,
9302 snapshot: &DisplaySnapshot,
9303 initial_point: Point,
9304 is_wrapped: bool,
9305 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9306 cx: &mut ViewContext<Editor>,
9307 ) -> Option<MultiBufferDiffHunk> {
9308 let display_point = initial_point.to_display_point(snapshot);
9309 let mut hunks = hunks
9310 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9311 .filter(|(display_hunk, _)| {
9312 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9313 })
9314 .dedup();
9315
9316 if let Some((display_hunk, hunk)) = hunks.next() {
9317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9318 let row = display_hunk.start_display_row();
9319 let point = DisplayPoint::new(row, 0);
9320 s.select_display_ranges([point..point]);
9321 });
9322
9323 Some(hunk)
9324 } else {
9325 None
9326 }
9327 }
9328
9329 pub fn go_to_definition(
9330 &mut self,
9331 _: &GoToDefinition,
9332 cx: &mut ViewContext<Self>,
9333 ) -> Task<Result<Navigated>> {
9334 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9335 cx.spawn(|editor, mut cx| async move {
9336 if definition.await? == Navigated::Yes {
9337 return Ok(Navigated::Yes);
9338 }
9339 match editor.update(&mut cx, |editor, cx| {
9340 editor.find_all_references(&FindAllReferences, cx)
9341 })? {
9342 Some(references) => references.await,
9343 None => Ok(Navigated::No),
9344 }
9345 })
9346 }
9347
9348 pub fn go_to_declaration(
9349 &mut self,
9350 _: &GoToDeclaration,
9351 cx: &mut ViewContext<Self>,
9352 ) -> Task<Result<Navigated>> {
9353 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9354 }
9355
9356 pub fn go_to_declaration_split(
9357 &mut self,
9358 _: &GoToDeclaration,
9359 cx: &mut ViewContext<Self>,
9360 ) -> Task<Result<Navigated>> {
9361 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9362 }
9363
9364 pub fn go_to_implementation(
9365 &mut self,
9366 _: &GoToImplementation,
9367 cx: &mut ViewContext<Self>,
9368 ) -> Task<Result<Navigated>> {
9369 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9370 }
9371
9372 pub fn go_to_implementation_split(
9373 &mut self,
9374 _: &GoToImplementationSplit,
9375 cx: &mut ViewContext<Self>,
9376 ) -> Task<Result<Navigated>> {
9377 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9378 }
9379
9380 pub fn go_to_type_definition(
9381 &mut self,
9382 _: &GoToTypeDefinition,
9383 cx: &mut ViewContext<Self>,
9384 ) -> Task<Result<Navigated>> {
9385 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9386 }
9387
9388 pub fn go_to_definition_split(
9389 &mut self,
9390 _: &GoToDefinitionSplit,
9391 cx: &mut ViewContext<Self>,
9392 ) -> Task<Result<Navigated>> {
9393 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9394 }
9395
9396 pub fn go_to_type_definition_split(
9397 &mut self,
9398 _: &GoToTypeDefinitionSplit,
9399 cx: &mut ViewContext<Self>,
9400 ) -> Task<Result<Navigated>> {
9401 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9402 }
9403
9404 fn go_to_definition_of_kind(
9405 &mut self,
9406 kind: GotoDefinitionKind,
9407 split: bool,
9408 cx: &mut ViewContext<Self>,
9409 ) -> Task<Result<Navigated>> {
9410 let Some(provider) = self.semantics_provider.clone() else {
9411 return Task::ready(Ok(Navigated::No));
9412 };
9413 let head = self.selections.newest::<usize>(cx).head();
9414 let buffer = self.buffer.read(cx);
9415 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9416 text_anchor
9417 } else {
9418 return Task::ready(Ok(Navigated::No));
9419 };
9420
9421 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9422 return Task::ready(Ok(Navigated::No));
9423 };
9424
9425 cx.spawn(|editor, mut cx| async move {
9426 let definitions = definitions.await?;
9427 let navigated = editor
9428 .update(&mut cx, |editor, cx| {
9429 editor.navigate_to_hover_links(
9430 Some(kind),
9431 definitions
9432 .into_iter()
9433 .filter(|location| {
9434 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9435 })
9436 .map(HoverLink::Text)
9437 .collect::<Vec<_>>(),
9438 split,
9439 cx,
9440 )
9441 })?
9442 .await?;
9443 anyhow::Ok(navigated)
9444 })
9445 }
9446
9447 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9448 let selection = self.selections.newest_anchor();
9449 let head = selection.head();
9450 let tail = selection.tail();
9451
9452 let Some((buffer, start_position)) =
9453 self.buffer.read(cx).text_anchor_for_position(head, cx)
9454 else {
9455 return;
9456 };
9457
9458 let end_position = if head != tail {
9459 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9460 return;
9461 };
9462 Some(pos)
9463 } else {
9464 None
9465 };
9466
9467 let url_finder = cx.spawn(|editor, mut cx| async move {
9468 let url = if let Some(end_pos) = end_position {
9469 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9470 } else {
9471 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9472 };
9473
9474 if let Some(url) = url {
9475 editor.update(&mut cx, |_, cx| {
9476 cx.open_url(&url);
9477 })
9478 } else {
9479 Ok(())
9480 }
9481 });
9482
9483 url_finder.detach();
9484 }
9485
9486 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9487 let Some(workspace) = self.workspace() else {
9488 return;
9489 };
9490
9491 let position = self.selections.newest_anchor().head();
9492
9493 let Some((buffer, buffer_position)) =
9494 self.buffer.read(cx).text_anchor_for_position(position, cx)
9495 else {
9496 return;
9497 };
9498
9499 let project = self.project.clone();
9500
9501 cx.spawn(|_, mut cx| async move {
9502 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9503
9504 if let Some((_, path)) = result {
9505 workspace
9506 .update(&mut cx, |workspace, cx| {
9507 workspace.open_resolved_path(path, cx)
9508 })?
9509 .await?;
9510 }
9511 anyhow::Ok(())
9512 })
9513 .detach();
9514 }
9515
9516 pub(crate) fn navigate_to_hover_links(
9517 &mut self,
9518 kind: Option<GotoDefinitionKind>,
9519 mut definitions: Vec<HoverLink>,
9520 split: bool,
9521 cx: &mut ViewContext<Editor>,
9522 ) -> Task<Result<Navigated>> {
9523 // If there is one definition, just open it directly
9524 if definitions.len() == 1 {
9525 let definition = definitions.pop().unwrap();
9526
9527 enum TargetTaskResult {
9528 Location(Option<Location>),
9529 AlreadyNavigated,
9530 }
9531
9532 let target_task = match definition {
9533 HoverLink::Text(link) => {
9534 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9535 }
9536 HoverLink::InlayHint(lsp_location, server_id) => {
9537 let computation = self.compute_target_location(lsp_location, server_id, cx);
9538 cx.background_executor().spawn(async move {
9539 let location = computation.await?;
9540 Ok(TargetTaskResult::Location(location))
9541 })
9542 }
9543 HoverLink::Url(url) => {
9544 cx.open_url(&url);
9545 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9546 }
9547 HoverLink::File(path) => {
9548 if let Some(workspace) = self.workspace() {
9549 cx.spawn(|_, mut cx| async move {
9550 workspace
9551 .update(&mut cx, |workspace, cx| {
9552 workspace.open_resolved_path(path, cx)
9553 })?
9554 .await
9555 .map(|_| TargetTaskResult::AlreadyNavigated)
9556 })
9557 } else {
9558 Task::ready(Ok(TargetTaskResult::Location(None)))
9559 }
9560 }
9561 };
9562 cx.spawn(|editor, mut cx| async move {
9563 let target = match target_task.await.context("target resolution task")? {
9564 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9565 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9566 TargetTaskResult::Location(Some(target)) => target,
9567 };
9568
9569 editor.update(&mut cx, |editor, cx| {
9570 let Some(workspace) = editor.workspace() else {
9571 return Navigated::No;
9572 };
9573 let pane = workspace.read(cx).active_pane().clone();
9574
9575 let range = target.range.to_offset(target.buffer.read(cx));
9576 let range = editor.range_for_match(&range);
9577
9578 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9579 let buffer = target.buffer.read(cx);
9580 let range = check_multiline_range(buffer, range);
9581 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9582 s.select_ranges([range]);
9583 });
9584 } else {
9585 cx.window_context().defer(move |cx| {
9586 let target_editor: View<Self> =
9587 workspace.update(cx, |workspace, cx| {
9588 let pane = if split {
9589 workspace.adjacent_pane(cx)
9590 } else {
9591 workspace.active_pane().clone()
9592 };
9593
9594 workspace.open_project_item(
9595 pane,
9596 target.buffer.clone(),
9597 true,
9598 true,
9599 cx,
9600 )
9601 });
9602 target_editor.update(cx, |target_editor, cx| {
9603 // When selecting a definition in a different buffer, disable the nav history
9604 // to avoid creating a history entry at the previous cursor location.
9605 pane.update(cx, |pane, _| pane.disable_history());
9606 let buffer = target.buffer.read(cx);
9607 let range = check_multiline_range(buffer, range);
9608 target_editor.change_selections(
9609 Some(Autoscroll::focused()),
9610 cx,
9611 |s| {
9612 s.select_ranges([range]);
9613 },
9614 );
9615 pane.update(cx, |pane, _| pane.enable_history());
9616 });
9617 });
9618 }
9619 Navigated::Yes
9620 })
9621 })
9622 } else if !definitions.is_empty() {
9623 cx.spawn(|editor, mut cx| async move {
9624 let (title, location_tasks, workspace) = editor
9625 .update(&mut cx, |editor, cx| {
9626 let tab_kind = match kind {
9627 Some(GotoDefinitionKind::Implementation) => "Implementations",
9628 _ => "Definitions",
9629 };
9630 let title = definitions
9631 .iter()
9632 .find_map(|definition| match definition {
9633 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9634 let buffer = origin.buffer.read(cx);
9635 format!(
9636 "{} for {}",
9637 tab_kind,
9638 buffer
9639 .text_for_range(origin.range.clone())
9640 .collect::<String>()
9641 )
9642 }),
9643 HoverLink::InlayHint(_, _) => None,
9644 HoverLink::Url(_) => None,
9645 HoverLink::File(_) => None,
9646 })
9647 .unwrap_or(tab_kind.to_string());
9648 let location_tasks = definitions
9649 .into_iter()
9650 .map(|definition| match definition {
9651 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9652 HoverLink::InlayHint(lsp_location, server_id) => {
9653 editor.compute_target_location(lsp_location, server_id, cx)
9654 }
9655 HoverLink::Url(_) => Task::ready(Ok(None)),
9656 HoverLink::File(_) => Task::ready(Ok(None)),
9657 })
9658 .collect::<Vec<_>>();
9659 (title, location_tasks, editor.workspace().clone())
9660 })
9661 .context("location tasks preparation")?;
9662
9663 let locations = future::join_all(location_tasks)
9664 .await
9665 .into_iter()
9666 .filter_map(|location| location.transpose())
9667 .collect::<Result<_>>()
9668 .context("location tasks")?;
9669
9670 let Some(workspace) = workspace else {
9671 return Ok(Navigated::No);
9672 };
9673 let opened = workspace
9674 .update(&mut cx, |workspace, cx| {
9675 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9676 })
9677 .ok();
9678
9679 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9680 })
9681 } else {
9682 Task::ready(Ok(Navigated::No))
9683 }
9684 }
9685
9686 fn compute_target_location(
9687 &self,
9688 lsp_location: lsp::Location,
9689 server_id: LanguageServerId,
9690 cx: &mut ViewContext<Self>,
9691 ) -> Task<anyhow::Result<Option<Location>>> {
9692 let Some(project) = self.project.clone() else {
9693 return Task::ready(Ok(None));
9694 };
9695
9696 cx.spawn(move |editor, mut cx| async move {
9697 let location_task = editor.update(&mut cx, |_, cx| {
9698 project.update(cx, |project, cx| {
9699 let language_server_name = project
9700 .language_server_statuses(cx)
9701 .find(|(id, _)| server_id == *id)
9702 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9703 language_server_name.map(|language_server_name| {
9704 project.open_local_buffer_via_lsp(
9705 lsp_location.uri.clone(),
9706 server_id,
9707 language_server_name,
9708 cx,
9709 )
9710 })
9711 })
9712 })?;
9713 let location = match location_task {
9714 Some(task) => Some({
9715 let target_buffer_handle = task.await.context("open local buffer")?;
9716 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9717 let target_start = target_buffer
9718 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9719 let target_end = target_buffer
9720 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9721 target_buffer.anchor_after(target_start)
9722 ..target_buffer.anchor_before(target_end)
9723 })?;
9724 Location {
9725 buffer: target_buffer_handle,
9726 range,
9727 }
9728 }),
9729 None => None,
9730 };
9731 Ok(location)
9732 })
9733 }
9734
9735 pub fn find_all_references(
9736 &mut self,
9737 _: &FindAllReferences,
9738 cx: &mut ViewContext<Self>,
9739 ) -> Option<Task<Result<Navigated>>> {
9740 let selection = self.selections.newest::<usize>(cx);
9741 let multi_buffer = self.buffer.read(cx);
9742 let head = selection.head();
9743
9744 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9745 let head_anchor = multi_buffer_snapshot.anchor_at(
9746 head,
9747 if head < selection.tail() {
9748 Bias::Right
9749 } else {
9750 Bias::Left
9751 },
9752 );
9753
9754 match self
9755 .find_all_references_task_sources
9756 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9757 {
9758 Ok(_) => {
9759 log::info!(
9760 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9761 );
9762 return None;
9763 }
9764 Err(i) => {
9765 self.find_all_references_task_sources.insert(i, head_anchor);
9766 }
9767 }
9768
9769 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9770 let workspace = self.workspace()?;
9771 let project = workspace.read(cx).project().clone();
9772 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9773 Some(cx.spawn(|editor, mut cx| async move {
9774 let _cleanup = defer({
9775 let mut cx = cx.clone();
9776 move || {
9777 let _ = editor.update(&mut cx, |editor, _| {
9778 if let Ok(i) =
9779 editor
9780 .find_all_references_task_sources
9781 .binary_search_by(|anchor| {
9782 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9783 })
9784 {
9785 editor.find_all_references_task_sources.remove(i);
9786 }
9787 });
9788 }
9789 });
9790
9791 let locations = references.await?;
9792 if locations.is_empty() {
9793 return anyhow::Ok(Navigated::No);
9794 }
9795
9796 workspace.update(&mut cx, |workspace, cx| {
9797 let title = locations
9798 .first()
9799 .as_ref()
9800 .map(|location| {
9801 let buffer = location.buffer.read(cx);
9802 format!(
9803 "References to `{}`",
9804 buffer
9805 .text_for_range(location.range.clone())
9806 .collect::<String>()
9807 )
9808 })
9809 .unwrap();
9810 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9811 Navigated::Yes
9812 })
9813 }))
9814 }
9815
9816 /// Opens a multibuffer with the given project locations in it
9817 pub fn open_locations_in_multibuffer(
9818 workspace: &mut Workspace,
9819 mut locations: Vec<Location>,
9820 title: String,
9821 split: bool,
9822 cx: &mut ViewContext<Workspace>,
9823 ) {
9824 // If there are multiple definitions, open them in a multibuffer
9825 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9826 let mut locations = locations.into_iter().peekable();
9827 let mut ranges_to_highlight = Vec::new();
9828 let capability = workspace.project().read(cx).capability();
9829
9830 let excerpt_buffer = cx.new_model(|cx| {
9831 let mut multibuffer = MultiBuffer::new(capability);
9832 while let Some(location) = locations.next() {
9833 let buffer = location.buffer.read(cx);
9834 let mut ranges_for_buffer = Vec::new();
9835 let range = location.range.to_offset(buffer);
9836 ranges_for_buffer.push(range.clone());
9837
9838 while let Some(next_location) = locations.peek() {
9839 if next_location.buffer == location.buffer {
9840 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9841 locations.next();
9842 } else {
9843 break;
9844 }
9845 }
9846
9847 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9848 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9849 location.buffer.clone(),
9850 ranges_for_buffer,
9851 DEFAULT_MULTIBUFFER_CONTEXT,
9852 cx,
9853 ))
9854 }
9855
9856 multibuffer.with_title(title)
9857 });
9858
9859 let editor = cx.new_view(|cx| {
9860 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9861 });
9862 editor.update(cx, |editor, cx| {
9863 if let Some(first_range) = ranges_to_highlight.first() {
9864 editor.change_selections(None, cx, |selections| {
9865 selections.clear_disjoint();
9866 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9867 });
9868 }
9869 editor.highlight_background::<Self>(
9870 &ranges_to_highlight,
9871 |theme| theme.editor_highlighted_line_background,
9872 cx,
9873 );
9874 editor.register_buffers_with_language_servers(cx);
9875 });
9876
9877 let item = Box::new(editor);
9878 let item_id = item.item_id();
9879
9880 if split {
9881 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9882 } else {
9883 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9884 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9885 pane.close_current_preview_item(cx)
9886 } else {
9887 None
9888 }
9889 });
9890 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9891 }
9892 workspace.active_pane().update(cx, |pane, cx| {
9893 pane.set_preview_item_id(Some(item_id), cx);
9894 });
9895 }
9896
9897 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9898 use language::ToOffset as _;
9899
9900 let provider = self.semantics_provider.clone()?;
9901 let selection = self.selections.newest_anchor().clone();
9902 let (cursor_buffer, cursor_buffer_position) = self
9903 .buffer
9904 .read(cx)
9905 .text_anchor_for_position(selection.head(), cx)?;
9906 let (tail_buffer, cursor_buffer_position_end) = self
9907 .buffer
9908 .read(cx)
9909 .text_anchor_for_position(selection.tail(), cx)?;
9910 if tail_buffer != cursor_buffer {
9911 return None;
9912 }
9913
9914 let snapshot = cursor_buffer.read(cx).snapshot();
9915 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9916 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9917 let prepare_rename = provider
9918 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9919 .unwrap_or_else(|| Task::ready(Ok(None)));
9920 drop(snapshot);
9921
9922 Some(cx.spawn(|this, mut cx| async move {
9923 let rename_range = if let Some(range) = prepare_rename.await? {
9924 Some(range)
9925 } else {
9926 this.update(&mut cx, |this, cx| {
9927 let buffer = this.buffer.read(cx).snapshot(cx);
9928 let mut buffer_highlights = this
9929 .document_highlights_for_position(selection.head(), &buffer)
9930 .filter(|highlight| {
9931 highlight.start.excerpt_id == selection.head().excerpt_id
9932 && highlight.end.excerpt_id == selection.head().excerpt_id
9933 });
9934 buffer_highlights
9935 .next()
9936 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9937 })?
9938 };
9939 if let Some(rename_range) = rename_range {
9940 this.update(&mut cx, |this, cx| {
9941 let snapshot = cursor_buffer.read(cx).snapshot();
9942 let rename_buffer_range = rename_range.to_offset(&snapshot);
9943 let cursor_offset_in_rename_range =
9944 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9945 let cursor_offset_in_rename_range_end =
9946 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9947
9948 this.take_rename(false, cx);
9949 let buffer = this.buffer.read(cx).read(cx);
9950 let cursor_offset = selection.head().to_offset(&buffer);
9951 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9952 let rename_end = rename_start + rename_buffer_range.len();
9953 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9954 let mut old_highlight_id = None;
9955 let old_name: Arc<str> = buffer
9956 .chunks(rename_start..rename_end, true)
9957 .map(|chunk| {
9958 if old_highlight_id.is_none() {
9959 old_highlight_id = chunk.syntax_highlight_id;
9960 }
9961 chunk.text
9962 })
9963 .collect::<String>()
9964 .into();
9965
9966 drop(buffer);
9967
9968 // Position the selection in the rename editor so that it matches the current selection.
9969 this.show_local_selections = false;
9970 let rename_editor = cx.new_view(|cx| {
9971 let mut editor = Editor::single_line(cx);
9972 editor.buffer.update(cx, |buffer, cx| {
9973 buffer.edit([(0..0, old_name.clone())], None, cx)
9974 });
9975 let rename_selection_range = match cursor_offset_in_rename_range
9976 .cmp(&cursor_offset_in_rename_range_end)
9977 {
9978 Ordering::Equal => {
9979 editor.select_all(&SelectAll, cx);
9980 return editor;
9981 }
9982 Ordering::Less => {
9983 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9984 }
9985 Ordering::Greater => {
9986 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9987 }
9988 };
9989 if rename_selection_range.end > old_name.len() {
9990 editor.select_all(&SelectAll, cx);
9991 } else {
9992 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9993 s.select_ranges([rename_selection_range]);
9994 });
9995 }
9996 editor
9997 });
9998 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9999 if e == &EditorEvent::Focused {
10000 cx.emit(EditorEvent::FocusedIn)
10001 }
10002 })
10003 .detach();
10004
10005 let write_highlights =
10006 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10007 let read_highlights =
10008 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10009 let ranges = write_highlights
10010 .iter()
10011 .flat_map(|(_, ranges)| ranges.iter())
10012 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10013 .cloned()
10014 .collect();
10015
10016 this.highlight_text::<Rename>(
10017 ranges,
10018 HighlightStyle {
10019 fade_out: Some(0.6),
10020 ..Default::default()
10021 },
10022 cx,
10023 );
10024 let rename_focus_handle = rename_editor.focus_handle(cx);
10025 cx.focus(&rename_focus_handle);
10026 let block_id = this.insert_blocks(
10027 [BlockProperties {
10028 style: BlockStyle::Flex,
10029 placement: BlockPlacement::Below(range.start),
10030 height: 1,
10031 render: Arc::new({
10032 let rename_editor = rename_editor.clone();
10033 move |cx: &mut BlockContext| {
10034 let mut text_style = cx.editor_style.text.clone();
10035 if let Some(highlight_style) = old_highlight_id
10036 .and_then(|h| h.style(&cx.editor_style.syntax))
10037 {
10038 text_style = text_style.highlight(highlight_style);
10039 }
10040 div()
10041 .block_mouse_down()
10042 .pl(cx.anchor_x)
10043 .child(EditorElement::new(
10044 &rename_editor,
10045 EditorStyle {
10046 background: cx.theme().system().transparent,
10047 local_player: cx.editor_style.local_player,
10048 text: text_style,
10049 scrollbar_width: cx.editor_style.scrollbar_width,
10050 syntax: cx.editor_style.syntax.clone(),
10051 status: cx.editor_style.status.clone(),
10052 inlay_hints_style: HighlightStyle {
10053 font_weight: Some(FontWeight::BOLD),
10054 ..make_inlay_hints_style(cx)
10055 },
10056 inline_completion_styles: make_suggestion_styles(
10057 cx,
10058 ),
10059 ..EditorStyle::default()
10060 },
10061 ))
10062 .into_any_element()
10063 }
10064 }),
10065 priority: 0,
10066 }],
10067 Some(Autoscroll::fit()),
10068 cx,
10069 )[0];
10070 this.pending_rename = Some(RenameState {
10071 range,
10072 old_name,
10073 editor: rename_editor,
10074 block_id,
10075 });
10076 })?;
10077 }
10078
10079 Ok(())
10080 }))
10081 }
10082
10083 pub fn confirm_rename(
10084 &mut self,
10085 _: &ConfirmRename,
10086 cx: &mut ViewContext<Self>,
10087 ) -> Option<Task<Result<()>>> {
10088 let rename = self.take_rename(false, cx)?;
10089 let workspace = self.workspace()?.downgrade();
10090 let (buffer, start) = self
10091 .buffer
10092 .read(cx)
10093 .text_anchor_for_position(rename.range.start, cx)?;
10094 let (end_buffer, _) = self
10095 .buffer
10096 .read(cx)
10097 .text_anchor_for_position(rename.range.end, cx)?;
10098 if buffer != end_buffer {
10099 return None;
10100 }
10101
10102 let old_name = rename.old_name;
10103 let new_name = rename.editor.read(cx).text(cx);
10104
10105 let rename = self.semantics_provider.as_ref()?.perform_rename(
10106 &buffer,
10107 start,
10108 new_name.clone(),
10109 cx,
10110 )?;
10111
10112 Some(cx.spawn(|editor, mut cx| async move {
10113 let project_transaction = rename.await?;
10114 Self::open_project_transaction(
10115 &editor,
10116 workspace,
10117 project_transaction,
10118 format!("Rename: {} → {}", old_name, new_name),
10119 cx.clone(),
10120 )
10121 .await?;
10122
10123 editor.update(&mut cx, |editor, cx| {
10124 editor.refresh_document_highlights(cx);
10125 })?;
10126 Ok(())
10127 }))
10128 }
10129
10130 fn take_rename(
10131 &mut self,
10132 moving_cursor: bool,
10133 cx: &mut ViewContext<Self>,
10134 ) -> Option<RenameState> {
10135 let rename = self.pending_rename.take()?;
10136 if rename.editor.focus_handle(cx).is_focused(cx) {
10137 cx.focus(&self.focus_handle);
10138 }
10139
10140 self.remove_blocks(
10141 [rename.block_id].into_iter().collect(),
10142 Some(Autoscroll::fit()),
10143 cx,
10144 );
10145 self.clear_highlights::<Rename>(cx);
10146 self.show_local_selections = true;
10147
10148 if moving_cursor {
10149 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10150 editor.selections.newest::<usize>(cx).head()
10151 });
10152
10153 // Update the selection to match the position of the selection inside
10154 // the rename editor.
10155 let snapshot = self.buffer.read(cx).read(cx);
10156 let rename_range = rename.range.to_offset(&snapshot);
10157 let cursor_in_editor = snapshot
10158 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10159 .min(rename_range.end);
10160 drop(snapshot);
10161
10162 self.change_selections(None, cx, |s| {
10163 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10164 });
10165 } else {
10166 self.refresh_document_highlights(cx);
10167 }
10168
10169 Some(rename)
10170 }
10171
10172 pub fn pending_rename(&self) -> Option<&RenameState> {
10173 self.pending_rename.as_ref()
10174 }
10175
10176 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10177 let project = match &self.project {
10178 Some(project) => project.clone(),
10179 None => return None,
10180 };
10181
10182 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10183 }
10184
10185 fn format_selections(
10186 &mut self,
10187 _: &FormatSelections,
10188 cx: &mut ViewContext<Self>,
10189 ) -> Option<Task<Result<()>>> {
10190 let project = match &self.project {
10191 Some(project) => project.clone(),
10192 None => return None,
10193 };
10194
10195 let selections = self
10196 .selections
10197 .all_adjusted(cx)
10198 .into_iter()
10199 .filter(|s| !s.is_empty())
10200 .collect_vec();
10201
10202 Some(self.perform_format(
10203 project,
10204 FormatTrigger::Manual,
10205 FormatTarget::Ranges(selections),
10206 cx,
10207 ))
10208 }
10209
10210 fn perform_format(
10211 &mut self,
10212 project: Model<Project>,
10213 trigger: FormatTrigger,
10214 target: FormatTarget,
10215 cx: &mut ViewContext<Self>,
10216 ) -> Task<Result<()>> {
10217 let buffer = self.buffer().clone();
10218 let mut buffers = buffer.read(cx).all_buffers();
10219 if trigger == FormatTrigger::Save {
10220 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10221 }
10222
10223 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10224 let format = project.update(cx, |project, cx| {
10225 project.format(buffers, true, trigger, target, cx)
10226 });
10227
10228 cx.spawn(|_, mut cx| async move {
10229 let transaction = futures::select_biased! {
10230 () = timeout => {
10231 log::warn!("timed out waiting for formatting");
10232 None
10233 }
10234 transaction = format.log_err().fuse() => transaction,
10235 };
10236
10237 buffer
10238 .update(&mut cx, |buffer, cx| {
10239 if let Some(transaction) = transaction {
10240 if !buffer.is_singleton() {
10241 buffer.push_transaction(&transaction.0, cx);
10242 }
10243 }
10244
10245 cx.notify();
10246 })
10247 .ok();
10248
10249 Ok(())
10250 })
10251 }
10252
10253 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10254 if let Some(project) = self.project.clone() {
10255 self.buffer.update(cx, |multi_buffer, cx| {
10256 project.update(cx, |project, cx| {
10257 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10258 });
10259 })
10260 }
10261 }
10262
10263 fn cancel_language_server_work(
10264 &mut self,
10265 _: &actions::CancelLanguageServerWork,
10266 cx: &mut ViewContext<Self>,
10267 ) {
10268 if let Some(project) = self.project.clone() {
10269 self.buffer.update(cx, |multi_buffer, cx| {
10270 project.update(cx, |project, cx| {
10271 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10272 });
10273 })
10274 }
10275 }
10276
10277 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10278 cx.show_character_palette();
10279 }
10280
10281 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10282 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10283 let buffer = self.buffer.read(cx).snapshot(cx);
10284 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10285 let is_valid = buffer
10286 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10287 .any(|entry| {
10288 entry.diagnostic.is_primary
10289 && !entry.range.is_empty()
10290 && entry.range.start == primary_range_start
10291 && entry.diagnostic.message == active_diagnostics.primary_message
10292 });
10293
10294 if is_valid != active_diagnostics.is_valid {
10295 active_diagnostics.is_valid = is_valid;
10296 let mut new_styles = HashMap::default();
10297 for (block_id, diagnostic) in &active_diagnostics.blocks {
10298 new_styles.insert(
10299 *block_id,
10300 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10301 );
10302 }
10303 self.display_map.update(cx, |display_map, _cx| {
10304 display_map.replace_blocks(new_styles)
10305 });
10306 }
10307 }
10308 }
10309
10310 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10311 self.dismiss_diagnostics(cx);
10312 let snapshot = self.snapshot(cx);
10313 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10314 let buffer = self.buffer.read(cx).snapshot(cx);
10315
10316 let mut primary_range = None;
10317 let mut primary_message = None;
10318 let mut group_end = Point::zero();
10319 let diagnostic_group = buffer
10320 .diagnostic_group::<MultiBufferPoint>(group_id)
10321 .filter_map(|entry| {
10322 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10323 && (entry.range.start.row == entry.range.end.row
10324 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10325 {
10326 return None;
10327 }
10328 if entry.range.end > group_end {
10329 group_end = entry.range.end;
10330 }
10331 if entry.diagnostic.is_primary {
10332 primary_range = Some(entry.range.clone());
10333 primary_message = Some(entry.diagnostic.message.clone());
10334 }
10335 Some(entry)
10336 })
10337 .collect::<Vec<_>>();
10338 let primary_range = primary_range?;
10339 let primary_message = primary_message?;
10340 let primary_range =
10341 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10342
10343 let blocks = display_map
10344 .insert_blocks(
10345 diagnostic_group.iter().map(|entry| {
10346 let diagnostic = entry.diagnostic.clone();
10347 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10348 BlockProperties {
10349 style: BlockStyle::Fixed,
10350 placement: BlockPlacement::Below(
10351 buffer.anchor_after(entry.range.start),
10352 ),
10353 height: message_height,
10354 render: diagnostic_block_renderer(diagnostic, None, true, true),
10355 priority: 0,
10356 }
10357 }),
10358 cx,
10359 )
10360 .into_iter()
10361 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10362 .collect();
10363
10364 Some(ActiveDiagnosticGroup {
10365 primary_range,
10366 primary_message,
10367 group_id,
10368 blocks,
10369 is_valid: true,
10370 })
10371 });
10372 self.active_diagnostics.is_some()
10373 }
10374
10375 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10376 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10377 self.display_map.update(cx, |display_map, cx| {
10378 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10379 });
10380 cx.notify();
10381 }
10382 }
10383
10384 pub fn set_selections_from_remote(
10385 &mut self,
10386 selections: Vec<Selection<Anchor>>,
10387 pending_selection: Option<Selection<Anchor>>,
10388 cx: &mut ViewContext<Self>,
10389 ) {
10390 let old_cursor_position = self.selections.newest_anchor().head();
10391 self.selections.change_with(cx, |s| {
10392 s.select_anchors(selections);
10393 if let Some(pending_selection) = pending_selection {
10394 s.set_pending(pending_selection, SelectMode::Character);
10395 } else {
10396 s.clear_pending();
10397 }
10398 });
10399 self.selections_did_change(false, &old_cursor_position, true, cx);
10400 }
10401
10402 fn push_to_selection_history(&mut self) {
10403 self.selection_history.push(SelectionHistoryEntry {
10404 selections: self.selections.disjoint_anchors(),
10405 select_next_state: self.select_next_state.clone(),
10406 select_prev_state: self.select_prev_state.clone(),
10407 add_selections_state: self.add_selections_state.clone(),
10408 });
10409 }
10410
10411 pub fn transact(
10412 &mut self,
10413 cx: &mut ViewContext<Self>,
10414 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10415 ) -> Option<TransactionId> {
10416 self.start_transaction_at(Instant::now(), cx);
10417 update(self, cx);
10418 self.end_transaction_at(Instant::now(), cx)
10419 }
10420
10421 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10422 self.end_selection(cx);
10423 if let Some(tx_id) = self
10424 .buffer
10425 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10426 {
10427 self.selection_history
10428 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10429 cx.emit(EditorEvent::TransactionBegun {
10430 transaction_id: tx_id,
10431 })
10432 }
10433 }
10434
10435 pub fn end_transaction_at(
10436 &mut self,
10437 now: Instant,
10438 cx: &mut ViewContext<Self>,
10439 ) -> Option<TransactionId> {
10440 if let Some(transaction_id) = self
10441 .buffer
10442 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10443 {
10444 if let Some((_, end_selections)) =
10445 self.selection_history.transaction_mut(transaction_id)
10446 {
10447 *end_selections = Some(self.selections.disjoint_anchors());
10448 } else {
10449 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10450 }
10451
10452 cx.emit(EditorEvent::Edited { transaction_id });
10453 Some(transaction_id)
10454 } else {
10455 None
10456 }
10457 }
10458
10459 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10460 if self.is_singleton(cx) {
10461 let selection = self.selections.newest::<Point>(cx);
10462
10463 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10464 let range = if selection.is_empty() {
10465 let point = selection.head().to_display_point(&display_map);
10466 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10467 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10468 .to_point(&display_map);
10469 start..end
10470 } else {
10471 selection.range()
10472 };
10473 if display_map.folds_in_range(range).next().is_some() {
10474 self.unfold_lines(&Default::default(), cx)
10475 } else {
10476 self.fold(&Default::default(), cx)
10477 }
10478 } else {
10479 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10480 let mut toggled_buffers = HashSet::default();
10481 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10482 self.selections
10483 .disjoint_anchors()
10484 .into_iter()
10485 .map(|selection| selection.range()),
10486 ) {
10487 let buffer_id = buffer_snapshot.remote_id();
10488 if toggled_buffers.insert(buffer_id) {
10489 if self.buffer_folded(buffer_id, cx) {
10490 self.unfold_buffer(buffer_id, cx);
10491 } else {
10492 self.fold_buffer(buffer_id, cx);
10493 }
10494 }
10495 }
10496 }
10497 }
10498
10499 pub fn toggle_fold_recursive(
10500 &mut self,
10501 _: &actions::ToggleFoldRecursive,
10502 cx: &mut ViewContext<Self>,
10503 ) {
10504 let selection = self.selections.newest::<Point>(cx);
10505
10506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10507 let range = if selection.is_empty() {
10508 let point = selection.head().to_display_point(&display_map);
10509 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10510 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10511 .to_point(&display_map);
10512 start..end
10513 } else {
10514 selection.range()
10515 };
10516 if display_map.folds_in_range(range).next().is_some() {
10517 self.unfold_recursive(&Default::default(), cx)
10518 } else {
10519 self.fold_recursive(&Default::default(), cx)
10520 }
10521 }
10522
10523 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10524 if self.is_singleton(cx) {
10525 let mut to_fold = Vec::new();
10526 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10527 let selections = self.selections.all_adjusted(cx);
10528
10529 for selection in selections {
10530 let range = selection.range().sorted();
10531 let buffer_start_row = range.start.row;
10532
10533 if range.start.row != range.end.row {
10534 let mut found = false;
10535 let mut row = range.start.row;
10536 while row <= range.end.row {
10537 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10538 {
10539 found = true;
10540 row = crease.range().end.row + 1;
10541 to_fold.push(crease);
10542 } else {
10543 row += 1
10544 }
10545 }
10546 if found {
10547 continue;
10548 }
10549 }
10550
10551 for row in (0..=range.start.row).rev() {
10552 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10553 if crease.range().end.row >= buffer_start_row {
10554 to_fold.push(crease);
10555 if row <= range.start.row {
10556 break;
10557 }
10558 }
10559 }
10560 }
10561 }
10562
10563 self.fold_creases(to_fold, true, cx);
10564 } else {
10565 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10566 let mut folded_buffers = HashSet::default();
10567 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10568 self.selections
10569 .disjoint_anchors()
10570 .into_iter()
10571 .map(|selection| selection.range()),
10572 ) {
10573 let buffer_id = buffer_snapshot.remote_id();
10574 if folded_buffers.insert(buffer_id) {
10575 self.fold_buffer(buffer_id, cx);
10576 }
10577 }
10578 }
10579 }
10580
10581 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10582 if !self.buffer.read(cx).is_singleton() {
10583 return;
10584 }
10585
10586 let fold_at_level = fold_at.level;
10587 let snapshot = self.buffer.read(cx).snapshot(cx);
10588 let mut to_fold = Vec::new();
10589 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10590
10591 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10592 while start_row < end_row {
10593 match self
10594 .snapshot(cx)
10595 .crease_for_buffer_row(MultiBufferRow(start_row))
10596 {
10597 Some(crease) => {
10598 let nested_start_row = crease.range().start.row + 1;
10599 let nested_end_row = crease.range().end.row;
10600
10601 if current_level < fold_at_level {
10602 stack.push((nested_start_row, nested_end_row, current_level + 1));
10603 } else if current_level == fold_at_level {
10604 to_fold.push(crease);
10605 }
10606
10607 start_row = nested_end_row + 1;
10608 }
10609 None => start_row += 1,
10610 }
10611 }
10612 }
10613
10614 self.fold_creases(to_fold, true, cx);
10615 }
10616
10617 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10618 if self.buffer.read(cx).is_singleton() {
10619 let mut fold_ranges = Vec::new();
10620 let snapshot = self.buffer.read(cx).snapshot(cx);
10621
10622 for row in 0..snapshot.max_row().0 {
10623 if let Some(foldable_range) =
10624 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10625 {
10626 fold_ranges.push(foldable_range);
10627 }
10628 }
10629
10630 self.fold_creases(fold_ranges, true, cx);
10631 } else {
10632 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10633 editor
10634 .update(&mut cx, |editor, cx| {
10635 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10636 editor.fold_buffer(buffer_id, cx);
10637 }
10638 })
10639 .ok();
10640 });
10641 }
10642 }
10643
10644 pub fn fold_function_bodies(
10645 &mut self,
10646 _: &actions::FoldFunctionBodies,
10647 cx: &mut ViewContext<Self>,
10648 ) {
10649 let snapshot = self.buffer.read(cx).snapshot(cx);
10650 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10651 return;
10652 };
10653 let creases = buffer
10654 .function_body_fold_ranges(0..buffer.len())
10655 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10656 .collect();
10657
10658 self.fold_creases(creases, true, cx);
10659 }
10660
10661 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10662 let mut to_fold = Vec::new();
10663 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10664 let selections = self.selections.all_adjusted(cx);
10665
10666 for selection in selections {
10667 let range = selection.range().sorted();
10668 let buffer_start_row = range.start.row;
10669
10670 if range.start.row != range.end.row {
10671 let mut found = false;
10672 for row in range.start.row..=range.end.row {
10673 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10674 found = true;
10675 to_fold.push(crease);
10676 }
10677 }
10678 if found {
10679 continue;
10680 }
10681 }
10682
10683 for row in (0..=range.start.row).rev() {
10684 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10685 if crease.range().end.row >= buffer_start_row {
10686 to_fold.push(crease);
10687 } else {
10688 break;
10689 }
10690 }
10691 }
10692 }
10693
10694 self.fold_creases(to_fold, true, cx);
10695 }
10696
10697 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10698 let buffer_row = fold_at.buffer_row;
10699 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10700
10701 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10702 let autoscroll = self
10703 .selections
10704 .all::<Point>(cx)
10705 .iter()
10706 .any(|selection| crease.range().overlaps(&selection.range()));
10707
10708 self.fold_creases(vec![crease], autoscroll, cx);
10709 }
10710 }
10711
10712 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10713 if self.is_singleton(cx) {
10714 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10715 let buffer = &display_map.buffer_snapshot;
10716 let selections = self.selections.all::<Point>(cx);
10717 let ranges = selections
10718 .iter()
10719 .map(|s| {
10720 let range = s.display_range(&display_map).sorted();
10721 let mut start = range.start.to_point(&display_map);
10722 let mut end = range.end.to_point(&display_map);
10723 start.column = 0;
10724 end.column = buffer.line_len(MultiBufferRow(end.row));
10725 start..end
10726 })
10727 .collect::<Vec<_>>();
10728
10729 self.unfold_ranges(&ranges, true, true, cx);
10730 } else {
10731 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10732 let mut unfolded_buffers = HashSet::default();
10733 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10734 self.selections
10735 .disjoint_anchors()
10736 .into_iter()
10737 .map(|selection| selection.range()),
10738 ) {
10739 let buffer_id = buffer_snapshot.remote_id();
10740 if unfolded_buffers.insert(buffer_id) {
10741 self.unfold_buffer(buffer_id, cx);
10742 }
10743 }
10744 }
10745 }
10746
10747 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10748 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10749 let selections = self.selections.all::<Point>(cx);
10750 let ranges = selections
10751 .iter()
10752 .map(|s| {
10753 let mut range = s.display_range(&display_map).sorted();
10754 *range.start.column_mut() = 0;
10755 *range.end.column_mut() = display_map.line_len(range.end.row());
10756 let start = range.start.to_point(&display_map);
10757 let end = range.end.to_point(&display_map);
10758 start..end
10759 })
10760 .collect::<Vec<_>>();
10761
10762 self.unfold_ranges(&ranges, true, true, cx);
10763 }
10764
10765 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10766 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10767
10768 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10769 ..Point::new(
10770 unfold_at.buffer_row.0,
10771 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10772 );
10773
10774 let autoscroll = self
10775 .selections
10776 .all::<Point>(cx)
10777 .iter()
10778 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10779
10780 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10781 }
10782
10783 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10784 if self.buffer.read(cx).is_singleton() {
10785 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10786 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10787 } else {
10788 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10789 editor
10790 .update(&mut cx, |editor, cx| {
10791 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10792 editor.unfold_buffer(buffer_id, cx);
10793 }
10794 })
10795 .ok();
10796 });
10797 }
10798 }
10799
10800 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10801 let selections = self.selections.all::<Point>(cx);
10802 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10803 let line_mode = self.selections.line_mode;
10804 let ranges = selections
10805 .into_iter()
10806 .map(|s| {
10807 if line_mode {
10808 let start = Point::new(s.start.row, 0);
10809 let end = Point::new(
10810 s.end.row,
10811 display_map
10812 .buffer_snapshot
10813 .line_len(MultiBufferRow(s.end.row)),
10814 );
10815 Crease::simple(start..end, display_map.fold_placeholder.clone())
10816 } else {
10817 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10818 }
10819 })
10820 .collect::<Vec<_>>();
10821 self.fold_creases(ranges, true, cx);
10822 }
10823
10824 pub fn fold_creases<T: ToOffset + Clone>(
10825 &mut self,
10826 creases: Vec<Crease<T>>,
10827 auto_scroll: bool,
10828 cx: &mut ViewContext<Self>,
10829 ) {
10830 if creases.is_empty() {
10831 return;
10832 }
10833
10834 let mut buffers_affected = HashSet::default();
10835 let multi_buffer = self.buffer().read(cx);
10836 for crease in &creases {
10837 if let Some((_, buffer, _)) =
10838 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10839 {
10840 buffers_affected.insert(buffer.read(cx).remote_id());
10841 };
10842 }
10843
10844 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10845
10846 if auto_scroll {
10847 self.request_autoscroll(Autoscroll::fit(), cx);
10848 }
10849
10850 for buffer_id in buffers_affected {
10851 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10852 }
10853
10854 cx.notify();
10855
10856 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10857 // Clear diagnostics block when folding a range that contains it.
10858 let snapshot = self.snapshot(cx);
10859 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10860 drop(snapshot);
10861 self.active_diagnostics = Some(active_diagnostics);
10862 self.dismiss_diagnostics(cx);
10863 } else {
10864 self.active_diagnostics = Some(active_diagnostics);
10865 }
10866 }
10867
10868 self.scrollbar_marker_state.dirty = true;
10869 }
10870
10871 /// Removes any folds whose ranges intersect any of the given ranges.
10872 pub fn unfold_ranges<T: ToOffset + Clone>(
10873 &mut self,
10874 ranges: &[Range<T>],
10875 inclusive: bool,
10876 auto_scroll: bool,
10877 cx: &mut ViewContext<Self>,
10878 ) {
10879 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10880 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10881 });
10882 }
10883
10884 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10885 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10886 return;
10887 }
10888 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10889 return;
10890 };
10891 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10892 self.display_map
10893 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10894 cx.emit(EditorEvent::BufferFoldToggled {
10895 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10896 folded: true,
10897 });
10898 cx.notify();
10899 }
10900
10901 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10902 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10903 return;
10904 }
10905 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10906 return;
10907 };
10908 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10909 self.display_map.update(cx, |display_map, cx| {
10910 display_map.unfold_buffer(buffer_id, cx);
10911 });
10912 cx.emit(EditorEvent::BufferFoldToggled {
10913 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10914 folded: false,
10915 });
10916 cx.notify();
10917 }
10918
10919 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10920 self.display_map.read(cx).buffer_folded(buffer)
10921 }
10922
10923 /// Removes any folds with the given ranges.
10924 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10925 &mut self,
10926 ranges: &[Range<T>],
10927 type_id: TypeId,
10928 auto_scroll: bool,
10929 cx: &mut ViewContext<Self>,
10930 ) {
10931 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10932 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10933 });
10934 }
10935
10936 fn remove_folds_with<T: ToOffset + Clone>(
10937 &mut self,
10938 ranges: &[Range<T>],
10939 auto_scroll: bool,
10940 cx: &mut ViewContext<Self>,
10941 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10942 ) {
10943 if ranges.is_empty() {
10944 return;
10945 }
10946
10947 let mut buffers_affected = HashSet::default();
10948 let multi_buffer = self.buffer().read(cx);
10949 for range in ranges {
10950 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10951 buffers_affected.insert(buffer.read(cx).remote_id());
10952 };
10953 }
10954
10955 self.display_map.update(cx, update);
10956
10957 if auto_scroll {
10958 self.request_autoscroll(Autoscroll::fit(), cx);
10959 }
10960
10961 for buffer_id in buffers_affected {
10962 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10963 }
10964
10965 cx.notify();
10966 self.scrollbar_marker_state.dirty = true;
10967 self.active_indent_guides_state.dirty = true;
10968 }
10969
10970 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10971 self.display_map.read(cx).fold_placeholder.clone()
10972 }
10973
10974 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10975 if hovered != self.gutter_hovered {
10976 self.gutter_hovered = hovered;
10977 cx.notify();
10978 }
10979 }
10980
10981 pub fn insert_blocks(
10982 &mut self,
10983 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10984 autoscroll: Option<Autoscroll>,
10985 cx: &mut ViewContext<Self>,
10986 ) -> Vec<CustomBlockId> {
10987 let blocks = self
10988 .display_map
10989 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10990 if let Some(autoscroll) = autoscroll {
10991 self.request_autoscroll(autoscroll, cx);
10992 }
10993 cx.notify();
10994 blocks
10995 }
10996
10997 pub fn resize_blocks(
10998 &mut self,
10999 heights: HashMap<CustomBlockId, u32>,
11000 autoscroll: Option<Autoscroll>,
11001 cx: &mut ViewContext<Self>,
11002 ) {
11003 self.display_map
11004 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11005 if let Some(autoscroll) = autoscroll {
11006 self.request_autoscroll(autoscroll, cx);
11007 }
11008 cx.notify();
11009 }
11010
11011 pub fn replace_blocks(
11012 &mut self,
11013 renderers: HashMap<CustomBlockId, RenderBlock>,
11014 autoscroll: Option<Autoscroll>,
11015 cx: &mut ViewContext<Self>,
11016 ) {
11017 self.display_map
11018 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11019 if let Some(autoscroll) = autoscroll {
11020 self.request_autoscroll(autoscroll, cx);
11021 }
11022 cx.notify();
11023 }
11024
11025 pub fn remove_blocks(
11026 &mut self,
11027 block_ids: HashSet<CustomBlockId>,
11028 autoscroll: Option<Autoscroll>,
11029 cx: &mut ViewContext<Self>,
11030 ) {
11031 self.display_map.update(cx, |display_map, cx| {
11032 display_map.remove_blocks(block_ids, cx)
11033 });
11034 if let Some(autoscroll) = autoscroll {
11035 self.request_autoscroll(autoscroll, cx);
11036 }
11037 cx.notify();
11038 }
11039
11040 pub fn row_for_block(
11041 &self,
11042 block_id: CustomBlockId,
11043 cx: &mut ViewContext<Self>,
11044 ) -> Option<DisplayRow> {
11045 self.display_map
11046 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11047 }
11048
11049 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11050 self.focused_block = Some(focused_block);
11051 }
11052
11053 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11054 self.focused_block.take()
11055 }
11056
11057 pub fn insert_creases(
11058 &mut self,
11059 creases: impl IntoIterator<Item = Crease<Anchor>>,
11060 cx: &mut ViewContext<Self>,
11061 ) -> Vec<CreaseId> {
11062 self.display_map
11063 .update(cx, |map, cx| map.insert_creases(creases, cx))
11064 }
11065
11066 pub fn remove_creases(
11067 &mut self,
11068 ids: impl IntoIterator<Item = CreaseId>,
11069 cx: &mut ViewContext<Self>,
11070 ) {
11071 self.display_map
11072 .update(cx, |map, cx| map.remove_creases(ids, cx));
11073 }
11074
11075 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11076 self.display_map
11077 .update(cx, |map, cx| map.snapshot(cx))
11078 .longest_row()
11079 }
11080
11081 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11082 self.display_map
11083 .update(cx, |map, cx| map.snapshot(cx))
11084 .max_point()
11085 }
11086
11087 pub fn text(&self, cx: &AppContext) -> String {
11088 self.buffer.read(cx).read(cx).text()
11089 }
11090
11091 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11092 let text = self.text(cx);
11093 let text = text.trim();
11094
11095 if text.is_empty() {
11096 return None;
11097 }
11098
11099 Some(text.to_string())
11100 }
11101
11102 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11103 self.transact(cx, |this, cx| {
11104 this.buffer
11105 .read(cx)
11106 .as_singleton()
11107 .expect("you can only call set_text on editors for singleton buffers")
11108 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11109 });
11110 }
11111
11112 pub fn display_text(&self, cx: &mut AppContext) -> String {
11113 self.display_map
11114 .update(cx, |map, cx| map.snapshot(cx))
11115 .text()
11116 }
11117
11118 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11119 let mut wrap_guides = smallvec::smallvec![];
11120
11121 if self.show_wrap_guides == Some(false) {
11122 return wrap_guides;
11123 }
11124
11125 let settings = self.buffer.read(cx).settings_at(0, cx);
11126 if settings.show_wrap_guides {
11127 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11128 wrap_guides.push((soft_wrap as usize, true));
11129 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11130 wrap_guides.push((soft_wrap as usize, true));
11131 }
11132 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11133 }
11134
11135 wrap_guides
11136 }
11137
11138 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11139 let settings = self.buffer.read(cx).settings_at(0, cx);
11140 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11141 match mode {
11142 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11143 SoftWrap::None
11144 }
11145 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11146 language_settings::SoftWrap::PreferredLineLength => {
11147 SoftWrap::Column(settings.preferred_line_length)
11148 }
11149 language_settings::SoftWrap::Bounded => {
11150 SoftWrap::Bounded(settings.preferred_line_length)
11151 }
11152 }
11153 }
11154
11155 pub fn set_soft_wrap_mode(
11156 &mut self,
11157 mode: language_settings::SoftWrap,
11158 cx: &mut ViewContext<Self>,
11159 ) {
11160 self.soft_wrap_mode_override = Some(mode);
11161 cx.notify();
11162 }
11163
11164 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11165 self.text_style_refinement = Some(style);
11166 }
11167
11168 /// called by the Element so we know what style we were most recently rendered with.
11169 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11170 let rem_size = cx.rem_size();
11171 self.display_map.update(cx, |map, cx| {
11172 map.set_font(
11173 style.text.font(),
11174 style.text.font_size.to_pixels(rem_size),
11175 cx,
11176 )
11177 });
11178 self.style = Some(style);
11179 }
11180
11181 pub fn style(&self) -> Option<&EditorStyle> {
11182 self.style.as_ref()
11183 }
11184
11185 // Called by the element. This method is not designed to be called outside of the editor
11186 // element's layout code because it does not notify when rewrapping is computed synchronously.
11187 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11188 self.display_map
11189 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11190 }
11191
11192 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11193 if self.soft_wrap_mode_override.is_some() {
11194 self.soft_wrap_mode_override.take();
11195 } else {
11196 let soft_wrap = match self.soft_wrap_mode(cx) {
11197 SoftWrap::GitDiff => return,
11198 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11199 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11200 language_settings::SoftWrap::None
11201 }
11202 };
11203 self.soft_wrap_mode_override = Some(soft_wrap);
11204 }
11205 cx.notify();
11206 }
11207
11208 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11209 let Some(workspace) = self.workspace() else {
11210 return;
11211 };
11212 let fs = workspace.read(cx).app_state().fs.clone();
11213 let current_show = TabBarSettings::get_global(cx).show;
11214 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11215 setting.show = Some(!current_show);
11216 });
11217 }
11218
11219 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11220 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11221 self.buffer
11222 .read(cx)
11223 .settings_at(0, cx)
11224 .indent_guides
11225 .enabled
11226 });
11227 self.show_indent_guides = Some(!currently_enabled);
11228 cx.notify();
11229 }
11230
11231 fn should_show_indent_guides(&self) -> Option<bool> {
11232 self.show_indent_guides
11233 }
11234
11235 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11236 let mut editor_settings = EditorSettings::get_global(cx).clone();
11237 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11238 EditorSettings::override_global(editor_settings, cx);
11239 }
11240
11241 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11242 self.use_relative_line_numbers
11243 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11244 }
11245
11246 pub fn toggle_relative_line_numbers(
11247 &mut self,
11248 _: &ToggleRelativeLineNumbers,
11249 cx: &mut ViewContext<Self>,
11250 ) {
11251 let is_relative = self.should_use_relative_line_numbers(cx);
11252 self.set_relative_line_number(Some(!is_relative), cx)
11253 }
11254
11255 pub fn set_relative_line_number(
11256 &mut self,
11257 is_relative: Option<bool>,
11258 cx: &mut ViewContext<Self>,
11259 ) {
11260 self.use_relative_line_numbers = is_relative;
11261 cx.notify();
11262 }
11263
11264 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11265 self.show_gutter = show_gutter;
11266 cx.notify();
11267 }
11268
11269 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11270 self.show_line_numbers = Some(show_line_numbers);
11271 cx.notify();
11272 }
11273
11274 pub fn set_show_git_diff_gutter(
11275 &mut self,
11276 show_git_diff_gutter: bool,
11277 cx: &mut ViewContext<Self>,
11278 ) {
11279 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11280 cx.notify();
11281 }
11282
11283 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11284 self.show_code_actions = Some(show_code_actions);
11285 cx.notify();
11286 }
11287
11288 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11289 self.show_runnables = Some(show_runnables);
11290 cx.notify();
11291 }
11292
11293 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11294 if self.display_map.read(cx).masked != masked {
11295 self.display_map.update(cx, |map, _| map.masked = masked);
11296 }
11297 cx.notify()
11298 }
11299
11300 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11301 self.show_wrap_guides = Some(show_wrap_guides);
11302 cx.notify();
11303 }
11304
11305 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11306 self.show_indent_guides = Some(show_indent_guides);
11307 cx.notify();
11308 }
11309
11310 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11311 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11312 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11313 if let Some(dir) = file.abs_path(cx).parent() {
11314 return Some(dir.to_owned());
11315 }
11316 }
11317
11318 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11319 return Some(project_path.path.to_path_buf());
11320 }
11321 }
11322
11323 None
11324 }
11325
11326 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11327 self.active_excerpt(cx)?
11328 .1
11329 .read(cx)
11330 .file()
11331 .and_then(|f| f.as_local())
11332 }
11333
11334 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11335 if let Some(target) = self.target_file(cx) {
11336 cx.reveal_path(&target.abs_path(cx));
11337 }
11338 }
11339
11340 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11341 if let Some(file) = self.target_file(cx) {
11342 if let Some(path) = file.abs_path(cx).to_str() {
11343 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11344 }
11345 }
11346 }
11347
11348 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11349 if let Some(file) = self.target_file(cx) {
11350 if let Some(path) = file.path().to_str() {
11351 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11352 }
11353 }
11354 }
11355
11356 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11357 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11358
11359 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11360 self.start_git_blame(true, cx);
11361 }
11362
11363 cx.notify();
11364 }
11365
11366 pub fn toggle_git_blame_inline(
11367 &mut self,
11368 _: &ToggleGitBlameInline,
11369 cx: &mut ViewContext<Self>,
11370 ) {
11371 self.toggle_git_blame_inline_internal(true, cx);
11372 cx.notify();
11373 }
11374
11375 pub fn git_blame_inline_enabled(&self) -> bool {
11376 self.git_blame_inline_enabled
11377 }
11378
11379 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11380 self.show_selection_menu = self
11381 .show_selection_menu
11382 .map(|show_selections_menu| !show_selections_menu)
11383 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11384
11385 cx.notify();
11386 }
11387
11388 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11389 self.show_selection_menu
11390 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11391 }
11392
11393 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11394 if let Some(project) = self.project.as_ref() {
11395 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11396 return;
11397 };
11398
11399 if buffer.read(cx).file().is_none() {
11400 return;
11401 }
11402
11403 let focused = self.focus_handle(cx).contains_focused(cx);
11404
11405 let project = project.clone();
11406 let blame =
11407 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11408 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11409 self.blame = Some(blame);
11410 }
11411 }
11412
11413 fn toggle_git_blame_inline_internal(
11414 &mut self,
11415 user_triggered: bool,
11416 cx: &mut ViewContext<Self>,
11417 ) {
11418 if self.git_blame_inline_enabled {
11419 self.git_blame_inline_enabled = false;
11420 self.show_git_blame_inline = false;
11421 self.show_git_blame_inline_delay_task.take();
11422 } else {
11423 self.git_blame_inline_enabled = true;
11424 self.start_git_blame_inline(user_triggered, cx);
11425 }
11426
11427 cx.notify();
11428 }
11429
11430 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11431 self.start_git_blame(user_triggered, cx);
11432
11433 if ProjectSettings::get_global(cx)
11434 .git
11435 .inline_blame_delay()
11436 .is_some()
11437 {
11438 self.start_inline_blame_timer(cx);
11439 } else {
11440 self.show_git_blame_inline = true
11441 }
11442 }
11443
11444 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11445 self.blame.as_ref()
11446 }
11447
11448 pub fn show_git_blame_gutter(&self) -> bool {
11449 self.show_git_blame_gutter
11450 }
11451
11452 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11453 self.show_git_blame_gutter && self.has_blame_entries(cx)
11454 }
11455
11456 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11457 self.show_git_blame_inline
11458 && self.focus_handle.is_focused(cx)
11459 && !self.newest_selection_head_on_empty_line(cx)
11460 && self.has_blame_entries(cx)
11461 }
11462
11463 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11464 self.blame()
11465 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11466 }
11467
11468 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11469 let cursor_anchor = self.selections.newest_anchor().head();
11470
11471 let snapshot = self.buffer.read(cx).snapshot(cx);
11472 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11473
11474 snapshot.line_len(buffer_row) == 0
11475 }
11476
11477 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11478 let buffer_and_selection = maybe!({
11479 let selection = self.selections.newest::<Point>(cx);
11480 let selection_range = selection.range();
11481
11482 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11483 (buffer, selection_range.start.row..selection_range.end.row)
11484 } else {
11485 let buffer_ranges = self
11486 .buffer()
11487 .read(cx)
11488 .range_to_buffer_ranges(selection_range, cx);
11489
11490 let (buffer, range, _) = if selection.reversed {
11491 buffer_ranges.first()
11492 } else {
11493 buffer_ranges.last()
11494 }?;
11495
11496 let snapshot = buffer.read(cx).snapshot();
11497 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11498 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11499 (buffer.clone(), selection)
11500 };
11501
11502 Some((buffer, selection))
11503 });
11504
11505 let Some((buffer, selection)) = buffer_and_selection else {
11506 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11507 };
11508
11509 let Some(project) = self.project.as_ref() else {
11510 return Task::ready(Err(anyhow!("editor does not have project")));
11511 };
11512
11513 project.update(cx, |project, cx| {
11514 project.get_permalink_to_line(&buffer, selection, cx)
11515 })
11516 }
11517
11518 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11519 let permalink_task = self.get_permalink_to_line(cx);
11520 let workspace = self.workspace();
11521
11522 cx.spawn(|_, mut cx| async move {
11523 match permalink_task.await {
11524 Ok(permalink) => {
11525 cx.update(|cx| {
11526 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11527 })
11528 .ok();
11529 }
11530 Err(err) => {
11531 let message = format!("Failed to copy permalink: {err}");
11532
11533 Err::<(), anyhow::Error>(err).log_err();
11534
11535 if let Some(workspace) = workspace {
11536 workspace
11537 .update(&mut cx, |workspace, cx| {
11538 struct CopyPermalinkToLine;
11539
11540 workspace.show_toast(
11541 Toast::new(
11542 NotificationId::unique::<CopyPermalinkToLine>(),
11543 message,
11544 ),
11545 cx,
11546 )
11547 })
11548 .ok();
11549 }
11550 }
11551 }
11552 })
11553 .detach();
11554 }
11555
11556 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11557 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11558 if let Some(file) = self.target_file(cx) {
11559 if let Some(path) = file.path().to_str() {
11560 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11561 }
11562 }
11563 }
11564
11565 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11566 let permalink_task = self.get_permalink_to_line(cx);
11567 let workspace = self.workspace();
11568
11569 cx.spawn(|_, mut cx| async move {
11570 match permalink_task.await {
11571 Ok(permalink) => {
11572 cx.update(|cx| {
11573 cx.open_url(permalink.as_ref());
11574 })
11575 .ok();
11576 }
11577 Err(err) => {
11578 let message = format!("Failed to open permalink: {err}");
11579
11580 Err::<(), anyhow::Error>(err).log_err();
11581
11582 if let Some(workspace) = workspace {
11583 workspace
11584 .update(&mut cx, |workspace, cx| {
11585 struct OpenPermalinkToLine;
11586
11587 workspace.show_toast(
11588 Toast::new(
11589 NotificationId::unique::<OpenPermalinkToLine>(),
11590 message,
11591 ),
11592 cx,
11593 )
11594 })
11595 .ok();
11596 }
11597 }
11598 }
11599 })
11600 .detach();
11601 }
11602
11603 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11604 self.insert_uuid(UuidVersion::V4, cx);
11605 }
11606
11607 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11608 self.insert_uuid(UuidVersion::V7, cx);
11609 }
11610
11611 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11612 self.transact(cx, |this, cx| {
11613 let edits = this
11614 .selections
11615 .all::<Point>(cx)
11616 .into_iter()
11617 .map(|selection| {
11618 let uuid = match version {
11619 UuidVersion::V4 => uuid::Uuid::new_v4(),
11620 UuidVersion::V7 => uuid::Uuid::now_v7(),
11621 };
11622
11623 (selection.range(), uuid.to_string())
11624 });
11625 this.edit(edits, cx);
11626 this.refresh_inline_completion(true, false, cx);
11627 });
11628 }
11629
11630 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11631 /// last highlight added will be used.
11632 ///
11633 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11634 pub fn highlight_rows<T: 'static>(
11635 &mut self,
11636 range: Range<Anchor>,
11637 color: Hsla,
11638 should_autoscroll: bool,
11639 cx: &mut ViewContext<Self>,
11640 ) {
11641 let snapshot = self.buffer().read(cx).snapshot(cx);
11642 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11643 let ix = row_highlights.binary_search_by(|highlight| {
11644 Ordering::Equal
11645 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11646 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11647 });
11648
11649 if let Err(mut ix) = ix {
11650 let index = post_inc(&mut self.highlight_order);
11651
11652 // If this range intersects with the preceding highlight, then merge it with
11653 // the preceding highlight. Otherwise insert a new highlight.
11654 let mut merged = false;
11655 if ix > 0 {
11656 let prev_highlight = &mut row_highlights[ix - 1];
11657 if prev_highlight
11658 .range
11659 .end
11660 .cmp(&range.start, &snapshot)
11661 .is_ge()
11662 {
11663 ix -= 1;
11664 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11665 prev_highlight.range.end = range.end;
11666 }
11667 merged = true;
11668 prev_highlight.index = index;
11669 prev_highlight.color = color;
11670 prev_highlight.should_autoscroll = should_autoscroll;
11671 }
11672 }
11673
11674 if !merged {
11675 row_highlights.insert(
11676 ix,
11677 RowHighlight {
11678 range: range.clone(),
11679 index,
11680 color,
11681 should_autoscroll,
11682 },
11683 );
11684 }
11685
11686 // If any of the following highlights intersect with this one, merge them.
11687 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11688 let highlight = &row_highlights[ix];
11689 if next_highlight
11690 .range
11691 .start
11692 .cmp(&highlight.range.end, &snapshot)
11693 .is_le()
11694 {
11695 if next_highlight
11696 .range
11697 .end
11698 .cmp(&highlight.range.end, &snapshot)
11699 .is_gt()
11700 {
11701 row_highlights[ix].range.end = next_highlight.range.end;
11702 }
11703 row_highlights.remove(ix + 1);
11704 } else {
11705 break;
11706 }
11707 }
11708 }
11709 }
11710
11711 /// Remove any highlighted row ranges of the given type that intersect the
11712 /// given ranges.
11713 pub fn remove_highlighted_rows<T: 'static>(
11714 &mut self,
11715 ranges_to_remove: Vec<Range<Anchor>>,
11716 cx: &mut ViewContext<Self>,
11717 ) {
11718 let snapshot = self.buffer().read(cx).snapshot(cx);
11719 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11720 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11721 row_highlights.retain(|highlight| {
11722 while let Some(range_to_remove) = ranges_to_remove.peek() {
11723 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11724 Ordering::Less | Ordering::Equal => {
11725 ranges_to_remove.next();
11726 }
11727 Ordering::Greater => {
11728 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11729 Ordering::Less | Ordering::Equal => {
11730 return false;
11731 }
11732 Ordering::Greater => break,
11733 }
11734 }
11735 }
11736 }
11737
11738 true
11739 })
11740 }
11741
11742 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11743 pub fn clear_row_highlights<T: 'static>(&mut self) {
11744 self.highlighted_rows.remove(&TypeId::of::<T>());
11745 }
11746
11747 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11748 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11749 self.highlighted_rows
11750 .get(&TypeId::of::<T>())
11751 .map_or(&[] as &[_], |vec| vec.as_slice())
11752 .iter()
11753 .map(|highlight| (highlight.range.clone(), highlight.color))
11754 }
11755
11756 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11757 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11758 /// Allows to ignore certain kinds of highlights.
11759 pub fn highlighted_display_rows(
11760 &mut self,
11761 cx: &mut WindowContext,
11762 ) -> BTreeMap<DisplayRow, Hsla> {
11763 let snapshot = self.snapshot(cx);
11764 let mut used_highlight_orders = HashMap::default();
11765 self.highlighted_rows
11766 .iter()
11767 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11768 .fold(
11769 BTreeMap::<DisplayRow, Hsla>::new(),
11770 |mut unique_rows, highlight| {
11771 let start = highlight.range.start.to_display_point(&snapshot);
11772 let end = highlight.range.end.to_display_point(&snapshot);
11773 let start_row = start.row().0;
11774 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11775 && end.column() == 0
11776 {
11777 end.row().0.saturating_sub(1)
11778 } else {
11779 end.row().0
11780 };
11781 for row in start_row..=end_row {
11782 let used_index =
11783 used_highlight_orders.entry(row).or_insert(highlight.index);
11784 if highlight.index >= *used_index {
11785 *used_index = highlight.index;
11786 unique_rows.insert(DisplayRow(row), highlight.color);
11787 }
11788 }
11789 unique_rows
11790 },
11791 )
11792 }
11793
11794 pub fn highlighted_display_row_for_autoscroll(
11795 &self,
11796 snapshot: &DisplaySnapshot,
11797 ) -> Option<DisplayRow> {
11798 self.highlighted_rows
11799 .values()
11800 .flat_map(|highlighted_rows| highlighted_rows.iter())
11801 .filter_map(|highlight| {
11802 if highlight.should_autoscroll {
11803 Some(highlight.range.start.to_display_point(snapshot).row())
11804 } else {
11805 None
11806 }
11807 })
11808 .min()
11809 }
11810
11811 pub fn set_search_within_ranges(
11812 &mut self,
11813 ranges: &[Range<Anchor>],
11814 cx: &mut ViewContext<Self>,
11815 ) {
11816 self.highlight_background::<SearchWithinRange>(
11817 ranges,
11818 |colors| colors.editor_document_highlight_read_background,
11819 cx,
11820 )
11821 }
11822
11823 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11824 self.breadcrumb_header = Some(new_header);
11825 }
11826
11827 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11828 self.clear_background_highlights::<SearchWithinRange>(cx);
11829 }
11830
11831 pub fn highlight_background<T: 'static>(
11832 &mut self,
11833 ranges: &[Range<Anchor>],
11834 color_fetcher: fn(&ThemeColors) -> Hsla,
11835 cx: &mut ViewContext<Self>,
11836 ) {
11837 self.background_highlights
11838 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11839 self.scrollbar_marker_state.dirty = true;
11840 cx.notify();
11841 }
11842
11843 pub fn clear_background_highlights<T: 'static>(
11844 &mut self,
11845 cx: &mut ViewContext<Self>,
11846 ) -> Option<BackgroundHighlight> {
11847 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11848 if !text_highlights.1.is_empty() {
11849 self.scrollbar_marker_state.dirty = true;
11850 cx.notify();
11851 }
11852 Some(text_highlights)
11853 }
11854
11855 pub fn highlight_gutter<T: 'static>(
11856 &mut self,
11857 ranges: &[Range<Anchor>],
11858 color_fetcher: fn(&AppContext) -> Hsla,
11859 cx: &mut ViewContext<Self>,
11860 ) {
11861 self.gutter_highlights
11862 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11863 cx.notify();
11864 }
11865
11866 pub fn clear_gutter_highlights<T: 'static>(
11867 &mut self,
11868 cx: &mut ViewContext<Self>,
11869 ) -> Option<GutterHighlight> {
11870 cx.notify();
11871 self.gutter_highlights.remove(&TypeId::of::<T>())
11872 }
11873
11874 #[cfg(feature = "test-support")]
11875 pub fn all_text_background_highlights(
11876 &mut self,
11877 cx: &mut ViewContext<Self>,
11878 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11879 let snapshot = self.snapshot(cx);
11880 let buffer = &snapshot.buffer_snapshot;
11881 let start = buffer.anchor_before(0);
11882 let end = buffer.anchor_after(buffer.len());
11883 let theme = cx.theme().colors();
11884 self.background_highlights_in_range(start..end, &snapshot, theme)
11885 }
11886
11887 #[cfg(feature = "test-support")]
11888 pub fn search_background_highlights(
11889 &mut self,
11890 cx: &mut ViewContext<Self>,
11891 ) -> Vec<Range<Point>> {
11892 let snapshot = self.buffer().read(cx).snapshot(cx);
11893
11894 let highlights = self
11895 .background_highlights
11896 .get(&TypeId::of::<items::BufferSearchHighlights>());
11897
11898 if let Some((_color, ranges)) = highlights {
11899 ranges
11900 .iter()
11901 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11902 .collect_vec()
11903 } else {
11904 vec![]
11905 }
11906 }
11907
11908 fn document_highlights_for_position<'a>(
11909 &'a self,
11910 position: Anchor,
11911 buffer: &'a MultiBufferSnapshot,
11912 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11913 let read_highlights = self
11914 .background_highlights
11915 .get(&TypeId::of::<DocumentHighlightRead>())
11916 .map(|h| &h.1);
11917 let write_highlights = self
11918 .background_highlights
11919 .get(&TypeId::of::<DocumentHighlightWrite>())
11920 .map(|h| &h.1);
11921 let left_position = position.bias_left(buffer);
11922 let right_position = position.bias_right(buffer);
11923 read_highlights
11924 .into_iter()
11925 .chain(write_highlights)
11926 .flat_map(move |ranges| {
11927 let start_ix = match ranges.binary_search_by(|probe| {
11928 let cmp = probe.end.cmp(&left_position, buffer);
11929 if cmp.is_ge() {
11930 Ordering::Greater
11931 } else {
11932 Ordering::Less
11933 }
11934 }) {
11935 Ok(i) | Err(i) => i,
11936 };
11937
11938 ranges[start_ix..]
11939 .iter()
11940 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11941 })
11942 }
11943
11944 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11945 self.background_highlights
11946 .get(&TypeId::of::<T>())
11947 .map_or(false, |(_, highlights)| !highlights.is_empty())
11948 }
11949
11950 pub fn background_highlights_in_range(
11951 &self,
11952 search_range: Range<Anchor>,
11953 display_snapshot: &DisplaySnapshot,
11954 theme: &ThemeColors,
11955 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11956 let mut results = Vec::new();
11957 for (color_fetcher, ranges) in self.background_highlights.values() {
11958 let color = color_fetcher(theme);
11959 let start_ix = match ranges.binary_search_by(|probe| {
11960 let cmp = probe
11961 .end
11962 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11963 if cmp.is_gt() {
11964 Ordering::Greater
11965 } else {
11966 Ordering::Less
11967 }
11968 }) {
11969 Ok(i) | Err(i) => i,
11970 };
11971 for range in &ranges[start_ix..] {
11972 if range
11973 .start
11974 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11975 .is_ge()
11976 {
11977 break;
11978 }
11979
11980 let start = range.start.to_display_point(display_snapshot);
11981 let end = range.end.to_display_point(display_snapshot);
11982 results.push((start..end, color))
11983 }
11984 }
11985 results
11986 }
11987
11988 pub fn background_highlight_row_ranges<T: 'static>(
11989 &self,
11990 search_range: Range<Anchor>,
11991 display_snapshot: &DisplaySnapshot,
11992 count: usize,
11993 ) -> Vec<RangeInclusive<DisplayPoint>> {
11994 let mut results = Vec::new();
11995 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11996 return vec![];
11997 };
11998
11999 let start_ix = match ranges.binary_search_by(|probe| {
12000 let cmp = probe
12001 .end
12002 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12003 if cmp.is_gt() {
12004 Ordering::Greater
12005 } else {
12006 Ordering::Less
12007 }
12008 }) {
12009 Ok(i) | Err(i) => i,
12010 };
12011 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12012 if let (Some(start_display), Some(end_display)) = (start, end) {
12013 results.push(
12014 start_display.to_display_point(display_snapshot)
12015 ..=end_display.to_display_point(display_snapshot),
12016 );
12017 }
12018 };
12019 let mut start_row: Option<Point> = None;
12020 let mut end_row: Option<Point> = None;
12021 if ranges.len() > count {
12022 return Vec::new();
12023 }
12024 for range in &ranges[start_ix..] {
12025 if range
12026 .start
12027 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12028 .is_ge()
12029 {
12030 break;
12031 }
12032 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12033 if let Some(current_row) = &end_row {
12034 if end.row == current_row.row {
12035 continue;
12036 }
12037 }
12038 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12039 if start_row.is_none() {
12040 assert_eq!(end_row, None);
12041 start_row = Some(start);
12042 end_row = Some(end);
12043 continue;
12044 }
12045 if let Some(current_end) = end_row.as_mut() {
12046 if start.row > current_end.row + 1 {
12047 push_region(start_row, end_row);
12048 start_row = Some(start);
12049 end_row = Some(end);
12050 } else {
12051 // Merge two hunks.
12052 *current_end = end;
12053 }
12054 } else {
12055 unreachable!();
12056 }
12057 }
12058 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12059 push_region(start_row, end_row);
12060 results
12061 }
12062
12063 pub fn gutter_highlights_in_range(
12064 &self,
12065 search_range: Range<Anchor>,
12066 display_snapshot: &DisplaySnapshot,
12067 cx: &AppContext,
12068 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12069 let mut results = Vec::new();
12070 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12071 let color = color_fetcher(cx);
12072 let start_ix = match ranges.binary_search_by(|probe| {
12073 let cmp = probe
12074 .end
12075 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12076 if cmp.is_gt() {
12077 Ordering::Greater
12078 } else {
12079 Ordering::Less
12080 }
12081 }) {
12082 Ok(i) | Err(i) => i,
12083 };
12084 for range in &ranges[start_ix..] {
12085 if range
12086 .start
12087 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12088 .is_ge()
12089 {
12090 break;
12091 }
12092
12093 let start = range.start.to_display_point(display_snapshot);
12094 let end = range.end.to_display_point(display_snapshot);
12095 results.push((start..end, color))
12096 }
12097 }
12098 results
12099 }
12100
12101 /// Get the text ranges corresponding to the redaction query
12102 pub fn redacted_ranges(
12103 &self,
12104 search_range: Range<Anchor>,
12105 display_snapshot: &DisplaySnapshot,
12106 cx: &WindowContext,
12107 ) -> Vec<Range<DisplayPoint>> {
12108 display_snapshot
12109 .buffer_snapshot
12110 .redacted_ranges(search_range, |file| {
12111 if let Some(file) = file {
12112 file.is_private()
12113 && EditorSettings::get(
12114 Some(SettingsLocation {
12115 worktree_id: file.worktree_id(cx),
12116 path: file.path().as_ref(),
12117 }),
12118 cx,
12119 )
12120 .redact_private_values
12121 } else {
12122 false
12123 }
12124 })
12125 .map(|range| {
12126 range.start.to_display_point(display_snapshot)
12127 ..range.end.to_display_point(display_snapshot)
12128 })
12129 .collect()
12130 }
12131
12132 pub fn highlight_text<T: 'static>(
12133 &mut self,
12134 ranges: Vec<Range<Anchor>>,
12135 style: HighlightStyle,
12136 cx: &mut ViewContext<Self>,
12137 ) {
12138 self.display_map.update(cx, |map, _| {
12139 map.highlight_text(TypeId::of::<T>(), ranges, style)
12140 });
12141 cx.notify();
12142 }
12143
12144 pub(crate) fn highlight_inlays<T: 'static>(
12145 &mut self,
12146 highlights: Vec<InlayHighlight>,
12147 style: HighlightStyle,
12148 cx: &mut ViewContext<Self>,
12149 ) {
12150 self.display_map.update(cx, |map, _| {
12151 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12152 });
12153 cx.notify();
12154 }
12155
12156 pub fn text_highlights<'a, T: 'static>(
12157 &'a self,
12158 cx: &'a AppContext,
12159 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12160 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12161 }
12162
12163 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12164 let cleared = self
12165 .display_map
12166 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12167 if cleared {
12168 cx.notify();
12169 }
12170 }
12171
12172 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12173 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12174 && self.focus_handle.is_focused(cx)
12175 }
12176
12177 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12178 self.show_cursor_when_unfocused = is_enabled;
12179 cx.notify();
12180 }
12181
12182 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12183 self.project
12184 .as_ref()
12185 .map(|project| project.read(cx).lsp_store())
12186 }
12187
12188 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12189 cx.notify();
12190 }
12191
12192 fn on_buffer_event(
12193 &mut self,
12194 multibuffer: Model<MultiBuffer>,
12195 event: &multi_buffer::Event,
12196 cx: &mut ViewContext<Self>,
12197 ) {
12198 match event {
12199 multi_buffer::Event::Edited {
12200 singleton_buffer_edited,
12201 edited_buffer: buffer_edited,
12202 } => {
12203 self.scrollbar_marker_state.dirty = true;
12204 self.active_indent_guides_state.dirty = true;
12205 self.refresh_active_diagnostics(cx);
12206 self.refresh_code_actions(cx);
12207 if self.has_active_inline_completion() {
12208 self.update_visible_inline_completion(cx);
12209 }
12210 if let Some(buffer) = buffer_edited {
12211 let buffer_id = buffer.read(cx).remote_id();
12212 if !self.registered_buffers.contains_key(&buffer_id) {
12213 if let Some(lsp_store) = self.lsp_store(cx) {
12214 lsp_store.update(cx, |lsp_store, cx| {
12215 self.registered_buffers.insert(
12216 buffer_id,
12217 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12218 );
12219 })
12220 }
12221 }
12222 }
12223 cx.emit(EditorEvent::BufferEdited);
12224 cx.emit(SearchEvent::MatchesInvalidated);
12225 if *singleton_buffer_edited {
12226 if let Some(project) = &self.project {
12227 let project = project.read(cx);
12228 #[allow(clippy::mutable_key_type)]
12229 let languages_affected = multibuffer
12230 .read(cx)
12231 .all_buffers()
12232 .into_iter()
12233 .filter_map(|buffer| {
12234 let buffer = buffer.read(cx);
12235 let language = buffer.language()?;
12236 if project.is_local()
12237 && project
12238 .language_servers_for_local_buffer(buffer, cx)
12239 .count()
12240 == 0
12241 {
12242 None
12243 } else {
12244 Some(language)
12245 }
12246 })
12247 .cloned()
12248 .collect::<HashSet<_>>();
12249 if !languages_affected.is_empty() {
12250 self.refresh_inlay_hints(
12251 InlayHintRefreshReason::BufferEdited(languages_affected),
12252 cx,
12253 );
12254 }
12255 }
12256 }
12257
12258 let Some(project) = &self.project else { return };
12259 let (telemetry, is_via_ssh) = {
12260 let project = project.read(cx);
12261 let telemetry = project.client().telemetry().clone();
12262 let is_via_ssh = project.is_via_ssh();
12263 (telemetry, is_via_ssh)
12264 };
12265 refresh_linked_ranges(self, cx);
12266 telemetry.log_edit_event("editor", is_via_ssh);
12267 }
12268 multi_buffer::Event::ExcerptsAdded {
12269 buffer,
12270 predecessor,
12271 excerpts,
12272 } => {
12273 self.tasks_update_task = Some(self.refresh_runnables(cx));
12274 let buffer_id = buffer.read(cx).remote_id();
12275 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12276 if let Some(project) = &self.project {
12277 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12278 }
12279 }
12280 cx.emit(EditorEvent::ExcerptsAdded {
12281 buffer: buffer.clone(),
12282 predecessor: *predecessor,
12283 excerpts: excerpts.clone(),
12284 });
12285 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12286 }
12287 multi_buffer::Event::ExcerptsRemoved { ids } => {
12288 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12289 let buffer = self.buffer.read(cx);
12290 self.registered_buffers
12291 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12292 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12293 }
12294 multi_buffer::Event::ExcerptsEdited { ids } => {
12295 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12296 }
12297 multi_buffer::Event::ExcerptsExpanded { ids } => {
12298 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12299 }
12300 multi_buffer::Event::Reparsed(buffer_id) => {
12301 self.tasks_update_task = Some(self.refresh_runnables(cx));
12302
12303 cx.emit(EditorEvent::Reparsed(*buffer_id));
12304 }
12305 multi_buffer::Event::LanguageChanged(buffer_id) => {
12306 linked_editing_ranges::refresh_linked_ranges(self, cx);
12307 cx.emit(EditorEvent::Reparsed(*buffer_id));
12308 cx.notify();
12309 }
12310 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12311 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12312 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12313 cx.emit(EditorEvent::TitleChanged)
12314 }
12315 // multi_buffer::Event::DiffBaseChanged => {
12316 // self.scrollbar_marker_state.dirty = true;
12317 // cx.emit(EditorEvent::DiffBaseChanged);
12318 // cx.notify();
12319 // }
12320 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12321 multi_buffer::Event::DiagnosticsUpdated => {
12322 self.refresh_active_diagnostics(cx);
12323 self.scrollbar_marker_state.dirty = true;
12324 cx.notify();
12325 }
12326 _ => {}
12327 };
12328 }
12329
12330 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12331 cx.notify();
12332 }
12333
12334 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12335 self.tasks_update_task = Some(self.refresh_runnables(cx));
12336 self.refresh_inline_completion(true, false, cx);
12337 self.refresh_inlay_hints(
12338 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12339 self.selections.newest_anchor().head(),
12340 &self.buffer.read(cx).snapshot(cx),
12341 cx,
12342 )),
12343 cx,
12344 );
12345
12346 let old_cursor_shape = self.cursor_shape;
12347
12348 {
12349 let editor_settings = EditorSettings::get_global(cx);
12350 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12351 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12352 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12353 }
12354
12355 if old_cursor_shape != self.cursor_shape {
12356 cx.emit(EditorEvent::CursorShapeChanged);
12357 }
12358
12359 let project_settings = ProjectSettings::get_global(cx);
12360 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12361
12362 if self.mode == EditorMode::Full {
12363 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12364 if self.git_blame_inline_enabled != inline_blame_enabled {
12365 self.toggle_git_blame_inline_internal(false, cx);
12366 }
12367 }
12368
12369 cx.notify();
12370 }
12371
12372 pub fn set_searchable(&mut self, searchable: bool) {
12373 self.searchable = searchable;
12374 }
12375
12376 pub fn searchable(&self) -> bool {
12377 self.searchable
12378 }
12379
12380 fn open_proposed_changes_editor(
12381 &mut self,
12382 _: &OpenProposedChangesEditor,
12383 cx: &mut ViewContext<Self>,
12384 ) {
12385 let Some(workspace) = self.workspace() else {
12386 cx.propagate();
12387 return;
12388 };
12389
12390 let selections = self.selections.all::<usize>(cx);
12391 let buffer = self.buffer.read(cx);
12392 let mut new_selections_by_buffer = HashMap::default();
12393 for selection in selections {
12394 for (buffer, range, _) in
12395 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12396 {
12397 let mut range = range.to_point(buffer.read(cx));
12398 range.start.column = 0;
12399 range.end.column = buffer.read(cx).line_len(range.end.row);
12400 new_selections_by_buffer
12401 .entry(buffer)
12402 .or_insert(Vec::new())
12403 .push(range)
12404 }
12405 }
12406
12407 let proposed_changes_buffers = new_selections_by_buffer
12408 .into_iter()
12409 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12410 .collect::<Vec<_>>();
12411 let proposed_changes_editor = cx.new_view(|cx| {
12412 ProposedChangesEditor::new(
12413 "Proposed changes",
12414 proposed_changes_buffers,
12415 self.project.clone(),
12416 cx,
12417 )
12418 });
12419
12420 cx.window_context().defer(move |cx| {
12421 workspace.update(cx, |workspace, cx| {
12422 workspace.active_pane().update(cx, |pane, cx| {
12423 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12424 });
12425 });
12426 });
12427 }
12428
12429 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12430 self.open_excerpts_common(None, true, cx)
12431 }
12432
12433 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12434 self.open_excerpts_common(None, false, cx)
12435 }
12436
12437 fn open_excerpts_common(
12438 &mut self,
12439 jump_data: Option<JumpData>,
12440 split: bool,
12441 cx: &mut ViewContext<Self>,
12442 ) {
12443 let Some(workspace) = self.workspace() else {
12444 cx.propagate();
12445 return;
12446 };
12447
12448 if self.buffer.read(cx).is_singleton() {
12449 cx.propagate();
12450 return;
12451 }
12452
12453 let mut new_selections_by_buffer = HashMap::default();
12454 match &jump_data {
12455 Some(jump_data) => {
12456 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12457 if let Some(buffer) = multi_buffer_snapshot
12458 .buffer_id_for_excerpt(jump_data.excerpt_id)
12459 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12460 {
12461 let buffer_snapshot = buffer.read(cx).snapshot();
12462 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12463 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12464 } else {
12465 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12466 };
12467 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12468 new_selections_by_buffer.insert(
12469 buffer,
12470 (
12471 vec![jump_to_offset..jump_to_offset],
12472 Some(jump_data.line_offset_from_top),
12473 ),
12474 );
12475 }
12476 }
12477 None => {
12478 let selections = self.selections.all::<usize>(cx);
12479 let buffer = self.buffer.read(cx);
12480 for selection in selections {
12481 for (mut buffer_handle, mut range, _) in
12482 buffer.range_to_buffer_ranges(selection.range(), cx)
12483 {
12484 // When editing branch buffers, jump to the corresponding location
12485 // in their base buffer.
12486 let buffer = buffer_handle.read(cx);
12487 if let Some(base_buffer) = buffer.base_buffer() {
12488 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12489 buffer_handle = base_buffer;
12490 }
12491
12492 if selection.reversed {
12493 mem::swap(&mut range.start, &mut range.end);
12494 }
12495 new_selections_by_buffer
12496 .entry(buffer_handle)
12497 .or_insert((Vec::new(), None))
12498 .0
12499 .push(range)
12500 }
12501 }
12502 }
12503 }
12504
12505 if new_selections_by_buffer.is_empty() {
12506 return;
12507 }
12508
12509 // We defer the pane interaction because we ourselves are a workspace item
12510 // and activating a new item causes the pane to call a method on us reentrantly,
12511 // which panics if we're on the stack.
12512 cx.window_context().defer(move |cx| {
12513 workspace.update(cx, |workspace, cx| {
12514 let pane = if split {
12515 workspace.adjacent_pane(cx)
12516 } else {
12517 workspace.active_pane().clone()
12518 };
12519
12520 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12521 let editor = buffer
12522 .read(cx)
12523 .file()
12524 .is_none()
12525 .then(|| {
12526 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12527 // so `workspace.open_project_item` will never find them, always opening a new editor.
12528 // Instead, we try to activate the existing editor in the pane first.
12529 let (editor, pane_item_index) =
12530 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12531 let editor = item.downcast::<Editor>()?;
12532 let singleton_buffer =
12533 editor.read(cx).buffer().read(cx).as_singleton()?;
12534 if singleton_buffer == buffer {
12535 Some((editor, i))
12536 } else {
12537 None
12538 }
12539 })?;
12540 pane.update(cx, |pane, cx| {
12541 pane.activate_item(pane_item_index, true, true, cx)
12542 });
12543 Some(editor)
12544 })
12545 .flatten()
12546 .unwrap_or_else(|| {
12547 workspace.open_project_item::<Self>(
12548 pane.clone(),
12549 buffer,
12550 true,
12551 true,
12552 cx,
12553 )
12554 });
12555
12556 editor.update(cx, |editor, cx| {
12557 let autoscroll = match scroll_offset {
12558 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12559 None => Autoscroll::newest(),
12560 };
12561 let nav_history = editor.nav_history.take();
12562 editor.change_selections(Some(autoscroll), cx, |s| {
12563 s.select_ranges(ranges);
12564 });
12565 editor.nav_history = nav_history;
12566 });
12567 }
12568 })
12569 });
12570 }
12571
12572 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12573 let snapshot = self.buffer.read(cx).read(cx);
12574 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12575 Some(
12576 ranges
12577 .iter()
12578 .map(move |range| {
12579 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12580 })
12581 .collect(),
12582 )
12583 }
12584
12585 fn selection_replacement_ranges(
12586 &self,
12587 range: Range<OffsetUtf16>,
12588 cx: &mut AppContext,
12589 ) -> Vec<Range<OffsetUtf16>> {
12590 let selections = self.selections.all::<OffsetUtf16>(cx);
12591 let newest_selection = selections
12592 .iter()
12593 .max_by_key(|selection| selection.id)
12594 .unwrap();
12595 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12596 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12597 let snapshot = self.buffer.read(cx).read(cx);
12598 selections
12599 .into_iter()
12600 .map(|mut selection| {
12601 selection.start.0 =
12602 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12603 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12604 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12605 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12606 })
12607 .collect()
12608 }
12609
12610 fn report_editor_event(
12611 &self,
12612 event_type: &'static str,
12613 file_extension: Option<String>,
12614 cx: &AppContext,
12615 ) {
12616 if cfg!(any(test, feature = "test-support")) {
12617 return;
12618 }
12619
12620 let Some(project) = &self.project else { return };
12621
12622 // If None, we are in a file without an extension
12623 let file = self
12624 .buffer
12625 .read(cx)
12626 .as_singleton()
12627 .and_then(|b| b.read(cx).file());
12628 let file_extension = file_extension.or(file
12629 .as_ref()
12630 .and_then(|file| Path::new(file.file_name(cx)).extension())
12631 .and_then(|e| e.to_str())
12632 .map(|a| a.to_string()));
12633
12634 let vim_mode = cx
12635 .global::<SettingsStore>()
12636 .raw_user_settings()
12637 .get("vim_mode")
12638 == Some(&serde_json::Value::Bool(true));
12639
12640 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12641 == language::language_settings::InlineCompletionProvider::Copilot;
12642 let copilot_enabled_for_language = self
12643 .buffer
12644 .read(cx)
12645 .settings_at(0, cx)
12646 .show_inline_completions;
12647
12648 let project = project.read(cx);
12649 telemetry::event!(
12650 event_type,
12651 file_extension,
12652 vim_mode,
12653 copilot_enabled,
12654 copilot_enabled_for_language,
12655 is_via_ssh = project.is_via_ssh(),
12656 );
12657 }
12658
12659 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12660 /// with each line being an array of {text, highlight} objects.
12661 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12662 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12663 return;
12664 };
12665
12666 #[derive(Serialize)]
12667 struct Chunk<'a> {
12668 text: String,
12669 highlight: Option<&'a str>,
12670 }
12671
12672 let snapshot = buffer.read(cx).snapshot();
12673 let range = self
12674 .selected_text_range(false, cx)
12675 .and_then(|selection| {
12676 if selection.range.is_empty() {
12677 None
12678 } else {
12679 Some(selection.range)
12680 }
12681 })
12682 .unwrap_or_else(|| 0..snapshot.len());
12683
12684 let chunks = snapshot.chunks(range, true);
12685 let mut lines = Vec::new();
12686 let mut line: VecDeque<Chunk> = VecDeque::new();
12687
12688 let Some(style) = self.style.as_ref() else {
12689 return;
12690 };
12691
12692 for chunk in chunks {
12693 let highlight = chunk
12694 .syntax_highlight_id
12695 .and_then(|id| id.name(&style.syntax));
12696 let mut chunk_lines = chunk.text.split('\n').peekable();
12697 while let Some(text) = chunk_lines.next() {
12698 let mut merged_with_last_token = false;
12699 if let Some(last_token) = line.back_mut() {
12700 if last_token.highlight == highlight {
12701 last_token.text.push_str(text);
12702 merged_with_last_token = true;
12703 }
12704 }
12705
12706 if !merged_with_last_token {
12707 line.push_back(Chunk {
12708 text: text.into(),
12709 highlight,
12710 });
12711 }
12712
12713 if chunk_lines.peek().is_some() {
12714 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12715 line.pop_front();
12716 }
12717 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12718 line.pop_back();
12719 }
12720
12721 lines.push(mem::take(&mut line));
12722 }
12723 }
12724 }
12725
12726 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12727 return;
12728 };
12729 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12730 }
12731
12732 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12733 self.request_autoscroll(Autoscroll::newest(), cx);
12734 let position = self.selections.newest_display(cx).start;
12735 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12736 }
12737
12738 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12739 &self.inlay_hint_cache
12740 }
12741
12742 pub fn replay_insert_event(
12743 &mut self,
12744 text: &str,
12745 relative_utf16_range: Option<Range<isize>>,
12746 cx: &mut ViewContext<Self>,
12747 ) {
12748 if !self.input_enabled {
12749 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12750 return;
12751 }
12752 if let Some(relative_utf16_range) = relative_utf16_range {
12753 let selections = self.selections.all::<OffsetUtf16>(cx);
12754 self.change_selections(None, cx, |s| {
12755 let new_ranges = selections.into_iter().map(|range| {
12756 let start = OffsetUtf16(
12757 range
12758 .head()
12759 .0
12760 .saturating_add_signed(relative_utf16_range.start),
12761 );
12762 let end = OffsetUtf16(
12763 range
12764 .head()
12765 .0
12766 .saturating_add_signed(relative_utf16_range.end),
12767 );
12768 start..end
12769 });
12770 s.select_ranges(new_ranges);
12771 });
12772 }
12773
12774 self.handle_input(text, cx);
12775 }
12776
12777 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12778 let Some(provider) = self.semantics_provider.as_ref() else {
12779 return false;
12780 };
12781
12782 let mut supports = false;
12783 self.buffer().read(cx).for_each_buffer(|buffer| {
12784 supports |= provider.supports_inlay_hints(buffer, cx);
12785 });
12786 supports
12787 }
12788
12789 pub fn focus(&self, cx: &mut WindowContext) {
12790 cx.focus(&self.focus_handle)
12791 }
12792
12793 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12794 self.focus_handle.is_focused(cx)
12795 }
12796
12797 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12798 cx.emit(EditorEvent::Focused);
12799
12800 if let Some(descendant) = self
12801 .last_focused_descendant
12802 .take()
12803 .and_then(|descendant| descendant.upgrade())
12804 {
12805 cx.focus(&descendant);
12806 } else {
12807 if let Some(blame) = self.blame.as_ref() {
12808 blame.update(cx, GitBlame::focus)
12809 }
12810
12811 self.blink_manager.update(cx, BlinkManager::enable);
12812 self.show_cursor_names(cx);
12813 self.buffer.update(cx, |buffer, cx| {
12814 buffer.finalize_last_transaction(cx);
12815 if self.leader_peer_id.is_none() {
12816 buffer.set_active_selections(
12817 &self.selections.disjoint_anchors(),
12818 self.selections.line_mode,
12819 self.cursor_shape,
12820 cx,
12821 );
12822 }
12823 });
12824 }
12825 }
12826
12827 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12828 cx.emit(EditorEvent::FocusedIn)
12829 }
12830
12831 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12832 if event.blurred != self.focus_handle {
12833 self.last_focused_descendant = Some(event.blurred);
12834 }
12835 }
12836
12837 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12838 self.blink_manager.update(cx, BlinkManager::disable);
12839 self.buffer
12840 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12841
12842 if let Some(blame) = self.blame.as_ref() {
12843 blame.update(cx, GitBlame::blur)
12844 }
12845 if !self.hover_state.focused(cx) {
12846 hide_hover(self, cx);
12847 }
12848
12849 self.hide_context_menu(cx);
12850 cx.emit(EditorEvent::Blurred);
12851 cx.notify();
12852 }
12853
12854 pub fn register_action<A: Action>(
12855 &mut self,
12856 listener: impl Fn(&A, &mut WindowContext) + 'static,
12857 ) -> Subscription {
12858 let id = self.next_editor_action_id.post_inc();
12859 let listener = Arc::new(listener);
12860 self.editor_actions.borrow_mut().insert(
12861 id,
12862 Box::new(move |cx| {
12863 let cx = cx.window_context();
12864 let listener = listener.clone();
12865 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12866 let action = action.downcast_ref().unwrap();
12867 if phase == DispatchPhase::Bubble {
12868 listener(action, cx)
12869 }
12870 })
12871 }),
12872 );
12873
12874 let editor_actions = self.editor_actions.clone();
12875 Subscription::new(move || {
12876 editor_actions.borrow_mut().remove(&id);
12877 })
12878 }
12879
12880 pub fn file_header_size(&self) -> u32 {
12881 FILE_HEADER_HEIGHT
12882 }
12883
12884 pub fn revert(
12885 &mut self,
12886 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12887 cx: &mut ViewContext<Self>,
12888 ) {
12889 self.buffer().update(cx, |multi_buffer, cx| {
12890 for (buffer_id, changes) in revert_changes {
12891 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12892 buffer.update(cx, |buffer, cx| {
12893 buffer.edit(
12894 changes.into_iter().map(|(range, text)| {
12895 (range, text.to_string().map(Arc::<str>::from))
12896 }),
12897 None,
12898 cx,
12899 );
12900 });
12901 }
12902 }
12903 });
12904 self.change_selections(None, cx, |selections| selections.refresh());
12905 }
12906
12907 pub fn to_pixel_point(
12908 &mut self,
12909 source: multi_buffer::Anchor,
12910 editor_snapshot: &EditorSnapshot,
12911 cx: &mut ViewContext<Self>,
12912 ) -> Option<gpui::Point<Pixels>> {
12913 let source_point = source.to_display_point(editor_snapshot);
12914 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12915 }
12916
12917 pub fn display_to_pixel_point(
12918 &self,
12919 source: DisplayPoint,
12920 editor_snapshot: &EditorSnapshot,
12921 cx: &WindowContext,
12922 ) -> Option<gpui::Point<Pixels>> {
12923 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12924 let text_layout_details = self.text_layout_details(cx);
12925 let scroll_top = text_layout_details
12926 .scroll_anchor
12927 .scroll_position(editor_snapshot)
12928 .y;
12929
12930 if source.row().as_f32() < scroll_top.floor() {
12931 return None;
12932 }
12933 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12934 let source_y = line_height * (source.row().as_f32() - scroll_top);
12935 Some(gpui::Point::new(source_x, source_y))
12936 }
12937
12938 pub fn has_active_completions_menu(&self) -> bool {
12939 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12940 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12941 })
12942 }
12943
12944 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12945 self.addons
12946 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12947 }
12948
12949 pub fn unregister_addon<T: Addon>(&mut self) {
12950 self.addons.remove(&std::any::TypeId::of::<T>());
12951 }
12952
12953 pub fn addon<T: Addon>(&self) -> Option<&T> {
12954 let type_id = std::any::TypeId::of::<T>();
12955 self.addons
12956 .get(&type_id)
12957 .and_then(|item| item.to_any().downcast_ref::<T>())
12958 }
12959
12960 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12961 let text_layout_details = self.text_layout_details(cx);
12962 let style = &text_layout_details.editor_style;
12963 let font_id = cx.text_system().resolve_font(&style.text.font());
12964 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12965 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12966
12967 let em_width = cx
12968 .text_system()
12969 .typographic_bounds(font_id, font_size, 'm')
12970 .unwrap()
12971 .size
12972 .width;
12973
12974 gpui::Point::new(em_width, line_height)
12975 }
12976}
12977
12978fn get_unstaged_changes_for_buffers(
12979 project: &Model<Project>,
12980 buffers: impl IntoIterator<Item = Model<Buffer>>,
12981 cx: &mut ViewContext<Editor>,
12982) {
12983 let mut tasks = Vec::new();
12984 project.update(cx, |project, cx| {
12985 for buffer in buffers {
12986 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12987 }
12988 });
12989 cx.spawn(|this, mut cx| async move {
12990 let change_sets = futures::future::join_all(tasks).await;
12991 this.update(&mut cx, |this, cx| {
12992 for change_set in change_sets {
12993 if let Some(change_set) = change_set.log_err() {
12994 this.diff_map.add_change_set(change_set, cx);
12995 }
12996 }
12997 })
12998 .ok();
12999 })
13000 .detach();
13001}
13002
13003fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13004 let tab_size = tab_size.get() as usize;
13005 let mut width = offset;
13006
13007 for ch in text.chars() {
13008 width += if ch == '\t' {
13009 tab_size - (width % tab_size)
13010 } else {
13011 1
13012 };
13013 }
13014
13015 width - offset
13016}
13017
13018#[cfg(test)]
13019mod tests {
13020 use super::*;
13021
13022 #[test]
13023 fn test_string_size_with_expanded_tabs() {
13024 let nz = |val| NonZeroU32::new(val).unwrap();
13025 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13026 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13027 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13028 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13029 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13030 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13031 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13032 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13033 }
13034}
13035
13036/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13037struct WordBreakingTokenizer<'a> {
13038 input: &'a str,
13039}
13040
13041impl<'a> WordBreakingTokenizer<'a> {
13042 fn new(input: &'a str) -> Self {
13043 Self { input }
13044 }
13045}
13046
13047fn is_char_ideographic(ch: char) -> bool {
13048 use unicode_script::Script::*;
13049 use unicode_script::UnicodeScript;
13050 matches!(ch.script(), Han | Tangut | Yi)
13051}
13052
13053fn is_grapheme_ideographic(text: &str) -> bool {
13054 text.chars().any(is_char_ideographic)
13055}
13056
13057fn is_grapheme_whitespace(text: &str) -> bool {
13058 text.chars().any(|x| x.is_whitespace())
13059}
13060
13061fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13062 text.chars().next().map_or(false, |ch| {
13063 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13064 })
13065}
13066
13067#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13068struct WordBreakToken<'a> {
13069 token: &'a str,
13070 grapheme_len: usize,
13071 is_whitespace: bool,
13072}
13073
13074impl<'a> Iterator for WordBreakingTokenizer<'a> {
13075 /// Yields a span, the count of graphemes in the token, and whether it was
13076 /// whitespace. Note that it also breaks at word boundaries.
13077 type Item = WordBreakToken<'a>;
13078
13079 fn next(&mut self) -> Option<Self::Item> {
13080 use unicode_segmentation::UnicodeSegmentation;
13081 if self.input.is_empty() {
13082 return None;
13083 }
13084
13085 let mut iter = self.input.graphemes(true).peekable();
13086 let mut offset = 0;
13087 let mut graphemes = 0;
13088 if let Some(first_grapheme) = iter.next() {
13089 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13090 offset += first_grapheme.len();
13091 graphemes += 1;
13092 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13093 if let Some(grapheme) = iter.peek().copied() {
13094 if should_stay_with_preceding_ideograph(grapheme) {
13095 offset += grapheme.len();
13096 graphemes += 1;
13097 }
13098 }
13099 } else {
13100 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13101 let mut next_word_bound = words.peek().copied();
13102 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13103 next_word_bound = words.next();
13104 }
13105 while let Some(grapheme) = iter.peek().copied() {
13106 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13107 break;
13108 };
13109 if is_grapheme_whitespace(grapheme) != is_whitespace {
13110 break;
13111 };
13112 offset += grapheme.len();
13113 graphemes += 1;
13114 iter.next();
13115 }
13116 }
13117 let token = &self.input[..offset];
13118 self.input = &self.input[offset..];
13119 if is_whitespace {
13120 Some(WordBreakToken {
13121 token: " ",
13122 grapheme_len: 1,
13123 is_whitespace: true,
13124 })
13125 } else {
13126 Some(WordBreakToken {
13127 token,
13128 grapheme_len: graphemes,
13129 is_whitespace: false,
13130 })
13131 }
13132 } else {
13133 None
13134 }
13135 }
13136}
13137
13138#[test]
13139fn test_word_breaking_tokenizer() {
13140 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13141 ("", &[]),
13142 (" ", &[(" ", 1, true)]),
13143 ("Ʒ", &[("Ʒ", 1, false)]),
13144 ("Ǽ", &[("Ǽ", 1, false)]),
13145 ("⋑", &[("⋑", 1, false)]),
13146 ("⋑⋑", &[("⋑⋑", 2, false)]),
13147 (
13148 "原理,进而",
13149 &[
13150 ("原", 1, false),
13151 ("理,", 2, false),
13152 ("进", 1, false),
13153 ("而", 1, false),
13154 ],
13155 ),
13156 (
13157 "hello world",
13158 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13159 ),
13160 (
13161 "hello, world",
13162 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13163 ),
13164 (
13165 " hello world",
13166 &[
13167 (" ", 1, true),
13168 ("hello", 5, false),
13169 (" ", 1, true),
13170 ("world", 5, false),
13171 ],
13172 ),
13173 (
13174 "这是什么 \n 钢笔",
13175 &[
13176 ("这", 1, false),
13177 ("是", 1, false),
13178 ("什", 1, false),
13179 ("么", 1, false),
13180 (" ", 1, true),
13181 ("钢", 1, false),
13182 ("笔", 1, false),
13183 ],
13184 ),
13185 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13186 ];
13187
13188 for (input, result) in tests {
13189 assert_eq!(
13190 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13191 result
13192 .iter()
13193 .copied()
13194 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13195 token,
13196 grapheme_len,
13197 is_whitespace,
13198 })
13199 .collect::<Vec<_>>()
13200 );
13201 }
13202}
13203
13204fn wrap_with_prefix(
13205 line_prefix: String,
13206 unwrapped_text: String,
13207 wrap_column: usize,
13208 tab_size: NonZeroU32,
13209) -> String {
13210 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13211 let mut wrapped_text = String::new();
13212 let mut current_line = line_prefix.clone();
13213
13214 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13215 let mut current_line_len = line_prefix_len;
13216 for WordBreakToken {
13217 token,
13218 grapheme_len,
13219 is_whitespace,
13220 } in tokenizer
13221 {
13222 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13223 wrapped_text.push_str(current_line.trim_end());
13224 wrapped_text.push('\n');
13225 current_line.truncate(line_prefix.len());
13226 current_line_len = line_prefix_len;
13227 if !is_whitespace {
13228 current_line.push_str(token);
13229 current_line_len += grapheme_len;
13230 }
13231 } else if !is_whitespace {
13232 current_line.push_str(token);
13233 current_line_len += grapheme_len;
13234 } else if current_line_len != line_prefix_len {
13235 current_line.push(' ');
13236 current_line_len += 1;
13237 }
13238 }
13239
13240 if !current_line.is_empty() {
13241 wrapped_text.push_str(¤t_line);
13242 }
13243 wrapped_text
13244}
13245
13246#[test]
13247fn test_wrap_with_prefix() {
13248 assert_eq!(
13249 wrap_with_prefix(
13250 "# ".to_string(),
13251 "abcdefg".to_string(),
13252 4,
13253 NonZeroU32::new(4).unwrap()
13254 ),
13255 "# abcdefg"
13256 );
13257 assert_eq!(
13258 wrap_with_prefix(
13259 "".to_string(),
13260 "\thello world".to_string(),
13261 8,
13262 NonZeroU32::new(4).unwrap()
13263 ),
13264 "hello\nworld"
13265 );
13266 assert_eq!(
13267 wrap_with_prefix(
13268 "// ".to_string(),
13269 "xx \nyy zz aa bb cc".to_string(),
13270 12,
13271 NonZeroU32::new(4).unwrap()
13272 ),
13273 "// xx yy zz\n// aa bb cc"
13274 );
13275 assert_eq!(
13276 wrap_with_prefix(
13277 String::new(),
13278 "这是什么 \n 钢笔".to_string(),
13279 3,
13280 NonZeroU32::new(4).unwrap()
13281 ),
13282 "这是什\n么 钢\n笔"
13283 );
13284}
13285
13286fn hunks_for_selections(
13287 snapshot: &EditorSnapshot,
13288 selections: &[Selection<Point>],
13289) -> Vec<MultiBufferDiffHunk> {
13290 hunks_for_ranges(
13291 selections.iter().map(|selection| selection.range()),
13292 snapshot,
13293 )
13294}
13295
13296pub fn hunks_for_ranges(
13297 ranges: impl Iterator<Item = Range<Point>>,
13298 snapshot: &EditorSnapshot,
13299) -> Vec<MultiBufferDiffHunk> {
13300 let mut hunks = Vec::new();
13301 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13302 HashMap::default();
13303 for query_range in ranges {
13304 let query_rows =
13305 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13306 for hunk in snapshot.diff_map.diff_hunks_in_range(
13307 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13308 &snapshot.buffer_snapshot,
13309 ) {
13310 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13311 // when the caret is just above or just below the deleted hunk.
13312 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13313 let related_to_selection = if allow_adjacent {
13314 hunk.row_range.overlaps(&query_rows)
13315 || hunk.row_range.start == query_rows.end
13316 || hunk.row_range.end == query_rows.start
13317 } else {
13318 hunk.row_range.overlaps(&query_rows)
13319 };
13320 if related_to_selection {
13321 if !processed_buffer_rows
13322 .entry(hunk.buffer_id)
13323 .or_default()
13324 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13325 {
13326 continue;
13327 }
13328 hunks.push(hunk);
13329 }
13330 }
13331 }
13332
13333 hunks
13334}
13335
13336pub trait CollaborationHub {
13337 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13338 fn user_participant_indices<'a>(
13339 &self,
13340 cx: &'a AppContext,
13341 ) -> &'a HashMap<u64, ParticipantIndex>;
13342 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13343}
13344
13345impl CollaborationHub for Model<Project> {
13346 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13347 self.read(cx).collaborators()
13348 }
13349
13350 fn user_participant_indices<'a>(
13351 &self,
13352 cx: &'a AppContext,
13353 ) -> &'a HashMap<u64, ParticipantIndex> {
13354 self.read(cx).user_store().read(cx).participant_indices()
13355 }
13356
13357 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13358 let this = self.read(cx);
13359 let user_ids = this.collaborators().values().map(|c| c.user_id);
13360 this.user_store().read_with(cx, |user_store, cx| {
13361 user_store.participant_names(user_ids, cx)
13362 })
13363 }
13364}
13365
13366pub trait SemanticsProvider {
13367 fn hover(
13368 &self,
13369 buffer: &Model<Buffer>,
13370 position: text::Anchor,
13371 cx: &mut AppContext,
13372 ) -> Option<Task<Vec<project::Hover>>>;
13373
13374 fn inlay_hints(
13375 &self,
13376 buffer_handle: Model<Buffer>,
13377 range: Range<text::Anchor>,
13378 cx: &mut AppContext,
13379 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13380
13381 fn resolve_inlay_hint(
13382 &self,
13383 hint: InlayHint,
13384 buffer_handle: Model<Buffer>,
13385 server_id: LanguageServerId,
13386 cx: &mut AppContext,
13387 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13388
13389 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13390
13391 fn document_highlights(
13392 &self,
13393 buffer: &Model<Buffer>,
13394 position: text::Anchor,
13395 cx: &mut AppContext,
13396 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13397
13398 fn definitions(
13399 &self,
13400 buffer: &Model<Buffer>,
13401 position: text::Anchor,
13402 kind: GotoDefinitionKind,
13403 cx: &mut AppContext,
13404 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13405
13406 fn range_for_rename(
13407 &self,
13408 buffer: &Model<Buffer>,
13409 position: text::Anchor,
13410 cx: &mut AppContext,
13411 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13412
13413 fn perform_rename(
13414 &self,
13415 buffer: &Model<Buffer>,
13416 position: text::Anchor,
13417 new_name: String,
13418 cx: &mut AppContext,
13419 ) -> Option<Task<Result<ProjectTransaction>>>;
13420}
13421
13422pub trait CompletionProvider {
13423 fn completions(
13424 &self,
13425 buffer: &Model<Buffer>,
13426 buffer_position: text::Anchor,
13427 trigger: CompletionContext,
13428 cx: &mut ViewContext<Editor>,
13429 ) -> Task<Result<Vec<Completion>>>;
13430
13431 fn resolve_completions(
13432 &self,
13433 buffer: Model<Buffer>,
13434 completion_indices: Vec<usize>,
13435 completions: Rc<RefCell<Box<[Completion]>>>,
13436 cx: &mut ViewContext<Editor>,
13437 ) -> Task<Result<bool>>;
13438
13439 fn apply_additional_edits_for_completion(
13440 &self,
13441 _buffer: Model<Buffer>,
13442 _completions: Rc<RefCell<Box<[Completion]>>>,
13443 _completion_index: usize,
13444 _push_to_history: bool,
13445 _cx: &mut ViewContext<Editor>,
13446 ) -> Task<Result<Option<language::Transaction>>> {
13447 Task::ready(Ok(None))
13448 }
13449
13450 fn is_completion_trigger(
13451 &self,
13452 buffer: &Model<Buffer>,
13453 position: language::Anchor,
13454 text: &str,
13455 trigger_in_words: bool,
13456 cx: &mut ViewContext<Editor>,
13457 ) -> bool;
13458
13459 fn sort_completions(&self) -> bool {
13460 true
13461 }
13462}
13463
13464pub trait CodeActionProvider {
13465 fn code_actions(
13466 &self,
13467 buffer: &Model<Buffer>,
13468 range: Range<text::Anchor>,
13469 cx: &mut WindowContext,
13470 ) -> Task<Result<Vec<CodeAction>>>;
13471
13472 fn apply_code_action(
13473 &self,
13474 buffer_handle: Model<Buffer>,
13475 action: CodeAction,
13476 excerpt_id: ExcerptId,
13477 push_to_history: bool,
13478 cx: &mut WindowContext,
13479 ) -> Task<Result<ProjectTransaction>>;
13480}
13481
13482impl CodeActionProvider for Model<Project> {
13483 fn code_actions(
13484 &self,
13485 buffer: &Model<Buffer>,
13486 range: Range<text::Anchor>,
13487 cx: &mut WindowContext,
13488 ) -> Task<Result<Vec<CodeAction>>> {
13489 self.update(cx, |project, cx| {
13490 project.code_actions(buffer, range, None, cx)
13491 })
13492 }
13493
13494 fn apply_code_action(
13495 &self,
13496 buffer_handle: Model<Buffer>,
13497 action: CodeAction,
13498 _excerpt_id: ExcerptId,
13499 push_to_history: bool,
13500 cx: &mut WindowContext,
13501 ) -> Task<Result<ProjectTransaction>> {
13502 self.update(cx, |project, cx| {
13503 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13504 })
13505 }
13506}
13507
13508fn snippet_completions(
13509 project: &Project,
13510 buffer: &Model<Buffer>,
13511 buffer_position: text::Anchor,
13512 cx: &mut AppContext,
13513) -> Task<Result<Vec<Completion>>> {
13514 let language = buffer.read(cx).language_at(buffer_position);
13515 let language_name = language.as_ref().map(|language| language.lsp_id());
13516 let snippet_store = project.snippets().read(cx);
13517 let snippets = snippet_store.snippets_for(language_name, cx);
13518
13519 if snippets.is_empty() {
13520 return Task::ready(Ok(vec![]));
13521 }
13522 let snapshot = buffer.read(cx).text_snapshot();
13523 let chars: String = snapshot
13524 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13525 .collect();
13526
13527 let scope = language.map(|language| language.default_scope());
13528 let executor = cx.background_executor().clone();
13529
13530 cx.background_executor().spawn(async move {
13531 let classifier = CharClassifier::new(scope).for_completion(true);
13532 let mut last_word = chars
13533 .chars()
13534 .take_while(|c| classifier.is_word(*c))
13535 .collect::<String>();
13536 last_word = last_word.chars().rev().collect();
13537
13538 if last_word.is_empty() {
13539 return Ok(vec![]);
13540 }
13541
13542 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13543 let to_lsp = |point: &text::Anchor| {
13544 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13545 point_to_lsp(end)
13546 };
13547 let lsp_end = to_lsp(&buffer_position);
13548
13549 let candidates = snippets
13550 .iter()
13551 .enumerate()
13552 .flat_map(|(ix, snippet)| {
13553 snippet
13554 .prefix
13555 .iter()
13556 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13557 })
13558 .collect::<Vec<StringMatchCandidate>>();
13559
13560 let mut matches = fuzzy::match_strings(
13561 &candidates,
13562 &last_word,
13563 last_word.chars().any(|c| c.is_uppercase()),
13564 100,
13565 &Default::default(),
13566 executor,
13567 )
13568 .await;
13569
13570 // Remove all candidates where the query's start does not match the start of any word in the candidate
13571 if let Some(query_start) = last_word.chars().next() {
13572 matches.retain(|string_match| {
13573 split_words(&string_match.string).any(|word| {
13574 // Check that the first codepoint of the word as lowercase matches the first
13575 // codepoint of the query as lowercase
13576 word.chars()
13577 .flat_map(|codepoint| codepoint.to_lowercase())
13578 .zip(query_start.to_lowercase())
13579 .all(|(word_cp, query_cp)| word_cp == query_cp)
13580 })
13581 });
13582 }
13583
13584 let matched_strings = matches
13585 .into_iter()
13586 .map(|m| m.string)
13587 .collect::<HashSet<_>>();
13588
13589 let result: Vec<Completion> = snippets
13590 .into_iter()
13591 .filter_map(|snippet| {
13592 let matching_prefix = snippet
13593 .prefix
13594 .iter()
13595 .find(|prefix| matched_strings.contains(*prefix))?;
13596 let start = as_offset - last_word.len();
13597 let start = snapshot.anchor_before(start);
13598 let range = start..buffer_position;
13599 let lsp_start = to_lsp(&start);
13600 let lsp_range = lsp::Range {
13601 start: lsp_start,
13602 end: lsp_end,
13603 };
13604 Some(Completion {
13605 old_range: range,
13606 new_text: snippet.body.clone(),
13607 resolved: false,
13608 label: CodeLabel {
13609 text: matching_prefix.clone(),
13610 runs: vec![],
13611 filter_range: 0..matching_prefix.len(),
13612 },
13613 server_id: LanguageServerId(usize::MAX),
13614 documentation: snippet.description.clone().map(Documentation::SingleLine),
13615 lsp_completion: lsp::CompletionItem {
13616 label: snippet.prefix.first().unwrap().clone(),
13617 kind: Some(CompletionItemKind::SNIPPET),
13618 label_details: snippet.description.as_ref().map(|description| {
13619 lsp::CompletionItemLabelDetails {
13620 detail: Some(description.clone()),
13621 description: None,
13622 }
13623 }),
13624 insert_text_format: Some(InsertTextFormat::SNIPPET),
13625 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13626 lsp::InsertReplaceEdit {
13627 new_text: snippet.body.clone(),
13628 insert: lsp_range,
13629 replace: lsp_range,
13630 },
13631 )),
13632 filter_text: Some(snippet.body.clone()),
13633 sort_text: Some(char::MAX.to_string()),
13634 ..Default::default()
13635 },
13636 confirm: None,
13637 })
13638 })
13639 .collect();
13640
13641 Ok(result)
13642 })
13643}
13644
13645impl CompletionProvider for Model<Project> {
13646 fn completions(
13647 &self,
13648 buffer: &Model<Buffer>,
13649 buffer_position: text::Anchor,
13650 options: CompletionContext,
13651 cx: &mut ViewContext<Editor>,
13652 ) -> Task<Result<Vec<Completion>>> {
13653 self.update(cx, |project, cx| {
13654 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13655 let project_completions = project.completions(buffer, buffer_position, options, cx);
13656 cx.background_executor().spawn(async move {
13657 let mut completions = project_completions.await?;
13658 let snippets_completions = snippets.await?;
13659 completions.extend(snippets_completions);
13660 Ok(completions)
13661 })
13662 })
13663 }
13664
13665 fn resolve_completions(
13666 &self,
13667 buffer: Model<Buffer>,
13668 completion_indices: Vec<usize>,
13669 completions: Rc<RefCell<Box<[Completion]>>>,
13670 cx: &mut ViewContext<Editor>,
13671 ) -> Task<Result<bool>> {
13672 self.update(cx, |project, cx| {
13673 project.lsp_store().update(cx, |lsp_store, cx| {
13674 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13675 })
13676 })
13677 }
13678
13679 fn apply_additional_edits_for_completion(
13680 &self,
13681 buffer: Model<Buffer>,
13682 completions: Rc<RefCell<Box<[Completion]>>>,
13683 completion_index: usize,
13684 push_to_history: bool,
13685 cx: &mut ViewContext<Editor>,
13686 ) -> Task<Result<Option<language::Transaction>>> {
13687 self.update(cx, |project, cx| {
13688 project.lsp_store().update(cx, |lsp_store, cx| {
13689 lsp_store.apply_additional_edits_for_completion(
13690 buffer,
13691 completions,
13692 completion_index,
13693 push_to_history,
13694 cx,
13695 )
13696 })
13697 })
13698 }
13699
13700 fn is_completion_trigger(
13701 &self,
13702 buffer: &Model<Buffer>,
13703 position: language::Anchor,
13704 text: &str,
13705 trigger_in_words: bool,
13706 cx: &mut ViewContext<Editor>,
13707 ) -> bool {
13708 let mut chars = text.chars();
13709 let char = if let Some(char) = chars.next() {
13710 char
13711 } else {
13712 return false;
13713 };
13714 if chars.next().is_some() {
13715 return false;
13716 }
13717
13718 let buffer = buffer.read(cx);
13719 let snapshot = buffer.snapshot();
13720 if !snapshot.settings_at(position, cx).show_completions_on_input {
13721 return false;
13722 }
13723 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13724 if trigger_in_words && classifier.is_word(char) {
13725 return true;
13726 }
13727
13728 buffer.completion_triggers().contains(text)
13729 }
13730}
13731
13732impl SemanticsProvider for Model<Project> {
13733 fn hover(
13734 &self,
13735 buffer: &Model<Buffer>,
13736 position: text::Anchor,
13737 cx: &mut AppContext,
13738 ) -> Option<Task<Vec<project::Hover>>> {
13739 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13740 }
13741
13742 fn document_highlights(
13743 &self,
13744 buffer: &Model<Buffer>,
13745 position: text::Anchor,
13746 cx: &mut AppContext,
13747 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13748 Some(self.update(cx, |project, cx| {
13749 project.document_highlights(buffer, position, cx)
13750 }))
13751 }
13752
13753 fn definitions(
13754 &self,
13755 buffer: &Model<Buffer>,
13756 position: text::Anchor,
13757 kind: GotoDefinitionKind,
13758 cx: &mut AppContext,
13759 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13760 Some(self.update(cx, |project, cx| match kind {
13761 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13762 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13763 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13764 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13765 }))
13766 }
13767
13768 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13769 // TODO: make this work for remote projects
13770 self.read(cx)
13771 .language_servers_for_local_buffer(buffer.read(cx), cx)
13772 .any(
13773 |(_, server)| match server.capabilities().inlay_hint_provider {
13774 Some(lsp::OneOf::Left(enabled)) => enabled,
13775 Some(lsp::OneOf::Right(_)) => true,
13776 None => false,
13777 },
13778 )
13779 }
13780
13781 fn inlay_hints(
13782 &self,
13783 buffer_handle: Model<Buffer>,
13784 range: Range<text::Anchor>,
13785 cx: &mut AppContext,
13786 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13787 Some(self.update(cx, |project, cx| {
13788 project.inlay_hints(buffer_handle, range, cx)
13789 }))
13790 }
13791
13792 fn resolve_inlay_hint(
13793 &self,
13794 hint: InlayHint,
13795 buffer_handle: Model<Buffer>,
13796 server_id: LanguageServerId,
13797 cx: &mut AppContext,
13798 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13799 Some(self.update(cx, |project, cx| {
13800 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13801 }))
13802 }
13803
13804 fn range_for_rename(
13805 &self,
13806 buffer: &Model<Buffer>,
13807 position: text::Anchor,
13808 cx: &mut AppContext,
13809 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13810 Some(self.update(cx, |project, cx| {
13811 project.prepare_rename(buffer.clone(), position, cx)
13812 }))
13813 }
13814
13815 fn perform_rename(
13816 &self,
13817 buffer: &Model<Buffer>,
13818 position: text::Anchor,
13819 new_name: String,
13820 cx: &mut AppContext,
13821 ) -> Option<Task<Result<ProjectTransaction>>> {
13822 Some(self.update(cx, |project, cx| {
13823 project.perform_rename(buffer.clone(), position, new_name, cx)
13824 }))
13825 }
13826}
13827
13828fn inlay_hint_settings(
13829 location: Anchor,
13830 snapshot: &MultiBufferSnapshot,
13831 cx: &mut ViewContext<'_, Editor>,
13832) -> InlayHintSettings {
13833 let file = snapshot.file_at(location);
13834 let language = snapshot.language_at(location).map(|l| l.name());
13835 language_settings(language, file, cx).inlay_hints
13836}
13837
13838fn consume_contiguous_rows(
13839 contiguous_row_selections: &mut Vec<Selection<Point>>,
13840 selection: &Selection<Point>,
13841 display_map: &DisplaySnapshot,
13842 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13843) -> (MultiBufferRow, MultiBufferRow) {
13844 contiguous_row_selections.push(selection.clone());
13845 let start_row = MultiBufferRow(selection.start.row);
13846 let mut end_row = ending_row(selection, display_map);
13847
13848 while let Some(next_selection) = selections.peek() {
13849 if next_selection.start.row <= end_row.0 {
13850 end_row = ending_row(next_selection, display_map);
13851 contiguous_row_selections.push(selections.next().unwrap().clone());
13852 } else {
13853 break;
13854 }
13855 }
13856 (start_row, end_row)
13857}
13858
13859fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13860 if next_selection.end.column > 0 || next_selection.is_empty() {
13861 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13862 } else {
13863 MultiBufferRow(next_selection.end.row)
13864 }
13865}
13866
13867impl EditorSnapshot {
13868 pub fn remote_selections_in_range<'a>(
13869 &'a self,
13870 range: &'a Range<Anchor>,
13871 collaboration_hub: &dyn CollaborationHub,
13872 cx: &'a AppContext,
13873 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13874 let participant_names = collaboration_hub.user_names(cx);
13875 let participant_indices = collaboration_hub.user_participant_indices(cx);
13876 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13877 let collaborators_by_replica_id = collaborators_by_peer_id
13878 .iter()
13879 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13880 .collect::<HashMap<_, _>>();
13881 self.buffer_snapshot
13882 .selections_in_range(range, false)
13883 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13884 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13885 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13886 let user_name = participant_names.get(&collaborator.user_id).cloned();
13887 Some(RemoteSelection {
13888 replica_id,
13889 selection,
13890 cursor_shape,
13891 line_mode,
13892 participant_index,
13893 peer_id: collaborator.peer_id,
13894 user_name,
13895 })
13896 })
13897 }
13898
13899 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13900 self.display_snapshot.buffer_snapshot.language_at(position)
13901 }
13902
13903 pub fn is_focused(&self) -> bool {
13904 self.is_focused
13905 }
13906
13907 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13908 self.placeholder_text.as_ref()
13909 }
13910
13911 pub fn scroll_position(&self) -> gpui::Point<f32> {
13912 self.scroll_anchor.scroll_position(&self.display_snapshot)
13913 }
13914
13915 fn gutter_dimensions(
13916 &self,
13917 font_id: FontId,
13918 font_size: Pixels,
13919 em_width: Pixels,
13920 em_advance: Pixels,
13921 max_line_number_width: Pixels,
13922 cx: &AppContext,
13923 ) -> GutterDimensions {
13924 if !self.show_gutter {
13925 return GutterDimensions::default();
13926 }
13927 let descent = cx.text_system().descent(font_id, font_size);
13928
13929 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13930 matches!(
13931 ProjectSettings::get_global(cx).git.git_gutter,
13932 Some(GitGutterSetting::TrackedFiles)
13933 )
13934 });
13935 let gutter_settings = EditorSettings::get_global(cx).gutter;
13936 let show_line_numbers = self
13937 .show_line_numbers
13938 .unwrap_or(gutter_settings.line_numbers);
13939 let line_gutter_width = if show_line_numbers {
13940 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13941 let min_width_for_number_on_gutter = em_advance * 4.0;
13942 max_line_number_width.max(min_width_for_number_on_gutter)
13943 } else {
13944 0.0.into()
13945 };
13946
13947 let show_code_actions = self
13948 .show_code_actions
13949 .unwrap_or(gutter_settings.code_actions);
13950
13951 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13952
13953 let git_blame_entries_width =
13954 self.git_blame_gutter_max_author_length
13955 .map(|max_author_length| {
13956 // Length of the author name, but also space for the commit hash,
13957 // the spacing and the timestamp.
13958 let max_char_count = max_author_length
13959 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13960 + 7 // length of commit sha
13961 + 14 // length of max relative timestamp ("60 minutes ago")
13962 + 4; // gaps and margins
13963
13964 em_advance * max_char_count
13965 });
13966
13967 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13968 left_padding += if show_code_actions || show_runnables {
13969 em_width * 3.0
13970 } else if show_git_gutter && show_line_numbers {
13971 em_width * 2.0
13972 } else if show_git_gutter || show_line_numbers {
13973 em_width
13974 } else {
13975 px(0.)
13976 };
13977
13978 let right_padding = if gutter_settings.folds && show_line_numbers {
13979 em_width * 4.0
13980 } else if gutter_settings.folds {
13981 em_width * 3.0
13982 } else if show_line_numbers {
13983 em_width
13984 } else {
13985 px(0.)
13986 };
13987
13988 GutterDimensions {
13989 left_padding,
13990 right_padding,
13991 width: line_gutter_width + left_padding + right_padding,
13992 margin: -descent,
13993 git_blame_entries_width,
13994 }
13995 }
13996
13997 pub fn render_crease_toggle(
13998 &self,
13999 buffer_row: MultiBufferRow,
14000 row_contains_cursor: bool,
14001 editor: View<Editor>,
14002 cx: &mut WindowContext,
14003 ) -> Option<AnyElement> {
14004 let folded = self.is_line_folded(buffer_row);
14005 let mut is_foldable = false;
14006
14007 if let Some(crease) = self
14008 .crease_snapshot
14009 .query_row(buffer_row, &self.buffer_snapshot)
14010 {
14011 is_foldable = true;
14012 match crease {
14013 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14014 if let Some(render_toggle) = render_toggle {
14015 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14016 if folded {
14017 editor.update(cx, |editor, cx| {
14018 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14019 });
14020 } else {
14021 editor.update(cx, |editor, cx| {
14022 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14023 });
14024 }
14025 });
14026 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14027 }
14028 }
14029 }
14030 }
14031
14032 is_foldable |= self.starts_indent(buffer_row);
14033
14034 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14035 Some(
14036 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14037 .toggle_state(folded)
14038 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14039 if folded {
14040 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14041 } else {
14042 this.fold_at(&FoldAt { buffer_row }, cx);
14043 }
14044 }))
14045 .into_any_element(),
14046 )
14047 } else {
14048 None
14049 }
14050 }
14051
14052 pub fn render_crease_trailer(
14053 &self,
14054 buffer_row: MultiBufferRow,
14055 cx: &mut WindowContext,
14056 ) -> Option<AnyElement> {
14057 let folded = self.is_line_folded(buffer_row);
14058 if let Crease::Inline { render_trailer, .. } = self
14059 .crease_snapshot
14060 .query_row(buffer_row, &self.buffer_snapshot)?
14061 {
14062 let render_trailer = render_trailer.as_ref()?;
14063 Some(render_trailer(buffer_row, folded, cx))
14064 } else {
14065 None
14066 }
14067 }
14068}
14069
14070impl Deref for EditorSnapshot {
14071 type Target = DisplaySnapshot;
14072
14073 fn deref(&self) -> &Self::Target {
14074 &self.display_snapshot
14075 }
14076}
14077
14078#[derive(Clone, Debug, PartialEq, Eq)]
14079pub enum EditorEvent {
14080 InputIgnored {
14081 text: Arc<str>,
14082 },
14083 InputHandled {
14084 utf16_range_to_replace: Option<Range<isize>>,
14085 text: Arc<str>,
14086 },
14087 ExcerptsAdded {
14088 buffer: Model<Buffer>,
14089 predecessor: ExcerptId,
14090 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14091 },
14092 ExcerptsRemoved {
14093 ids: Vec<ExcerptId>,
14094 },
14095 BufferFoldToggled {
14096 ids: Vec<ExcerptId>,
14097 folded: bool,
14098 },
14099 ExcerptsEdited {
14100 ids: Vec<ExcerptId>,
14101 },
14102 ExcerptsExpanded {
14103 ids: Vec<ExcerptId>,
14104 },
14105 BufferEdited,
14106 Edited {
14107 transaction_id: clock::Lamport,
14108 },
14109 Reparsed(BufferId),
14110 Focused,
14111 FocusedIn,
14112 Blurred,
14113 DirtyChanged,
14114 Saved,
14115 TitleChanged,
14116 DiffBaseChanged,
14117 SelectionsChanged {
14118 local: bool,
14119 },
14120 ScrollPositionChanged {
14121 local: bool,
14122 autoscroll: bool,
14123 },
14124 Closed,
14125 TransactionUndone {
14126 transaction_id: clock::Lamport,
14127 },
14128 TransactionBegun {
14129 transaction_id: clock::Lamport,
14130 },
14131 Reloaded,
14132 CursorShapeChanged,
14133}
14134
14135impl EventEmitter<EditorEvent> for Editor {}
14136
14137impl FocusableView for Editor {
14138 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14139 self.focus_handle.clone()
14140 }
14141}
14142
14143impl Render for Editor {
14144 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14145 let settings = ThemeSettings::get_global(cx);
14146
14147 let mut text_style = match self.mode {
14148 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14149 color: cx.theme().colors().editor_foreground,
14150 font_family: settings.ui_font.family.clone(),
14151 font_features: settings.ui_font.features.clone(),
14152 font_fallbacks: settings.ui_font.fallbacks.clone(),
14153 font_size: rems(0.875).into(),
14154 font_weight: settings.ui_font.weight,
14155 line_height: relative(settings.buffer_line_height.value()),
14156 ..Default::default()
14157 },
14158 EditorMode::Full => TextStyle {
14159 color: cx.theme().colors().editor_foreground,
14160 font_family: settings.buffer_font.family.clone(),
14161 font_features: settings.buffer_font.features.clone(),
14162 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14163 font_size: settings.buffer_font_size(cx).into(),
14164 font_weight: settings.buffer_font.weight,
14165 line_height: relative(settings.buffer_line_height.value()),
14166 ..Default::default()
14167 },
14168 };
14169 if let Some(text_style_refinement) = &self.text_style_refinement {
14170 text_style.refine(text_style_refinement)
14171 }
14172
14173 let background = match self.mode {
14174 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14175 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14176 EditorMode::Full => cx.theme().colors().editor_background,
14177 };
14178
14179 EditorElement::new(
14180 cx.view(),
14181 EditorStyle {
14182 background,
14183 local_player: cx.theme().players().local(),
14184 text: text_style,
14185 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14186 syntax: cx.theme().syntax().clone(),
14187 status: cx.theme().status().clone(),
14188 inlay_hints_style: make_inlay_hints_style(cx),
14189 inline_completion_styles: make_suggestion_styles(cx),
14190 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14191 },
14192 )
14193 }
14194}
14195
14196impl ViewInputHandler for Editor {
14197 fn text_for_range(
14198 &mut self,
14199 range_utf16: Range<usize>,
14200 adjusted_range: &mut Option<Range<usize>>,
14201 cx: &mut ViewContext<Self>,
14202 ) -> Option<String> {
14203 let snapshot = self.buffer.read(cx).read(cx);
14204 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14205 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14206 if (start.0..end.0) != range_utf16 {
14207 adjusted_range.replace(start.0..end.0);
14208 }
14209 Some(snapshot.text_for_range(start..end).collect())
14210 }
14211
14212 fn selected_text_range(
14213 &mut self,
14214 ignore_disabled_input: bool,
14215 cx: &mut ViewContext<Self>,
14216 ) -> Option<UTF16Selection> {
14217 // Prevent the IME menu from appearing when holding down an alphabetic key
14218 // while input is disabled.
14219 if !ignore_disabled_input && !self.input_enabled {
14220 return None;
14221 }
14222
14223 let selection = self.selections.newest::<OffsetUtf16>(cx);
14224 let range = selection.range();
14225
14226 Some(UTF16Selection {
14227 range: range.start.0..range.end.0,
14228 reversed: selection.reversed,
14229 })
14230 }
14231
14232 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14233 let snapshot = self.buffer.read(cx).read(cx);
14234 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14235 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14236 }
14237
14238 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14239 self.clear_highlights::<InputComposition>(cx);
14240 self.ime_transaction.take();
14241 }
14242
14243 fn replace_text_in_range(
14244 &mut self,
14245 range_utf16: Option<Range<usize>>,
14246 text: &str,
14247 cx: &mut ViewContext<Self>,
14248 ) {
14249 if !self.input_enabled {
14250 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14251 return;
14252 }
14253
14254 self.transact(cx, |this, cx| {
14255 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14256 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14257 Some(this.selection_replacement_ranges(range_utf16, cx))
14258 } else {
14259 this.marked_text_ranges(cx)
14260 };
14261
14262 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14263 let newest_selection_id = this.selections.newest_anchor().id;
14264 this.selections
14265 .all::<OffsetUtf16>(cx)
14266 .iter()
14267 .zip(ranges_to_replace.iter())
14268 .find_map(|(selection, range)| {
14269 if selection.id == newest_selection_id {
14270 Some(
14271 (range.start.0 as isize - selection.head().0 as isize)
14272 ..(range.end.0 as isize - selection.head().0 as isize),
14273 )
14274 } else {
14275 None
14276 }
14277 })
14278 });
14279
14280 cx.emit(EditorEvent::InputHandled {
14281 utf16_range_to_replace: range_to_replace,
14282 text: text.into(),
14283 });
14284
14285 if let Some(new_selected_ranges) = new_selected_ranges {
14286 this.change_selections(None, cx, |selections| {
14287 selections.select_ranges(new_selected_ranges)
14288 });
14289 this.backspace(&Default::default(), cx);
14290 }
14291
14292 this.handle_input(text, cx);
14293 });
14294
14295 if let Some(transaction) = self.ime_transaction {
14296 self.buffer.update(cx, |buffer, cx| {
14297 buffer.group_until_transaction(transaction, cx);
14298 });
14299 }
14300
14301 self.unmark_text(cx);
14302 }
14303
14304 fn replace_and_mark_text_in_range(
14305 &mut self,
14306 range_utf16: Option<Range<usize>>,
14307 text: &str,
14308 new_selected_range_utf16: Option<Range<usize>>,
14309 cx: &mut ViewContext<Self>,
14310 ) {
14311 if !self.input_enabled {
14312 return;
14313 }
14314
14315 let transaction = self.transact(cx, |this, cx| {
14316 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14317 let snapshot = this.buffer.read(cx).read(cx);
14318 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14319 for marked_range in &mut marked_ranges {
14320 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14321 marked_range.start.0 += relative_range_utf16.start;
14322 marked_range.start =
14323 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14324 marked_range.end =
14325 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14326 }
14327 }
14328 Some(marked_ranges)
14329 } else if let Some(range_utf16) = range_utf16 {
14330 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14331 Some(this.selection_replacement_ranges(range_utf16, cx))
14332 } else {
14333 None
14334 };
14335
14336 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14337 let newest_selection_id = this.selections.newest_anchor().id;
14338 this.selections
14339 .all::<OffsetUtf16>(cx)
14340 .iter()
14341 .zip(ranges_to_replace.iter())
14342 .find_map(|(selection, range)| {
14343 if selection.id == newest_selection_id {
14344 Some(
14345 (range.start.0 as isize - selection.head().0 as isize)
14346 ..(range.end.0 as isize - selection.head().0 as isize),
14347 )
14348 } else {
14349 None
14350 }
14351 })
14352 });
14353
14354 cx.emit(EditorEvent::InputHandled {
14355 utf16_range_to_replace: range_to_replace,
14356 text: text.into(),
14357 });
14358
14359 if let Some(ranges) = ranges_to_replace {
14360 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14361 }
14362
14363 let marked_ranges = {
14364 let snapshot = this.buffer.read(cx).read(cx);
14365 this.selections
14366 .disjoint_anchors()
14367 .iter()
14368 .map(|selection| {
14369 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14370 })
14371 .collect::<Vec<_>>()
14372 };
14373
14374 if text.is_empty() {
14375 this.unmark_text(cx);
14376 } else {
14377 this.highlight_text::<InputComposition>(
14378 marked_ranges.clone(),
14379 HighlightStyle {
14380 underline: Some(UnderlineStyle {
14381 thickness: px(1.),
14382 color: None,
14383 wavy: false,
14384 }),
14385 ..Default::default()
14386 },
14387 cx,
14388 );
14389 }
14390
14391 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14392 let use_autoclose = this.use_autoclose;
14393 let use_auto_surround = this.use_auto_surround;
14394 this.set_use_autoclose(false);
14395 this.set_use_auto_surround(false);
14396 this.handle_input(text, cx);
14397 this.set_use_autoclose(use_autoclose);
14398 this.set_use_auto_surround(use_auto_surround);
14399
14400 if let Some(new_selected_range) = new_selected_range_utf16 {
14401 let snapshot = this.buffer.read(cx).read(cx);
14402 let new_selected_ranges = marked_ranges
14403 .into_iter()
14404 .map(|marked_range| {
14405 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14406 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14407 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14408 snapshot.clip_offset_utf16(new_start, Bias::Left)
14409 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14410 })
14411 .collect::<Vec<_>>();
14412
14413 drop(snapshot);
14414 this.change_selections(None, cx, |selections| {
14415 selections.select_ranges(new_selected_ranges)
14416 });
14417 }
14418 });
14419
14420 self.ime_transaction = self.ime_transaction.or(transaction);
14421 if let Some(transaction) = self.ime_transaction {
14422 self.buffer.update(cx, |buffer, cx| {
14423 buffer.group_until_transaction(transaction, cx);
14424 });
14425 }
14426
14427 if self.text_highlights::<InputComposition>(cx).is_none() {
14428 self.ime_transaction.take();
14429 }
14430 }
14431
14432 fn bounds_for_range(
14433 &mut self,
14434 range_utf16: Range<usize>,
14435 element_bounds: gpui::Bounds<Pixels>,
14436 cx: &mut ViewContext<Self>,
14437 ) -> Option<gpui::Bounds<Pixels>> {
14438 let text_layout_details = self.text_layout_details(cx);
14439 let gpui::Point {
14440 x: em_width,
14441 y: line_height,
14442 } = self.character_size(cx);
14443
14444 let snapshot = self.snapshot(cx);
14445 let scroll_position = snapshot.scroll_position();
14446 let scroll_left = scroll_position.x * em_width;
14447
14448 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14449 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14450 + self.gutter_dimensions.width
14451 + self.gutter_dimensions.margin;
14452 let y = line_height * (start.row().as_f32() - scroll_position.y);
14453
14454 Some(Bounds {
14455 origin: element_bounds.origin + point(x, y),
14456 size: size(em_width, line_height),
14457 })
14458 }
14459}
14460
14461trait SelectionExt {
14462 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14463 fn spanned_rows(
14464 &self,
14465 include_end_if_at_line_start: bool,
14466 map: &DisplaySnapshot,
14467 ) -> Range<MultiBufferRow>;
14468}
14469
14470impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14471 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14472 let start = self
14473 .start
14474 .to_point(&map.buffer_snapshot)
14475 .to_display_point(map);
14476 let end = self
14477 .end
14478 .to_point(&map.buffer_snapshot)
14479 .to_display_point(map);
14480 if self.reversed {
14481 end..start
14482 } else {
14483 start..end
14484 }
14485 }
14486
14487 fn spanned_rows(
14488 &self,
14489 include_end_if_at_line_start: bool,
14490 map: &DisplaySnapshot,
14491 ) -> Range<MultiBufferRow> {
14492 let start = self.start.to_point(&map.buffer_snapshot);
14493 let mut end = self.end.to_point(&map.buffer_snapshot);
14494 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14495 end.row -= 1;
14496 }
14497
14498 let buffer_start = map.prev_line_boundary(start).0;
14499 let buffer_end = map.next_line_boundary(end).0;
14500 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14501 }
14502}
14503
14504impl<T: InvalidationRegion> InvalidationStack<T> {
14505 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14506 where
14507 S: Clone + ToOffset,
14508 {
14509 while let Some(region) = self.last() {
14510 let all_selections_inside_invalidation_ranges =
14511 if selections.len() == region.ranges().len() {
14512 selections
14513 .iter()
14514 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14515 .all(|(selection, invalidation_range)| {
14516 let head = selection.head().to_offset(buffer);
14517 invalidation_range.start <= head && invalidation_range.end >= head
14518 })
14519 } else {
14520 false
14521 };
14522
14523 if all_selections_inside_invalidation_ranges {
14524 break;
14525 } else {
14526 self.pop();
14527 }
14528 }
14529 }
14530}
14531
14532impl<T> Default for InvalidationStack<T> {
14533 fn default() -> Self {
14534 Self(Default::default())
14535 }
14536}
14537
14538impl<T> Deref for InvalidationStack<T> {
14539 type Target = Vec<T>;
14540
14541 fn deref(&self) -> &Self::Target {
14542 &self.0
14543 }
14544}
14545
14546impl<T> DerefMut for InvalidationStack<T> {
14547 fn deref_mut(&mut self) -> &mut Self::Target {
14548 &mut self.0
14549 }
14550}
14551
14552impl InvalidationRegion for SnippetState {
14553 fn ranges(&self) -> &[Range<Anchor>] {
14554 &self.ranges[self.active_index]
14555 }
14556}
14557
14558pub fn diagnostic_block_renderer(
14559 diagnostic: Diagnostic,
14560 max_message_rows: Option<u8>,
14561 allow_closing: bool,
14562 _is_valid: bool,
14563) -> RenderBlock {
14564 let (text_without_backticks, code_ranges) =
14565 highlight_diagnostic_message(&diagnostic, max_message_rows);
14566
14567 Arc::new(move |cx: &mut BlockContext| {
14568 let group_id: SharedString = cx.block_id.to_string().into();
14569
14570 let mut text_style = cx.text_style().clone();
14571 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14572 let theme_settings = ThemeSettings::get_global(cx);
14573 text_style.font_family = theme_settings.buffer_font.family.clone();
14574 text_style.font_style = theme_settings.buffer_font.style;
14575 text_style.font_features = theme_settings.buffer_font.features.clone();
14576 text_style.font_weight = theme_settings.buffer_font.weight;
14577
14578 let multi_line_diagnostic = diagnostic.message.contains('\n');
14579
14580 let buttons = |diagnostic: &Diagnostic| {
14581 if multi_line_diagnostic {
14582 v_flex()
14583 } else {
14584 h_flex()
14585 }
14586 .when(allow_closing, |div| {
14587 div.children(diagnostic.is_primary.then(|| {
14588 IconButton::new("close-block", IconName::XCircle)
14589 .icon_color(Color::Muted)
14590 .size(ButtonSize::Compact)
14591 .style(ButtonStyle::Transparent)
14592 .visible_on_hover(group_id.clone())
14593 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14594 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14595 }))
14596 })
14597 .child(
14598 IconButton::new("copy-block", IconName::Copy)
14599 .icon_color(Color::Muted)
14600 .size(ButtonSize::Compact)
14601 .style(ButtonStyle::Transparent)
14602 .visible_on_hover(group_id.clone())
14603 .on_click({
14604 let message = diagnostic.message.clone();
14605 move |_click, cx| {
14606 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14607 }
14608 })
14609 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14610 )
14611 };
14612
14613 let icon_size = buttons(&diagnostic)
14614 .into_any_element()
14615 .layout_as_root(AvailableSpace::min_size(), cx);
14616
14617 h_flex()
14618 .id(cx.block_id)
14619 .group(group_id.clone())
14620 .relative()
14621 .size_full()
14622 .block_mouse_down()
14623 .pl(cx.gutter_dimensions.width)
14624 .w(cx.max_width - cx.gutter_dimensions.full_width())
14625 .child(
14626 div()
14627 .flex()
14628 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14629 .flex_shrink(),
14630 )
14631 .child(buttons(&diagnostic))
14632 .child(div().flex().flex_shrink_0().child(
14633 StyledText::new(text_without_backticks.clone()).with_highlights(
14634 &text_style,
14635 code_ranges.iter().map(|range| {
14636 (
14637 range.clone(),
14638 HighlightStyle {
14639 font_weight: Some(FontWeight::BOLD),
14640 ..Default::default()
14641 },
14642 )
14643 }),
14644 ),
14645 ))
14646 .into_any_element()
14647 })
14648}
14649
14650fn inline_completion_edit_text(
14651 editor_snapshot: &EditorSnapshot,
14652 edits: &Vec<(Range<Anchor>, String)>,
14653 include_deletions: bool,
14654 cx: &WindowContext,
14655) -> InlineCompletionText {
14656 let edit_start = edits
14657 .first()
14658 .unwrap()
14659 .0
14660 .start
14661 .to_display_point(editor_snapshot);
14662
14663 let mut text = String::new();
14664 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14665 let mut highlights = Vec::new();
14666 for (old_range, new_text) in edits {
14667 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14668 text.extend(
14669 editor_snapshot
14670 .buffer_snapshot
14671 .chunks(offset..old_offset_range.start, false)
14672 .map(|chunk| chunk.text),
14673 );
14674 offset = old_offset_range.end;
14675
14676 let start = text.len();
14677 let color = if include_deletions && new_text.is_empty() {
14678 text.extend(
14679 editor_snapshot
14680 .buffer_snapshot
14681 .chunks(old_offset_range.start..offset, false)
14682 .map(|chunk| chunk.text),
14683 );
14684 cx.theme().status().deleted_background
14685 } else {
14686 text.push_str(new_text);
14687 cx.theme().status().created_background
14688 };
14689 let end = text.len();
14690
14691 highlights.push((
14692 start..end,
14693 HighlightStyle {
14694 background_color: Some(color),
14695 ..Default::default()
14696 },
14697 ));
14698 }
14699
14700 let edit_end = edits
14701 .last()
14702 .unwrap()
14703 .0
14704 .end
14705 .to_display_point(editor_snapshot);
14706 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14707 .to_offset(editor_snapshot, Bias::Right);
14708 text.extend(
14709 editor_snapshot
14710 .buffer_snapshot
14711 .chunks(offset..end_of_line, false)
14712 .map(|chunk| chunk.text),
14713 );
14714
14715 InlineCompletionText::Edit {
14716 text: text.into(),
14717 highlights,
14718 }
14719}
14720
14721pub fn highlight_diagnostic_message(
14722 diagnostic: &Diagnostic,
14723 mut max_message_rows: Option<u8>,
14724) -> (SharedString, Vec<Range<usize>>) {
14725 let mut text_without_backticks = String::new();
14726 let mut code_ranges = Vec::new();
14727
14728 if let Some(source) = &diagnostic.source {
14729 text_without_backticks.push_str(source);
14730 code_ranges.push(0..source.len());
14731 text_without_backticks.push_str(": ");
14732 }
14733
14734 let mut prev_offset = 0;
14735 let mut in_code_block = false;
14736 let has_row_limit = max_message_rows.is_some();
14737 let mut newline_indices = diagnostic
14738 .message
14739 .match_indices('\n')
14740 .filter(|_| has_row_limit)
14741 .map(|(ix, _)| ix)
14742 .fuse()
14743 .peekable();
14744
14745 for (quote_ix, _) in diagnostic
14746 .message
14747 .match_indices('`')
14748 .chain([(diagnostic.message.len(), "")])
14749 {
14750 let mut first_newline_ix = None;
14751 let mut last_newline_ix = None;
14752 while let Some(newline_ix) = newline_indices.peek() {
14753 if *newline_ix < quote_ix {
14754 if first_newline_ix.is_none() {
14755 first_newline_ix = Some(*newline_ix);
14756 }
14757 last_newline_ix = Some(*newline_ix);
14758
14759 if let Some(rows_left) = &mut max_message_rows {
14760 if *rows_left == 0 {
14761 break;
14762 } else {
14763 *rows_left -= 1;
14764 }
14765 }
14766 let _ = newline_indices.next();
14767 } else {
14768 break;
14769 }
14770 }
14771 let prev_len = text_without_backticks.len();
14772 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14773 text_without_backticks.push_str(new_text);
14774 if in_code_block {
14775 code_ranges.push(prev_len..text_without_backticks.len());
14776 }
14777 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14778 in_code_block = !in_code_block;
14779 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14780 text_without_backticks.push_str("...");
14781 break;
14782 }
14783 }
14784
14785 (text_without_backticks.into(), code_ranges)
14786}
14787
14788fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14789 match severity {
14790 DiagnosticSeverity::ERROR => colors.error,
14791 DiagnosticSeverity::WARNING => colors.warning,
14792 DiagnosticSeverity::INFORMATION => colors.info,
14793 DiagnosticSeverity::HINT => colors.info,
14794 _ => colors.ignored,
14795 }
14796}
14797
14798pub fn styled_runs_for_code_label<'a>(
14799 label: &'a CodeLabel,
14800 syntax_theme: &'a theme::SyntaxTheme,
14801) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14802 let fade_out = HighlightStyle {
14803 fade_out: Some(0.35),
14804 ..Default::default()
14805 };
14806
14807 let mut prev_end = label.filter_range.end;
14808 label
14809 .runs
14810 .iter()
14811 .enumerate()
14812 .flat_map(move |(ix, (range, highlight_id))| {
14813 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14814 style
14815 } else {
14816 return Default::default();
14817 };
14818 let mut muted_style = style;
14819 muted_style.highlight(fade_out);
14820
14821 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14822 if range.start >= label.filter_range.end {
14823 if range.start > prev_end {
14824 runs.push((prev_end..range.start, fade_out));
14825 }
14826 runs.push((range.clone(), muted_style));
14827 } else if range.end <= label.filter_range.end {
14828 runs.push((range.clone(), style));
14829 } else {
14830 runs.push((range.start..label.filter_range.end, style));
14831 runs.push((label.filter_range.end..range.end, muted_style));
14832 }
14833 prev_end = cmp::max(prev_end, range.end);
14834
14835 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14836 runs.push((prev_end..label.text.len(), fade_out));
14837 }
14838
14839 runs
14840 })
14841}
14842
14843pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14844 let mut prev_index = 0;
14845 let mut prev_codepoint: Option<char> = None;
14846 text.char_indices()
14847 .chain([(text.len(), '\0')])
14848 .filter_map(move |(index, codepoint)| {
14849 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14850 let is_boundary = index == text.len()
14851 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14852 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14853 if is_boundary {
14854 let chunk = &text[prev_index..index];
14855 prev_index = index;
14856 Some(chunk)
14857 } else {
14858 None
14859 }
14860 })
14861}
14862
14863pub trait RangeToAnchorExt: Sized {
14864 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14865
14866 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14867 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14868 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14869 }
14870}
14871
14872impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14873 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14874 let start_offset = self.start.to_offset(snapshot);
14875 let end_offset = self.end.to_offset(snapshot);
14876 if start_offset == end_offset {
14877 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14878 } else {
14879 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14880 }
14881 }
14882}
14883
14884pub trait RowExt {
14885 fn as_f32(&self) -> f32;
14886
14887 fn next_row(&self) -> Self;
14888
14889 fn previous_row(&self) -> Self;
14890
14891 fn minus(&self, other: Self) -> u32;
14892}
14893
14894impl RowExt for DisplayRow {
14895 fn as_f32(&self) -> f32 {
14896 self.0 as f32
14897 }
14898
14899 fn next_row(&self) -> Self {
14900 Self(self.0 + 1)
14901 }
14902
14903 fn previous_row(&self) -> Self {
14904 Self(self.0.saturating_sub(1))
14905 }
14906
14907 fn minus(&self, other: Self) -> u32 {
14908 self.0 - other.0
14909 }
14910}
14911
14912impl RowExt for MultiBufferRow {
14913 fn as_f32(&self) -> f32 {
14914 self.0 as f32
14915 }
14916
14917 fn next_row(&self) -> Self {
14918 Self(self.0 + 1)
14919 }
14920
14921 fn previous_row(&self) -> Self {
14922 Self(self.0.saturating_sub(1))
14923 }
14924
14925 fn minus(&self, other: Self) -> u32 {
14926 self.0 - other.0
14927 }
14928}
14929
14930trait RowRangeExt {
14931 type Row;
14932
14933 fn len(&self) -> usize;
14934
14935 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14936}
14937
14938impl RowRangeExt for Range<MultiBufferRow> {
14939 type Row = MultiBufferRow;
14940
14941 fn len(&self) -> usize {
14942 (self.end.0 - self.start.0) as usize
14943 }
14944
14945 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14946 (self.start.0..self.end.0).map(MultiBufferRow)
14947 }
14948}
14949
14950impl RowRangeExt for Range<DisplayRow> {
14951 type Row = DisplayRow;
14952
14953 fn len(&self) -> usize {
14954 (self.end.0 - self.start.0) as usize
14955 }
14956
14957 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14958 (self.start.0..self.end.0).map(DisplayRow)
14959 }
14960}
14961
14962fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14963 if hunk.diff_base_byte_range.is_empty() {
14964 DiffHunkStatus::Added
14965 } else if hunk.row_range.is_empty() {
14966 DiffHunkStatus::Removed
14967 } else {
14968 DiffHunkStatus::Modified
14969 }
14970}
14971
14972/// If select range has more than one line, we
14973/// just point the cursor to range.start.
14974fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14975 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14976 range
14977 } else {
14978 range.start..range.start
14979 }
14980}
14981
14982pub struct KillRing(ClipboardItem);
14983impl Global for KillRing {}
14984
14985const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);