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