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